SemaOverload.cpp 457 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492
  1. //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
  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/SemaInternal.h"
  14. #include "clang/Sema/Lookup.h"
  15. #include "clang/Sema/Initialization.h"
  16. #include "clang/Sema/Template.h"
  17. #include "clang/Sema/TemplateDeduction.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Lex/Preprocessor.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/CXXInheritance.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExprObjC.h"
  26. #include "clang/AST/TypeOrdering.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "llvm/ADT/DenseSet.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/ADT/SmallString.h"
  31. #include "llvm/ADT/STLExtras.h"
  32. #include <algorithm>
  33. namespace clang {
  34. using namespace sema;
  35. /// A convenience routine for creating a decayed reference to a
  36. /// function.
  37. static ExprResult
  38. CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
  39. SourceLocation Loc = SourceLocation(),
  40. const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
  41. DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
  42. VK_LValue, Loc, LocInfo);
  43. if (HadMultipleCandidates)
  44. DRE->setHadMultipleCandidates(true);
  45. ExprResult E = S.Owned(DRE);
  46. E = S.DefaultFunctionArrayConversion(E.take());
  47. if (E.isInvalid())
  48. return ExprError();
  49. return E;
  50. }
  51. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  52. bool InOverloadResolution,
  53. StandardConversionSequence &SCS,
  54. bool CStyle,
  55. bool AllowObjCWritebackConversion);
  56. static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  57. QualType &ToType,
  58. bool InOverloadResolution,
  59. StandardConversionSequence &SCS,
  60. bool CStyle);
  61. static OverloadingResult
  62. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  63. UserDefinedConversionSequence& User,
  64. OverloadCandidateSet& Conversions,
  65. bool AllowExplicit);
  66. static ImplicitConversionSequence::CompareKind
  67. CompareStandardConversionSequences(Sema &S,
  68. const StandardConversionSequence& SCS1,
  69. const StandardConversionSequence& SCS2);
  70. static ImplicitConversionSequence::CompareKind
  71. CompareQualificationConversions(Sema &S,
  72. const StandardConversionSequence& SCS1,
  73. const StandardConversionSequence& SCS2);
  74. static ImplicitConversionSequence::CompareKind
  75. CompareDerivedToBaseConversions(Sema &S,
  76. const StandardConversionSequence& SCS1,
  77. const StandardConversionSequence& SCS2);
  78. /// GetConversionCategory - Retrieve the implicit conversion
  79. /// category corresponding to the given implicit conversion kind.
  80. ImplicitConversionCategory
  81. GetConversionCategory(ImplicitConversionKind Kind) {
  82. static const ImplicitConversionCategory
  83. Category[(int)ICK_Num_Conversion_Kinds] = {
  84. ICC_Identity,
  85. ICC_Lvalue_Transformation,
  86. ICC_Lvalue_Transformation,
  87. ICC_Lvalue_Transformation,
  88. ICC_Identity,
  89. ICC_Qualification_Adjustment,
  90. ICC_Promotion,
  91. ICC_Promotion,
  92. ICC_Promotion,
  93. ICC_Conversion,
  94. ICC_Conversion,
  95. ICC_Conversion,
  96. ICC_Conversion,
  97. ICC_Conversion,
  98. ICC_Conversion,
  99. ICC_Conversion,
  100. ICC_Conversion,
  101. ICC_Conversion,
  102. ICC_Conversion,
  103. ICC_Conversion,
  104. ICC_Conversion,
  105. ICC_Conversion
  106. };
  107. return Category[(int)Kind];
  108. }
  109. /// GetConversionRank - Retrieve the implicit conversion rank
  110. /// corresponding to the given implicit conversion kind.
  111. ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
  112. static const ImplicitConversionRank
  113. Rank[(int)ICK_Num_Conversion_Kinds] = {
  114. ICR_Exact_Match,
  115. ICR_Exact_Match,
  116. ICR_Exact_Match,
  117. ICR_Exact_Match,
  118. ICR_Exact_Match,
  119. ICR_Exact_Match,
  120. ICR_Promotion,
  121. ICR_Promotion,
  122. ICR_Promotion,
  123. ICR_Conversion,
  124. ICR_Conversion,
  125. ICR_Conversion,
  126. ICR_Conversion,
  127. ICR_Conversion,
  128. ICR_Conversion,
  129. ICR_Conversion,
  130. ICR_Conversion,
  131. ICR_Conversion,
  132. ICR_Conversion,
  133. ICR_Conversion,
  134. ICR_Complex_Real_Conversion,
  135. ICR_Conversion,
  136. ICR_Conversion,
  137. ICR_Writeback_Conversion
  138. };
  139. return Rank[(int)Kind];
  140. }
  141. /// GetImplicitConversionName - Return the name of this kind of
  142. /// implicit conversion.
  143. const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
  144. static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
  145. "No conversion",
  146. "Lvalue-to-rvalue",
  147. "Array-to-pointer",
  148. "Function-to-pointer",
  149. "Noreturn adjustment",
  150. "Qualification",
  151. "Integral promotion",
  152. "Floating point promotion",
  153. "Complex promotion",
  154. "Integral conversion",
  155. "Floating conversion",
  156. "Complex conversion",
  157. "Floating-integral conversion",
  158. "Pointer conversion",
  159. "Pointer-to-member conversion",
  160. "Boolean conversion",
  161. "Compatible-types conversion",
  162. "Derived-to-base conversion",
  163. "Vector conversion",
  164. "Vector splat",
  165. "Complex-real conversion",
  166. "Block Pointer conversion",
  167. "Transparent Union Conversion"
  168. "Writeback conversion"
  169. };
  170. return Name[Kind];
  171. }
  172. /// StandardConversionSequence - Set the standard conversion
  173. /// sequence to the identity conversion.
  174. void StandardConversionSequence::setAsIdentityConversion() {
  175. First = ICK_Identity;
  176. Second = ICK_Identity;
  177. Third = ICK_Identity;
  178. DeprecatedStringLiteralToCharPtr = false;
  179. QualificationIncludesObjCLifetime = false;
  180. ReferenceBinding = false;
  181. DirectBinding = false;
  182. IsLvalueReference = true;
  183. BindsToFunctionLvalue = false;
  184. BindsToRvalue = false;
  185. BindsImplicitObjectArgumentWithoutRefQualifier = false;
  186. ObjCLifetimeConversionBinding = false;
  187. CopyConstructor = 0;
  188. }
  189. /// getRank - Retrieve the rank of this standard conversion sequence
  190. /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
  191. /// implicit conversions.
  192. ImplicitConversionRank StandardConversionSequence::getRank() const {
  193. ImplicitConversionRank Rank = ICR_Exact_Match;
  194. if (GetConversionRank(First) > Rank)
  195. Rank = GetConversionRank(First);
  196. if (GetConversionRank(Second) > Rank)
  197. Rank = GetConversionRank(Second);
  198. if (GetConversionRank(Third) > Rank)
  199. Rank = GetConversionRank(Third);
  200. return Rank;
  201. }
  202. /// isPointerConversionToBool - Determines whether this conversion is
  203. /// a conversion of a pointer or pointer-to-member to bool. This is
  204. /// used as part of the ranking of standard conversion sequences
  205. /// (C++ 13.3.3.2p4).
  206. bool StandardConversionSequence::isPointerConversionToBool() const {
  207. // Note that FromType has not necessarily been transformed by the
  208. // array-to-pointer or function-to-pointer implicit conversions, so
  209. // check for their presence as well as checking whether FromType is
  210. // a pointer.
  211. if (getToType(1)->isBooleanType() &&
  212. (getFromType()->isPointerType() ||
  213. getFromType()->isObjCObjectPointerType() ||
  214. getFromType()->isBlockPointerType() ||
  215. getFromType()->isNullPtrType() ||
  216. First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
  217. return true;
  218. return false;
  219. }
  220. /// isPointerConversionToVoidPointer - Determines whether this
  221. /// conversion is a conversion of a pointer to a void pointer. This is
  222. /// used as part of the ranking of standard conversion sequences (C++
  223. /// 13.3.3.2p4).
  224. bool
  225. StandardConversionSequence::
  226. isPointerConversionToVoidPointer(ASTContext& Context) const {
  227. QualType FromType = getFromType();
  228. QualType ToType = getToType(1);
  229. // Note that FromType has not necessarily been transformed by the
  230. // array-to-pointer implicit conversion, so check for its presence
  231. // and redo the conversion to get a pointer.
  232. if (First == ICK_Array_To_Pointer)
  233. FromType = Context.getArrayDecayedType(FromType);
  234. if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
  235. if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
  236. return ToPtrType->getPointeeType()->isVoidType();
  237. return false;
  238. }
  239. /// Skip any implicit casts which could be either part of a narrowing conversion
  240. /// or after one in an implicit conversion.
  241. static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
  242. while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
  243. switch (ICE->getCastKind()) {
  244. case CK_NoOp:
  245. case CK_IntegralCast:
  246. case CK_IntegralToBoolean:
  247. case CK_IntegralToFloating:
  248. case CK_FloatingToIntegral:
  249. case CK_FloatingToBoolean:
  250. case CK_FloatingCast:
  251. Converted = ICE->getSubExpr();
  252. continue;
  253. default:
  254. return Converted;
  255. }
  256. }
  257. return Converted;
  258. }
  259. /// Check if this standard conversion sequence represents a narrowing
  260. /// conversion, according to C++11 [dcl.init.list]p7.
  261. ///
  262. /// \param Ctx The AST context.
  263. /// \param Converted The result of applying this standard conversion sequence.
  264. /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
  265. /// value of the expression prior to the narrowing conversion.
  266. /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
  267. /// type of the expression prior to the narrowing conversion.
  268. NarrowingKind
  269. StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
  270. const Expr *Converted,
  271. APValue &ConstantValue,
  272. QualType &ConstantType) const {
  273. assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
  274. // C++11 [dcl.init.list]p7:
  275. // A narrowing conversion is an implicit conversion ...
  276. QualType FromType = getToType(0);
  277. QualType ToType = getToType(1);
  278. switch (Second) {
  279. // -- from a floating-point type to an integer type, or
  280. //
  281. // -- from an integer type or unscoped enumeration type to a floating-point
  282. // type, except where the source is a constant expression and the actual
  283. // value after conversion will fit into the target type and will produce
  284. // the original value when converted back to the original type, or
  285. case ICK_Floating_Integral:
  286. if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
  287. return NK_Type_Narrowing;
  288. } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
  289. llvm::APSInt IntConstantValue;
  290. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  291. if (Initializer &&
  292. Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
  293. // Convert the integer to the floating type.
  294. llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
  295. Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
  296. llvm::APFloat::rmNearestTiesToEven);
  297. // And back.
  298. llvm::APSInt ConvertedValue = IntConstantValue;
  299. bool ignored;
  300. Result.convertToInteger(ConvertedValue,
  301. llvm::APFloat::rmTowardZero, &ignored);
  302. // If the resulting value is different, this was a narrowing conversion.
  303. if (IntConstantValue != ConvertedValue) {
  304. ConstantValue = APValue(IntConstantValue);
  305. ConstantType = Initializer->getType();
  306. return NK_Constant_Narrowing;
  307. }
  308. } else {
  309. // Variables are always narrowings.
  310. return NK_Variable_Narrowing;
  311. }
  312. }
  313. return NK_Not_Narrowing;
  314. // -- from long double to double or float, or from double to float, except
  315. // where the source is a constant expression and the actual value after
  316. // conversion is within the range of values that can be represented (even
  317. // if it cannot be represented exactly), or
  318. case ICK_Floating_Conversion:
  319. if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
  320. Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
  321. // FromType is larger than ToType.
  322. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  323. if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
  324. // Constant!
  325. assert(ConstantValue.isFloat());
  326. llvm::APFloat FloatVal = ConstantValue.getFloat();
  327. // Convert the source value into the target type.
  328. bool ignored;
  329. llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
  330. Ctx.getFloatTypeSemantics(ToType),
  331. llvm::APFloat::rmNearestTiesToEven, &ignored);
  332. // If there was no overflow, the source value is within the range of
  333. // values that can be represented.
  334. if (ConvertStatus & llvm::APFloat::opOverflow) {
  335. ConstantType = Initializer->getType();
  336. return NK_Constant_Narrowing;
  337. }
  338. } else {
  339. return NK_Variable_Narrowing;
  340. }
  341. }
  342. return NK_Not_Narrowing;
  343. // -- from an integer type or unscoped enumeration type to an integer type
  344. // that cannot represent all the values of the original type, except where
  345. // the source is a constant expression and the actual value after
  346. // conversion will fit into the target type and will produce the original
  347. // value when converted back to the original type.
  348. case ICK_Boolean_Conversion: // Bools are integers too.
  349. if (!FromType->isIntegralOrUnscopedEnumerationType()) {
  350. // Boolean conversions can be from pointers and pointers to members
  351. // [conv.bool], and those aren't considered narrowing conversions.
  352. return NK_Not_Narrowing;
  353. } // Otherwise, fall through to the integral case.
  354. case ICK_Integral_Conversion: {
  355. assert(FromType->isIntegralOrUnscopedEnumerationType());
  356. assert(ToType->isIntegralOrUnscopedEnumerationType());
  357. const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
  358. const unsigned FromWidth = Ctx.getIntWidth(FromType);
  359. const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
  360. const unsigned ToWidth = Ctx.getIntWidth(ToType);
  361. if (FromWidth > ToWidth ||
  362. (FromWidth == ToWidth && FromSigned != ToSigned) ||
  363. (FromSigned && !ToSigned)) {
  364. // Not all values of FromType can be represented in ToType.
  365. llvm::APSInt InitializerValue;
  366. const Expr *Initializer = IgnoreNarrowingConversion(Converted);
  367. if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
  368. // Such conversions on variables are always narrowing.
  369. return NK_Variable_Narrowing;
  370. }
  371. bool Narrowing = false;
  372. if (FromWidth < ToWidth) {
  373. // Negative -> unsigned is narrowing. Otherwise, more bits is never
  374. // narrowing.
  375. if (InitializerValue.isSigned() && InitializerValue.isNegative())
  376. Narrowing = true;
  377. } else {
  378. // Add a bit to the InitializerValue so we don't have to worry about
  379. // signed vs. unsigned comparisons.
  380. InitializerValue = InitializerValue.extend(
  381. InitializerValue.getBitWidth() + 1);
  382. // Convert the initializer to and from the target width and signed-ness.
  383. llvm::APSInt ConvertedValue = InitializerValue;
  384. ConvertedValue = ConvertedValue.trunc(ToWidth);
  385. ConvertedValue.setIsSigned(ToSigned);
  386. ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
  387. ConvertedValue.setIsSigned(InitializerValue.isSigned());
  388. // If the result is different, this was a narrowing conversion.
  389. if (ConvertedValue != InitializerValue)
  390. Narrowing = true;
  391. }
  392. if (Narrowing) {
  393. ConstantType = Initializer->getType();
  394. ConstantValue = APValue(InitializerValue);
  395. return NK_Constant_Narrowing;
  396. }
  397. }
  398. return NK_Not_Narrowing;
  399. }
  400. default:
  401. // Other kinds of conversions are not narrowings.
  402. return NK_Not_Narrowing;
  403. }
  404. }
  405. /// DebugPrint - Print this standard conversion sequence to standard
  406. /// error. Useful for debugging overloading issues.
  407. void StandardConversionSequence::DebugPrint() const {
  408. raw_ostream &OS = llvm::errs();
  409. bool PrintedSomething = false;
  410. if (First != ICK_Identity) {
  411. OS << GetImplicitConversionName(First);
  412. PrintedSomething = true;
  413. }
  414. if (Second != ICK_Identity) {
  415. if (PrintedSomething) {
  416. OS << " -> ";
  417. }
  418. OS << GetImplicitConversionName(Second);
  419. if (CopyConstructor) {
  420. OS << " (by copy constructor)";
  421. } else if (DirectBinding) {
  422. OS << " (direct reference binding)";
  423. } else if (ReferenceBinding) {
  424. OS << " (reference binding)";
  425. }
  426. PrintedSomething = true;
  427. }
  428. if (Third != ICK_Identity) {
  429. if (PrintedSomething) {
  430. OS << " -> ";
  431. }
  432. OS << GetImplicitConversionName(Third);
  433. PrintedSomething = true;
  434. }
  435. if (!PrintedSomething) {
  436. OS << "No conversions required";
  437. }
  438. }
  439. /// DebugPrint - Print this user-defined conversion sequence to standard
  440. /// error. Useful for debugging overloading issues.
  441. void UserDefinedConversionSequence::DebugPrint() const {
  442. raw_ostream &OS = llvm::errs();
  443. if (Before.First || Before.Second || Before.Third) {
  444. Before.DebugPrint();
  445. OS << " -> ";
  446. }
  447. if (ConversionFunction)
  448. OS << '\'' << *ConversionFunction << '\'';
  449. else
  450. OS << "aggregate initialization";
  451. if (After.First || After.Second || After.Third) {
  452. OS << " -> ";
  453. After.DebugPrint();
  454. }
  455. }
  456. /// DebugPrint - Print this implicit conversion sequence to standard
  457. /// error. Useful for debugging overloading issues.
  458. void ImplicitConversionSequence::DebugPrint() const {
  459. raw_ostream &OS = llvm::errs();
  460. switch (ConversionKind) {
  461. case StandardConversion:
  462. OS << "Standard conversion: ";
  463. Standard.DebugPrint();
  464. break;
  465. case UserDefinedConversion:
  466. OS << "User-defined conversion: ";
  467. UserDefined.DebugPrint();
  468. break;
  469. case EllipsisConversion:
  470. OS << "Ellipsis conversion";
  471. break;
  472. case AmbiguousConversion:
  473. OS << "Ambiguous conversion";
  474. break;
  475. case BadConversion:
  476. OS << "Bad conversion";
  477. break;
  478. }
  479. OS << "\n";
  480. }
  481. void AmbiguousConversionSequence::construct() {
  482. new (&conversions()) ConversionSet();
  483. }
  484. void AmbiguousConversionSequence::destruct() {
  485. conversions().~ConversionSet();
  486. }
  487. void
  488. AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
  489. FromTypePtr = O.FromTypePtr;
  490. ToTypePtr = O.ToTypePtr;
  491. new (&conversions()) ConversionSet(O.conversions());
  492. }
  493. namespace {
  494. // Structure used by OverloadCandidate::DeductionFailureInfo to store
  495. // template parameter and template argument information.
  496. struct DFIParamWithArguments {
  497. TemplateParameter Param;
  498. TemplateArgument FirstArg;
  499. TemplateArgument SecondArg;
  500. };
  501. }
  502. /// \brief Convert from Sema's representation of template deduction information
  503. /// to the form used in overload-candidate information.
  504. OverloadCandidate::DeductionFailureInfo
  505. static MakeDeductionFailureInfo(ASTContext &Context,
  506. Sema::TemplateDeductionResult TDK,
  507. TemplateDeductionInfo &Info) {
  508. OverloadCandidate::DeductionFailureInfo Result;
  509. Result.Result = static_cast<unsigned>(TDK);
  510. Result.HasDiagnostic = false;
  511. Result.Data = 0;
  512. switch (TDK) {
  513. case Sema::TDK_Success:
  514. case Sema::TDK_InstantiationDepth:
  515. case Sema::TDK_TooManyArguments:
  516. case Sema::TDK_TooFewArguments:
  517. break;
  518. case Sema::TDK_Incomplete:
  519. case Sema::TDK_InvalidExplicitArguments:
  520. Result.Data = Info.Param.getOpaqueValue();
  521. break;
  522. case Sema::TDK_Inconsistent:
  523. case Sema::TDK_Underqualified: {
  524. // FIXME: Should allocate from normal heap so that we can free this later.
  525. DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
  526. Saved->Param = Info.Param;
  527. Saved->FirstArg = Info.FirstArg;
  528. Saved->SecondArg = Info.SecondArg;
  529. Result.Data = Saved;
  530. break;
  531. }
  532. case Sema::TDK_SubstitutionFailure:
  533. Result.Data = Info.take();
  534. if (Info.hasSFINAEDiagnostic()) {
  535. PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
  536. SourceLocation(), PartialDiagnostic::NullDiagnostic());
  537. Info.takeSFINAEDiagnostic(*Diag);
  538. Result.HasDiagnostic = true;
  539. }
  540. break;
  541. case Sema::TDK_NonDeducedMismatch:
  542. case Sema::TDK_FailedOverloadResolution:
  543. break;
  544. }
  545. return Result;
  546. }
  547. void OverloadCandidate::DeductionFailureInfo::Destroy() {
  548. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  549. case Sema::TDK_Success:
  550. case Sema::TDK_InstantiationDepth:
  551. case Sema::TDK_Incomplete:
  552. case Sema::TDK_TooManyArguments:
  553. case Sema::TDK_TooFewArguments:
  554. case Sema::TDK_InvalidExplicitArguments:
  555. break;
  556. case Sema::TDK_Inconsistent:
  557. case Sema::TDK_Underqualified:
  558. // FIXME: Destroy the data?
  559. Data = 0;
  560. break;
  561. case Sema::TDK_SubstitutionFailure:
  562. // FIXME: Destroy the template argument list?
  563. Data = 0;
  564. if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
  565. Diag->~PartialDiagnosticAt();
  566. HasDiagnostic = false;
  567. }
  568. break;
  569. // Unhandled
  570. case Sema::TDK_NonDeducedMismatch:
  571. case Sema::TDK_FailedOverloadResolution:
  572. break;
  573. }
  574. }
  575. PartialDiagnosticAt *
  576. OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
  577. if (HasDiagnostic)
  578. return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
  579. return 0;
  580. }
  581. TemplateParameter
  582. OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
  583. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  584. case Sema::TDK_Success:
  585. case Sema::TDK_InstantiationDepth:
  586. case Sema::TDK_TooManyArguments:
  587. case Sema::TDK_TooFewArguments:
  588. case Sema::TDK_SubstitutionFailure:
  589. return TemplateParameter();
  590. case Sema::TDK_Incomplete:
  591. case Sema::TDK_InvalidExplicitArguments:
  592. return TemplateParameter::getFromOpaqueValue(Data);
  593. case Sema::TDK_Inconsistent:
  594. case Sema::TDK_Underqualified:
  595. return static_cast<DFIParamWithArguments*>(Data)->Param;
  596. // Unhandled
  597. case Sema::TDK_NonDeducedMismatch:
  598. case Sema::TDK_FailedOverloadResolution:
  599. break;
  600. }
  601. return TemplateParameter();
  602. }
  603. TemplateArgumentList *
  604. OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
  605. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  606. case Sema::TDK_Success:
  607. case Sema::TDK_InstantiationDepth:
  608. case Sema::TDK_TooManyArguments:
  609. case Sema::TDK_TooFewArguments:
  610. case Sema::TDK_Incomplete:
  611. case Sema::TDK_InvalidExplicitArguments:
  612. case Sema::TDK_Inconsistent:
  613. case Sema::TDK_Underqualified:
  614. return 0;
  615. case Sema::TDK_SubstitutionFailure:
  616. return static_cast<TemplateArgumentList*>(Data);
  617. // Unhandled
  618. case Sema::TDK_NonDeducedMismatch:
  619. case Sema::TDK_FailedOverloadResolution:
  620. break;
  621. }
  622. return 0;
  623. }
  624. const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
  625. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  626. case Sema::TDK_Success:
  627. case Sema::TDK_InstantiationDepth:
  628. case Sema::TDK_Incomplete:
  629. case Sema::TDK_TooManyArguments:
  630. case Sema::TDK_TooFewArguments:
  631. case Sema::TDK_InvalidExplicitArguments:
  632. case Sema::TDK_SubstitutionFailure:
  633. return 0;
  634. case Sema::TDK_Inconsistent:
  635. case Sema::TDK_Underqualified:
  636. return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
  637. // Unhandled
  638. case Sema::TDK_NonDeducedMismatch:
  639. case Sema::TDK_FailedOverloadResolution:
  640. break;
  641. }
  642. return 0;
  643. }
  644. const TemplateArgument *
  645. OverloadCandidate::DeductionFailureInfo::getSecondArg() {
  646. switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
  647. case Sema::TDK_Success:
  648. case Sema::TDK_InstantiationDepth:
  649. case Sema::TDK_Incomplete:
  650. case Sema::TDK_TooManyArguments:
  651. case Sema::TDK_TooFewArguments:
  652. case Sema::TDK_InvalidExplicitArguments:
  653. case Sema::TDK_SubstitutionFailure:
  654. return 0;
  655. case Sema::TDK_Inconsistent:
  656. case Sema::TDK_Underqualified:
  657. return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
  658. // Unhandled
  659. case Sema::TDK_NonDeducedMismatch:
  660. case Sema::TDK_FailedOverloadResolution:
  661. break;
  662. }
  663. return 0;
  664. }
  665. void OverloadCandidateSet::clear() {
  666. for (iterator i = begin(), e = end(); i != e; ++i) {
  667. for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
  668. i->Conversions[ii].~ImplicitConversionSequence();
  669. if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
  670. i->DeductionFailure.Destroy();
  671. }
  672. NumInlineSequences = 0;
  673. Candidates.clear();
  674. Functions.clear();
  675. }
  676. namespace {
  677. class UnbridgedCastsSet {
  678. struct Entry {
  679. Expr **Addr;
  680. Expr *Saved;
  681. };
  682. SmallVector<Entry, 2> Entries;
  683. public:
  684. void save(Sema &S, Expr *&E) {
  685. assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  686. Entry entry = { &E, E };
  687. Entries.push_back(entry);
  688. E = S.stripARCUnbridgedCast(E);
  689. }
  690. void restore() {
  691. for (SmallVectorImpl<Entry>::iterator
  692. i = Entries.begin(), e = Entries.end(); i != e; ++i)
  693. *i->Addr = i->Saved;
  694. }
  695. };
  696. }
  697. /// checkPlaceholderForOverload - Do any interesting placeholder-like
  698. /// preprocessing on the given expression.
  699. ///
  700. /// \param unbridgedCasts a collection to which to add unbridged casts;
  701. /// without this, they will be immediately diagnosed as errors
  702. ///
  703. /// Return true on unrecoverable error.
  704. static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
  705. UnbridgedCastsSet *unbridgedCasts = 0) {
  706. if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
  707. // We can't handle overloaded expressions here because overload
  708. // resolution might reasonably tweak them.
  709. if (placeholder->getKind() == BuiltinType::Overload) return false;
  710. // If the context potentially accepts unbridged ARC casts, strip
  711. // the unbridged cast and add it to the collection for later restoration.
  712. if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
  713. unbridgedCasts) {
  714. unbridgedCasts->save(S, E);
  715. return false;
  716. }
  717. // Go ahead and check everything else.
  718. ExprResult result = S.CheckPlaceholderExpr(E);
  719. if (result.isInvalid())
  720. return true;
  721. E = result.take();
  722. return false;
  723. }
  724. // Nothing to do.
  725. return false;
  726. }
  727. /// checkArgPlaceholdersForOverload - Check a set of call operands for
  728. /// placeholders.
  729. static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
  730. unsigned numArgs,
  731. UnbridgedCastsSet &unbridged) {
  732. for (unsigned i = 0; i != numArgs; ++i)
  733. if (checkPlaceholderForOverload(S, args[i], &unbridged))
  734. return true;
  735. return false;
  736. }
  737. // IsOverload - Determine whether the given New declaration is an
  738. // overload of the declarations in Old. This routine returns false if
  739. // New and Old cannot be overloaded, e.g., if New has the same
  740. // signature as some function in Old (C++ 1.3.10) or if the Old
  741. // declarations aren't functions (or function templates) at all. When
  742. // it does return false, MatchedDecl will point to the decl that New
  743. // cannot be overloaded with. This decl may be a UsingShadowDecl on
  744. // top of the underlying declaration.
  745. //
  746. // Example: Given the following input:
  747. //
  748. // void f(int, float); // #1
  749. // void f(int, int); // #2
  750. // int f(int, int); // #3
  751. //
  752. // When we process #1, there is no previous declaration of "f",
  753. // so IsOverload will not be used.
  754. //
  755. // When we process #2, Old contains only the FunctionDecl for #1. By
  756. // comparing the parameter types, we see that #1 and #2 are overloaded
  757. // (since they have different signatures), so this routine returns
  758. // false; MatchedDecl is unchanged.
  759. //
  760. // When we process #3, Old is an overload set containing #1 and #2. We
  761. // compare the signatures of #3 to #1 (they're overloaded, so we do
  762. // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
  763. // identical (return types of functions are not part of the
  764. // signature), IsOverload returns false and MatchedDecl will be set to
  765. // point to the FunctionDecl for #2.
  766. //
  767. // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
  768. // into a class by a using declaration. The rules for whether to hide
  769. // shadow declarations ignore some properties which otherwise figure
  770. // into a function template's signature.
  771. Sema::OverloadKind
  772. Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
  773. NamedDecl *&Match, bool NewIsUsingDecl) {
  774. for (LookupResult::iterator I = Old.begin(), E = Old.end();
  775. I != E; ++I) {
  776. NamedDecl *OldD = *I;
  777. bool OldIsUsingDecl = false;
  778. if (isa<UsingShadowDecl>(OldD)) {
  779. OldIsUsingDecl = true;
  780. // We can always introduce two using declarations into the same
  781. // context, even if they have identical signatures.
  782. if (NewIsUsingDecl) continue;
  783. OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
  784. }
  785. // If either declaration was introduced by a using declaration,
  786. // we'll need to use slightly different rules for matching.
  787. // Essentially, these rules are the normal rules, except that
  788. // function templates hide function templates with different
  789. // return types or template parameter lists.
  790. bool UseMemberUsingDeclRules =
  791. (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
  792. if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
  793. if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
  794. if (UseMemberUsingDeclRules && OldIsUsingDecl) {
  795. HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
  796. continue;
  797. }
  798. Match = *I;
  799. return Ovl_Match;
  800. }
  801. } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
  802. if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
  803. if (UseMemberUsingDeclRules && OldIsUsingDecl) {
  804. HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
  805. continue;
  806. }
  807. Match = *I;
  808. return Ovl_Match;
  809. }
  810. } else if (isa<UsingDecl>(OldD)) {
  811. // We can overload with these, which can show up when doing
  812. // redeclaration checks for UsingDecls.
  813. assert(Old.getLookupKind() == LookupUsingDeclName);
  814. } else if (isa<TagDecl>(OldD)) {
  815. // We can always overload with tags by hiding them.
  816. } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
  817. // Optimistically assume that an unresolved using decl will
  818. // overload; if it doesn't, we'll have to diagnose during
  819. // template instantiation.
  820. } else {
  821. // (C++ 13p1):
  822. // Only function declarations can be overloaded; object and type
  823. // declarations cannot be overloaded.
  824. Match = *I;
  825. return Ovl_NonFunction;
  826. }
  827. }
  828. return Ovl_Overload;
  829. }
  830. bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
  831. bool UseUsingDeclRules) {
  832. // If both of the functions are extern "C", then they are not
  833. // overloads.
  834. if (Old->isExternC() && New->isExternC())
  835. return false;
  836. FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
  837. FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
  838. // C++ [temp.fct]p2:
  839. // A function template can be overloaded with other function templates
  840. // and with normal (non-template) functions.
  841. if ((OldTemplate == 0) != (NewTemplate == 0))
  842. return true;
  843. // Is the function New an overload of the function Old?
  844. QualType OldQType = Context.getCanonicalType(Old->getType());
  845. QualType NewQType = Context.getCanonicalType(New->getType());
  846. // Compare the signatures (C++ 1.3.10) of the two functions to
  847. // determine whether they are overloads. If we find any mismatch
  848. // in the signature, they are overloads.
  849. // If either of these functions is a K&R-style function (no
  850. // prototype), then we consider them to have matching signatures.
  851. if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
  852. isa<FunctionNoProtoType>(NewQType.getTypePtr()))
  853. return false;
  854. const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
  855. const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
  856. // The signature of a function includes the types of its
  857. // parameters (C++ 1.3.10), which includes the presence or absence
  858. // of the ellipsis; see C++ DR 357).
  859. if (OldQType != NewQType &&
  860. (OldType->getNumArgs() != NewType->getNumArgs() ||
  861. OldType->isVariadic() != NewType->isVariadic() ||
  862. !FunctionArgTypesAreEqual(OldType, NewType)))
  863. return true;
  864. // C++ [temp.over.link]p4:
  865. // The signature of a function template consists of its function
  866. // signature, its return type and its template parameter list. The names
  867. // of the template parameters are significant only for establishing the
  868. // relationship between the template parameters and the rest of the
  869. // signature.
  870. //
  871. // We check the return type and template parameter lists for function
  872. // templates first; the remaining checks follow.
  873. //
  874. // However, we don't consider either of these when deciding whether
  875. // a member introduced by a shadow declaration is hidden.
  876. if (!UseUsingDeclRules && NewTemplate &&
  877. (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  878. OldTemplate->getTemplateParameters(),
  879. false, TPL_TemplateMatch) ||
  880. OldType->getResultType() != NewType->getResultType()))
  881. return true;
  882. // If the function is a class member, its signature includes the
  883. // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
  884. //
  885. // As part of this, also check whether one of the member functions
  886. // is static, in which case they are not overloads (C++
  887. // 13.1p2). While not part of the definition of the signature,
  888. // this check is important to determine whether these functions
  889. // can be overloaded.
  890. CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
  891. CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
  892. if (OldMethod && NewMethod &&
  893. !OldMethod->isStatic() && !NewMethod->isStatic() &&
  894. (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
  895. OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
  896. if (!UseUsingDeclRules &&
  897. OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
  898. (OldMethod->getRefQualifier() == RQ_None ||
  899. NewMethod->getRefQualifier() == RQ_None)) {
  900. // C++0x [over.load]p2:
  901. // - Member function declarations with the same name and the same
  902. // parameter-type-list as well as member function template
  903. // declarations with the same name, the same parameter-type-list, and
  904. // the same template parameter lists cannot be overloaded if any of
  905. // them, but not all, have a ref-qualifier (8.3.5).
  906. Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
  907. << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
  908. Diag(OldMethod->getLocation(), diag::note_previous_declaration);
  909. }
  910. return true;
  911. }
  912. // The signatures match; this is not an overload.
  913. return false;
  914. }
  915. /// \brief Checks availability of the function depending on the current
  916. /// function context. Inside an unavailable function, unavailability is ignored.
  917. ///
  918. /// \returns true if \arg FD is unavailable and current context is inside
  919. /// an available function, false otherwise.
  920. bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
  921. return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
  922. }
  923. /// \brief Tries a user-defined conversion from From to ToType.
  924. ///
  925. /// Produces an implicit conversion sequence for when a standard conversion
  926. /// is not an option. See TryImplicitConversion for more information.
  927. static ImplicitConversionSequence
  928. TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  929. bool SuppressUserConversions,
  930. bool AllowExplicit,
  931. bool InOverloadResolution,
  932. bool CStyle,
  933. bool AllowObjCWritebackConversion) {
  934. ImplicitConversionSequence ICS;
  935. if (SuppressUserConversions) {
  936. // We're not in the case above, so there is no conversion that
  937. // we can perform.
  938. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  939. return ICS;
  940. }
  941. // Attempt user-defined conversion.
  942. OverloadCandidateSet Conversions(From->getExprLoc());
  943. OverloadingResult UserDefResult
  944. = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
  945. AllowExplicit);
  946. if (UserDefResult == OR_Success) {
  947. ICS.setUserDefined();
  948. // C++ [over.ics.user]p4:
  949. // A conversion of an expression of class type to the same class
  950. // type is given Exact Match rank, and a conversion of an
  951. // expression of class type to a base class of that type is
  952. // given Conversion rank, in spite of the fact that a copy
  953. // constructor (i.e., a user-defined conversion function) is
  954. // called for those cases.
  955. if (CXXConstructorDecl *Constructor
  956. = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
  957. QualType FromCanon
  958. = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
  959. QualType ToCanon
  960. = S.Context.getCanonicalType(ToType).getUnqualifiedType();
  961. if (Constructor->isCopyConstructor() &&
  962. (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
  963. // Turn this into a "standard" conversion sequence, so that it
  964. // gets ranked with standard conversion sequences.
  965. ICS.setStandard();
  966. ICS.Standard.setAsIdentityConversion();
  967. ICS.Standard.setFromType(From->getType());
  968. ICS.Standard.setAllToTypes(ToType);
  969. ICS.Standard.CopyConstructor = Constructor;
  970. if (ToCanon != FromCanon)
  971. ICS.Standard.Second = ICK_Derived_To_Base;
  972. }
  973. }
  974. // C++ [over.best.ics]p4:
  975. // However, when considering the argument of a user-defined
  976. // conversion function that is a candidate by 13.3.1.3 when
  977. // invoked for the copying of the temporary in the second step
  978. // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
  979. // 13.3.1.6 in all cases, only standard conversion sequences and
  980. // ellipsis conversion sequences are allowed.
  981. if (SuppressUserConversions && ICS.isUserDefined()) {
  982. ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
  983. }
  984. } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
  985. ICS.setAmbiguous();
  986. ICS.Ambiguous.setFromType(From->getType());
  987. ICS.Ambiguous.setToType(ToType);
  988. for (OverloadCandidateSet::iterator Cand = Conversions.begin();
  989. Cand != Conversions.end(); ++Cand)
  990. if (Cand->Viable)
  991. ICS.Ambiguous.addConversion(Cand->Function);
  992. } else {
  993. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  994. }
  995. return ICS;
  996. }
  997. /// TryImplicitConversion - Attempt to perform an implicit conversion
  998. /// from the given expression (Expr) to the given type (ToType). This
  999. /// function returns an implicit conversion sequence that can be used
  1000. /// to perform the initialization. Given
  1001. ///
  1002. /// void f(float f);
  1003. /// void g(int i) { f(i); }
  1004. ///
  1005. /// this routine would produce an implicit conversion sequence to
  1006. /// describe the initialization of f from i, which will be a standard
  1007. /// conversion sequence containing an lvalue-to-rvalue conversion (C++
  1008. /// 4.1) followed by a floating-integral conversion (C++ 4.9).
  1009. //
  1010. /// Note that this routine only determines how the conversion can be
  1011. /// performed; it does not actually perform the conversion. As such,
  1012. /// it will not produce any diagnostics if no conversion is available,
  1013. /// but will instead return an implicit conversion sequence of kind
  1014. /// "BadConversion".
  1015. ///
  1016. /// If @p SuppressUserConversions, then user-defined conversions are
  1017. /// not permitted.
  1018. /// If @p AllowExplicit, then explicit user-defined conversions are
  1019. /// permitted.
  1020. ///
  1021. /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
  1022. /// writeback conversion, which allows __autoreleasing id* parameters to
  1023. /// be initialized with __strong id* or __weak id* arguments.
  1024. static ImplicitConversionSequence
  1025. TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
  1026. bool SuppressUserConversions,
  1027. bool AllowExplicit,
  1028. bool InOverloadResolution,
  1029. bool CStyle,
  1030. bool AllowObjCWritebackConversion) {
  1031. ImplicitConversionSequence ICS;
  1032. if (IsStandardConversion(S, From, ToType, InOverloadResolution,
  1033. ICS.Standard, CStyle, AllowObjCWritebackConversion)){
  1034. ICS.setStandard();
  1035. return ICS;
  1036. }
  1037. if (!S.getLangOpts().CPlusPlus) {
  1038. ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
  1039. return ICS;
  1040. }
  1041. // C++ [over.ics.user]p4:
  1042. // A conversion of an expression of class type to the same class
  1043. // type is given Exact Match rank, and a conversion of an
  1044. // expression of class type to a base class of that type is
  1045. // given Conversion rank, in spite of the fact that a copy/move
  1046. // constructor (i.e., a user-defined conversion function) is
  1047. // called for those cases.
  1048. QualType FromType = From->getType();
  1049. if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
  1050. (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
  1051. S.IsDerivedFrom(FromType, ToType))) {
  1052. ICS.setStandard();
  1053. ICS.Standard.setAsIdentityConversion();
  1054. ICS.Standard.setFromType(FromType);
  1055. ICS.Standard.setAllToTypes(ToType);
  1056. // We don't actually check at this point whether there is a valid
  1057. // copy/move constructor, since overloading just assumes that it
  1058. // exists. When we actually perform initialization, we'll find the
  1059. // appropriate constructor to copy the returned object, if needed.
  1060. ICS.Standard.CopyConstructor = 0;
  1061. // Determine whether this is considered a derived-to-base conversion.
  1062. if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
  1063. ICS.Standard.Second = ICK_Derived_To_Base;
  1064. return ICS;
  1065. }
  1066. return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  1067. AllowExplicit, InOverloadResolution, CStyle,
  1068. AllowObjCWritebackConversion);
  1069. }
  1070. ImplicitConversionSequence
  1071. Sema::TryImplicitConversion(Expr *From, QualType ToType,
  1072. bool SuppressUserConversions,
  1073. bool AllowExplicit,
  1074. bool InOverloadResolution,
  1075. bool CStyle,
  1076. bool AllowObjCWritebackConversion) {
  1077. return clang::TryImplicitConversion(*this, From, ToType,
  1078. SuppressUserConversions, AllowExplicit,
  1079. InOverloadResolution, CStyle,
  1080. AllowObjCWritebackConversion);
  1081. }
  1082. /// PerformImplicitConversion - Perform an implicit conversion of the
  1083. /// expression From to the type ToType. Returns the
  1084. /// converted expression. Flavor is the kind of conversion we're
  1085. /// performing, used in the error message. If @p AllowExplicit,
  1086. /// explicit user-defined conversions are permitted.
  1087. ExprResult
  1088. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1089. AssignmentAction Action, bool AllowExplicit) {
  1090. ImplicitConversionSequence ICS;
  1091. return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
  1092. }
  1093. ExprResult
  1094. Sema::PerformImplicitConversion(Expr *From, QualType ToType,
  1095. AssignmentAction Action, bool AllowExplicit,
  1096. ImplicitConversionSequence& ICS) {
  1097. if (checkPlaceholderForOverload(*this, From))
  1098. return ExprError();
  1099. // Objective-C ARC: Determine whether we will allow the writeback conversion.
  1100. bool AllowObjCWritebackConversion
  1101. = getLangOpts().ObjCAutoRefCount &&
  1102. (Action == AA_Passing || Action == AA_Sending);
  1103. ICS = clang::TryImplicitConversion(*this, From, ToType,
  1104. /*SuppressUserConversions=*/false,
  1105. AllowExplicit,
  1106. /*InOverloadResolution=*/false,
  1107. /*CStyle=*/false,
  1108. AllowObjCWritebackConversion);
  1109. return PerformImplicitConversion(From, ToType, ICS, Action);
  1110. }
  1111. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1112. /// conversion that strips "noreturn" off the nested function type.
  1113. bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
  1114. QualType &ResultTy) {
  1115. if (Context.hasSameUnqualifiedType(FromType, ToType))
  1116. return false;
  1117. // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
  1118. // where F adds one of the following at most once:
  1119. // - a pointer
  1120. // - a member pointer
  1121. // - a block pointer
  1122. CanQualType CanTo = Context.getCanonicalType(ToType);
  1123. CanQualType CanFrom = Context.getCanonicalType(FromType);
  1124. Type::TypeClass TyClass = CanTo->getTypeClass();
  1125. if (TyClass != CanFrom->getTypeClass()) return false;
  1126. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
  1127. if (TyClass == Type::Pointer) {
  1128. CanTo = CanTo.getAs<PointerType>()->getPointeeType();
  1129. CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
  1130. } else if (TyClass == Type::BlockPointer) {
  1131. CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
  1132. CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
  1133. } else if (TyClass == Type::MemberPointer) {
  1134. CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
  1135. CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
  1136. } else {
  1137. return false;
  1138. }
  1139. TyClass = CanTo->getTypeClass();
  1140. if (TyClass != CanFrom->getTypeClass()) return false;
  1141. if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
  1142. return false;
  1143. }
  1144. const FunctionType *FromFn = cast<FunctionType>(CanFrom);
  1145. FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
  1146. if (!EInfo.getNoReturn()) return false;
  1147. FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
  1148. assert(QualType(FromFn, 0).isCanonical());
  1149. if (QualType(FromFn, 0) != CanTo) return false;
  1150. ResultTy = ToType;
  1151. return true;
  1152. }
  1153. /// \brief Determine whether the conversion from FromType to ToType is a valid
  1154. /// vector conversion.
  1155. ///
  1156. /// \param ICK Will be set to the vector conversion kind, if this is a vector
  1157. /// conversion.
  1158. static bool IsVectorConversion(ASTContext &Context, QualType FromType,
  1159. QualType ToType, ImplicitConversionKind &ICK) {
  1160. // We need at least one of these types to be a vector type to have a vector
  1161. // conversion.
  1162. if (!ToType->isVectorType() && !FromType->isVectorType())
  1163. return false;
  1164. // Identical types require no conversions.
  1165. if (Context.hasSameUnqualifiedType(FromType, ToType))
  1166. return false;
  1167. // There are no conversions between extended vector types, only identity.
  1168. if (ToType->isExtVectorType()) {
  1169. // There are no conversions between extended vector types other than the
  1170. // identity conversion.
  1171. if (FromType->isExtVectorType())
  1172. return false;
  1173. // Vector splat from any arithmetic type to a vector.
  1174. if (FromType->isArithmeticType()) {
  1175. ICK = ICK_Vector_Splat;
  1176. return true;
  1177. }
  1178. }
  1179. // We can perform the conversion between vector types in the following cases:
  1180. // 1)vector types are equivalent AltiVec and GCC vector types
  1181. // 2)lax vector conversions are permitted and the vector types are of the
  1182. // same size
  1183. if (ToType->isVectorType() && FromType->isVectorType()) {
  1184. if (Context.areCompatibleVectorTypes(FromType, ToType) ||
  1185. (Context.getLangOpts().LaxVectorConversions &&
  1186. (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
  1187. ICK = ICK_Vector_Conversion;
  1188. return true;
  1189. }
  1190. }
  1191. return false;
  1192. }
  1193. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  1194. bool InOverloadResolution,
  1195. StandardConversionSequence &SCS,
  1196. bool CStyle);
  1197. /// IsStandardConversion - Determines whether there is a standard
  1198. /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
  1199. /// expression From to the type ToType. Standard conversion sequences
  1200. /// only consider non-class types; for conversions that involve class
  1201. /// types, use TryImplicitConversion. If a conversion exists, SCS will
  1202. /// contain the standard conversion sequence required to perform this
  1203. /// conversion and this routine will return true. Otherwise, this
  1204. /// routine will return false and the value of SCS is unspecified.
  1205. static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
  1206. bool InOverloadResolution,
  1207. StandardConversionSequence &SCS,
  1208. bool CStyle,
  1209. bool AllowObjCWritebackConversion) {
  1210. QualType FromType = From->getType();
  1211. // Standard conversions (C++ [conv])
  1212. SCS.setAsIdentityConversion();
  1213. SCS.DeprecatedStringLiteralToCharPtr = false;
  1214. SCS.IncompatibleObjC = false;
  1215. SCS.setFromType(FromType);
  1216. SCS.CopyConstructor = 0;
  1217. // There are no standard conversions for class types in C++, so
  1218. // abort early. When overloading in C, however, we do permit
  1219. if (FromType->isRecordType() || ToType->isRecordType()) {
  1220. if (S.getLangOpts().CPlusPlus)
  1221. return false;
  1222. // When we're overloading in C, we allow, as standard conversions,
  1223. }
  1224. // The first conversion can be an lvalue-to-rvalue conversion,
  1225. // array-to-pointer conversion, or function-to-pointer conversion
  1226. // (C++ 4p1).
  1227. if (FromType == S.Context.OverloadTy) {
  1228. DeclAccessPair AccessPair;
  1229. if (FunctionDecl *Fn
  1230. = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
  1231. AccessPair)) {
  1232. // We were able to resolve the address of the overloaded function,
  1233. // so we can convert to the type of that function.
  1234. FromType = Fn->getType();
  1235. // we can sometimes resolve &foo<int> regardless of ToType, so check
  1236. // if the type matches (identity) or we are converting to bool
  1237. if (!S.Context.hasSameUnqualifiedType(
  1238. S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
  1239. QualType resultTy;
  1240. // if the function type matches except for [[noreturn]], it's ok
  1241. if (!S.IsNoReturnConversion(FromType,
  1242. S.ExtractUnqualifiedFunctionType(ToType), resultTy))
  1243. // otherwise, only a boolean conversion is standard
  1244. if (!ToType->isBooleanType())
  1245. return false;
  1246. }
  1247. // Check if the "from" expression is taking the address of an overloaded
  1248. // function and recompute the FromType accordingly. Take advantage of the
  1249. // fact that non-static member functions *must* have such an address-of
  1250. // expression.
  1251. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
  1252. if (Method && !Method->isStatic()) {
  1253. assert(isa<UnaryOperator>(From->IgnoreParens()) &&
  1254. "Non-unary operator on non-static member address");
  1255. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
  1256. == UO_AddrOf &&
  1257. "Non-address-of operator on non-static member address");
  1258. const Type *ClassType
  1259. = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
  1260. FromType = S.Context.getMemberPointerType(FromType, ClassType);
  1261. } else if (isa<UnaryOperator>(From->IgnoreParens())) {
  1262. assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
  1263. UO_AddrOf &&
  1264. "Non-address-of operator for overloaded function expression");
  1265. FromType = S.Context.getPointerType(FromType);
  1266. }
  1267. // Check that we've computed the proper type after overload resolution.
  1268. assert(S.Context.hasSameType(
  1269. FromType,
  1270. S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
  1271. } else {
  1272. return false;
  1273. }
  1274. }
  1275. // Lvalue-to-rvalue conversion (C++11 4.1):
  1276. // A glvalue (3.10) of a non-function, non-array type T can
  1277. // be converted to a prvalue.
  1278. bool argIsLValue = From->isGLValue();
  1279. if (argIsLValue &&
  1280. !FromType->isFunctionType() && !FromType->isArrayType() &&
  1281. S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
  1282. SCS.First = ICK_Lvalue_To_Rvalue;
  1283. // C11 6.3.2.1p2:
  1284. // ... if the lvalue has atomic type, the value has the non-atomic version
  1285. // of the type of the lvalue ...
  1286. if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
  1287. FromType = Atomic->getValueType();
  1288. // If T is a non-class type, the type of the rvalue is the
  1289. // cv-unqualified version of T. Otherwise, the type of the rvalue
  1290. // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
  1291. // just strip the qualifiers because they don't matter.
  1292. FromType = FromType.getUnqualifiedType();
  1293. } else if (FromType->isArrayType()) {
  1294. // Array-to-pointer conversion (C++ 4.2)
  1295. SCS.First = ICK_Array_To_Pointer;
  1296. // An lvalue or rvalue of type "array of N T" or "array of unknown
  1297. // bound of T" can be converted to an rvalue of type "pointer to
  1298. // T" (C++ 4.2p1).
  1299. FromType = S.Context.getArrayDecayedType(FromType);
  1300. if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
  1301. // This conversion is deprecated. (C++ D.4).
  1302. SCS.DeprecatedStringLiteralToCharPtr = true;
  1303. // For the purpose of ranking in overload resolution
  1304. // (13.3.3.1.1), this conversion is considered an
  1305. // array-to-pointer conversion followed by a qualification
  1306. // conversion (4.4). (C++ 4.2p2)
  1307. SCS.Second = ICK_Identity;
  1308. SCS.Third = ICK_Qualification;
  1309. SCS.QualificationIncludesObjCLifetime = false;
  1310. SCS.setAllToTypes(FromType);
  1311. return true;
  1312. }
  1313. } else if (FromType->isFunctionType() && argIsLValue) {
  1314. // Function-to-pointer conversion (C++ 4.3).
  1315. SCS.First = ICK_Function_To_Pointer;
  1316. // An lvalue of function type T can be converted to an rvalue of
  1317. // type "pointer to T." The result is a pointer to the
  1318. // function. (C++ 4.3p1).
  1319. FromType = S.Context.getPointerType(FromType);
  1320. } else {
  1321. // We don't require any conversions for the first step.
  1322. SCS.First = ICK_Identity;
  1323. }
  1324. SCS.setToType(0, FromType);
  1325. // The second conversion can be an integral promotion, floating
  1326. // point promotion, integral conversion, floating point conversion,
  1327. // floating-integral conversion, pointer conversion,
  1328. // pointer-to-member conversion, or boolean conversion (C++ 4p1).
  1329. // For overloading in C, this can also be a "compatible-type"
  1330. // conversion.
  1331. bool IncompatibleObjC = false;
  1332. ImplicitConversionKind SecondICK = ICK_Identity;
  1333. if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
  1334. // The unqualified versions of the types are the same: there's no
  1335. // conversion to do.
  1336. SCS.Second = ICK_Identity;
  1337. } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
  1338. // Integral promotion (C++ 4.5).
  1339. SCS.Second = ICK_Integral_Promotion;
  1340. FromType = ToType.getUnqualifiedType();
  1341. } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
  1342. // Floating point promotion (C++ 4.6).
  1343. SCS.Second = ICK_Floating_Promotion;
  1344. FromType = ToType.getUnqualifiedType();
  1345. } else if (S.IsComplexPromotion(FromType, ToType)) {
  1346. // Complex promotion (Clang extension)
  1347. SCS.Second = ICK_Complex_Promotion;
  1348. FromType = ToType.getUnqualifiedType();
  1349. } else if (ToType->isBooleanType() &&
  1350. (FromType->isArithmeticType() ||
  1351. FromType->isAnyPointerType() ||
  1352. FromType->isBlockPointerType() ||
  1353. FromType->isMemberPointerType() ||
  1354. FromType->isNullPtrType())) {
  1355. // Boolean conversions (C++ 4.12).
  1356. SCS.Second = ICK_Boolean_Conversion;
  1357. FromType = S.Context.BoolTy;
  1358. } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
  1359. ToType->isIntegralType(S.Context)) {
  1360. // Integral conversions (C++ 4.7).
  1361. SCS.Second = ICK_Integral_Conversion;
  1362. FromType = ToType.getUnqualifiedType();
  1363. } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
  1364. // Complex conversions (C99 6.3.1.6)
  1365. SCS.Second = ICK_Complex_Conversion;
  1366. FromType = ToType.getUnqualifiedType();
  1367. } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
  1368. (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
  1369. // Complex-real conversions (C99 6.3.1.7)
  1370. SCS.Second = ICK_Complex_Real;
  1371. FromType = ToType.getUnqualifiedType();
  1372. } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
  1373. // Floating point conversions (C++ 4.8).
  1374. SCS.Second = ICK_Floating_Conversion;
  1375. FromType = ToType.getUnqualifiedType();
  1376. } else if ((FromType->isRealFloatingType() &&
  1377. ToType->isIntegralType(S.Context)) ||
  1378. (FromType->isIntegralOrUnscopedEnumerationType() &&
  1379. ToType->isRealFloatingType())) {
  1380. // Floating-integral conversions (C++ 4.9).
  1381. SCS.Second = ICK_Floating_Integral;
  1382. FromType = ToType.getUnqualifiedType();
  1383. } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
  1384. SCS.Second = ICK_Block_Pointer_Conversion;
  1385. } else if (AllowObjCWritebackConversion &&
  1386. S.isObjCWritebackConversion(FromType, ToType, FromType)) {
  1387. SCS.Second = ICK_Writeback_Conversion;
  1388. } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
  1389. FromType, IncompatibleObjC)) {
  1390. // Pointer conversions (C++ 4.10).
  1391. SCS.Second = ICK_Pointer_Conversion;
  1392. SCS.IncompatibleObjC = IncompatibleObjC;
  1393. FromType = FromType.getUnqualifiedType();
  1394. } else if (S.IsMemberPointerConversion(From, FromType, ToType,
  1395. InOverloadResolution, FromType)) {
  1396. // Pointer to member conversions (4.11).
  1397. SCS.Second = ICK_Pointer_Member;
  1398. } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
  1399. SCS.Second = SecondICK;
  1400. FromType = ToType.getUnqualifiedType();
  1401. } else if (!S.getLangOpts().CPlusPlus &&
  1402. S.Context.typesAreCompatible(ToType, FromType)) {
  1403. // Compatible conversions (Clang extension for C function overloading)
  1404. SCS.Second = ICK_Compatible_Conversion;
  1405. FromType = ToType.getUnqualifiedType();
  1406. } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
  1407. // Treat a conversion that strips "noreturn" as an identity conversion.
  1408. SCS.Second = ICK_NoReturn_Adjustment;
  1409. } else if (IsTransparentUnionStandardConversion(S, From, ToType,
  1410. InOverloadResolution,
  1411. SCS, CStyle)) {
  1412. SCS.Second = ICK_TransparentUnionConversion;
  1413. FromType = ToType;
  1414. } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
  1415. CStyle)) {
  1416. // tryAtomicConversion has updated the standard conversion sequence
  1417. // appropriately.
  1418. return true;
  1419. } else {
  1420. // No second conversion required.
  1421. SCS.Second = ICK_Identity;
  1422. }
  1423. SCS.setToType(1, FromType);
  1424. QualType CanonFrom;
  1425. QualType CanonTo;
  1426. // The third conversion can be a qualification conversion (C++ 4p1).
  1427. bool ObjCLifetimeConversion;
  1428. if (S.IsQualificationConversion(FromType, ToType, CStyle,
  1429. ObjCLifetimeConversion)) {
  1430. SCS.Third = ICK_Qualification;
  1431. SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
  1432. FromType = ToType;
  1433. CanonFrom = S.Context.getCanonicalType(FromType);
  1434. CanonTo = S.Context.getCanonicalType(ToType);
  1435. } else {
  1436. // No conversion required
  1437. SCS.Third = ICK_Identity;
  1438. // C++ [over.best.ics]p6:
  1439. // [...] Any difference in top-level cv-qualification is
  1440. // subsumed by the initialization itself and does not constitute
  1441. // a conversion. [...]
  1442. CanonFrom = S.Context.getCanonicalType(FromType);
  1443. CanonTo = S.Context.getCanonicalType(ToType);
  1444. if (CanonFrom.getLocalUnqualifiedType()
  1445. == CanonTo.getLocalUnqualifiedType() &&
  1446. (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
  1447. || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
  1448. || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
  1449. FromType = ToType;
  1450. CanonFrom = CanonTo;
  1451. }
  1452. }
  1453. SCS.setToType(2, FromType);
  1454. // If we have not converted the argument type to the parameter type,
  1455. // this is a bad conversion sequence.
  1456. if (CanonFrom != CanonTo)
  1457. return false;
  1458. return true;
  1459. }
  1460. static bool
  1461. IsTransparentUnionStandardConversion(Sema &S, Expr* From,
  1462. QualType &ToType,
  1463. bool InOverloadResolution,
  1464. StandardConversionSequence &SCS,
  1465. bool CStyle) {
  1466. const RecordType *UT = ToType->getAsUnionType();
  1467. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1468. return false;
  1469. // The field to initialize within the transparent union.
  1470. RecordDecl *UD = UT->getDecl();
  1471. // It's compatible if the expression matches any of the fields.
  1472. for (RecordDecl::field_iterator it = UD->field_begin(),
  1473. itend = UD->field_end();
  1474. it != itend; ++it) {
  1475. if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
  1476. CStyle, /*ObjCWritebackConversion=*/false)) {
  1477. ToType = it->getType();
  1478. return true;
  1479. }
  1480. }
  1481. return false;
  1482. }
  1483. /// IsIntegralPromotion - Determines whether the conversion from the
  1484. /// expression From (whose potentially-adjusted type is FromType) to
  1485. /// ToType is an integral promotion (C++ 4.5). If so, returns true and
  1486. /// sets PromotedType to the promoted type.
  1487. bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
  1488. const BuiltinType *To = ToType->getAs<BuiltinType>();
  1489. // All integers are built-in.
  1490. if (!To) {
  1491. return false;
  1492. }
  1493. // An rvalue of type char, signed char, unsigned char, short int, or
  1494. // unsigned short int can be converted to an rvalue of type int if
  1495. // int can represent all the values of the source type; otherwise,
  1496. // the source rvalue can be converted to an rvalue of type unsigned
  1497. // int (C++ 4.5p1).
  1498. if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
  1499. !FromType->isEnumeralType()) {
  1500. if (// We can promote any signed, promotable integer type to an int
  1501. (FromType->isSignedIntegerType() ||
  1502. // We can promote any unsigned integer type whose size is
  1503. // less than int to an int.
  1504. (!FromType->isSignedIntegerType() &&
  1505. Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
  1506. return To->getKind() == BuiltinType::Int;
  1507. }
  1508. return To->getKind() == BuiltinType::UInt;
  1509. }
  1510. // C++0x [conv.prom]p3:
  1511. // A prvalue of an unscoped enumeration type whose underlying type is not
  1512. // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
  1513. // following types that can represent all the values of the enumeration
  1514. // (i.e., the values in the range bmin to bmax as described in 7.2): int,
  1515. // unsigned int, long int, unsigned long int, long long int, or unsigned
  1516. // long long int. If none of the types in that list can represent all the
  1517. // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
  1518. // type can be converted to an rvalue a prvalue of the extended integer type
  1519. // with lowest integer conversion rank (4.13) greater than the rank of long
  1520. // long in which all the values of the enumeration can be represented. If
  1521. // there are two such extended types, the signed one is chosen.
  1522. if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
  1523. // C++0x 7.2p9: Note that this implicit enum to int conversion is not
  1524. // provided for a scoped enumeration.
  1525. if (FromEnumType->getDecl()->isScoped())
  1526. return false;
  1527. // We have already pre-calculated the promotion type, so this is trivial.
  1528. if (ToType->isIntegerType() &&
  1529. !RequireCompleteType(From->getLocStart(), FromType, 0))
  1530. return Context.hasSameUnqualifiedType(ToType,
  1531. FromEnumType->getDecl()->getPromotionType());
  1532. }
  1533. // C++0x [conv.prom]p2:
  1534. // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
  1535. // to an rvalue a prvalue of the first of the following types that can
  1536. // represent all the values of its underlying type: int, unsigned int,
  1537. // long int, unsigned long int, long long int, or unsigned long long int.
  1538. // If none of the types in that list can represent all the values of its
  1539. // underlying type, an rvalue a prvalue of type char16_t, char32_t,
  1540. // or wchar_t can be converted to an rvalue a prvalue of its underlying
  1541. // type.
  1542. if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
  1543. ToType->isIntegerType()) {
  1544. // Determine whether the type we're converting from is signed or
  1545. // unsigned.
  1546. bool FromIsSigned = FromType->isSignedIntegerType();
  1547. uint64_t FromSize = Context.getTypeSize(FromType);
  1548. // The types we'll try to promote to, in the appropriate
  1549. // order. Try each of these types.
  1550. QualType PromoteTypes[6] = {
  1551. Context.IntTy, Context.UnsignedIntTy,
  1552. Context.LongTy, Context.UnsignedLongTy ,
  1553. Context.LongLongTy, Context.UnsignedLongLongTy
  1554. };
  1555. for (int Idx = 0; Idx < 6; ++Idx) {
  1556. uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
  1557. if (FromSize < ToSize ||
  1558. (FromSize == ToSize &&
  1559. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
  1560. // We found the type that we can promote to. If this is the
  1561. // type we wanted, we have a promotion. Otherwise, no
  1562. // promotion.
  1563. return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
  1564. }
  1565. }
  1566. }
  1567. // An rvalue for an integral bit-field (9.6) can be converted to an
  1568. // rvalue of type int if int can represent all the values of the
  1569. // bit-field; otherwise, it can be converted to unsigned int if
  1570. // unsigned int can represent all the values of the bit-field. If
  1571. // the bit-field is larger yet, no integral promotion applies to
  1572. // it. If the bit-field has an enumerated type, it is treated as any
  1573. // other value of that type for promotion purposes (C++ 4.5p3).
  1574. // FIXME: We should delay checking of bit-fields until we actually perform the
  1575. // conversion.
  1576. using llvm::APSInt;
  1577. if (From)
  1578. if (FieldDecl *MemberDecl = From->getBitField()) {
  1579. APSInt BitWidth;
  1580. if (FromType->isIntegralType(Context) &&
  1581. MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
  1582. APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
  1583. ToSize = Context.getTypeSize(ToType);
  1584. // Are we promoting to an int from a bitfield that fits in an int?
  1585. if (BitWidth < ToSize ||
  1586. (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
  1587. return To->getKind() == BuiltinType::Int;
  1588. }
  1589. // Are we promoting to an unsigned int from an unsigned bitfield
  1590. // that fits into an unsigned int?
  1591. if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
  1592. return To->getKind() == BuiltinType::UInt;
  1593. }
  1594. return false;
  1595. }
  1596. }
  1597. // An rvalue of type bool can be converted to an rvalue of type int,
  1598. // with false becoming zero and true becoming one (C++ 4.5p4).
  1599. if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
  1600. return true;
  1601. }
  1602. return false;
  1603. }
  1604. /// IsFloatingPointPromotion - Determines whether the conversion from
  1605. /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
  1606. /// returns true and sets PromotedType to the promoted type.
  1607. bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
  1608. if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
  1609. if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
  1610. /// An rvalue of type float can be converted to an rvalue of type
  1611. /// double. (C++ 4.6p1).
  1612. if (FromBuiltin->getKind() == BuiltinType::Float &&
  1613. ToBuiltin->getKind() == BuiltinType::Double)
  1614. return true;
  1615. // C99 6.3.1.5p1:
  1616. // When a float is promoted to double or long double, or a
  1617. // double is promoted to long double [...].
  1618. if (!getLangOpts().CPlusPlus &&
  1619. (FromBuiltin->getKind() == BuiltinType::Float ||
  1620. FromBuiltin->getKind() == BuiltinType::Double) &&
  1621. (ToBuiltin->getKind() == BuiltinType::LongDouble))
  1622. return true;
  1623. // Half can be promoted to float.
  1624. if (FromBuiltin->getKind() == BuiltinType::Half &&
  1625. ToBuiltin->getKind() == BuiltinType::Float)
  1626. return true;
  1627. }
  1628. return false;
  1629. }
  1630. /// \brief Determine if a conversion is a complex promotion.
  1631. ///
  1632. /// A complex promotion is defined as a complex -> complex conversion
  1633. /// where the conversion between the underlying real types is a
  1634. /// floating-point or integral promotion.
  1635. bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
  1636. const ComplexType *FromComplex = FromType->getAs<ComplexType>();
  1637. if (!FromComplex)
  1638. return false;
  1639. const ComplexType *ToComplex = ToType->getAs<ComplexType>();
  1640. if (!ToComplex)
  1641. return false;
  1642. return IsFloatingPointPromotion(FromComplex->getElementType(),
  1643. ToComplex->getElementType()) ||
  1644. IsIntegralPromotion(0, FromComplex->getElementType(),
  1645. ToComplex->getElementType());
  1646. }
  1647. /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
  1648. /// the pointer type FromPtr to a pointer to type ToPointee, with the
  1649. /// same type qualifiers as FromPtr has on its pointee type. ToType,
  1650. /// if non-empty, will be a pointer to ToType that may or may not have
  1651. /// the right set of qualifiers on its pointee.
  1652. ///
  1653. static QualType
  1654. BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
  1655. QualType ToPointee, QualType ToType,
  1656. ASTContext &Context,
  1657. bool StripObjCLifetime = false) {
  1658. assert((FromPtr->getTypeClass() == Type::Pointer ||
  1659. FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
  1660. "Invalid similarly-qualified pointer type");
  1661. /// Conversions to 'id' subsume cv-qualifier conversions.
  1662. if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
  1663. return ToType.getUnqualifiedType();
  1664. QualType CanonFromPointee
  1665. = Context.getCanonicalType(FromPtr->getPointeeType());
  1666. QualType CanonToPointee = Context.getCanonicalType(ToPointee);
  1667. Qualifiers Quals = CanonFromPointee.getQualifiers();
  1668. if (StripObjCLifetime)
  1669. Quals.removeObjCLifetime();
  1670. // Exact qualifier match -> return the pointer type we're converting to.
  1671. if (CanonToPointee.getLocalQualifiers() == Quals) {
  1672. // ToType is exactly what we need. Return it.
  1673. if (!ToType.isNull())
  1674. return ToType.getUnqualifiedType();
  1675. // Build a pointer to ToPointee. It has the right qualifiers
  1676. // already.
  1677. if (isa<ObjCObjectPointerType>(ToType))
  1678. return Context.getObjCObjectPointerType(ToPointee);
  1679. return Context.getPointerType(ToPointee);
  1680. }
  1681. // Just build a canonical type that has the right qualifiers.
  1682. QualType QualifiedCanonToPointee
  1683. = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
  1684. if (isa<ObjCObjectPointerType>(ToType))
  1685. return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
  1686. return Context.getPointerType(QualifiedCanonToPointee);
  1687. }
  1688. static bool isNullPointerConstantForConversion(Expr *Expr,
  1689. bool InOverloadResolution,
  1690. ASTContext &Context) {
  1691. // Handle value-dependent integral null pointer constants correctly.
  1692. // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
  1693. if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
  1694. Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
  1695. return !InOverloadResolution;
  1696. return Expr->isNullPointerConstant(Context,
  1697. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  1698. : Expr::NPC_ValueDependentIsNull);
  1699. }
  1700. /// IsPointerConversion - Determines whether the conversion of the
  1701. /// expression From, which has the (possibly adjusted) type FromType,
  1702. /// can be converted to the type ToType via a pointer conversion (C++
  1703. /// 4.10). If so, returns true and places the converted type (that
  1704. /// might differ from ToType in its cv-qualifiers at some level) into
  1705. /// ConvertedType.
  1706. ///
  1707. /// This routine also supports conversions to and from block pointers
  1708. /// and conversions with Objective-C's 'id', 'id<protocols...>', and
  1709. /// pointers to interfaces. FIXME: Once we've determined the
  1710. /// appropriate overloading rules for Objective-C, we may want to
  1711. /// split the Objective-C checks into a different routine; however,
  1712. /// GCC seems to consider all of these conversions to be pointer
  1713. /// conversions, so for now they live here. IncompatibleObjC will be
  1714. /// set if the conversion is an allowed Objective-C conversion that
  1715. /// should result in a warning.
  1716. bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
  1717. bool InOverloadResolution,
  1718. QualType& ConvertedType,
  1719. bool &IncompatibleObjC) {
  1720. IncompatibleObjC = false;
  1721. if (isObjCPointerConversion(FromType, ToType, ConvertedType,
  1722. IncompatibleObjC))
  1723. return true;
  1724. // Conversion from a null pointer constant to any Objective-C pointer type.
  1725. if (ToType->isObjCObjectPointerType() &&
  1726. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1727. ConvertedType = ToType;
  1728. return true;
  1729. }
  1730. // Blocks: Block pointers can be converted to void*.
  1731. if (FromType->isBlockPointerType() && ToType->isPointerType() &&
  1732. ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
  1733. ConvertedType = ToType;
  1734. return true;
  1735. }
  1736. // Blocks: A null pointer constant can be converted to a block
  1737. // pointer type.
  1738. if (ToType->isBlockPointerType() &&
  1739. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1740. ConvertedType = ToType;
  1741. return true;
  1742. }
  1743. // If the left-hand-side is nullptr_t, the right side can be a null
  1744. // pointer constant.
  1745. if (ToType->isNullPtrType() &&
  1746. isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1747. ConvertedType = ToType;
  1748. return true;
  1749. }
  1750. const PointerType* ToTypePtr = ToType->getAs<PointerType>();
  1751. if (!ToTypePtr)
  1752. return false;
  1753. // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
  1754. if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
  1755. ConvertedType = ToType;
  1756. return true;
  1757. }
  1758. // Beyond this point, both types need to be pointers
  1759. // , including objective-c pointers.
  1760. QualType ToPointeeType = ToTypePtr->getPointeeType();
  1761. if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
  1762. !getLangOpts().ObjCAutoRefCount) {
  1763. ConvertedType = BuildSimilarlyQualifiedPointerType(
  1764. FromType->getAs<ObjCObjectPointerType>(),
  1765. ToPointeeType,
  1766. ToType, Context);
  1767. return true;
  1768. }
  1769. const PointerType *FromTypePtr = FromType->getAs<PointerType>();
  1770. if (!FromTypePtr)
  1771. return false;
  1772. QualType FromPointeeType = FromTypePtr->getPointeeType();
  1773. // If the unqualified pointee types are the same, this can't be a
  1774. // pointer conversion, so don't do all of the work below.
  1775. if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
  1776. return false;
  1777. // An rvalue of type "pointer to cv T," where T is an object type,
  1778. // can be converted to an rvalue of type "pointer to cv void" (C++
  1779. // 4.10p2).
  1780. if (FromPointeeType->isIncompleteOrObjectType() &&
  1781. ToPointeeType->isVoidType()) {
  1782. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1783. ToPointeeType,
  1784. ToType, Context,
  1785. /*StripObjCLifetime=*/true);
  1786. return true;
  1787. }
  1788. // MSVC allows implicit function to void* type conversion.
  1789. if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
  1790. ToPointeeType->isVoidType()) {
  1791. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1792. ToPointeeType,
  1793. ToType, Context);
  1794. return true;
  1795. }
  1796. // When we're overloading in C, we allow a special kind of pointer
  1797. // conversion for compatible-but-not-identical pointee types.
  1798. if (!getLangOpts().CPlusPlus &&
  1799. Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
  1800. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1801. ToPointeeType,
  1802. ToType, Context);
  1803. return true;
  1804. }
  1805. // C++ [conv.ptr]p3:
  1806. //
  1807. // An rvalue of type "pointer to cv D," where D is a class type,
  1808. // can be converted to an rvalue of type "pointer to cv B," where
  1809. // B is a base class (clause 10) of D. If B is an inaccessible
  1810. // (clause 11) or ambiguous (10.2) base class of D, a program that
  1811. // necessitates this conversion is ill-formed. The result of the
  1812. // conversion is a pointer to the base class sub-object of the
  1813. // derived class object. The null pointer value is converted to
  1814. // the null pointer value of the destination type.
  1815. //
  1816. // Note that we do not check for ambiguity or inaccessibility
  1817. // here. That is handled by CheckPointerConversion.
  1818. if (getLangOpts().CPlusPlus &&
  1819. FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  1820. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
  1821. !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
  1822. IsDerivedFrom(FromPointeeType, ToPointeeType)) {
  1823. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1824. ToPointeeType,
  1825. ToType, Context);
  1826. return true;
  1827. }
  1828. if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
  1829. Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
  1830. ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
  1831. ToPointeeType,
  1832. ToType, Context);
  1833. return true;
  1834. }
  1835. return false;
  1836. }
  1837. /// \brief Adopt the given qualifiers for the given type.
  1838. static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
  1839. Qualifiers TQs = T.getQualifiers();
  1840. // Check whether qualifiers already match.
  1841. if (TQs == Qs)
  1842. return T;
  1843. if (Qs.compatiblyIncludes(TQs))
  1844. return Context.getQualifiedType(T, Qs);
  1845. return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
  1846. }
  1847. /// isObjCPointerConversion - Determines whether this is an
  1848. /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
  1849. /// with the same arguments and return values.
  1850. bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
  1851. QualType& ConvertedType,
  1852. bool &IncompatibleObjC) {
  1853. if (!getLangOpts().ObjC1)
  1854. return false;
  1855. // The set of qualifiers on the type we're converting from.
  1856. Qualifiers FromQualifiers = FromType.getQualifiers();
  1857. // First, we handle all conversions on ObjC object pointer types.
  1858. const ObjCObjectPointerType* ToObjCPtr =
  1859. ToType->getAs<ObjCObjectPointerType>();
  1860. const ObjCObjectPointerType *FromObjCPtr =
  1861. FromType->getAs<ObjCObjectPointerType>();
  1862. if (ToObjCPtr && FromObjCPtr) {
  1863. // If the pointee types are the same (ignoring qualifications),
  1864. // then this is not a pointer conversion.
  1865. if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
  1866. FromObjCPtr->getPointeeType()))
  1867. return false;
  1868. // Check for compatible
  1869. // Objective C++: We're able to convert between "id" or "Class" and a
  1870. // pointer to any interface (in both directions).
  1871. if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
  1872. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  1873. return true;
  1874. }
  1875. // Conversions with Objective-C's id<...>.
  1876. if ((FromObjCPtr->isObjCQualifiedIdType() ||
  1877. ToObjCPtr->isObjCQualifiedIdType()) &&
  1878. Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
  1879. /*compare=*/false)) {
  1880. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  1881. return true;
  1882. }
  1883. // Objective C++: We're able to convert from a pointer to an
  1884. // interface to a pointer to a different interface.
  1885. if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
  1886. const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
  1887. const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
  1888. if (getLangOpts().CPlusPlus && LHS && RHS &&
  1889. !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
  1890. FromObjCPtr->getPointeeType()))
  1891. return false;
  1892. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  1893. ToObjCPtr->getPointeeType(),
  1894. ToType, Context);
  1895. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  1896. return true;
  1897. }
  1898. if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
  1899. // Okay: this is some kind of implicit downcast of Objective-C
  1900. // interfaces, which is permitted. However, we're going to
  1901. // complain about it.
  1902. IncompatibleObjC = true;
  1903. ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
  1904. ToObjCPtr->getPointeeType(),
  1905. ToType, Context);
  1906. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  1907. return true;
  1908. }
  1909. }
  1910. // Beyond this point, both types need to be C pointers or block pointers.
  1911. QualType ToPointeeType;
  1912. if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
  1913. ToPointeeType = ToCPtr->getPointeeType();
  1914. else if (const BlockPointerType *ToBlockPtr =
  1915. ToType->getAs<BlockPointerType>()) {
  1916. // Objective C++: We're able to convert from a pointer to any object
  1917. // to a block pointer type.
  1918. if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
  1919. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  1920. return true;
  1921. }
  1922. ToPointeeType = ToBlockPtr->getPointeeType();
  1923. }
  1924. else if (FromType->getAs<BlockPointerType>() &&
  1925. ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
  1926. // Objective C++: We're able to convert from a block pointer type to a
  1927. // pointer to any object.
  1928. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  1929. return true;
  1930. }
  1931. else
  1932. return false;
  1933. QualType FromPointeeType;
  1934. if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
  1935. FromPointeeType = FromCPtr->getPointeeType();
  1936. else if (const BlockPointerType *FromBlockPtr =
  1937. FromType->getAs<BlockPointerType>())
  1938. FromPointeeType = FromBlockPtr->getPointeeType();
  1939. else
  1940. return false;
  1941. // If we have pointers to pointers, recursively check whether this
  1942. // is an Objective-C conversion.
  1943. if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
  1944. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  1945. IncompatibleObjC)) {
  1946. // We always complain about this conversion.
  1947. IncompatibleObjC = true;
  1948. ConvertedType = Context.getPointerType(ConvertedType);
  1949. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  1950. return true;
  1951. }
  1952. // Allow conversion of pointee being objective-c pointer to another one;
  1953. // as in I* to id.
  1954. if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
  1955. ToPointeeType->getAs<ObjCObjectPointerType>() &&
  1956. isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
  1957. IncompatibleObjC)) {
  1958. ConvertedType = Context.getPointerType(ConvertedType);
  1959. ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
  1960. return true;
  1961. }
  1962. // If we have pointers to functions or blocks, check whether the only
  1963. // differences in the argument and result types are in Objective-C
  1964. // pointer conversions. If so, we permit the conversion (but
  1965. // complain about it).
  1966. const FunctionProtoType *FromFunctionType
  1967. = FromPointeeType->getAs<FunctionProtoType>();
  1968. const FunctionProtoType *ToFunctionType
  1969. = ToPointeeType->getAs<FunctionProtoType>();
  1970. if (FromFunctionType && ToFunctionType) {
  1971. // If the function types are exactly the same, this isn't an
  1972. // Objective-C pointer conversion.
  1973. if (Context.getCanonicalType(FromPointeeType)
  1974. == Context.getCanonicalType(ToPointeeType))
  1975. return false;
  1976. // Perform the quick checks that will tell us whether these
  1977. // function types are obviously different.
  1978. if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
  1979. FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
  1980. FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
  1981. return false;
  1982. bool HasObjCConversion = false;
  1983. if (Context.getCanonicalType(FromFunctionType->getResultType())
  1984. == Context.getCanonicalType(ToFunctionType->getResultType())) {
  1985. // Okay, the types match exactly. Nothing to do.
  1986. } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
  1987. ToFunctionType->getResultType(),
  1988. ConvertedType, IncompatibleObjC)) {
  1989. // Okay, we have an Objective-C pointer conversion.
  1990. HasObjCConversion = true;
  1991. } else {
  1992. // Function types are too different. Abort.
  1993. return false;
  1994. }
  1995. // Check argument types.
  1996. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
  1997. ArgIdx != NumArgs; ++ArgIdx) {
  1998. QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
  1999. QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
  2000. if (Context.getCanonicalType(FromArgType)
  2001. == Context.getCanonicalType(ToArgType)) {
  2002. // Okay, the types match exactly. Nothing to do.
  2003. } else if (isObjCPointerConversion(FromArgType, ToArgType,
  2004. ConvertedType, IncompatibleObjC)) {
  2005. // Okay, we have an Objective-C pointer conversion.
  2006. HasObjCConversion = true;
  2007. } else {
  2008. // Argument types are too different. Abort.
  2009. return false;
  2010. }
  2011. }
  2012. if (HasObjCConversion) {
  2013. // We had an Objective-C conversion. Allow this pointer
  2014. // conversion, but complain about it.
  2015. ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
  2016. IncompatibleObjC = true;
  2017. return true;
  2018. }
  2019. }
  2020. return false;
  2021. }
  2022. /// \brief Determine whether this is an Objective-C writeback conversion,
  2023. /// used for parameter passing when performing automatic reference counting.
  2024. ///
  2025. /// \param FromType The type we're converting form.
  2026. ///
  2027. /// \param ToType The type we're converting to.
  2028. ///
  2029. /// \param ConvertedType The type that will be produced after applying
  2030. /// this conversion.
  2031. bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
  2032. QualType &ConvertedType) {
  2033. if (!getLangOpts().ObjCAutoRefCount ||
  2034. Context.hasSameUnqualifiedType(FromType, ToType))
  2035. return false;
  2036. // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
  2037. QualType ToPointee;
  2038. if (const PointerType *ToPointer = ToType->getAs<PointerType>())
  2039. ToPointee = ToPointer->getPointeeType();
  2040. else
  2041. return false;
  2042. Qualifiers ToQuals = ToPointee.getQualifiers();
  2043. if (!ToPointee->isObjCLifetimeType() ||
  2044. ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
  2045. !ToQuals.withoutObjCLifetime().empty())
  2046. return false;
  2047. // Argument must be a pointer to __strong to __weak.
  2048. QualType FromPointee;
  2049. if (const PointerType *FromPointer = FromType->getAs<PointerType>())
  2050. FromPointee = FromPointer->getPointeeType();
  2051. else
  2052. return false;
  2053. Qualifiers FromQuals = FromPointee.getQualifiers();
  2054. if (!FromPointee->isObjCLifetimeType() ||
  2055. (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
  2056. FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
  2057. return false;
  2058. // Make sure that we have compatible qualifiers.
  2059. FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2060. if (!ToQuals.compatiblyIncludes(FromQuals))
  2061. return false;
  2062. // Remove qualifiers from the pointee type we're converting from; they
  2063. // aren't used in the compatibility check belong, and we'll be adding back
  2064. // qualifiers (with __autoreleasing) if the compatibility check succeeds.
  2065. FromPointee = FromPointee.getUnqualifiedType();
  2066. // The unqualified form of the pointee types must be compatible.
  2067. ToPointee = ToPointee.getUnqualifiedType();
  2068. bool IncompatibleObjC;
  2069. if (Context.typesAreCompatible(FromPointee, ToPointee))
  2070. FromPointee = ToPointee;
  2071. else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
  2072. IncompatibleObjC))
  2073. return false;
  2074. /// \brief Construct the type we're converting to, which is a pointer to
  2075. /// __autoreleasing pointee.
  2076. FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
  2077. ConvertedType = Context.getPointerType(FromPointee);
  2078. return true;
  2079. }
  2080. bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
  2081. QualType& ConvertedType) {
  2082. QualType ToPointeeType;
  2083. if (const BlockPointerType *ToBlockPtr =
  2084. ToType->getAs<BlockPointerType>())
  2085. ToPointeeType = ToBlockPtr->getPointeeType();
  2086. else
  2087. return false;
  2088. QualType FromPointeeType;
  2089. if (const BlockPointerType *FromBlockPtr =
  2090. FromType->getAs<BlockPointerType>())
  2091. FromPointeeType = FromBlockPtr->getPointeeType();
  2092. else
  2093. return false;
  2094. // We have pointer to blocks, check whether the only
  2095. // differences in the argument and result types are in Objective-C
  2096. // pointer conversions. If so, we permit the conversion.
  2097. const FunctionProtoType *FromFunctionType
  2098. = FromPointeeType->getAs<FunctionProtoType>();
  2099. const FunctionProtoType *ToFunctionType
  2100. = ToPointeeType->getAs<FunctionProtoType>();
  2101. if (!FromFunctionType || !ToFunctionType)
  2102. return false;
  2103. if (Context.hasSameType(FromPointeeType, ToPointeeType))
  2104. return true;
  2105. // Perform the quick checks that will tell us whether these
  2106. // function types are obviously different.
  2107. if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
  2108. FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
  2109. return false;
  2110. FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
  2111. FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
  2112. if (FromEInfo != ToEInfo)
  2113. return false;
  2114. bool IncompatibleObjC = false;
  2115. if (Context.hasSameType(FromFunctionType->getResultType(),
  2116. ToFunctionType->getResultType())) {
  2117. // Okay, the types match exactly. Nothing to do.
  2118. } else {
  2119. QualType RHS = FromFunctionType->getResultType();
  2120. QualType LHS = ToFunctionType->getResultType();
  2121. if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
  2122. !RHS.hasQualifiers() && LHS.hasQualifiers())
  2123. LHS = LHS.getUnqualifiedType();
  2124. if (Context.hasSameType(RHS,LHS)) {
  2125. // OK exact match.
  2126. } else if (isObjCPointerConversion(RHS, LHS,
  2127. ConvertedType, IncompatibleObjC)) {
  2128. if (IncompatibleObjC)
  2129. return false;
  2130. // Okay, we have an Objective-C pointer conversion.
  2131. }
  2132. else
  2133. return false;
  2134. }
  2135. // Check argument types.
  2136. for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
  2137. ArgIdx != NumArgs; ++ArgIdx) {
  2138. IncompatibleObjC = false;
  2139. QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
  2140. QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
  2141. if (Context.hasSameType(FromArgType, ToArgType)) {
  2142. // Okay, the types match exactly. Nothing to do.
  2143. } else if (isObjCPointerConversion(ToArgType, FromArgType,
  2144. ConvertedType, IncompatibleObjC)) {
  2145. if (IncompatibleObjC)
  2146. return false;
  2147. // Okay, we have an Objective-C pointer conversion.
  2148. } else
  2149. // Argument types are too different. Abort.
  2150. return false;
  2151. }
  2152. if (LangOpts.ObjCAutoRefCount &&
  2153. !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
  2154. ToFunctionType))
  2155. return false;
  2156. ConvertedType = ToType;
  2157. return true;
  2158. }
  2159. enum {
  2160. ft_default,
  2161. ft_different_class,
  2162. ft_parameter_arity,
  2163. ft_parameter_mismatch,
  2164. ft_return_type,
  2165. ft_qualifer_mismatch
  2166. };
  2167. /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
  2168. /// function types. Catches different number of parameter, mismatch in
  2169. /// parameter types, and different return types.
  2170. void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
  2171. QualType FromType, QualType ToType) {
  2172. // If either type is not valid, include no extra info.
  2173. if (FromType.isNull() || ToType.isNull()) {
  2174. PDiag << ft_default;
  2175. return;
  2176. }
  2177. // Get the function type from the pointers.
  2178. if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
  2179. const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
  2180. *ToMember = ToType->getAs<MemberPointerType>();
  2181. if (FromMember->getClass() != ToMember->getClass()) {
  2182. PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
  2183. << QualType(FromMember->getClass(), 0);
  2184. return;
  2185. }
  2186. FromType = FromMember->getPointeeType();
  2187. ToType = ToMember->getPointeeType();
  2188. }
  2189. if (FromType->isPointerType())
  2190. FromType = FromType->getPointeeType();
  2191. if (ToType->isPointerType())
  2192. ToType = ToType->getPointeeType();
  2193. // Remove references.
  2194. FromType = FromType.getNonReferenceType();
  2195. ToType = ToType.getNonReferenceType();
  2196. // Don't print extra info for non-specialized template functions.
  2197. if (FromType->isInstantiationDependentType() &&
  2198. !FromType->getAs<TemplateSpecializationType>()) {
  2199. PDiag << ft_default;
  2200. return;
  2201. }
  2202. // No extra info for same types.
  2203. if (Context.hasSameType(FromType, ToType)) {
  2204. PDiag << ft_default;
  2205. return;
  2206. }
  2207. const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
  2208. *ToFunction = ToType->getAs<FunctionProtoType>();
  2209. // Both types need to be function types.
  2210. if (!FromFunction || !ToFunction) {
  2211. PDiag << ft_default;
  2212. return;
  2213. }
  2214. if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
  2215. PDiag << ft_parameter_arity << ToFunction->getNumArgs()
  2216. << FromFunction->getNumArgs();
  2217. return;
  2218. }
  2219. // Handle different parameter types.
  2220. unsigned ArgPos;
  2221. if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
  2222. PDiag << ft_parameter_mismatch << ArgPos + 1
  2223. << ToFunction->getArgType(ArgPos)
  2224. << FromFunction->getArgType(ArgPos);
  2225. return;
  2226. }
  2227. // Handle different return type.
  2228. if (!Context.hasSameType(FromFunction->getResultType(),
  2229. ToFunction->getResultType())) {
  2230. PDiag << ft_return_type << ToFunction->getResultType()
  2231. << FromFunction->getResultType();
  2232. return;
  2233. }
  2234. unsigned FromQuals = FromFunction->getTypeQuals(),
  2235. ToQuals = ToFunction->getTypeQuals();
  2236. if (FromQuals != ToQuals) {
  2237. PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
  2238. return;
  2239. }
  2240. // Unable to find a difference, so add no extra info.
  2241. PDiag << ft_default;
  2242. }
  2243. /// FunctionArgTypesAreEqual - This routine checks two function proto types
  2244. /// for equality of their argument types. Caller has already checked that
  2245. /// they have same number of arguments. This routine assumes that Objective-C
  2246. /// pointer types which only differ in their protocol qualifiers are equal.
  2247. /// If the parameters are different, ArgPos will have the parameter index
  2248. /// of the first different parameter.
  2249. bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
  2250. const FunctionProtoType *NewType,
  2251. unsigned *ArgPos) {
  2252. if (!getLangOpts().ObjC1) {
  2253. for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
  2254. N = NewType->arg_type_begin(),
  2255. E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
  2256. if (!Context.hasSameType(*O, *N)) {
  2257. if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
  2258. return false;
  2259. }
  2260. }
  2261. return true;
  2262. }
  2263. for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
  2264. N = NewType->arg_type_begin(),
  2265. E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
  2266. QualType ToType = (*O);
  2267. QualType FromType = (*N);
  2268. if (!Context.hasSameType(ToType, FromType)) {
  2269. if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
  2270. if (const PointerType *PTFr = FromType->getAs<PointerType>())
  2271. if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
  2272. PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
  2273. (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
  2274. PTFr->getPointeeType()->isObjCQualifiedClassType()))
  2275. continue;
  2276. }
  2277. else if (const ObjCObjectPointerType *PTTo =
  2278. ToType->getAs<ObjCObjectPointerType>()) {
  2279. if (const ObjCObjectPointerType *PTFr =
  2280. FromType->getAs<ObjCObjectPointerType>())
  2281. if (Context.hasSameUnqualifiedType(
  2282. PTTo->getObjectType()->getBaseType(),
  2283. PTFr->getObjectType()->getBaseType()))
  2284. continue;
  2285. }
  2286. if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
  2287. return false;
  2288. }
  2289. }
  2290. return true;
  2291. }
  2292. /// CheckPointerConversion - Check the pointer conversion from the
  2293. /// expression From to the type ToType. This routine checks for
  2294. /// ambiguous or inaccessible derived-to-base pointer
  2295. /// conversions for which IsPointerConversion has already returned
  2296. /// true. It returns true and produces a diagnostic if there was an
  2297. /// error, or returns false otherwise.
  2298. bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
  2299. CastKind &Kind,
  2300. CXXCastPath& BasePath,
  2301. bool IgnoreBaseAccess) {
  2302. QualType FromType = From->getType();
  2303. bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
  2304. Kind = CK_BitCast;
  2305. if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
  2306. From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
  2307. Expr::NPCK_ZeroExpression) {
  2308. if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
  2309. DiagRuntimeBehavior(From->getExprLoc(), From,
  2310. PDiag(diag::warn_impcast_bool_to_null_pointer)
  2311. << ToType << From->getSourceRange());
  2312. else if (!isUnevaluatedContext())
  2313. Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
  2314. << ToType << From->getSourceRange();
  2315. }
  2316. if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
  2317. if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
  2318. QualType FromPointeeType = FromPtrType->getPointeeType(),
  2319. ToPointeeType = ToPtrType->getPointeeType();
  2320. if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
  2321. !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
  2322. // We must have a derived-to-base conversion. Check an
  2323. // ambiguous or inaccessible conversion.
  2324. if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
  2325. From->getExprLoc(),
  2326. From->getSourceRange(), &BasePath,
  2327. IgnoreBaseAccess))
  2328. return true;
  2329. // The conversion was successful.
  2330. Kind = CK_DerivedToBase;
  2331. }
  2332. }
  2333. } else if (const ObjCObjectPointerType *ToPtrType =
  2334. ToType->getAs<ObjCObjectPointerType>()) {
  2335. if (const ObjCObjectPointerType *FromPtrType =
  2336. FromType->getAs<ObjCObjectPointerType>()) {
  2337. // Objective-C++ conversions are always okay.
  2338. // FIXME: We should have a different class of conversions for the
  2339. // Objective-C++ implicit conversions.
  2340. if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
  2341. return false;
  2342. } else if (FromType->isBlockPointerType()) {
  2343. Kind = CK_BlockPointerToObjCPointerCast;
  2344. } else {
  2345. Kind = CK_CPointerToObjCPointerCast;
  2346. }
  2347. } else if (ToType->isBlockPointerType()) {
  2348. if (!FromType->isBlockPointerType())
  2349. Kind = CK_AnyPointerToBlockPointerCast;
  2350. }
  2351. // We shouldn't fall into this case unless it's valid for other
  2352. // reasons.
  2353. if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  2354. Kind = CK_NullToPointer;
  2355. return false;
  2356. }
  2357. /// IsMemberPointerConversion - Determines whether the conversion of the
  2358. /// expression From, which has the (possibly adjusted) type FromType, can be
  2359. /// converted to the type ToType via a member pointer conversion (C++ 4.11).
  2360. /// If so, returns true and places the converted type (that might differ from
  2361. /// ToType in its cv-qualifiers at some level) into ConvertedType.
  2362. bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
  2363. QualType ToType,
  2364. bool InOverloadResolution,
  2365. QualType &ConvertedType) {
  2366. const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
  2367. if (!ToTypePtr)
  2368. return false;
  2369. // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
  2370. if (From->isNullPointerConstant(Context,
  2371. InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
  2372. : Expr::NPC_ValueDependentIsNull)) {
  2373. ConvertedType = ToType;
  2374. return true;
  2375. }
  2376. // Otherwise, both types have to be member pointers.
  2377. const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
  2378. if (!FromTypePtr)
  2379. return false;
  2380. // A pointer to member of B can be converted to a pointer to member of D,
  2381. // where D is derived from B (C++ 4.11p2).
  2382. QualType FromClass(FromTypePtr->getClass(), 0);
  2383. QualType ToClass(ToTypePtr->getClass(), 0);
  2384. if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
  2385. !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
  2386. IsDerivedFrom(ToClass, FromClass)) {
  2387. ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
  2388. ToClass.getTypePtr());
  2389. return true;
  2390. }
  2391. return false;
  2392. }
  2393. /// CheckMemberPointerConversion - Check the member pointer conversion from the
  2394. /// expression From to the type ToType. This routine checks for ambiguous or
  2395. /// virtual or inaccessible base-to-derived member pointer conversions
  2396. /// for which IsMemberPointerConversion has already returned true. It returns
  2397. /// true and produces a diagnostic if there was an error, or returns false
  2398. /// otherwise.
  2399. bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
  2400. CastKind &Kind,
  2401. CXXCastPath &BasePath,
  2402. bool IgnoreBaseAccess) {
  2403. QualType FromType = From->getType();
  2404. const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
  2405. if (!FromPtrType) {
  2406. // This must be a null pointer to member pointer conversion
  2407. assert(From->isNullPointerConstant(Context,
  2408. Expr::NPC_ValueDependentIsNull) &&
  2409. "Expr must be null pointer constant!");
  2410. Kind = CK_NullToMemberPointer;
  2411. return false;
  2412. }
  2413. const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
  2414. assert(ToPtrType && "No member pointer cast has a target type "
  2415. "that is not a member pointer.");
  2416. QualType FromClass = QualType(FromPtrType->getClass(), 0);
  2417. QualType ToClass = QualType(ToPtrType->getClass(), 0);
  2418. // FIXME: What about dependent types?
  2419. assert(FromClass->isRecordType() && "Pointer into non-class.");
  2420. assert(ToClass->isRecordType() && "Pointer into non-class.");
  2421. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2422. /*DetectVirtual=*/true);
  2423. bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
  2424. assert(DerivationOkay &&
  2425. "Should not have been called if derivation isn't OK.");
  2426. (void)DerivationOkay;
  2427. if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
  2428. getUnqualifiedType())) {
  2429. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2430. Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
  2431. << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
  2432. return true;
  2433. }
  2434. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  2435. Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
  2436. << FromClass << ToClass << QualType(VBase, 0)
  2437. << From->getSourceRange();
  2438. return true;
  2439. }
  2440. if (!IgnoreBaseAccess)
  2441. CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
  2442. Paths.front(),
  2443. diag::err_downcast_from_inaccessible_base);
  2444. // Must be a base to derived member conversion.
  2445. BuildBasePathArray(Paths, BasePath);
  2446. Kind = CK_BaseToDerivedMemberPointer;
  2447. return false;
  2448. }
  2449. /// IsQualificationConversion - Determines whether the conversion from
  2450. /// an rvalue of type FromType to ToType is a qualification conversion
  2451. /// (C++ 4.4).
  2452. ///
  2453. /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
  2454. /// when the qualification conversion involves a change in the Objective-C
  2455. /// object lifetime.
  2456. bool
  2457. Sema::IsQualificationConversion(QualType FromType, QualType ToType,
  2458. bool CStyle, bool &ObjCLifetimeConversion) {
  2459. FromType = Context.getCanonicalType(FromType);
  2460. ToType = Context.getCanonicalType(ToType);
  2461. ObjCLifetimeConversion = false;
  2462. // If FromType and ToType are the same type, this is not a
  2463. // qualification conversion.
  2464. if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
  2465. return false;
  2466. // (C++ 4.4p4):
  2467. // A conversion can add cv-qualifiers at levels other than the first
  2468. // in multi-level pointers, subject to the following rules: [...]
  2469. bool PreviousToQualsIncludeConst = true;
  2470. bool UnwrappedAnyPointer = false;
  2471. while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
  2472. // Within each iteration of the loop, we check the qualifiers to
  2473. // determine if this still looks like a qualification
  2474. // conversion. Then, if all is well, we unwrap one more level of
  2475. // pointers or pointers-to-members and do it all again
  2476. // until there are no more pointers or pointers-to-members left to
  2477. // unwrap.
  2478. UnwrappedAnyPointer = true;
  2479. Qualifiers FromQuals = FromType.getQualifiers();
  2480. Qualifiers ToQuals = ToType.getQualifiers();
  2481. // Objective-C ARC:
  2482. // Check Objective-C lifetime conversions.
  2483. if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
  2484. UnwrappedAnyPointer) {
  2485. if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
  2486. ObjCLifetimeConversion = true;
  2487. FromQuals.removeObjCLifetime();
  2488. ToQuals.removeObjCLifetime();
  2489. } else {
  2490. // Qualification conversions cannot cast between different
  2491. // Objective-C lifetime qualifiers.
  2492. return false;
  2493. }
  2494. }
  2495. // Allow addition/removal of GC attributes but not changing GC attributes.
  2496. if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
  2497. (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
  2498. FromQuals.removeObjCGCAttr();
  2499. ToQuals.removeObjCGCAttr();
  2500. }
  2501. // -- for every j > 0, if const is in cv 1,j then const is in cv
  2502. // 2,j, and similarly for volatile.
  2503. if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
  2504. return false;
  2505. // -- if the cv 1,j and cv 2,j are different, then const is in
  2506. // every cv for 0 < k < j.
  2507. if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
  2508. && !PreviousToQualsIncludeConst)
  2509. return false;
  2510. // Keep track of whether all prior cv-qualifiers in the "to" type
  2511. // include const.
  2512. PreviousToQualsIncludeConst
  2513. = PreviousToQualsIncludeConst && ToQuals.hasConst();
  2514. }
  2515. // We are left with FromType and ToType being the pointee types
  2516. // after unwrapping the original FromType and ToType the same number
  2517. // of types. If we unwrapped any pointers, and if FromType and
  2518. // ToType have the same unqualified type (since we checked
  2519. // qualifiers above), then this is a qualification conversion.
  2520. return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
  2521. }
  2522. /// \brief - Determine whether this is a conversion from a scalar type to an
  2523. /// atomic type.
  2524. ///
  2525. /// If successful, updates \c SCS's second and third steps in the conversion
  2526. /// sequence to finish the conversion.
  2527. static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
  2528. bool InOverloadResolution,
  2529. StandardConversionSequence &SCS,
  2530. bool CStyle) {
  2531. const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
  2532. if (!ToAtomic)
  2533. return false;
  2534. StandardConversionSequence InnerSCS;
  2535. if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
  2536. InOverloadResolution, InnerSCS,
  2537. CStyle, /*AllowObjCWritebackConversion=*/false))
  2538. return false;
  2539. SCS.Second = InnerSCS.Second;
  2540. SCS.setToType(1, InnerSCS.getToType(1));
  2541. SCS.Third = InnerSCS.Third;
  2542. SCS.QualificationIncludesObjCLifetime
  2543. = InnerSCS.QualificationIncludesObjCLifetime;
  2544. SCS.setToType(2, InnerSCS.getToType(2));
  2545. return true;
  2546. }
  2547. static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
  2548. CXXConstructorDecl *Constructor,
  2549. QualType Type) {
  2550. const FunctionProtoType *CtorType =
  2551. Constructor->getType()->getAs<FunctionProtoType>();
  2552. if (CtorType->getNumArgs() > 0) {
  2553. QualType FirstArg = CtorType->getArgType(0);
  2554. if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
  2555. return true;
  2556. }
  2557. return false;
  2558. }
  2559. static OverloadingResult
  2560. IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
  2561. CXXRecordDecl *To,
  2562. UserDefinedConversionSequence &User,
  2563. OverloadCandidateSet &CandidateSet,
  2564. bool AllowExplicit) {
  2565. DeclContext::lookup_iterator Con, ConEnd;
  2566. for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
  2567. Con != ConEnd; ++Con) {
  2568. NamedDecl *D = *Con;
  2569. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2570. // Find the constructor (which may be a template).
  2571. CXXConstructorDecl *Constructor = 0;
  2572. FunctionTemplateDecl *ConstructorTmpl
  2573. = dyn_cast<FunctionTemplateDecl>(D);
  2574. if (ConstructorTmpl)
  2575. Constructor
  2576. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2577. else
  2578. Constructor = cast<CXXConstructorDecl>(D);
  2579. bool Usable = !Constructor->isInvalidDecl() &&
  2580. S.isInitListConstructor(Constructor) &&
  2581. (AllowExplicit || !Constructor->isExplicit());
  2582. if (Usable) {
  2583. // If the first argument is (a reference to) the target type,
  2584. // suppress conversions.
  2585. bool SuppressUserConversions =
  2586. isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
  2587. if (ConstructorTmpl)
  2588. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2589. /*ExplicitArgs*/ 0,
  2590. From, CandidateSet,
  2591. SuppressUserConversions);
  2592. else
  2593. S.AddOverloadCandidate(Constructor, FoundDecl,
  2594. From, CandidateSet,
  2595. SuppressUserConversions);
  2596. }
  2597. }
  2598. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2599. OverloadCandidateSet::iterator Best;
  2600. switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
  2601. case OR_Success: {
  2602. // Record the standard conversion we used and the conversion function.
  2603. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
  2604. S.MarkFunctionReferenced(From->getLocStart(), Constructor);
  2605. QualType ThisType = Constructor->getThisType(S.Context);
  2606. // Initializer lists don't have conversions as such.
  2607. User.Before.setAsIdentityConversion();
  2608. User.HadMultipleCandidates = HadMultipleCandidates;
  2609. User.ConversionFunction = Constructor;
  2610. User.FoundConversionFunction = Best->FoundDecl;
  2611. User.After.setAsIdentityConversion();
  2612. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2613. User.After.setAllToTypes(ToType);
  2614. return OR_Success;
  2615. }
  2616. case OR_No_Viable_Function:
  2617. return OR_No_Viable_Function;
  2618. case OR_Deleted:
  2619. return OR_Deleted;
  2620. case OR_Ambiguous:
  2621. return OR_Ambiguous;
  2622. }
  2623. llvm_unreachable("Invalid OverloadResult!");
  2624. }
  2625. /// Determines whether there is a user-defined conversion sequence
  2626. /// (C++ [over.ics.user]) that converts expression From to the type
  2627. /// ToType. If such a conversion exists, User will contain the
  2628. /// user-defined conversion sequence that performs such a conversion
  2629. /// and this routine will return true. Otherwise, this routine returns
  2630. /// false and User is unspecified.
  2631. ///
  2632. /// \param AllowExplicit true if the conversion should consider C++0x
  2633. /// "explicit" conversion functions as well as non-explicit conversion
  2634. /// functions (C++0x [class.conv.fct]p2).
  2635. static OverloadingResult
  2636. IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
  2637. UserDefinedConversionSequence &User,
  2638. OverloadCandidateSet &CandidateSet,
  2639. bool AllowExplicit) {
  2640. // Whether we will only visit constructors.
  2641. bool ConstructorsOnly = false;
  2642. // If the type we are conversion to is a class type, enumerate its
  2643. // constructors.
  2644. if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
  2645. // C++ [over.match.ctor]p1:
  2646. // When objects of class type are direct-initialized (8.5), or
  2647. // copy-initialized from an expression of the same or a
  2648. // derived class type (8.5), overload resolution selects the
  2649. // constructor. [...] For copy-initialization, the candidate
  2650. // functions are all the converting constructors (12.3.1) of
  2651. // that class. The argument list is the expression-list within
  2652. // the parentheses of the initializer.
  2653. if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
  2654. (From->getType()->getAs<RecordType>() &&
  2655. S.IsDerivedFrom(From->getType(), ToType)))
  2656. ConstructorsOnly = true;
  2657. S.RequireCompleteType(From->getLocStart(), ToType, 0);
  2658. // RequireCompleteType may have returned true due to some invalid decl
  2659. // during template instantiation, but ToType may be complete enough now
  2660. // to try to recover.
  2661. if (ToType->isIncompleteType()) {
  2662. // We're not going to find any constructors.
  2663. } else if (CXXRecordDecl *ToRecordDecl
  2664. = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
  2665. Expr **Args = &From;
  2666. unsigned NumArgs = 1;
  2667. bool ListInitializing = false;
  2668. if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
  2669. // But first, see if there is an init-list-contructor that will work.
  2670. OverloadingResult Result = IsInitializerListConstructorConversion(
  2671. S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
  2672. if (Result != OR_No_Viable_Function)
  2673. return Result;
  2674. // Never mind.
  2675. CandidateSet.clear();
  2676. // If we're list-initializing, we pass the individual elements as
  2677. // arguments, not the entire list.
  2678. Args = InitList->getInits();
  2679. NumArgs = InitList->getNumInits();
  2680. ListInitializing = true;
  2681. }
  2682. DeclContext::lookup_iterator Con, ConEnd;
  2683. for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
  2684. Con != ConEnd; ++Con) {
  2685. NamedDecl *D = *Con;
  2686. DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
  2687. // Find the constructor (which may be a template).
  2688. CXXConstructorDecl *Constructor = 0;
  2689. FunctionTemplateDecl *ConstructorTmpl
  2690. = dyn_cast<FunctionTemplateDecl>(D);
  2691. if (ConstructorTmpl)
  2692. Constructor
  2693. = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
  2694. else
  2695. Constructor = cast<CXXConstructorDecl>(D);
  2696. bool Usable = !Constructor->isInvalidDecl();
  2697. if (ListInitializing)
  2698. Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
  2699. else
  2700. Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
  2701. if (Usable) {
  2702. bool SuppressUserConversions = !ConstructorsOnly;
  2703. if (SuppressUserConversions && ListInitializing) {
  2704. SuppressUserConversions = false;
  2705. if (NumArgs == 1) {
  2706. // If the first argument is (a reference to) the target type,
  2707. // suppress conversions.
  2708. SuppressUserConversions = isFirstArgumentCompatibleWithType(
  2709. S.Context, Constructor, ToType);
  2710. }
  2711. }
  2712. if (ConstructorTmpl)
  2713. S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
  2714. /*ExplicitArgs*/ 0,
  2715. llvm::makeArrayRef(Args, NumArgs),
  2716. CandidateSet, SuppressUserConversions);
  2717. else
  2718. // Allow one user-defined conversion when user specifies a
  2719. // From->ToType conversion via an static cast (c-style, etc).
  2720. S.AddOverloadCandidate(Constructor, FoundDecl,
  2721. llvm::makeArrayRef(Args, NumArgs),
  2722. CandidateSet, SuppressUserConversions);
  2723. }
  2724. }
  2725. }
  2726. }
  2727. // Enumerate conversion functions, if we're allowed to.
  2728. if (ConstructorsOnly || isa<InitListExpr>(From)) {
  2729. } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
  2730. // No conversion functions from incomplete types.
  2731. } else if (const RecordType *FromRecordType
  2732. = From->getType()->getAs<RecordType>()) {
  2733. if (CXXRecordDecl *FromRecordDecl
  2734. = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
  2735. // Add all of the conversion functions as candidates.
  2736. const UnresolvedSetImpl *Conversions
  2737. = FromRecordDecl->getVisibleConversionFunctions();
  2738. for (UnresolvedSetImpl::iterator I = Conversions->begin(),
  2739. E = Conversions->end(); I != E; ++I) {
  2740. DeclAccessPair FoundDecl = I.getPair();
  2741. NamedDecl *D = FoundDecl.getDecl();
  2742. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  2743. if (isa<UsingShadowDecl>(D))
  2744. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2745. CXXConversionDecl *Conv;
  2746. FunctionTemplateDecl *ConvTemplate;
  2747. if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
  2748. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  2749. else
  2750. Conv = cast<CXXConversionDecl>(D);
  2751. if (AllowExplicit || !Conv->isExplicit()) {
  2752. if (ConvTemplate)
  2753. S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
  2754. ActingContext, From, ToType,
  2755. CandidateSet);
  2756. else
  2757. S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
  2758. From, ToType, CandidateSet);
  2759. }
  2760. }
  2761. }
  2762. }
  2763. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  2764. OverloadCandidateSet::iterator Best;
  2765. switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
  2766. case OR_Success:
  2767. // Record the standard conversion we used and the conversion function.
  2768. if (CXXConstructorDecl *Constructor
  2769. = dyn_cast<CXXConstructorDecl>(Best->Function)) {
  2770. S.MarkFunctionReferenced(From->getLocStart(), Constructor);
  2771. // C++ [over.ics.user]p1:
  2772. // If the user-defined conversion is specified by a
  2773. // constructor (12.3.1), the initial standard conversion
  2774. // sequence converts the source type to the type required by
  2775. // the argument of the constructor.
  2776. //
  2777. QualType ThisType = Constructor->getThisType(S.Context);
  2778. if (isa<InitListExpr>(From)) {
  2779. // Initializer lists don't have conversions as such.
  2780. User.Before.setAsIdentityConversion();
  2781. } else {
  2782. if (Best->Conversions[0].isEllipsis())
  2783. User.EllipsisConversion = true;
  2784. else {
  2785. User.Before = Best->Conversions[0].Standard;
  2786. User.EllipsisConversion = false;
  2787. }
  2788. }
  2789. User.HadMultipleCandidates = HadMultipleCandidates;
  2790. User.ConversionFunction = Constructor;
  2791. User.FoundConversionFunction = Best->FoundDecl;
  2792. User.After.setAsIdentityConversion();
  2793. User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
  2794. User.After.setAllToTypes(ToType);
  2795. return OR_Success;
  2796. }
  2797. if (CXXConversionDecl *Conversion
  2798. = dyn_cast<CXXConversionDecl>(Best->Function)) {
  2799. S.MarkFunctionReferenced(From->getLocStart(), Conversion);
  2800. // C++ [over.ics.user]p1:
  2801. //
  2802. // [...] If the user-defined conversion is specified by a
  2803. // conversion function (12.3.2), the initial standard
  2804. // conversion sequence converts the source type to the
  2805. // implicit object parameter of the conversion function.
  2806. User.Before = Best->Conversions[0].Standard;
  2807. User.HadMultipleCandidates = HadMultipleCandidates;
  2808. User.ConversionFunction = Conversion;
  2809. User.FoundConversionFunction = Best->FoundDecl;
  2810. User.EllipsisConversion = false;
  2811. // C++ [over.ics.user]p2:
  2812. // The second standard conversion sequence converts the
  2813. // result of the user-defined conversion to the target type
  2814. // for the sequence. Since an implicit conversion sequence
  2815. // is an initialization, the special rules for
  2816. // initialization by user-defined conversion apply when
  2817. // selecting the best user-defined conversion for a
  2818. // user-defined conversion sequence (see 13.3.3 and
  2819. // 13.3.3.1).
  2820. User.After = Best->FinalConversion;
  2821. return OR_Success;
  2822. }
  2823. llvm_unreachable("Not a constructor or conversion function?");
  2824. case OR_No_Viable_Function:
  2825. return OR_No_Viable_Function;
  2826. case OR_Deleted:
  2827. // No conversion here! We're done.
  2828. return OR_Deleted;
  2829. case OR_Ambiguous:
  2830. return OR_Ambiguous;
  2831. }
  2832. llvm_unreachable("Invalid OverloadResult!");
  2833. }
  2834. bool
  2835. Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
  2836. ImplicitConversionSequence ICS;
  2837. OverloadCandidateSet CandidateSet(From->getExprLoc());
  2838. OverloadingResult OvResult =
  2839. IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
  2840. CandidateSet, false);
  2841. if (OvResult == OR_Ambiguous)
  2842. Diag(From->getLocStart(),
  2843. diag::err_typecheck_ambiguous_condition)
  2844. << From->getType() << ToType << From->getSourceRange();
  2845. else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
  2846. Diag(From->getLocStart(),
  2847. diag::err_typecheck_nonviable_condition)
  2848. << From->getType() << ToType << From->getSourceRange();
  2849. else
  2850. return false;
  2851. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
  2852. return true;
  2853. }
  2854. /// \brief Compare the user-defined conversion functions or constructors
  2855. /// of two user-defined conversion sequences to determine whether any ordering
  2856. /// is possible.
  2857. static ImplicitConversionSequence::CompareKind
  2858. compareConversionFunctions(Sema &S,
  2859. FunctionDecl *Function1,
  2860. FunctionDecl *Function2) {
  2861. if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
  2862. return ImplicitConversionSequence::Indistinguishable;
  2863. // Objective-C++:
  2864. // If both conversion functions are implicitly-declared conversions from
  2865. // a lambda closure type to a function pointer and a block pointer,
  2866. // respectively, always prefer the conversion to a function pointer,
  2867. // because the function pointer is more lightweight and is more likely
  2868. // to keep code working.
  2869. CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
  2870. if (!Conv1)
  2871. return ImplicitConversionSequence::Indistinguishable;
  2872. CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
  2873. if (!Conv2)
  2874. return ImplicitConversionSequence::Indistinguishable;
  2875. if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
  2876. bool Block1 = Conv1->getConversionType()->isBlockPointerType();
  2877. bool Block2 = Conv2->getConversionType()->isBlockPointerType();
  2878. if (Block1 != Block2)
  2879. return Block1? ImplicitConversionSequence::Worse
  2880. : ImplicitConversionSequence::Better;
  2881. }
  2882. return ImplicitConversionSequence::Indistinguishable;
  2883. }
  2884. /// CompareImplicitConversionSequences - Compare two implicit
  2885. /// conversion sequences to determine whether one is better than the
  2886. /// other or if they are indistinguishable (C++ 13.3.3.2).
  2887. static ImplicitConversionSequence::CompareKind
  2888. CompareImplicitConversionSequences(Sema &S,
  2889. const ImplicitConversionSequence& ICS1,
  2890. const ImplicitConversionSequence& ICS2)
  2891. {
  2892. // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
  2893. // conversion sequences (as defined in 13.3.3.1)
  2894. // -- a standard conversion sequence (13.3.3.1.1) is a better
  2895. // conversion sequence than a user-defined conversion sequence or
  2896. // an ellipsis conversion sequence, and
  2897. // -- a user-defined conversion sequence (13.3.3.1.2) is a better
  2898. // conversion sequence than an ellipsis conversion sequence
  2899. // (13.3.3.1.3).
  2900. //
  2901. // C++0x [over.best.ics]p10:
  2902. // For the purpose of ranking implicit conversion sequences as
  2903. // described in 13.3.3.2, the ambiguous conversion sequence is
  2904. // treated as a user-defined sequence that is indistinguishable
  2905. // from any other user-defined conversion sequence.
  2906. if (ICS1.getKindRank() < ICS2.getKindRank())
  2907. return ImplicitConversionSequence::Better;
  2908. if (ICS2.getKindRank() < ICS1.getKindRank())
  2909. return ImplicitConversionSequence::Worse;
  2910. // The following checks require both conversion sequences to be of
  2911. // the same kind.
  2912. if (ICS1.getKind() != ICS2.getKind())
  2913. return ImplicitConversionSequence::Indistinguishable;
  2914. ImplicitConversionSequence::CompareKind Result =
  2915. ImplicitConversionSequence::Indistinguishable;
  2916. // Two implicit conversion sequences of the same form are
  2917. // indistinguishable conversion sequences unless one of the
  2918. // following rules apply: (C++ 13.3.3.2p3):
  2919. if (ICS1.isStandard())
  2920. Result = CompareStandardConversionSequences(S,
  2921. ICS1.Standard, ICS2.Standard);
  2922. else if (ICS1.isUserDefined()) {
  2923. // User-defined conversion sequence U1 is a better conversion
  2924. // sequence than another user-defined conversion sequence U2 if
  2925. // they contain the same user-defined conversion function or
  2926. // constructor and if the second standard conversion sequence of
  2927. // U1 is better than the second standard conversion sequence of
  2928. // U2 (C++ 13.3.3.2p3).
  2929. if (ICS1.UserDefined.ConversionFunction ==
  2930. ICS2.UserDefined.ConversionFunction)
  2931. Result = CompareStandardConversionSequences(S,
  2932. ICS1.UserDefined.After,
  2933. ICS2.UserDefined.After);
  2934. else
  2935. Result = compareConversionFunctions(S,
  2936. ICS1.UserDefined.ConversionFunction,
  2937. ICS2.UserDefined.ConversionFunction);
  2938. }
  2939. // List-initialization sequence L1 is a better conversion sequence than
  2940. // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
  2941. // for some X and L2 does not.
  2942. if (Result == ImplicitConversionSequence::Indistinguishable &&
  2943. !ICS1.isBad() &&
  2944. ICS1.isListInitializationSequence() &&
  2945. ICS2.isListInitializationSequence()) {
  2946. if (ICS1.isStdInitializerListElement() &&
  2947. !ICS2.isStdInitializerListElement())
  2948. return ImplicitConversionSequence::Better;
  2949. if (!ICS1.isStdInitializerListElement() &&
  2950. ICS2.isStdInitializerListElement())
  2951. return ImplicitConversionSequence::Worse;
  2952. }
  2953. return Result;
  2954. }
  2955. static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
  2956. while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
  2957. Qualifiers Quals;
  2958. T1 = Context.getUnqualifiedArrayType(T1, Quals);
  2959. T2 = Context.getUnqualifiedArrayType(T2, Quals);
  2960. }
  2961. return Context.hasSameUnqualifiedType(T1, T2);
  2962. }
  2963. // Per 13.3.3.2p3, compare the given standard conversion sequences to
  2964. // determine if one is a proper subset of the other.
  2965. static ImplicitConversionSequence::CompareKind
  2966. compareStandardConversionSubsets(ASTContext &Context,
  2967. const StandardConversionSequence& SCS1,
  2968. const StandardConversionSequence& SCS2) {
  2969. ImplicitConversionSequence::CompareKind Result
  2970. = ImplicitConversionSequence::Indistinguishable;
  2971. // the identity conversion sequence is considered to be a subsequence of
  2972. // any non-identity conversion sequence
  2973. if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
  2974. return ImplicitConversionSequence::Better;
  2975. else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
  2976. return ImplicitConversionSequence::Worse;
  2977. if (SCS1.Second != SCS2.Second) {
  2978. if (SCS1.Second == ICK_Identity)
  2979. Result = ImplicitConversionSequence::Better;
  2980. else if (SCS2.Second == ICK_Identity)
  2981. Result = ImplicitConversionSequence::Worse;
  2982. else
  2983. return ImplicitConversionSequence::Indistinguishable;
  2984. } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
  2985. return ImplicitConversionSequence::Indistinguishable;
  2986. if (SCS1.Third == SCS2.Third) {
  2987. return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
  2988. : ImplicitConversionSequence::Indistinguishable;
  2989. }
  2990. if (SCS1.Third == ICK_Identity)
  2991. return Result == ImplicitConversionSequence::Worse
  2992. ? ImplicitConversionSequence::Indistinguishable
  2993. : ImplicitConversionSequence::Better;
  2994. if (SCS2.Third == ICK_Identity)
  2995. return Result == ImplicitConversionSequence::Better
  2996. ? ImplicitConversionSequence::Indistinguishable
  2997. : ImplicitConversionSequence::Worse;
  2998. return ImplicitConversionSequence::Indistinguishable;
  2999. }
  3000. /// \brief Determine whether one of the given reference bindings is better
  3001. /// than the other based on what kind of bindings they are.
  3002. static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
  3003. const StandardConversionSequence &SCS2) {
  3004. // C++0x [over.ics.rank]p3b4:
  3005. // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
  3006. // implicit object parameter of a non-static member function declared
  3007. // without a ref-qualifier, and *either* S1 binds an rvalue reference
  3008. // to an rvalue and S2 binds an lvalue reference *or S1 binds an
  3009. // lvalue reference to a function lvalue and S2 binds an rvalue
  3010. // reference*.
  3011. //
  3012. // FIXME: Rvalue references. We're going rogue with the above edits,
  3013. // because the semantics in the current C++0x working paper (N3225 at the
  3014. // time of this writing) break the standard definition of std::forward
  3015. // and std::reference_wrapper when dealing with references to functions.
  3016. // Proposed wording changes submitted to CWG for consideration.
  3017. if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
  3018. SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
  3019. return false;
  3020. return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
  3021. SCS2.IsLvalueReference) ||
  3022. (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
  3023. !SCS2.IsLvalueReference);
  3024. }
  3025. /// CompareStandardConversionSequences - Compare two standard
  3026. /// conversion sequences to determine whether one is better than the
  3027. /// other or if they are indistinguishable (C++ 13.3.3.2p3).
  3028. static ImplicitConversionSequence::CompareKind
  3029. CompareStandardConversionSequences(Sema &S,
  3030. const StandardConversionSequence& SCS1,
  3031. const StandardConversionSequence& SCS2)
  3032. {
  3033. // Standard conversion sequence S1 is a better conversion sequence
  3034. // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
  3035. // -- S1 is a proper subsequence of S2 (comparing the conversion
  3036. // sequences in the canonical form defined by 13.3.3.1.1,
  3037. // excluding any Lvalue Transformation; the identity conversion
  3038. // sequence is considered to be a subsequence of any
  3039. // non-identity conversion sequence) or, if not that,
  3040. if (ImplicitConversionSequence::CompareKind CK
  3041. = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
  3042. return CK;
  3043. // -- the rank of S1 is better than the rank of S2 (by the rules
  3044. // defined below), or, if not that,
  3045. ImplicitConversionRank Rank1 = SCS1.getRank();
  3046. ImplicitConversionRank Rank2 = SCS2.getRank();
  3047. if (Rank1 < Rank2)
  3048. return ImplicitConversionSequence::Better;
  3049. else if (Rank2 < Rank1)
  3050. return ImplicitConversionSequence::Worse;
  3051. // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
  3052. // are indistinguishable unless one of the following rules
  3053. // applies:
  3054. // A conversion that is not a conversion of a pointer, or
  3055. // pointer to member, to bool is better than another conversion
  3056. // that is such a conversion.
  3057. if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
  3058. return SCS2.isPointerConversionToBool()
  3059. ? ImplicitConversionSequence::Better
  3060. : ImplicitConversionSequence::Worse;
  3061. // C++ [over.ics.rank]p4b2:
  3062. //
  3063. // If class B is derived directly or indirectly from class A,
  3064. // conversion of B* to A* is better than conversion of B* to
  3065. // void*, and conversion of A* to void* is better than conversion
  3066. // of B* to void*.
  3067. bool SCS1ConvertsToVoid
  3068. = SCS1.isPointerConversionToVoidPointer(S.Context);
  3069. bool SCS2ConvertsToVoid
  3070. = SCS2.isPointerConversionToVoidPointer(S.Context);
  3071. if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
  3072. // Exactly one of the conversion sequences is a conversion to
  3073. // a void pointer; it's the worse conversion.
  3074. return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
  3075. : ImplicitConversionSequence::Worse;
  3076. } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
  3077. // Neither conversion sequence converts to a void pointer; compare
  3078. // their derived-to-base conversions.
  3079. if (ImplicitConversionSequence::CompareKind DerivedCK
  3080. = CompareDerivedToBaseConversions(S, SCS1, SCS2))
  3081. return DerivedCK;
  3082. } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
  3083. !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
  3084. // Both conversion sequences are conversions to void
  3085. // pointers. Compare the source types to determine if there's an
  3086. // inheritance relationship in their sources.
  3087. QualType FromType1 = SCS1.getFromType();
  3088. QualType FromType2 = SCS2.getFromType();
  3089. // Adjust the types we're converting from via the array-to-pointer
  3090. // conversion, if we need to.
  3091. if (SCS1.First == ICK_Array_To_Pointer)
  3092. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3093. if (SCS2.First == ICK_Array_To_Pointer)
  3094. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3095. QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
  3096. QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
  3097. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3098. return ImplicitConversionSequence::Better;
  3099. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3100. return ImplicitConversionSequence::Worse;
  3101. // Objective-C++: If one interface is more specific than the
  3102. // other, it is the better one.
  3103. const ObjCObjectPointerType* FromObjCPtr1
  3104. = FromType1->getAs<ObjCObjectPointerType>();
  3105. const ObjCObjectPointerType* FromObjCPtr2
  3106. = FromType2->getAs<ObjCObjectPointerType>();
  3107. if (FromObjCPtr1 && FromObjCPtr2) {
  3108. bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
  3109. FromObjCPtr2);
  3110. bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
  3111. FromObjCPtr1);
  3112. if (AssignLeft != AssignRight) {
  3113. return AssignLeft? ImplicitConversionSequence::Better
  3114. : ImplicitConversionSequence::Worse;
  3115. }
  3116. }
  3117. }
  3118. // Compare based on qualification conversions (C++ 13.3.3.2p3,
  3119. // bullet 3).
  3120. if (ImplicitConversionSequence::CompareKind QualCK
  3121. = CompareQualificationConversions(S, SCS1, SCS2))
  3122. return QualCK;
  3123. if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
  3124. // Check for a better reference binding based on the kind of bindings.
  3125. if (isBetterReferenceBindingKind(SCS1, SCS2))
  3126. return ImplicitConversionSequence::Better;
  3127. else if (isBetterReferenceBindingKind(SCS2, SCS1))
  3128. return ImplicitConversionSequence::Worse;
  3129. // C++ [over.ics.rank]p3b4:
  3130. // -- S1 and S2 are reference bindings (8.5.3), and the types to
  3131. // which the references refer are the same type except for
  3132. // top-level cv-qualifiers, and the type to which the reference
  3133. // initialized by S2 refers is more cv-qualified than the type
  3134. // to which the reference initialized by S1 refers.
  3135. QualType T1 = SCS1.getToType(2);
  3136. QualType T2 = SCS2.getToType(2);
  3137. T1 = S.Context.getCanonicalType(T1);
  3138. T2 = S.Context.getCanonicalType(T2);
  3139. Qualifiers T1Quals, T2Quals;
  3140. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3141. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3142. if (UnqualT1 == UnqualT2) {
  3143. // Objective-C++ ARC: If the references refer to objects with different
  3144. // lifetimes, prefer bindings that don't change lifetime.
  3145. if (SCS1.ObjCLifetimeConversionBinding !=
  3146. SCS2.ObjCLifetimeConversionBinding) {
  3147. return SCS1.ObjCLifetimeConversionBinding
  3148. ? ImplicitConversionSequence::Worse
  3149. : ImplicitConversionSequence::Better;
  3150. }
  3151. // If the type is an array type, promote the element qualifiers to the
  3152. // type for comparison.
  3153. if (isa<ArrayType>(T1) && T1Quals)
  3154. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3155. if (isa<ArrayType>(T2) && T2Quals)
  3156. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3157. if (T2.isMoreQualifiedThan(T1))
  3158. return ImplicitConversionSequence::Better;
  3159. else if (T1.isMoreQualifiedThan(T2))
  3160. return ImplicitConversionSequence::Worse;
  3161. }
  3162. }
  3163. // In Microsoft mode, prefer an integral conversion to a
  3164. // floating-to-integral conversion if the integral conversion
  3165. // is between types of the same size.
  3166. // For example:
  3167. // void f(float);
  3168. // void f(int);
  3169. // int main {
  3170. // long a;
  3171. // f(a);
  3172. // }
  3173. // Here, MSVC will call f(int) instead of generating a compile error
  3174. // as clang will do in standard mode.
  3175. if (S.getLangOpts().MicrosoftMode &&
  3176. SCS1.Second == ICK_Integral_Conversion &&
  3177. SCS2.Second == ICK_Floating_Integral &&
  3178. S.Context.getTypeSize(SCS1.getFromType()) ==
  3179. S.Context.getTypeSize(SCS1.getToType(2)))
  3180. return ImplicitConversionSequence::Better;
  3181. return ImplicitConversionSequence::Indistinguishable;
  3182. }
  3183. /// CompareQualificationConversions - Compares two standard conversion
  3184. /// sequences to determine whether they can be ranked based on their
  3185. /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
  3186. ImplicitConversionSequence::CompareKind
  3187. CompareQualificationConversions(Sema &S,
  3188. const StandardConversionSequence& SCS1,
  3189. const StandardConversionSequence& SCS2) {
  3190. // C++ 13.3.3.2p3:
  3191. // -- S1 and S2 differ only in their qualification conversion and
  3192. // yield similar types T1 and T2 (C++ 4.4), respectively, and the
  3193. // cv-qualification signature of type T1 is a proper subset of
  3194. // the cv-qualification signature of type T2, and S1 is not the
  3195. // deprecated string literal array-to-pointer conversion (4.2).
  3196. if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
  3197. SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
  3198. return ImplicitConversionSequence::Indistinguishable;
  3199. // FIXME: the example in the standard doesn't use a qualification
  3200. // conversion (!)
  3201. QualType T1 = SCS1.getToType(2);
  3202. QualType T2 = SCS2.getToType(2);
  3203. T1 = S.Context.getCanonicalType(T1);
  3204. T2 = S.Context.getCanonicalType(T2);
  3205. Qualifiers T1Quals, T2Quals;
  3206. QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
  3207. QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
  3208. // If the types are the same, we won't learn anything by unwrapped
  3209. // them.
  3210. if (UnqualT1 == UnqualT2)
  3211. return ImplicitConversionSequence::Indistinguishable;
  3212. // If the type is an array type, promote the element qualifiers to the type
  3213. // for comparison.
  3214. if (isa<ArrayType>(T1) && T1Quals)
  3215. T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
  3216. if (isa<ArrayType>(T2) && T2Quals)
  3217. T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
  3218. ImplicitConversionSequence::CompareKind Result
  3219. = ImplicitConversionSequence::Indistinguishable;
  3220. // Objective-C++ ARC:
  3221. // Prefer qualification conversions not involving a change in lifetime
  3222. // to qualification conversions that do not change lifetime.
  3223. if (SCS1.QualificationIncludesObjCLifetime !=
  3224. SCS2.QualificationIncludesObjCLifetime) {
  3225. Result = SCS1.QualificationIncludesObjCLifetime
  3226. ? ImplicitConversionSequence::Worse
  3227. : ImplicitConversionSequence::Better;
  3228. }
  3229. while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
  3230. // Within each iteration of the loop, we check the qualifiers to
  3231. // determine if this still looks like a qualification
  3232. // conversion. Then, if all is well, we unwrap one more level of
  3233. // pointers or pointers-to-members and do it all again
  3234. // until there are no more pointers or pointers-to-members left
  3235. // to unwrap. This essentially mimics what
  3236. // IsQualificationConversion does, but here we're checking for a
  3237. // strict subset of qualifiers.
  3238. if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
  3239. // The qualifiers are the same, so this doesn't tell us anything
  3240. // about how the sequences rank.
  3241. ;
  3242. else if (T2.isMoreQualifiedThan(T1)) {
  3243. // T1 has fewer qualifiers, so it could be the better sequence.
  3244. if (Result == ImplicitConversionSequence::Worse)
  3245. // Neither has qualifiers that are a subset of the other's
  3246. // qualifiers.
  3247. return ImplicitConversionSequence::Indistinguishable;
  3248. Result = ImplicitConversionSequence::Better;
  3249. } else if (T1.isMoreQualifiedThan(T2)) {
  3250. // T2 has fewer qualifiers, so it could be the better sequence.
  3251. if (Result == ImplicitConversionSequence::Better)
  3252. // Neither has qualifiers that are a subset of the other's
  3253. // qualifiers.
  3254. return ImplicitConversionSequence::Indistinguishable;
  3255. Result = ImplicitConversionSequence::Worse;
  3256. } else {
  3257. // Qualifiers are disjoint.
  3258. return ImplicitConversionSequence::Indistinguishable;
  3259. }
  3260. // If the types after this point are equivalent, we're done.
  3261. if (S.Context.hasSameUnqualifiedType(T1, T2))
  3262. break;
  3263. }
  3264. // Check that the winning standard conversion sequence isn't using
  3265. // the deprecated string literal array to pointer conversion.
  3266. switch (Result) {
  3267. case ImplicitConversionSequence::Better:
  3268. if (SCS1.DeprecatedStringLiteralToCharPtr)
  3269. Result = ImplicitConversionSequence::Indistinguishable;
  3270. break;
  3271. case ImplicitConversionSequence::Indistinguishable:
  3272. break;
  3273. case ImplicitConversionSequence::Worse:
  3274. if (SCS2.DeprecatedStringLiteralToCharPtr)
  3275. Result = ImplicitConversionSequence::Indistinguishable;
  3276. break;
  3277. }
  3278. return Result;
  3279. }
  3280. /// CompareDerivedToBaseConversions - Compares two standard conversion
  3281. /// sequences to determine whether they can be ranked based on their
  3282. /// various kinds of derived-to-base conversions (C++
  3283. /// [over.ics.rank]p4b3). As part of these checks, we also look at
  3284. /// conversions between Objective-C interface types.
  3285. ImplicitConversionSequence::CompareKind
  3286. CompareDerivedToBaseConversions(Sema &S,
  3287. const StandardConversionSequence& SCS1,
  3288. const StandardConversionSequence& SCS2) {
  3289. QualType FromType1 = SCS1.getFromType();
  3290. QualType ToType1 = SCS1.getToType(1);
  3291. QualType FromType2 = SCS2.getFromType();
  3292. QualType ToType2 = SCS2.getToType(1);
  3293. // Adjust the types we're converting from via the array-to-pointer
  3294. // conversion, if we need to.
  3295. if (SCS1.First == ICK_Array_To_Pointer)
  3296. FromType1 = S.Context.getArrayDecayedType(FromType1);
  3297. if (SCS2.First == ICK_Array_To_Pointer)
  3298. FromType2 = S.Context.getArrayDecayedType(FromType2);
  3299. // Canonicalize all of the types.
  3300. FromType1 = S.Context.getCanonicalType(FromType1);
  3301. ToType1 = S.Context.getCanonicalType(ToType1);
  3302. FromType2 = S.Context.getCanonicalType(FromType2);
  3303. ToType2 = S.Context.getCanonicalType(ToType2);
  3304. // C++ [over.ics.rank]p4b3:
  3305. //
  3306. // If class B is derived directly or indirectly from class A and
  3307. // class C is derived directly or indirectly from B,
  3308. //
  3309. // Compare based on pointer conversions.
  3310. if (SCS1.Second == ICK_Pointer_Conversion &&
  3311. SCS2.Second == ICK_Pointer_Conversion &&
  3312. /*FIXME: Remove if Objective-C id conversions get their own rank*/
  3313. FromType1->isPointerType() && FromType2->isPointerType() &&
  3314. ToType1->isPointerType() && ToType2->isPointerType()) {
  3315. QualType FromPointee1
  3316. = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3317. QualType ToPointee1
  3318. = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3319. QualType FromPointee2
  3320. = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3321. QualType ToPointee2
  3322. = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
  3323. // -- conversion of C* to B* is better than conversion of C* to A*,
  3324. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3325. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3326. return ImplicitConversionSequence::Better;
  3327. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3328. return ImplicitConversionSequence::Worse;
  3329. }
  3330. // -- conversion of B* to A* is better than conversion of C* to A*,
  3331. if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
  3332. if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3333. return ImplicitConversionSequence::Better;
  3334. else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3335. return ImplicitConversionSequence::Worse;
  3336. }
  3337. } else if (SCS1.Second == ICK_Pointer_Conversion &&
  3338. SCS2.Second == ICK_Pointer_Conversion) {
  3339. const ObjCObjectPointerType *FromPtr1
  3340. = FromType1->getAs<ObjCObjectPointerType>();
  3341. const ObjCObjectPointerType *FromPtr2
  3342. = FromType2->getAs<ObjCObjectPointerType>();
  3343. const ObjCObjectPointerType *ToPtr1
  3344. = ToType1->getAs<ObjCObjectPointerType>();
  3345. const ObjCObjectPointerType *ToPtr2
  3346. = ToType2->getAs<ObjCObjectPointerType>();
  3347. if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
  3348. // Apply the same conversion ranking rules for Objective-C pointer types
  3349. // that we do for C++ pointers to class types. However, we employ the
  3350. // Objective-C pseudo-subtyping relationship used for assignment of
  3351. // Objective-C pointer types.
  3352. bool FromAssignLeft
  3353. = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
  3354. bool FromAssignRight
  3355. = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
  3356. bool ToAssignLeft
  3357. = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
  3358. bool ToAssignRight
  3359. = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
  3360. // A conversion to an a non-id object pointer type or qualified 'id'
  3361. // type is better than a conversion to 'id'.
  3362. if (ToPtr1->isObjCIdType() &&
  3363. (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
  3364. return ImplicitConversionSequence::Worse;
  3365. if (ToPtr2->isObjCIdType() &&
  3366. (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
  3367. return ImplicitConversionSequence::Better;
  3368. // A conversion to a non-id object pointer type is better than a
  3369. // conversion to a qualified 'id' type
  3370. if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
  3371. return ImplicitConversionSequence::Worse;
  3372. if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
  3373. return ImplicitConversionSequence::Better;
  3374. // A conversion to an a non-Class object pointer type or qualified 'Class'
  3375. // type is better than a conversion to 'Class'.
  3376. if (ToPtr1->isObjCClassType() &&
  3377. (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
  3378. return ImplicitConversionSequence::Worse;
  3379. if (ToPtr2->isObjCClassType() &&
  3380. (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
  3381. return ImplicitConversionSequence::Better;
  3382. // A conversion to a non-Class object pointer type is better than a
  3383. // conversion to a qualified 'Class' type.
  3384. if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
  3385. return ImplicitConversionSequence::Worse;
  3386. if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
  3387. return ImplicitConversionSequence::Better;
  3388. // -- "conversion of C* to B* is better than conversion of C* to A*,"
  3389. if (S.Context.hasSameType(FromType1, FromType2) &&
  3390. !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
  3391. (ToAssignLeft != ToAssignRight))
  3392. return ToAssignLeft? ImplicitConversionSequence::Worse
  3393. : ImplicitConversionSequence::Better;
  3394. // -- "conversion of B* to A* is better than conversion of C* to A*,"
  3395. if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
  3396. (FromAssignLeft != FromAssignRight))
  3397. return FromAssignLeft? ImplicitConversionSequence::Better
  3398. : ImplicitConversionSequence::Worse;
  3399. }
  3400. }
  3401. // Ranking of member-pointer types.
  3402. if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
  3403. FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
  3404. ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
  3405. const MemberPointerType * FromMemPointer1 =
  3406. FromType1->getAs<MemberPointerType>();
  3407. const MemberPointerType * ToMemPointer1 =
  3408. ToType1->getAs<MemberPointerType>();
  3409. const MemberPointerType * FromMemPointer2 =
  3410. FromType2->getAs<MemberPointerType>();
  3411. const MemberPointerType * ToMemPointer2 =
  3412. ToType2->getAs<MemberPointerType>();
  3413. const Type *FromPointeeType1 = FromMemPointer1->getClass();
  3414. const Type *ToPointeeType1 = ToMemPointer1->getClass();
  3415. const Type *FromPointeeType2 = FromMemPointer2->getClass();
  3416. const Type *ToPointeeType2 = ToMemPointer2->getClass();
  3417. QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
  3418. QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
  3419. QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
  3420. QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
  3421. // conversion of A::* to B::* is better than conversion of A::* to C::*,
  3422. if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
  3423. if (S.IsDerivedFrom(ToPointee1, ToPointee2))
  3424. return ImplicitConversionSequence::Worse;
  3425. else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
  3426. return ImplicitConversionSequence::Better;
  3427. }
  3428. // conversion of B::* to C::* is better than conversion of A::* to C::*
  3429. if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
  3430. if (S.IsDerivedFrom(FromPointee1, FromPointee2))
  3431. return ImplicitConversionSequence::Better;
  3432. else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
  3433. return ImplicitConversionSequence::Worse;
  3434. }
  3435. }
  3436. if (SCS1.Second == ICK_Derived_To_Base) {
  3437. // -- conversion of C to B is better than conversion of C to A,
  3438. // -- binding of an expression of type C to a reference of type
  3439. // B& is better than binding an expression of type C to a
  3440. // reference of type A&,
  3441. if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3442. !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3443. if (S.IsDerivedFrom(ToType1, ToType2))
  3444. return ImplicitConversionSequence::Better;
  3445. else if (S.IsDerivedFrom(ToType2, ToType1))
  3446. return ImplicitConversionSequence::Worse;
  3447. }
  3448. // -- conversion of B to A is better than conversion of C to A.
  3449. // -- binding of an expression of type B to a reference of type
  3450. // A& is better than binding an expression of type C to a
  3451. // reference of type A&,
  3452. if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
  3453. S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
  3454. if (S.IsDerivedFrom(FromType2, FromType1))
  3455. return ImplicitConversionSequence::Better;
  3456. else if (S.IsDerivedFrom(FromType1, FromType2))
  3457. return ImplicitConversionSequence::Worse;
  3458. }
  3459. }
  3460. return ImplicitConversionSequence::Indistinguishable;
  3461. }
  3462. /// CompareReferenceRelationship - Compare the two types T1 and T2 to
  3463. /// determine whether they are reference-related,
  3464. /// reference-compatible, reference-compatible with added
  3465. /// qualification, or incompatible, for use in C++ initialization by
  3466. /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
  3467. /// type, and the first type (T1) is the pointee type of the reference
  3468. /// type being initialized.
  3469. Sema::ReferenceCompareResult
  3470. Sema::CompareReferenceRelationship(SourceLocation Loc,
  3471. QualType OrigT1, QualType OrigT2,
  3472. bool &DerivedToBase,
  3473. bool &ObjCConversion,
  3474. bool &ObjCLifetimeConversion) {
  3475. assert(!OrigT1->isReferenceType() &&
  3476. "T1 must be the pointee type of the reference type");
  3477. assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
  3478. QualType T1 = Context.getCanonicalType(OrigT1);
  3479. QualType T2 = Context.getCanonicalType(OrigT2);
  3480. Qualifiers T1Quals, T2Quals;
  3481. QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
  3482. QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
  3483. // C++ [dcl.init.ref]p4:
  3484. // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
  3485. // reference-related to "cv2 T2" if T1 is the same type as T2, or
  3486. // T1 is a base class of T2.
  3487. DerivedToBase = false;
  3488. ObjCConversion = false;
  3489. ObjCLifetimeConversion = false;
  3490. if (UnqualT1 == UnqualT2) {
  3491. // Nothing to do.
  3492. } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
  3493. IsDerivedFrom(UnqualT2, UnqualT1))
  3494. DerivedToBase = true;
  3495. else if (UnqualT1->isObjCObjectOrInterfaceType() &&
  3496. UnqualT2->isObjCObjectOrInterfaceType() &&
  3497. Context.canBindObjCObjectType(UnqualT1, UnqualT2))
  3498. ObjCConversion = true;
  3499. else
  3500. return Ref_Incompatible;
  3501. // At this point, we know that T1 and T2 are reference-related (at
  3502. // least).
  3503. // If the type is an array type, promote the element qualifiers to the type
  3504. // for comparison.
  3505. if (isa<ArrayType>(T1) && T1Quals)
  3506. T1 = Context.getQualifiedType(UnqualT1, T1Quals);
  3507. if (isa<ArrayType>(T2) && T2Quals)
  3508. T2 = Context.getQualifiedType(UnqualT2, T2Quals);
  3509. // C++ [dcl.init.ref]p4:
  3510. // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
  3511. // reference-related to T2 and cv1 is the same cv-qualification
  3512. // as, or greater cv-qualification than, cv2. For purposes of
  3513. // overload resolution, cases for which cv1 is greater
  3514. // cv-qualification than cv2 are identified as
  3515. // reference-compatible with added qualification (see 13.3.3.2).
  3516. //
  3517. // Note that we also require equivalence of Objective-C GC and address-space
  3518. // qualifiers when performing these computations, so that e.g., an int in
  3519. // address space 1 is not reference-compatible with an int in address
  3520. // space 2.
  3521. if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
  3522. T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
  3523. T1Quals.removeObjCLifetime();
  3524. T2Quals.removeObjCLifetime();
  3525. ObjCLifetimeConversion = true;
  3526. }
  3527. if (T1Quals == T2Quals)
  3528. return Ref_Compatible;
  3529. else if (T1Quals.compatiblyIncludes(T2Quals))
  3530. return Ref_Compatible_With_Added_Qualification;
  3531. else
  3532. return Ref_Related;
  3533. }
  3534. /// \brief Look for a user-defined conversion to an value reference-compatible
  3535. /// with DeclType. Return true if something definite is found.
  3536. static bool
  3537. FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
  3538. QualType DeclType, SourceLocation DeclLoc,
  3539. Expr *Init, QualType T2, bool AllowRvalues,
  3540. bool AllowExplicit) {
  3541. assert(T2->isRecordType() && "Can only find conversions of record types.");
  3542. CXXRecordDecl *T2RecordDecl
  3543. = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
  3544. OverloadCandidateSet CandidateSet(DeclLoc);
  3545. const UnresolvedSetImpl *Conversions
  3546. = T2RecordDecl->getVisibleConversionFunctions();
  3547. for (UnresolvedSetImpl::iterator I = Conversions->begin(),
  3548. E = Conversions->end(); I != E; ++I) {
  3549. NamedDecl *D = *I;
  3550. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
  3551. if (isa<UsingShadowDecl>(D))
  3552. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  3553. FunctionTemplateDecl *ConvTemplate
  3554. = dyn_cast<FunctionTemplateDecl>(D);
  3555. CXXConversionDecl *Conv;
  3556. if (ConvTemplate)
  3557. Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
  3558. else
  3559. Conv = cast<CXXConversionDecl>(D);
  3560. // If this is an explicit conversion, and we're not allowed to consider
  3561. // explicit conversions, skip it.
  3562. if (!AllowExplicit && Conv->isExplicit())
  3563. continue;
  3564. if (AllowRvalues) {
  3565. bool DerivedToBase = false;
  3566. bool ObjCConversion = false;
  3567. bool ObjCLifetimeConversion = false;
  3568. // If we are initializing an rvalue reference, don't permit conversion
  3569. // functions that return lvalues.
  3570. if (!ConvTemplate && DeclType->isRValueReferenceType()) {
  3571. const ReferenceType *RefType
  3572. = Conv->getConversionType()->getAs<LValueReferenceType>();
  3573. if (RefType && !RefType->getPointeeType()->isFunctionType())
  3574. continue;
  3575. }
  3576. if (!ConvTemplate &&
  3577. S.CompareReferenceRelationship(
  3578. DeclLoc,
  3579. Conv->getConversionType().getNonReferenceType()
  3580. .getUnqualifiedType(),
  3581. DeclType.getNonReferenceType().getUnqualifiedType(),
  3582. DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
  3583. Sema::Ref_Incompatible)
  3584. continue;
  3585. } else {
  3586. // If the conversion function doesn't return a reference type,
  3587. // it can't be considered for this conversion. An rvalue reference
  3588. // is only acceptable if its referencee is a function type.
  3589. const ReferenceType *RefType =
  3590. Conv->getConversionType()->getAs<ReferenceType>();
  3591. if (!RefType ||
  3592. (!RefType->isLValueReferenceType() &&
  3593. !RefType->getPointeeType()->isFunctionType()))
  3594. continue;
  3595. }
  3596. if (ConvTemplate)
  3597. S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
  3598. Init, DeclType, CandidateSet);
  3599. else
  3600. S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
  3601. DeclType, CandidateSet);
  3602. }
  3603. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  3604. OverloadCandidateSet::iterator Best;
  3605. switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
  3606. case OR_Success:
  3607. // C++ [over.ics.ref]p1:
  3608. //
  3609. // [...] If the parameter binds directly to the result of
  3610. // applying a conversion function to the argument
  3611. // expression, the implicit conversion sequence is a
  3612. // user-defined conversion sequence (13.3.3.1.2), with the
  3613. // second standard conversion sequence either an identity
  3614. // conversion or, if the conversion function returns an
  3615. // entity of a type that is a derived class of the parameter
  3616. // type, a derived-to-base Conversion.
  3617. if (!Best->FinalConversion.DirectBinding)
  3618. return false;
  3619. if (Best->Function)
  3620. S.MarkFunctionReferenced(DeclLoc, Best->Function);
  3621. ICS.setUserDefined();
  3622. ICS.UserDefined.Before = Best->Conversions[0].Standard;
  3623. ICS.UserDefined.After = Best->FinalConversion;
  3624. ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
  3625. ICS.UserDefined.ConversionFunction = Best->Function;
  3626. ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
  3627. ICS.UserDefined.EllipsisConversion = false;
  3628. assert(ICS.UserDefined.After.ReferenceBinding &&
  3629. ICS.UserDefined.After.DirectBinding &&
  3630. "Expected a direct reference binding!");
  3631. return true;
  3632. case OR_Ambiguous:
  3633. ICS.setAmbiguous();
  3634. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
  3635. Cand != CandidateSet.end(); ++Cand)
  3636. if (Cand->Viable)
  3637. ICS.Ambiguous.addConversion(Cand->Function);
  3638. return true;
  3639. case OR_No_Viable_Function:
  3640. case OR_Deleted:
  3641. // There was no suitable conversion, or we found a deleted
  3642. // conversion; continue with other checks.
  3643. return false;
  3644. }
  3645. llvm_unreachable("Invalid OverloadResult!");
  3646. }
  3647. /// \brief Compute an implicit conversion sequence for reference
  3648. /// initialization.
  3649. static ImplicitConversionSequence
  3650. TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
  3651. SourceLocation DeclLoc,
  3652. bool SuppressUserConversions,
  3653. bool AllowExplicit) {
  3654. assert(DeclType->isReferenceType() && "Reference init needs a reference");
  3655. // Most paths end in a failed conversion.
  3656. ImplicitConversionSequence ICS;
  3657. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3658. QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
  3659. QualType T2 = Init->getType();
  3660. // If the initializer is the address of an overloaded function, try
  3661. // to resolve the overloaded function. If all goes well, T2 is the
  3662. // type of the resulting function.
  3663. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  3664. DeclAccessPair Found;
  3665. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
  3666. false, Found))
  3667. T2 = Fn->getType();
  3668. }
  3669. // Compute some basic properties of the types and the initializer.
  3670. bool isRValRef = DeclType->isRValueReferenceType();
  3671. bool DerivedToBase = false;
  3672. bool ObjCConversion = false;
  3673. bool ObjCLifetimeConversion = false;
  3674. Expr::Classification InitCategory = Init->Classify(S.Context);
  3675. Sema::ReferenceCompareResult RefRelationship
  3676. = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
  3677. ObjCConversion, ObjCLifetimeConversion);
  3678. // C++0x [dcl.init.ref]p5:
  3679. // A reference to type "cv1 T1" is initialized by an expression
  3680. // of type "cv2 T2" as follows:
  3681. // -- If reference is an lvalue reference and the initializer expression
  3682. if (!isRValRef) {
  3683. // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
  3684. // reference-compatible with "cv2 T2," or
  3685. //
  3686. // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
  3687. if (InitCategory.isLValue() &&
  3688. RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
  3689. // C++ [over.ics.ref]p1:
  3690. // When a parameter of reference type binds directly (8.5.3)
  3691. // to an argument expression, the implicit conversion sequence
  3692. // is the identity conversion, unless the argument expression
  3693. // has a type that is a derived class of the parameter type,
  3694. // in which case the implicit conversion sequence is a
  3695. // derived-to-base Conversion (13.3.3.1).
  3696. ICS.setStandard();
  3697. ICS.Standard.First = ICK_Identity;
  3698. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3699. : ObjCConversion? ICK_Compatible_Conversion
  3700. : ICK_Identity;
  3701. ICS.Standard.Third = ICK_Identity;
  3702. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3703. ICS.Standard.setToType(0, T2);
  3704. ICS.Standard.setToType(1, T1);
  3705. ICS.Standard.setToType(2, T1);
  3706. ICS.Standard.ReferenceBinding = true;
  3707. ICS.Standard.DirectBinding = true;
  3708. ICS.Standard.IsLvalueReference = !isRValRef;
  3709. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3710. ICS.Standard.BindsToRvalue = false;
  3711. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3712. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3713. ICS.Standard.CopyConstructor = 0;
  3714. // Nothing more to do: the inaccessibility/ambiguity check for
  3715. // derived-to-base conversions is suppressed when we're
  3716. // computing the implicit conversion sequence (C++
  3717. // [over.best.ics]p2).
  3718. return ICS;
  3719. }
  3720. // -- has a class type (i.e., T2 is a class type), where T1 is
  3721. // not reference-related to T2, and can be implicitly
  3722. // converted to an lvalue of type "cv3 T3," where "cv1 T1"
  3723. // is reference-compatible with "cv3 T3" 92) (this
  3724. // conversion is selected by enumerating the applicable
  3725. // conversion functions (13.3.1.6) and choosing the best
  3726. // one through overload resolution (13.3)),
  3727. if (!SuppressUserConversions && T2->isRecordType() &&
  3728. !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3729. RefRelationship == Sema::Ref_Incompatible) {
  3730. if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3731. Init, T2, /*AllowRvalues=*/false,
  3732. AllowExplicit))
  3733. return ICS;
  3734. }
  3735. }
  3736. // -- Otherwise, the reference shall be an lvalue reference to a
  3737. // non-volatile const type (i.e., cv1 shall be const), or the reference
  3738. // shall be an rvalue reference.
  3739. //
  3740. // We actually handle one oddity of C++ [over.ics.ref] at this
  3741. // point, which is that, due to p2 (which short-circuits reference
  3742. // binding by only attempting a simple conversion for non-direct
  3743. // bindings) and p3's strange wording, we allow a const volatile
  3744. // reference to bind to an rvalue. Hence the check for the presence
  3745. // of "const" rather than checking for "const" being the only
  3746. // qualifier.
  3747. // This is also the point where rvalue references and lvalue inits no longer
  3748. // go together.
  3749. if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
  3750. return ICS;
  3751. // -- If the initializer expression
  3752. //
  3753. // -- is an xvalue, class prvalue, array prvalue or function
  3754. // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
  3755. if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
  3756. (InitCategory.isXValue() ||
  3757. (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
  3758. (InitCategory.isLValue() && T2->isFunctionType()))) {
  3759. ICS.setStandard();
  3760. ICS.Standard.First = ICK_Identity;
  3761. ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
  3762. : ObjCConversion? ICK_Compatible_Conversion
  3763. : ICK_Identity;
  3764. ICS.Standard.Third = ICK_Identity;
  3765. ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
  3766. ICS.Standard.setToType(0, T2);
  3767. ICS.Standard.setToType(1, T1);
  3768. ICS.Standard.setToType(2, T1);
  3769. ICS.Standard.ReferenceBinding = true;
  3770. // In C++0x, this is always a direct binding. In C++98/03, it's a direct
  3771. // binding unless we're binding to a class prvalue.
  3772. // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
  3773. // allow the use of rvalue references in C++98/03 for the benefit of
  3774. // standard library implementors; therefore, we need the xvalue check here.
  3775. ICS.Standard.DirectBinding =
  3776. S.getLangOpts().CPlusPlus0x ||
  3777. (InitCategory.isPRValue() && !T2->isRecordType());
  3778. ICS.Standard.IsLvalueReference = !isRValRef;
  3779. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3780. ICS.Standard.BindsToRvalue = InitCategory.isRValue();
  3781. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3782. ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
  3783. ICS.Standard.CopyConstructor = 0;
  3784. return ICS;
  3785. }
  3786. // -- has a class type (i.e., T2 is a class type), where T1 is not
  3787. // reference-related to T2, and can be implicitly converted to
  3788. // an xvalue, class prvalue, or function lvalue of type
  3789. // "cv3 T3", where "cv1 T1" is reference-compatible with
  3790. // "cv3 T3",
  3791. //
  3792. // then the reference is bound to the value of the initializer
  3793. // expression in the first case and to the result of the conversion
  3794. // in the second case (or, in either case, to an appropriate base
  3795. // class subobject).
  3796. if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3797. T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
  3798. FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
  3799. Init, T2, /*AllowRvalues=*/true,
  3800. AllowExplicit)) {
  3801. // In the second case, if the reference is an rvalue reference
  3802. // and the second standard conversion sequence of the
  3803. // user-defined conversion sequence includes an lvalue-to-rvalue
  3804. // conversion, the program is ill-formed.
  3805. if (ICS.isUserDefined() && isRValRef &&
  3806. ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
  3807. ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
  3808. return ICS;
  3809. }
  3810. // -- Otherwise, a temporary of type "cv1 T1" is created and
  3811. // initialized from the initializer expression using the
  3812. // rules for a non-reference copy initialization (8.5). The
  3813. // reference is then bound to the temporary. If T1 is
  3814. // reference-related to T2, cv1 must be the same
  3815. // cv-qualification as, or greater cv-qualification than,
  3816. // cv2; otherwise, the program is ill-formed.
  3817. if (RefRelationship == Sema::Ref_Related) {
  3818. // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
  3819. // we would be reference-compatible or reference-compatible with
  3820. // added qualification. But that wasn't the case, so the reference
  3821. // initialization fails.
  3822. //
  3823. // Note that we only want to check address spaces and cvr-qualifiers here.
  3824. // ObjC GC and lifetime qualifiers aren't important.
  3825. Qualifiers T1Quals = T1.getQualifiers();
  3826. Qualifiers T2Quals = T2.getQualifiers();
  3827. T1Quals.removeObjCGCAttr();
  3828. T1Quals.removeObjCLifetime();
  3829. T2Quals.removeObjCGCAttr();
  3830. T2Quals.removeObjCLifetime();
  3831. if (!T1Quals.compatiblyIncludes(T2Quals))
  3832. return ICS;
  3833. }
  3834. // If at least one of the types is a class type, the types are not
  3835. // related, and we aren't allowed any user conversions, the
  3836. // reference binding fails. This case is important for breaking
  3837. // recursion, since TryImplicitConversion below will attempt to
  3838. // create a temporary through the use of a copy constructor.
  3839. if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
  3840. (T1->isRecordType() || T2->isRecordType()))
  3841. return ICS;
  3842. // If T1 is reference-related to T2 and the reference is an rvalue
  3843. // reference, the initializer expression shall not be an lvalue.
  3844. if (RefRelationship >= Sema::Ref_Related &&
  3845. isRValRef && Init->Classify(S.Context).isLValue())
  3846. return ICS;
  3847. // C++ [over.ics.ref]p2:
  3848. // When a parameter of reference type is not bound directly to
  3849. // an argument expression, the conversion sequence is the one
  3850. // required to convert the argument expression to the
  3851. // underlying type of the reference according to
  3852. // 13.3.3.1. Conceptually, this conversion sequence corresponds
  3853. // to copy-initializing a temporary of the underlying type with
  3854. // the argument expression. Any difference in top-level
  3855. // cv-qualification is subsumed by the initialization itself
  3856. // and does not constitute a conversion.
  3857. ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
  3858. /*AllowExplicit=*/false,
  3859. /*InOverloadResolution=*/false,
  3860. /*CStyle=*/false,
  3861. /*AllowObjCWritebackConversion=*/false);
  3862. // Of course, that's still a reference binding.
  3863. if (ICS.isStandard()) {
  3864. ICS.Standard.ReferenceBinding = true;
  3865. ICS.Standard.IsLvalueReference = !isRValRef;
  3866. ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
  3867. ICS.Standard.BindsToRvalue = true;
  3868. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3869. ICS.Standard.ObjCLifetimeConversionBinding = false;
  3870. } else if (ICS.isUserDefined()) {
  3871. // Don't allow rvalue references to bind to lvalues.
  3872. if (DeclType->isRValueReferenceType()) {
  3873. if (const ReferenceType *RefType
  3874. = ICS.UserDefined.ConversionFunction->getResultType()
  3875. ->getAs<LValueReferenceType>()) {
  3876. if (!RefType->getPointeeType()->isFunctionType()) {
  3877. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
  3878. DeclType);
  3879. return ICS;
  3880. }
  3881. }
  3882. }
  3883. ICS.UserDefined.After.ReferenceBinding = true;
  3884. ICS.UserDefined.After.IsLvalueReference = !isRValRef;
  3885. ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
  3886. ICS.UserDefined.After.BindsToRvalue = true;
  3887. ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  3888. ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
  3889. }
  3890. return ICS;
  3891. }
  3892. static ImplicitConversionSequence
  3893. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  3894. bool SuppressUserConversions,
  3895. bool InOverloadResolution,
  3896. bool AllowObjCWritebackConversion,
  3897. bool AllowExplicit = false);
  3898. /// TryListConversion - Try to copy-initialize a value of type ToType from the
  3899. /// initializer list From.
  3900. static ImplicitConversionSequence
  3901. TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
  3902. bool SuppressUserConversions,
  3903. bool InOverloadResolution,
  3904. bool AllowObjCWritebackConversion) {
  3905. // C++11 [over.ics.list]p1:
  3906. // When an argument is an initializer list, it is not an expression and
  3907. // special rules apply for converting it to a parameter type.
  3908. ImplicitConversionSequence Result;
  3909. Result.setBad(BadConversionSequence::no_conversion, From, ToType);
  3910. Result.setListInitializationSequence();
  3911. // We need a complete type for what follows. Incomplete types can never be
  3912. // initialized from init lists.
  3913. if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
  3914. return Result;
  3915. // C++11 [over.ics.list]p2:
  3916. // If the parameter type is std::initializer_list<X> or "array of X" and
  3917. // all the elements can be implicitly converted to X, the implicit
  3918. // conversion sequence is the worst conversion necessary to convert an
  3919. // element of the list to X.
  3920. bool toStdInitializerList = false;
  3921. QualType X;
  3922. if (ToType->isArrayType())
  3923. X = S.Context.getBaseElementType(ToType);
  3924. else
  3925. toStdInitializerList = S.isStdInitializerList(ToType, &X);
  3926. if (!X.isNull()) {
  3927. for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
  3928. Expr *Init = From->getInit(i);
  3929. ImplicitConversionSequence ICS =
  3930. TryCopyInitialization(S, Init, X, SuppressUserConversions,
  3931. InOverloadResolution,
  3932. AllowObjCWritebackConversion);
  3933. // If a single element isn't convertible, fail.
  3934. if (ICS.isBad()) {
  3935. Result = ICS;
  3936. break;
  3937. }
  3938. // Otherwise, look for the worst conversion.
  3939. if (Result.isBad() ||
  3940. CompareImplicitConversionSequences(S, ICS, Result) ==
  3941. ImplicitConversionSequence::Worse)
  3942. Result = ICS;
  3943. }
  3944. // For an empty list, we won't have computed any conversion sequence.
  3945. // Introduce the identity conversion sequence.
  3946. if (From->getNumInits() == 0) {
  3947. Result.setStandard();
  3948. Result.Standard.setAsIdentityConversion();
  3949. Result.Standard.setFromType(ToType);
  3950. Result.Standard.setAllToTypes(ToType);
  3951. }
  3952. Result.setListInitializationSequence();
  3953. Result.setStdInitializerListElement(toStdInitializerList);
  3954. return Result;
  3955. }
  3956. // C++11 [over.ics.list]p3:
  3957. // Otherwise, if the parameter is a non-aggregate class X and overload
  3958. // resolution chooses a single best constructor [...] the implicit
  3959. // conversion sequence is a user-defined conversion sequence. If multiple
  3960. // constructors are viable but none is better than the others, the
  3961. // implicit conversion sequence is a user-defined conversion sequence.
  3962. if (ToType->isRecordType() && !ToType->isAggregateType()) {
  3963. // This function can deal with initializer lists.
  3964. Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
  3965. /*AllowExplicit=*/false,
  3966. InOverloadResolution, /*CStyle=*/false,
  3967. AllowObjCWritebackConversion);
  3968. Result.setListInitializationSequence();
  3969. return Result;
  3970. }
  3971. // C++11 [over.ics.list]p4:
  3972. // Otherwise, if the parameter has an aggregate type which can be
  3973. // initialized from the initializer list [...] the implicit conversion
  3974. // sequence is a user-defined conversion sequence.
  3975. if (ToType->isAggregateType()) {
  3976. // Type is an aggregate, argument is an init list. At this point it comes
  3977. // down to checking whether the initialization works.
  3978. // FIXME: Find out whether this parameter is consumed or not.
  3979. InitializedEntity Entity =
  3980. InitializedEntity::InitializeParameter(S.Context, ToType,
  3981. /*Consumed=*/false);
  3982. if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
  3983. Result.setUserDefined();
  3984. Result.UserDefined.Before.setAsIdentityConversion();
  3985. // Initializer lists don't have a type.
  3986. Result.UserDefined.Before.setFromType(QualType());
  3987. Result.UserDefined.Before.setAllToTypes(QualType());
  3988. Result.UserDefined.After.setAsIdentityConversion();
  3989. Result.UserDefined.After.setFromType(ToType);
  3990. Result.UserDefined.After.setAllToTypes(ToType);
  3991. Result.UserDefined.ConversionFunction = 0;
  3992. }
  3993. return Result;
  3994. }
  3995. // C++11 [over.ics.list]p5:
  3996. // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
  3997. if (ToType->isReferenceType()) {
  3998. // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
  3999. // mention initializer lists in any way. So we go by what list-
  4000. // initialization would do and try to extrapolate from that.
  4001. QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
  4002. // If the initializer list has a single element that is reference-related
  4003. // to the parameter type, we initialize the reference from that.
  4004. if (From->getNumInits() == 1) {
  4005. Expr *Init = From->getInit(0);
  4006. QualType T2 = Init->getType();
  4007. // If the initializer is the address of an overloaded function, try
  4008. // to resolve the overloaded function. If all goes well, T2 is the
  4009. // type of the resulting function.
  4010. if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
  4011. DeclAccessPair Found;
  4012. if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
  4013. Init, ToType, false, Found))
  4014. T2 = Fn->getType();
  4015. }
  4016. // Compute some basic properties of the types and the initializer.
  4017. bool dummy1 = false;
  4018. bool dummy2 = false;
  4019. bool dummy3 = false;
  4020. Sema::ReferenceCompareResult RefRelationship
  4021. = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
  4022. dummy2, dummy3);
  4023. if (RefRelationship >= Sema::Ref_Related)
  4024. return TryReferenceInit(S, Init, ToType,
  4025. /*FIXME:*/From->getLocStart(),
  4026. SuppressUserConversions,
  4027. /*AllowExplicit=*/false);
  4028. }
  4029. // Otherwise, we bind the reference to a temporary created from the
  4030. // initializer list.
  4031. Result = TryListConversion(S, From, T1, SuppressUserConversions,
  4032. InOverloadResolution,
  4033. AllowObjCWritebackConversion);
  4034. if (Result.isFailure())
  4035. return Result;
  4036. assert(!Result.isEllipsis() &&
  4037. "Sub-initialization cannot result in ellipsis conversion.");
  4038. // Can we even bind to a temporary?
  4039. if (ToType->isRValueReferenceType() ||
  4040. (T1.isConstQualified() && !T1.isVolatileQualified())) {
  4041. StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
  4042. Result.UserDefined.After;
  4043. SCS.ReferenceBinding = true;
  4044. SCS.IsLvalueReference = ToType->isLValueReferenceType();
  4045. SCS.BindsToRvalue = true;
  4046. SCS.BindsToFunctionLvalue = false;
  4047. SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
  4048. SCS.ObjCLifetimeConversionBinding = false;
  4049. } else
  4050. Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
  4051. From, ToType);
  4052. return Result;
  4053. }
  4054. // C++11 [over.ics.list]p6:
  4055. // Otherwise, if the parameter type is not a class:
  4056. if (!ToType->isRecordType()) {
  4057. // - if the initializer list has one element, the implicit conversion
  4058. // sequence is the one required to convert the element to the
  4059. // parameter type.
  4060. unsigned NumInits = From->getNumInits();
  4061. if (NumInits == 1)
  4062. Result = TryCopyInitialization(S, From->getInit(0), ToType,
  4063. SuppressUserConversions,
  4064. InOverloadResolution,
  4065. AllowObjCWritebackConversion);
  4066. // - if the initializer list has no elements, the implicit conversion
  4067. // sequence is the identity conversion.
  4068. else if (NumInits == 0) {
  4069. Result.setStandard();
  4070. Result.Standard.setAsIdentityConversion();
  4071. Result.Standard.setFromType(ToType);
  4072. Result.Standard.setAllToTypes(ToType);
  4073. }
  4074. Result.setListInitializationSequence();
  4075. return Result;
  4076. }
  4077. // C++11 [over.ics.list]p7:
  4078. // In all cases other than those enumerated above, no conversion is possible
  4079. return Result;
  4080. }
  4081. /// TryCopyInitialization - Try to copy-initialize a value of type
  4082. /// ToType from the expression From. Return the implicit conversion
  4083. /// sequence required to pass this argument, which may be a bad
  4084. /// conversion sequence (meaning that the argument cannot be passed to
  4085. /// a parameter of this type). If @p SuppressUserConversions, then we
  4086. /// do not permit any user-defined conversion sequences.
  4087. static ImplicitConversionSequence
  4088. TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
  4089. bool SuppressUserConversions,
  4090. bool InOverloadResolution,
  4091. bool AllowObjCWritebackConversion,
  4092. bool AllowExplicit) {
  4093. if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
  4094. return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
  4095. InOverloadResolution,AllowObjCWritebackConversion);
  4096. if (ToType->isReferenceType())
  4097. return TryReferenceInit(S, From, ToType,
  4098. /*FIXME:*/From->getLocStart(),
  4099. SuppressUserConversions,
  4100. AllowExplicit);
  4101. return TryImplicitConversion(S, From, ToType,
  4102. SuppressUserConversions,
  4103. /*AllowExplicit=*/false,
  4104. InOverloadResolution,
  4105. /*CStyle=*/false,
  4106. AllowObjCWritebackConversion);
  4107. }
  4108. static bool TryCopyInitialization(const CanQualType FromQTy,
  4109. const CanQualType ToQTy,
  4110. Sema &S,
  4111. SourceLocation Loc,
  4112. ExprValueKind FromVK) {
  4113. OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
  4114. ImplicitConversionSequence ICS =
  4115. TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
  4116. return !ICS.isBad();
  4117. }
  4118. /// TryObjectArgumentInitialization - Try to initialize the object
  4119. /// parameter of the given member function (@c Method) from the
  4120. /// expression @p From.
  4121. static ImplicitConversionSequence
  4122. TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
  4123. Expr::Classification FromClassification,
  4124. CXXMethodDecl *Method,
  4125. CXXRecordDecl *ActingContext) {
  4126. QualType ClassType = S.Context.getTypeDeclType(ActingContext);
  4127. // [class.dtor]p2: A destructor can be invoked for a const, volatile or
  4128. // const volatile object.
  4129. unsigned Quals = isa<CXXDestructorDecl>(Method) ?
  4130. Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
  4131. QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
  4132. // Set up the conversion sequence as a "bad" conversion, to allow us
  4133. // to exit early.
  4134. ImplicitConversionSequence ICS;
  4135. // We need to have an object of class type.
  4136. QualType FromType = OrigFromType;
  4137. if (const PointerType *PT = FromType->getAs<PointerType>()) {
  4138. FromType = PT->getPointeeType();
  4139. // When we had a pointer, it's implicitly dereferenced, so we
  4140. // better have an lvalue.
  4141. assert(FromClassification.isLValue());
  4142. }
  4143. assert(FromType->isRecordType());
  4144. // C++0x [over.match.funcs]p4:
  4145. // For non-static member functions, the type of the implicit object
  4146. // parameter is
  4147. //
  4148. // - "lvalue reference to cv X" for functions declared without a
  4149. // ref-qualifier or with the & ref-qualifier
  4150. // - "rvalue reference to cv X" for functions declared with the &&
  4151. // ref-qualifier
  4152. //
  4153. // where X is the class of which the function is a member and cv is the
  4154. // cv-qualification on the member function declaration.
  4155. //
  4156. // However, when finding an implicit conversion sequence for the argument, we
  4157. // are not allowed to create temporaries or perform user-defined conversions
  4158. // (C++ [over.match.funcs]p5). We perform a simplified version of
  4159. // reference binding here, that allows class rvalues to bind to
  4160. // non-constant references.
  4161. // First check the qualifiers.
  4162. QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
  4163. if (ImplicitParamType.getCVRQualifiers()
  4164. != FromTypeCanon.getLocalCVRQualifiers() &&
  4165. !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
  4166. ICS.setBad(BadConversionSequence::bad_qualifiers,
  4167. OrigFromType, ImplicitParamType);
  4168. return ICS;
  4169. }
  4170. // Check that we have either the same type or a derived type. It
  4171. // affects the conversion rank.
  4172. QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
  4173. ImplicitConversionKind SecondKind;
  4174. if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
  4175. SecondKind = ICK_Identity;
  4176. } else if (S.IsDerivedFrom(FromType, ClassType))
  4177. SecondKind = ICK_Derived_To_Base;
  4178. else {
  4179. ICS.setBad(BadConversionSequence::unrelated_class,
  4180. FromType, ImplicitParamType);
  4181. return ICS;
  4182. }
  4183. // Check the ref-qualifier.
  4184. switch (Method->getRefQualifier()) {
  4185. case RQ_None:
  4186. // Do nothing; we don't care about lvalueness or rvalueness.
  4187. break;
  4188. case RQ_LValue:
  4189. if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
  4190. // non-const lvalue reference cannot bind to an rvalue
  4191. ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
  4192. ImplicitParamType);
  4193. return ICS;
  4194. }
  4195. break;
  4196. case RQ_RValue:
  4197. if (!FromClassification.isRValue()) {
  4198. // rvalue reference cannot bind to an lvalue
  4199. ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
  4200. ImplicitParamType);
  4201. return ICS;
  4202. }
  4203. break;
  4204. }
  4205. // Success. Mark this as a reference binding.
  4206. ICS.setStandard();
  4207. ICS.Standard.setAsIdentityConversion();
  4208. ICS.Standard.Second = SecondKind;
  4209. ICS.Standard.setFromType(FromType);
  4210. ICS.Standard.setAllToTypes(ImplicitParamType);
  4211. ICS.Standard.ReferenceBinding = true;
  4212. ICS.Standard.DirectBinding = true;
  4213. ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
  4214. ICS.Standard.BindsToFunctionLvalue = false;
  4215. ICS.Standard.BindsToRvalue = FromClassification.isRValue();
  4216. ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
  4217. = (Method->getRefQualifier() == RQ_None);
  4218. return ICS;
  4219. }
  4220. /// PerformObjectArgumentInitialization - Perform initialization of
  4221. /// the implicit object parameter for the given Method with the given
  4222. /// expression.
  4223. ExprResult
  4224. Sema::PerformObjectArgumentInitialization(Expr *From,
  4225. NestedNameSpecifier *Qualifier,
  4226. NamedDecl *FoundDecl,
  4227. CXXMethodDecl *Method) {
  4228. QualType FromRecordType, DestType;
  4229. QualType ImplicitParamRecordType =
  4230. Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
  4231. Expr::Classification FromClassification;
  4232. if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
  4233. FromRecordType = PT->getPointeeType();
  4234. DestType = Method->getThisType(Context);
  4235. FromClassification = Expr::Classification::makeSimpleLValue();
  4236. } else {
  4237. FromRecordType = From->getType();
  4238. DestType = ImplicitParamRecordType;
  4239. FromClassification = From->Classify(Context);
  4240. }
  4241. // Note that we always use the true parent context when performing
  4242. // the actual argument initialization.
  4243. ImplicitConversionSequence ICS
  4244. = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
  4245. Method, Method->getParent());
  4246. if (ICS.isBad()) {
  4247. if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
  4248. Qualifiers FromQs = FromRecordType.getQualifiers();
  4249. Qualifiers ToQs = DestType.getQualifiers();
  4250. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  4251. if (CVR) {
  4252. Diag(From->getLocStart(),
  4253. diag::err_member_function_call_bad_cvr)
  4254. << Method->getDeclName() << FromRecordType << (CVR - 1)
  4255. << From->getSourceRange();
  4256. Diag(Method->getLocation(), diag::note_previous_decl)
  4257. << Method->getDeclName();
  4258. return ExprError();
  4259. }
  4260. }
  4261. return Diag(From->getLocStart(),
  4262. diag::err_implicit_object_parameter_init)
  4263. << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
  4264. }
  4265. if (ICS.Standard.Second == ICK_Derived_To_Base) {
  4266. ExprResult FromRes =
  4267. PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
  4268. if (FromRes.isInvalid())
  4269. return ExprError();
  4270. From = FromRes.take();
  4271. }
  4272. if (!Context.hasSameType(From->getType(), DestType))
  4273. From = ImpCastExprToType(From, DestType, CK_NoOp,
  4274. From->getValueKind()).take();
  4275. return Owned(From);
  4276. }
  4277. /// TryContextuallyConvertToBool - Attempt to contextually convert the
  4278. /// expression From to bool (C++0x [conv]p3).
  4279. static ImplicitConversionSequence
  4280. TryContextuallyConvertToBool(Sema &S, Expr *From) {
  4281. // FIXME: This is pretty broken.
  4282. return TryImplicitConversion(S, From, S.Context.BoolTy,
  4283. // FIXME: Are these flags correct?
  4284. /*SuppressUserConversions=*/false,
  4285. /*AllowExplicit=*/true,
  4286. /*InOverloadResolution=*/false,
  4287. /*CStyle=*/false,
  4288. /*AllowObjCWritebackConversion=*/false);
  4289. }
  4290. /// PerformContextuallyConvertToBool - Perform a contextual conversion
  4291. /// of the expression From to bool (C++0x [conv]p3).
  4292. ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
  4293. if (checkPlaceholderForOverload(*this, From))
  4294. return ExprError();
  4295. ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
  4296. if (!ICS.isBad())
  4297. return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
  4298. if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
  4299. return Diag(From->getLocStart(),
  4300. diag::err_typecheck_bool_condition)
  4301. << From->getType() << From->getSourceRange();
  4302. return ExprError();
  4303. }
  4304. /// Check that the specified conversion is permitted in a converted constant
  4305. /// expression, according to C++11 [expr.const]p3. Return true if the conversion
  4306. /// is acceptable.
  4307. static bool CheckConvertedConstantConversions(Sema &S,
  4308. StandardConversionSequence &SCS) {
  4309. // Since we know that the target type is an integral or unscoped enumeration
  4310. // type, most conversion kinds are impossible. All possible First and Third
  4311. // conversions are fine.
  4312. switch (SCS.Second) {
  4313. case ICK_Identity:
  4314. case ICK_Integral_Promotion:
  4315. case ICK_Integral_Conversion:
  4316. return true;
  4317. case ICK_Boolean_Conversion:
  4318. // Conversion from an integral or unscoped enumeration type to bool is
  4319. // classified as ICK_Boolean_Conversion, but it's also an integral
  4320. // conversion, so it's permitted in a converted constant expression.
  4321. return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
  4322. SCS.getToType(2)->isBooleanType();
  4323. case ICK_Floating_Integral:
  4324. case ICK_Complex_Real:
  4325. return false;
  4326. case ICK_Lvalue_To_Rvalue:
  4327. case ICK_Array_To_Pointer:
  4328. case ICK_Function_To_Pointer:
  4329. case ICK_NoReturn_Adjustment:
  4330. case ICK_Qualification:
  4331. case ICK_Compatible_Conversion:
  4332. case ICK_Vector_Conversion:
  4333. case ICK_Vector_Splat:
  4334. case ICK_Derived_To_Base:
  4335. case ICK_Pointer_Conversion:
  4336. case ICK_Pointer_Member:
  4337. case ICK_Block_Pointer_Conversion:
  4338. case ICK_Writeback_Conversion:
  4339. case ICK_Floating_Promotion:
  4340. case ICK_Complex_Promotion:
  4341. case ICK_Complex_Conversion:
  4342. case ICK_Floating_Conversion:
  4343. case ICK_TransparentUnionConversion:
  4344. llvm_unreachable("unexpected second conversion kind");
  4345. case ICK_Num_Conversion_Kinds:
  4346. break;
  4347. }
  4348. llvm_unreachable("unknown conversion kind");
  4349. }
  4350. /// CheckConvertedConstantExpression - Check that the expression From is a
  4351. /// converted constant expression of type T, perform the conversion and produce
  4352. /// the converted expression, per C++11 [expr.const]p3.
  4353. ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
  4354. llvm::APSInt &Value,
  4355. CCEKind CCE) {
  4356. assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
  4357. assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
  4358. if (checkPlaceholderForOverload(*this, From))
  4359. return ExprError();
  4360. // C++11 [expr.const]p3 with proposed wording fixes:
  4361. // A converted constant expression of type T is a core constant expression,
  4362. // implicitly converted to a prvalue of type T, where the converted
  4363. // expression is a literal constant expression and the implicit conversion
  4364. // sequence contains only user-defined conversions, lvalue-to-rvalue
  4365. // conversions, integral promotions, and integral conversions other than
  4366. // narrowing conversions.
  4367. ImplicitConversionSequence ICS =
  4368. TryImplicitConversion(From, T,
  4369. /*SuppressUserConversions=*/false,
  4370. /*AllowExplicit=*/false,
  4371. /*InOverloadResolution=*/false,
  4372. /*CStyle=*/false,
  4373. /*AllowObjcWritebackConversion=*/false);
  4374. StandardConversionSequence *SCS = 0;
  4375. switch (ICS.getKind()) {
  4376. case ImplicitConversionSequence::StandardConversion:
  4377. if (!CheckConvertedConstantConversions(*this, ICS.Standard))
  4378. return Diag(From->getLocStart(),
  4379. diag::err_typecheck_converted_constant_expression_disallowed)
  4380. << From->getType() << From->getSourceRange() << T;
  4381. SCS = &ICS.Standard;
  4382. break;
  4383. case ImplicitConversionSequence::UserDefinedConversion:
  4384. // We are converting from class type to an integral or enumeration type, so
  4385. // the Before sequence must be trivial.
  4386. if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
  4387. return Diag(From->getLocStart(),
  4388. diag::err_typecheck_converted_constant_expression_disallowed)
  4389. << From->getType() << From->getSourceRange() << T;
  4390. SCS = &ICS.UserDefined.After;
  4391. break;
  4392. case ImplicitConversionSequence::AmbiguousConversion:
  4393. case ImplicitConversionSequence::BadConversion:
  4394. if (!DiagnoseMultipleUserDefinedConversion(From, T))
  4395. return Diag(From->getLocStart(),
  4396. diag::err_typecheck_converted_constant_expression)
  4397. << From->getType() << From->getSourceRange() << T;
  4398. return ExprError();
  4399. case ImplicitConversionSequence::EllipsisConversion:
  4400. llvm_unreachable("ellipsis conversion in converted constant expression");
  4401. }
  4402. ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
  4403. if (Result.isInvalid())
  4404. return Result;
  4405. // Check for a narrowing implicit conversion.
  4406. APValue PreNarrowingValue;
  4407. QualType PreNarrowingType;
  4408. switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
  4409. PreNarrowingType)) {
  4410. case NK_Variable_Narrowing:
  4411. // Implicit conversion to a narrower type, and the value is not a constant
  4412. // expression. We'll diagnose this in a moment.
  4413. case NK_Not_Narrowing:
  4414. break;
  4415. case NK_Constant_Narrowing:
  4416. Diag(From->getLocStart(),
  4417. isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
  4418. diag::err_cce_narrowing)
  4419. << CCE << /*Constant*/1
  4420. << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
  4421. break;
  4422. case NK_Type_Narrowing:
  4423. Diag(From->getLocStart(),
  4424. isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
  4425. diag::err_cce_narrowing)
  4426. << CCE << /*Constant*/0 << From->getType() << T;
  4427. break;
  4428. }
  4429. // Check the expression is a constant expression.
  4430. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  4431. Expr::EvalResult Eval;
  4432. Eval.Diag = &Notes;
  4433. if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
  4434. // The expression can't be folded, so we can't keep it at this position in
  4435. // the AST.
  4436. Result = ExprError();
  4437. } else {
  4438. Value = Eval.Val.getInt();
  4439. if (Notes.empty()) {
  4440. // It's a constant expression.
  4441. return Result;
  4442. }
  4443. }
  4444. // It's not a constant expression. Produce an appropriate diagnostic.
  4445. if (Notes.size() == 1 &&
  4446. Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
  4447. Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
  4448. else {
  4449. Diag(From->getLocStart(), diag::err_expr_not_cce)
  4450. << CCE << From->getSourceRange();
  4451. for (unsigned I = 0; I < Notes.size(); ++I)
  4452. Diag(Notes[I].first, Notes[I].second);
  4453. }
  4454. return Result;
  4455. }
  4456. /// dropPointerConversions - If the given standard conversion sequence
  4457. /// involves any pointer conversions, remove them. This may change
  4458. /// the result type of the conversion sequence.
  4459. static void dropPointerConversion(StandardConversionSequence &SCS) {
  4460. if (SCS.Second == ICK_Pointer_Conversion) {
  4461. SCS.Second = ICK_Identity;
  4462. SCS.Third = ICK_Identity;
  4463. SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
  4464. }
  4465. }
  4466. /// TryContextuallyConvertToObjCPointer - Attempt to contextually
  4467. /// convert the expression From to an Objective-C pointer type.
  4468. static ImplicitConversionSequence
  4469. TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
  4470. // Do an implicit conversion to 'id'.
  4471. QualType Ty = S.Context.getObjCIdType();
  4472. ImplicitConversionSequence ICS
  4473. = TryImplicitConversion(S, From, Ty,
  4474. // FIXME: Are these flags correct?
  4475. /*SuppressUserConversions=*/false,
  4476. /*AllowExplicit=*/true,
  4477. /*InOverloadResolution=*/false,
  4478. /*CStyle=*/false,
  4479. /*AllowObjCWritebackConversion=*/false);
  4480. // Strip off any final conversions to 'id'.
  4481. switch (ICS.getKind()) {
  4482. case ImplicitConversionSequence::BadConversion:
  4483. case ImplicitConversionSequence::AmbiguousConversion:
  4484. case ImplicitConversionSequence::EllipsisConversion:
  4485. break;
  4486. case ImplicitConversionSequence::UserDefinedConversion:
  4487. dropPointerConversion(ICS.UserDefined.After);
  4488. break;
  4489. case ImplicitConversionSequence::StandardConversion:
  4490. dropPointerConversion(ICS.Standard);
  4491. break;
  4492. }
  4493. return ICS;
  4494. }
  4495. /// PerformContextuallyConvertToObjCPointer - Perform a contextual
  4496. /// conversion of the expression From to an Objective-C pointer type.
  4497. ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
  4498. if (checkPlaceholderForOverload(*this, From))
  4499. return ExprError();
  4500. QualType Ty = Context.getObjCIdType();
  4501. ImplicitConversionSequence ICS =
  4502. TryContextuallyConvertToObjCPointer(*this, From);
  4503. if (!ICS.isBad())
  4504. return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
  4505. return ExprError();
  4506. }
  4507. /// Determine whether the provided type is an integral type, or an enumeration
  4508. /// type of a permitted flavor.
  4509. static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
  4510. return AllowScopedEnum ? T->isIntegralOrEnumerationType()
  4511. : T->isIntegralOrUnscopedEnumerationType();
  4512. }
  4513. /// \brief Attempt to convert the given expression to an integral or
  4514. /// enumeration type.
  4515. ///
  4516. /// This routine will attempt to convert an expression of class type to an
  4517. /// integral or enumeration type, if that class type only has a single
  4518. /// conversion to an integral or enumeration type.
  4519. ///
  4520. /// \param Loc The source location of the construct that requires the
  4521. /// conversion.
  4522. ///
  4523. /// \param From The expression we're converting from.
  4524. ///
  4525. /// \param Diagnoser Used to output any diagnostics.
  4526. ///
  4527. /// \param AllowScopedEnumerations Specifies whether conversions to scoped
  4528. /// enumerations should be considered.
  4529. ///
  4530. /// \returns The expression, converted to an integral or enumeration type if
  4531. /// successful.
  4532. ExprResult
  4533. Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
  4534. ICEConvertDiagnoser &Diagnoser,
  4535. bool AllowScopedEnumerations) {
  4536. // We can't perform any more checking for type-dependent expressions.
  4537. if (From->isTypeDependent())
  4538. return Owned(From);
  4539. // Process placeholders immediately.
  4540. if (From->hasPlaceholderType()) {
  4541. ExprResult result = CheckPlaceholderExpr(From);
  4542. if (result.isInvalid()) return result;
  4543. From = result.take();
  4544. }
  4545. // If the expression already has integral or enumeration type, we're golden.
  4546. QualType T = From->getType();
  4547. if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
  4548. return DefaultLvalueConversion(From);
  4549. // FIXME: Check for missing '()' if T is a function type?
  4550. // If we don't have a class type in C++, there's no way we can get an
  4551. // expression of integral or enumeration type.
  4552. const RecordType *RecordTy = T->getAs<RecordType>();
  4553. if (!RecordTy || !getLangOpts().CPlusPlus) {
  4554. if (!Diagnoser.Suppress)
  4555. Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
  4556. return Owned(From);
  4557. }
  4558. // We must have a complete class type.
  4559. struct TypeDiagnoserPartialDiag : TypeDiagnoser {
  4560. ICEConvertDiagnoser &Diagnoser;
  4561. Expr *From;
  4562. TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
  4563. : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
  4564. virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
  4565. Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
  4566. }
  4567. } IncompleteDiagnoser(Diagnoser, From);
  4568. if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
  4569. return Owned(From);
  4570. // Look for a conversion to an integral or enumeration type.
  4571. UnresolvedSet<4> ViableConversions;
  4572. UnresolvedSet<4> ExplicitConversions;
  4573. const UnresolvedSetImpl *Conversions
  4574. = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
  4575. bool HadMultipleCandidates = (Conversions->size() > 1);
  4576. for (UnresolvedSetImpl::iterator I = Conversions->begin(),
  4577. E = Conversions->end();
  4578. I != E;
  4579. ++I) {
  4580. if (CXXConversionDecl *Conversion
  4581. = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
  4582. if (isIntegralOrEnumerationType(
  4583. Conversion->getConversionType().getNonReferenceType(),
  4584. AllowScopedEnumerations)) {
  4585. if (Conversion->isExplicit())
  4586. ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
  4587. else
  4588. ViableConversions.addDecl(I.getDecl(), I.getAccess());
  4589. }
  4590. }
  4591. }
  4592. switch (ViableConversions.size()) {
  4593. case 0:
  4594. if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
  4595. DeclAccessPair Found = ExplicitConversions[0];
  4596. CXXConversionDecl *Conversion
  4597. = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4598. // The user probably meant to invoke the given explicit
  4599. // conversion; use it.
  4600. QualType ConvTy
  4601. = Conversion->getConversionType().getNonReferenceType();
  4602. std::string TypeStr;
  4603. ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
  4604. Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
  4605. << FixItHint::CreateInsertion(From->getLocStart(),
  4606. "static_cast<" + TypeStr + ">(")
  4607. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
  4608. ")");
  4609. Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
  4610. // If we aren't in a SFINAE context, build a call to the
  4611. // explicit conversion function.
  4612. if (isSFINAEContext())
  4613. return ExprError();
  4614. CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
  4615. ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
  4616. HadMultipleCandidates);
  4617. if (Result.isInvalid())
  4618. return ExprError();
  4619. // Record usage of conversion in an implicit cast.
  4620. From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
  4621. CK_UserDefinedConversion,
  4622. Result.get(), 0,
  4623. Result.get()->getValueKind());
  4624. }
  4625. // We'll complain below about a non-integral condition type.
  4626. break;
  4627. case 1: {
  4628. // Apply this conversion.
  4629. DeclAccessPair Found = ViableConversions[0];
  4630. CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
  4631. CXXConversionDecl *Conversion
  4632. = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
  4633. QualType ConvTy
  4634. = Conversion->getConversionType().getNonReferenceType();
  4635. if (!Diagnoser.SuppressConversion) {
  4636. if (isSFINAEContext())
  4637. return ExprError();
  4638. Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
  4639. << From->getSourceRange();
  4640. }
  4641. ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
  4642. HadMultipleCandidates);
  4643. if (Result.isInvalid())
  4644. return ExprError();
  4645. // Record usage of conversion in an implicit cast.
  4646. From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
  4647. CK_UserDefinedConversion,
  4648. Result.get(), 0,
  4649. Result.get()->getValueKind());
  4650. break;
  4651. }
  4652. default:
  4653. if (Diagnoser.Suppress)
  4654. return ExprError();
  4655. Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
  4656. for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
  4657. CXXConversionDecl *Conv
  4658. = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
  4659. QualType ConvTy = Conv->getConversionType().getNonReferenceType();
  4660. Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
  4661. }
  4662. return Owned(From);
  4663. }
  4664. if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
  4665. !Diagnoser.Suppress) {
  4666. Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
  4667. << From->getSourceRange();
  4668. }
  4669. return DefaultLvalueConversion(From);
  4670. }
  4671. /// AddOverloadCandidate - Adds the given function to the set of
  4672. /// candidate functions, using the given function call arguments. If
  4673. /// @p SuppressUserConversions, then don't allow user-defined
  4674. /// conversions via constructors or conversion operators.
  4675. ///
  4676. /// \param PartialOverloading true if we are performing "partial" overloading
  4677. /// based on an incomplete set of function arguments. This feature is used by
  4678. /// code completion.
  4679. void
  4680. Sema::AddOverloadCandidate(FunctionDecl *Function,
  4681. DeclAccessPair FoundDecl,
  4682. llvm::ArrayRef<Expr *> Args,
  4683. OverloadCandidateSet& CandidateSet,
  4684. bool SuppressUserConversions,
  4685. bool PartialOverloading,
  4686. bool AllowExplicit) {
  4687. const FunctionProtoType* Proto
  4688. = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
  4689. assert(Proto && "Functions without a prototype cannot be overloaded");
  4690. assert(!Function->getDescribedFunctionTemplate() &&
  4691. "Use AddTemplateOverloadCandidate for function templates");
  4692. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
  4693. if (!isa<CXXConstructorDecl>(Method)) {
  4694. // If we get here, it's because we're calling a member function
  4695. // that is named without a member access expression (e.g.,
  4696. // "this->f") that was either written explicitly or created
  4697. // implicitly. This can happen with a qualified call to a member
  4698. // function, e.g., X::f(). We use an empty type for the implied
  4699. // object argument (C++ [over.call.func]p3), and the acting context
  4700. // is irrelevant.
  4701. AddMethodCandidate(Method, FoundDecl, Method->getParent(),
  4702. QualType(), Expr::Classification::makeSimpleLValue(),
  4703. Args, CandidateSet, SuppressUserConversions);
  4704. return;
  4705. }
  4706. // We treat a constructor like a non-member function, since its object
  4707. // argument doesn't participate in overload resolution.
  4708. }
  4709. if (!CandidateSet.isNewCandidate(Function))
  4710. return;
  4711. // Overload resolution is always an unevaluated context.
  4712. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  4713. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
  4714. // C++ [class.copy]p3:
  4715. // A member function template is never instantiated to perform the copy
  4716. // of a class object to an object of its class type.
  4717. QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
  4718. if (Args.size() == 1 &&
  4719. Constructor->isSpecializationCopyingObject() &&
  4720. (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
  4721. IsDerivedFrom(Args[0]->getType(), ClassType)))
  4722. return;
  4723. }
  4724. // Add this candidate
  4725. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
  4726. Candidate.FoundDecl = FoundDecl;
  4727. Candidate.Function = Function;
  4728. Candidate.Viable = true;
  4729. Candidate.IsSurrogate = false;
  4730. Candidate.IgnoreObjectArgument = false;
  4731. Candidate.ExplicitCallArguments = Args.size();
  4732. unsigned NumArgsInProto = Proto->getNumArgs();
  4733. // (C++ 13.3.2p2): A candidate function having fewer than m
  4734. // parameters is viable only if it has an ellipsis in its parameter
  4735. // list (8.3.5).
  4736. if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
  4737. !Proto->isVariadic()) {
  4738. Candidate.Viable = false;
  4739. Candidate.FailureKind = ovl_fail_too_many_arguments;
  4740. return;
  4741. }
  4742. // (C++ 13.3.2p2): A candidate function having more than m parameters
  4743. // is viable only if the (m+1)st parameter has a default argument
  4744. // (8.3.6). For the purposes of overload resolution, the
  4745. // parameter list is truncated on the right, so that there are
  4746. // exactly m parameters.
  4747. unsigned MinRequiredArgs = Function->getMinRequiredArguments();
  4748. if (Args.size() < MinRequiredArgs && !PartialOverloading) {
  4749. // Not enough arguments.
  4750. Candidate.Viable = false;
  4751. Candidate.FailureKind = ovl_fail_too_few_arguments;
  4752. return;
  4753. }
  4754. // (CUDA B.1): Check for invalid calls between targets.
  4755. if (getLangOpts().CUDA)
  4756. if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
  4757. if (CheckCUDATarget(Caller, Function)) {
  4758. Candidate.Viable = false;
  4759. Candidate.FailureKind = ovl_fail_bad_target;
  4760. return;
  4761. }
  4762. // Determine the implicit conversion sequences for each of the
  4763. // arguments.
  4764. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  4765. if (ArgIdx < NumArgsInProto) {
  4766. // (C++ 13.3.2p3): for F to be a viable function, there shall
  4767. // exist for each argument an implicit conversion sequence
  4768. // (13.3.3.1) that converts that argument to the corresponding
  4769. // parameter of F.
  4770. QualType ParamType = Proto->getArgType(ArgIdx);
  4771. Candidate.Conversions[ArgIdx]
  4772. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  4773. SuppressUserConversions,
  4774. /*InOverloadResolution=*/true,
  4775. /*AllowObjCWritebackConversion=*/
  4776. getLangOpts().ObjCAutoRefCount,
  4777. AllowExplicit);
  4778. if (Candidate.Conversions[ArgIdx].isBad()) {
  4779. Candidate.Viable = false;
  4780. Candidate.FailureKind = ovl_fail_bad_conversion;
  4781. break;
  4782. }
  4783. } else {
  4784. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  4785. // argument for which there is no corresponding parameter is
  4786. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  4787. Candidate.Conversions[ArgIdx].setEllipsis();
  4788. }
  4789. }
  4790. }
  4791. /// \brief Add all of the function declarations in the given function set to
  4792. /// the overload canddiate set.
  4793. void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
  4794. llvm::ArrayRef<Expr *> Args,
  4795. OverloadCandidateSet& CandidateSet,
  4796. bool SuppressUserConversions,
  4797. TemplateArgumentListInfo *ExplicitTemplateArgs) {
  4798. for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
  4799. NamedDecl *D = F.getDecl()->getUnderlyingDecl();
  4800. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  4801. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  4802. AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
  4803. cast<CXXMethodDecl>(FD)->getParent(),
  4804. Args[0]->getType(), Args[0]->Classify(Context),
  4805. Args.slice(1), CandidateSet,
  4806. SuppressUserConversions);
  4807. else
  4808. AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
  4809. SuppressUserConversions);
  4810. } else {
  4811. FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
  4812. if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
  4813. !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
  4814. AddMethodTemplateCandidate(FunTmpl, F.getPair(),
  4815. cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
  4816. ExplicitTemplateArgs,
  4817. Args[0]->getType(),
  4818. Args[0]->Classify(Context), Args.slice(1),
  4819. CandidateSet, SuppressUserConversions);
  4820. else
  4821. AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
  4822. ExplicitTemplateArgs, Args,
  4823. CandidateSet, SuppressUserConversions);
  4824. }
  4825. }
  4826. }
  4827. /// AddMethodCandidate - Adds a named decl (which is some kind of
  4828. /// method) as a method candidate to the given overload set.
  4829. void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
  4830. QualType ObjectType,
  4831. Expr::Classification ObjectClassification,
  4832. Expr **Args, unsigned NumArgs,
  4833. OverloadCandidateSet& CandidateSet,
  4834. bool SuppressUserConversions) {
  4835. NamedDecl *Decl = FoundDecl.getDecl();
  4836. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
  4837. if (isa<UsingShadowDecl>(Decl))
  4838. Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
  4839. if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
  4840. assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
  4841. "Expected a member function template");
  4842. AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
  4843. /*ExplicitArgs*/ 0,
  4844. ObjectType, ObjectClassification,
  4845. llvm::makeArrayRef(Args, NumArgs), CandidateSet,
  4846. SuppressUserConversions);
  4847. } else {
  4848. AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
  4849. ObjectType, ObjectClassification,
  4850. llvm::makeArrayRef(Args, NumArgs),
  4851. CandidateSet, SuppressUserConversions);
  4852. }
  4853. }
  4854. /// AddMethodCandidate - Adds the given C++ member function to the set
  4855. /// of candidate functions, using the given function call arguments
  4856. /// and the object argument (@c Object). For example, in a call
  4857. /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
  4858. /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
  4859. /// allow user-defined conversions via constructors or conversion
  4860. /// operators.
  4861. void
  4862. Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
  4863. CXXRecordDecl *ActingContext, QualType ObjectType,
  4864. Expr::Classification ObjectClassification,
  4865. llvm::ArrayRef<Expr *> Args,
  4866. OverloadCandidateSet& CandidateSet,
  4867. bool SuppressUserConversions) {
  4868. const FunctionProtoType* Proto
  4869. = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
  4870. assert(Proto && "Methods without a prototype cannot be overloaded");
  4871. assert(!isa<CXXConstructorDecl>(Method) &&
  4872. "Use AddOverloadCandidate for constructors");
  4873. if (!CandidateSet.isNewCandidate(Method))
  4874. return;
  4875. // Overload resolution is always an unevaluated context.
  4876. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  4877. // Add this candidate
  4878. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  4879. Candidate.FoundDecl = FoundDecl;
  4880. Candidate.Function = Method;
  4881. Candidate.IsSurrogate = false;
  4882. Candidate.IgnoreObjectArgument = false;
  4883. Candidate.ExplicitCallArguments = Args.size();
  4884. unsigned NumArgsInProto = Proto->getNumArgs();
  4885. // (C++ 13.3.2p2): A candidate function having fewer than m
  4886. // parameters is viable only if it has an ellipsis in its parameter
  4887. // list (8.3.5).
  4888. if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
  4889. Candidate.Viable = false;
  4890. Candidate.FailureKind = ovl_fail_too_many_arguments;
  4891. return;
  4892. }
  4893. // (C++ 13.3.2p2): A candidate function having more than m parameters
  4894. // is viable only if the (m+1)st parameter has a default argument
  4895. // (8.3.6). For the purposes of overload resolution, the
  4896. // parameter list is truncated on the right, so that there are
  4897. // exactly m parameters.
  4898. unsigned MinRequiredArgs = Method->getMinRequiredArguments();
  4899. if (Args.size() < MinRequiredArgs) {
  4900. // Not enough arguments.
  4901. Candidate.Viable = false;
  4902. Candidate.FailureKind = ovl_fail_too_few_arguments;
  4903. return;
  4904. }
  4905. Candidate.Viable = true;
  4906. if (Method->isStatic() || ObjectType.isNull())
  4907. // The implicit object argument is ignored.
  4908. Candidate.IgnoreObjectArgument = true;
  4909. else {
  4910. // Determine the implicit conversion sequence for the object
  4911. // parameter.
  4912. Candidate.Conversions[0]
  4913. = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
  4914. Method, ActingContext);
  4915. if (Candidate.Conversions[0].isBad()) {
  4916. Candidate.Viable = false;
  4917. Candidate.FailureKind = ovl_fail_bad_conversion;
  4918. return;
  4919. }
  4920. }
  4921. // Determine the implicit conversion sequences for each of the
  4922. // arguments.
  4923. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  4924. if (ArgIdx < NumArgsInProto) {
  4925. // (C++ 13.3.2p3): for F to be a viable function, there shall
  4926. // exist for each argument an implicit conversion sequence
  4927. // (13.3.3.1) that converts that argument to the corresponding
  4928. // parameter of F.
  4929. QualType ParamType = Proto->getArgType(ArgIdx);
  4930. Candidate.Conversions[ArgIdx + 1]
  4931. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  4932. SuppressUserConversions,
  4933. /*InOverloadResolution=*/true,
  4934. /*AllowObjCWritebackConversion=*/
  4935. getLangOpts().ObjCAutoRefCount);
  4936. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  4937. Candidate.Viable = false;
  4938. Candidate.FailureKind = ovl_fail_bad_conversion;
  4939. break;
  4940. }
  4941. } else {
  4942. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  4943. // argument for which there is no corresponding parameter is
  4944. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  4945. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  4946. }
  4947. }
  4948. }
  4949. /// \brief Add a C++ member function template as a candidate to the candidate
  4950. /// set, using template argument deduction to produce an appropriate member
  4951. /// function template specialization.
  4952. void
  4953. Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
  4954. DeclAccessPair FoundDecl,
  4955. CXXRecordDecl *ActingContext,
  4956. TemplateArgumentListInfo *ExplicitTemplateArgs,
  4957. QualType ObjectType,
  4958. Expr::Classification ObjectClassification,
  4959. llvm::ArrayRef<Expr *> Args,
  4960. OverloadCandidateSet& CandidateSet,
  4961. bool SuppressUserConversions) {
  4962. if (!CandidateSet.isNewCandidate(MethodTmpl))
  4963. return;
  4964. // C++ [over.match.funcs]p7:
  4965. // In each case where a candidate is a function template, candidate
  4966. // function template specializations are generated using template argument
  4967. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  4968. // candidate functions in the usual way.113) A given name can refer to one
  4969. // or more function templates and also to a set of overloaded non-template
  4970. // functions. In such a case, the candidate functions generated from each
  4971. // function template are combined with the set of non-template candidate
  4972. // functions.
  4973. TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
  4974. FunctionDecl *Specialization = 0;
  4975. if (TemplateDeductionResult Result
  4976. = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
  4977. Specialization, Info)) {
  4978. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  4979. Candidate.FoundDecl = FoundDecl;
  4980. Candidate.Function = MethodTmpl->getTemplatedDecl();
  4981. Candidate.Viable = false;
  4982. Candidate.FailureKind = ovl_fail_bad_deduction;
  4983. Candidate.IsSurrogate = false;
  4984. Candidate.IgnoreObjectArgument = false;
  4985. Candidate.ExplicitCallArguments = Args.size();
  4986. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  4987. Info);
  4988. return;
  4989. }
  4990. // Add the function template specialization produced by template argument
  4991. // deduction as a candidate.
  4992. assert(Specialization && "Missing member function template specialization?");
  4993. assert(isa<CXXMethodDecl>(Specialization) &&
  4994. "Specialization is not a member function?");
  4995. AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
  4996. ActingContext, ObjectType, ObjectClassification, Args,
  4997. CandidateSet, SuppressUserConversions);
  4998. }
  4999. /// \brief Add a C++ function template specialization as a candidate
  5000. /// in the candidate set, using template argument deduction to produce
  5001. /// an appropriate function template specialization.
  5002. void
  5003. Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
  5004. DeclAccessPair FoundDecl,
  5005. TemplateArgumentListInfo *ExplicitTemplateArgs,
  5006. llvm::ArrayRef<Expr *> Args,
  5007. OverloadCandidateSet& CandidateSet,
  5008. bool SuppressUserConversions) {
  5009. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5010. return;
  5011. // C++ [over.match.funcs]p7:
  5012. // In each case where a candidate is a function template, candidate
  5013. // function template specializations are generated using template argument
  5014. // deduction (14.8.3, 14.8.2). Those candidates are then handled as
  5015. // candidate functions in the usual way.113) A given name can refer to one
  5016. // or more function templates and also to a set of overloaded non-template
  5017. // functions. In such a case, the candidate functions generated from each
  5018. // function template are combined with the set of non-template candidate
  5019. // functions.
  5020. TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
  5021. FunctionDecl *Specialization = 0;
  5022. if (TemplateDeductionResult Result
  5023. = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
  5024. Specialization, Info)) {
  5025. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5026. Candidate.FoundDecl = FoundDecl;
  5027. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5028. Candidate.Viable = false;
  5029. Candidate.FailureKind = ovl_fail_bad_deduction;
  5030. Candidate.IsSurrogate = false;
  5031. Candidate.IgnoreObjectArgument = false;
  5032. Candidate.ExplicitCallArguments = Args.size();
  5033. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5034. Info);
  5035. return;
  5036. }
  5037. // Add the function template specialization produced by template argument
  5038. // deduction as a candidate.
  5039. assert(Specialization && "Missing function template specialization?");
  5040. AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
  5041. SuppressUserConversions);
  5042. }
  5043. /// AddConversionCandidate - Add a C++ conversion function as a
  5044. /// candidate in the candidate set (C++ [over.match.conv],
  5045. /// C++ [over.match.copy]). From is the expression we're converting from,
  5046. /// and ToType is the type that we're eventually trying to convert to
  5047. /// (which may or may not be the same type as the type that the
  5048. /// conversion function produces).
  5049. void
  5050. Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
  5051. DeclAccessPair FoundDecl,
  5052. CXXRecordDecl *ActingContext,
  5053. Expr *From, QualType ToType,
  5054. OverloadCandidateSet& CandidateSet) {
  5055. assert(!Conversion->getDescribedFunctionTemplate() &&
  5056. "Conversion function templates use AddTemplateConversionCandidate");
  5057. QualType ConvType = Conversion->getConversionType().getNonReferenceType();
  5058. if (!CandidateSet.isNewCandidate(Conversion))
  5059. return;
  5060. // Overload resolution is always an unevaluated context.
  5061. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5062. // Add this candidate
  5063. OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
  5064. Candidate.FoundDecl = FoundDecl;
  5065. Candidate.Function = Conversion;
  5066. Candidate.IsSurrogate = false;
  5067. Candidate.IgnoreObjectArgument = false;
  5068. Candidate.FinalConversion.setAsIdentityConversion();
  5069. Candidate.FinalConversion.setFromType(ConvType);
  5070. Candidate.FinalConversion.setAllToTypes(ToType);
  5071. Candidate.Viable = true;
  5072. Candidate.ExplicitCallArguments = 1;
  5073. // C++ [over.match.funcs]p4:
  5074. // For conversion functions, the function is considered to be a member of
  5075. // the class of the implicit implied object argument for the purpose of
  5076. // defining the type of the implicit object parameter.
  5077. //
  5078. // Determine the implicit conversion sequence for the implicit
  5079. // object parameter.
  5080. QualType ImplicitParamType = From->getType();
  5081. if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
  5082. ImplicitParamType = FromPtrType->getPointeeType();
  5083. CXXRecordDecl *ConversionContext
  5084. = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
  5085. Candidate.Conversions[0]
  5086. = TryObjectArgumentInitialization(*this, From->getType(),
  5087. From->Classify(Context),
  5088. Conversion, ConversionContext);
  5089. if (Candidate.Conversions[0].isBad()) {
  5090. Candidate.Viable = false;
  5091. Candidate.FailureKind = ovl_fail_bad_conversion;
  5092. return;
  5093. }
  5094. // We won't go through a user-define type conversion function to convert a
  5095. // derived to base as such conversions are given Conversion Rank. They only
  5096. // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
  5097. QualType FromCanon
  5098. = Context.getCanonicalType(From->getType().getUnqualifiedType());
  5099. QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
  5100. if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
  5101. Candidate.Viable = false;
  5102. Candidate.FailureKind = ovl_fail_trivial_conversion;
  5103. return;
  5104. }
  5105. // To determine what the conversion from the result of calling the
  5106. // conversion function to the type we're eventually trying to
  5107. // convert to (ToType), we need to synthesize a call to the
  5108. // conversion function and attempt copy initialization from it. This
  5109. // makes sure that we get the right semantics with respect to
  5110. // lvalues/rvalues and the type. Fortunately, we can allocate this
  5111. // call on the stack and we don't need its arguments to be
  5112. // well-formed.
  5113. DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
  5114. VK_LValue, From->getLocStart());
  5115. ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
  5116. Context.getPointerType(Conversion->getType()),
  5117. CK_FunctionToPointerDecay,
  5118. &ConversionRef, VK_RValue);
  5119. QualType ConversionType = Conversion->getConversionType();
  5120. if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
  5121. Candidate.Viable = false;
  5122. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5123. return;
  5124. }
  5125. ExprValueKind VK = Expr::getValueKindForType(ConversionType);
  5126. // Note that it is safe to allocate CallExpr on the stack here because
  5127. // there are 0 arguments (i.e., nothing is allocated using ASTContext's
  5128. // allocator).
  5129. QualType CallResultType = ConversionType.getNonLValueExprType(Context);
  5130. CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
  5131. From->getLocStart());
  5132. ImplicitConversionSequence ICS =
  5133. TryCopyInitialization(*this, &Call, ToType,
  5134. /*SuppressUserConversions=*/true,
  5135. /*InOverloadResolution=*/false,
  5136. /*AllowObjCWritebackConversion=*/false);
  5137. switch (ICS.getKind()) {
  5138. case ImplicitConversionSequence::StandardConversion:
  5139. Candidate.FinalConversion = ICS.Standard;
  5140. // C++ [over.ics.user]p3:
  5141. // If the user-defined conversion is specified by a specialization of a
  5142. // conversion function template, the second standard conversion sequence
  5143. // shall have exact match rank.
  5144. if (Conversion->getPrimaryTemplate() &&
  5145. GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
  5146. Candidate.Viable = false;
  5147. Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
  5148. }
  5149. // C++0x [dcl.init.ref]p5:
  5150. // In the second case, if the reference is an rvalue reference and
  5151. // the second standard conversion sequence of the user-defined
  5152. // conversion sequence includes an lvalue-to-rvalue conversion, the
  5153. // program is ill-formed.
  5154. if (ToType->isRValueReferenceType() &&
  5155. ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
  5156. Candidate.Viable = false;
  5157. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5158. }
  5159. break;
  5160. case ImplicitConversionSequence::BadConversion:
  5161. Candidate.Viable = false;
  5162. Candidate.FailureKind = ovl_fail_bad_final_conversion;
  5163. break;
  5164. default:
  5165. llvm_unreachable(
  5166. "Can only end up with a standard conversion sequence or failure");
  5167. }
  5168. }
  5169. /// \brief Adds a conversion function template specialization
  5170. /// candidate to the overload set, using template argument deduction
  5171. /// to deduce the template arguments of the conversion function
  5172. /// template from the type that we are converting to (C++
  5173. /// [temp.deduct.conv]).
  5174. void
  5175. Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
  5176. DeclAccessPair FoundDecl,
  5177. CXXRecordDecl *ActingDC,
  5178. Expr *From, QualType ToType,
  5179. OverloadCandidateSet &CandidateSet) {
  5180. assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
  5181. "Only conversion function templates permitted here");
  5182. if (!CandidateSet.isNewCandidate(FunctionTemplate))
  5183. return;
  5184. TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
  5185. CXXConversionDecl *Specialization = 0;
  5186. if (TemplateDeductionResult Result
  5187. = DeduceTemplateArguments(FunctionTemplate, ToType,
  5188. Specialization, Info)) {
  5189. OverloadCandidate &Candidate = CandidateSet.addCandidate();
  5190. Candidate.FoundDecl = FoundDecl;
  5191. Candidate.Function = FunctionTemplate->getTemplatedDecl();
  5192. Candidate.Viable = false;
  5193. Candidate.FailureKind = ovl_fail_bad_deduction;
  5194. Candidate.IsSurrogate = false;
  5195. Candidate.IgnoreObjectArgument = false;
  5196. Candidate.ExplicitCallArguments = 1;
  5197. Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
  5198. Info);
  5199. return;
  5200. }
  5201. // Add the conversion function template specialization produced by
  5202. // template argument deduction as a candidate.
  5203. assert(Specialization && "Missing function template specialization?");
  5204. AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
  5205. CandidateSet);
  5206. }
  5207. /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
  5208. /// converts the given @c Object to a function pointer via the
  5209. /// conversion function @c Conversion, and then attempts to call it
  5210. /// with the given arguments (C++ [over.call.object]p2-4). Proto is
  5211. /// the type of function that we'll eventually be calling.
  5212. void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
  5213. DeclAccessPair FoundDecl,
  5214. CXXRecordDecl *ActingContext,
  5215. const FunctionProtoType *Proto,
  5216. Expr *Object,
  5217. llvm::ArrayRef<Expr *> Args,
  5218. OverloadCandidateSet& CandidateSet) {
  5219. if (!CandidateSet.isNewCandidate(Conversion))
  5220. return;
  5221. // Overload resolution is always an unevaluated context.
  5222. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5223. OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
  5224. Candidate.FoundDecl = FoundDecl;
  5225. Candidate.Function = 0;
  5226. Candidate.Surrogate = Conversion;
  5227. Candidate.Viable = true;
  5228. Candidate.IsSurrogate = true;
  5229. Candidate.IgnoreObjectArgument = false;
  5230. Candidate.ExplicitCallArguments = Args.size();
  5231. // Determine the implicit conversion sequence for the implicit
  5232. // object parameter.
  5233. ImplicitConversionSequence ObjectInit
  5234. = TryObjectArgumentInitialization(*this, Object->getType(),
  5235. Object->Classify(Context),
  5236. Conversion, ActingContext);
  5237. if (ObjectInit.isBad()) {
  5238. Candidate.Viable = false;
  5239. Candidate.FailureKind = ovl_fail_bad_conversion;
  5240. Candidate.Conversions[0] = ObjectInit;
  5241. return;
  5242. }
  5243. // The first conversion is actually a user-defined conversion whose
  5244. // first conversion is ObjectInit's standard conversion (which is
  5245. // effectively a reference binding). Record it as such.
  5246. Candidate.Conversions[0].setUserDefined();
  5247. Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
  5248. Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
  5249. Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
  5250. Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
  5251. Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
  5252. Candidate.Conversions[0].UserDefined.After
  5253. = Candidate.Conversions[0].UserDefined.Before;
  5254. Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
  5255. // Find the
  5256. unsigned NumArgsInProto = Proto->getNumArgs();
  5257. // (C++ 13.3.2p2): A candidate function having fewer than m
  5258. // parameters is viable only if it has an ellipsis in its parameter
  5259. // list (8.3.5).
  5260. if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
  5261. Candidate.Viable = false;
  5262. Candidate.FailureKind = ovl_fail_too_many_arguments;
  5263. return;
  5264. }
  5265. // Function types don't have any default arguments, so just check if
  5266. // we have enough arguments.
  5267. if (Args.size() < NumArgsInProto) {
  5268. // Not enough arguments.
  5269. Candidate.Viable = false;
  5270. Candidate.FailureKind = ovl_fail_too_few_arguments;
  5271. return;
  5272. }
  5273. // Determine the implicit conversion sequences for each of the
  5274. // arguments.
  5275. for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
  5276. if (ArgIdx < NumArgsInProto) {
  5277. // (C++ 13.3.2p3): for F to be a viable function, there shall
  5278. // exist for each argument an implicit conversion sequence
  5279. // (13.3.3.1) that converts that argument to the corresponding
  5280. // parameter of F.
  5281. QualType ParamType = Proto->getArgType(ArgIdx);
  5282. Candidate.Conversions[ArgIdx + 1]
  5283. = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
  5284. /*SuppressUserConversions=*/false,
  5285. /*InOverloadResolution=*/false,
  5286. /*AllowObjCWritebackConversion=*/
  5287. getLangOpts().ObjCAutoRefCount);
  5288. if (Candidate.Conversions[ArgIdx + 1].isBad()) {
  5289. Candidate.Viable = false;
  5290. Candidate.FailureKind = ovl_fail_bad_conversion;
  5291. break;
  5292. }
  5293. } else {
  5294. // (C++ 13.3.2p2): For the purposes of overload resolution, any
  5295. // argument for which there is no corresponding parameter is
  5296. // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
  5297. Candidate.Conversions[ArgIdx + 1].setEllipsis();
  5298. }
  5299. }
  5300. }
  5301. /// \brief Add overload candidates for overloaded operators that are
  5302. /// member functions.
  5303. ///
  5304. /// Add the overloaded operator candidates that are member functions
  5305. /// for the operator Op that was used in an operator expression such
  5306. /// as "x Op y". , Args/NumArgs provides the operator arguments, and
  5307. /// CandidateSet will store the added overload candidates. (C++
  5308. /// [over.match.oper]).
  5309. void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
  5310. SourceLocation OpLoc,
  5311. Expr **Args, unsigned NumArgs,
  5312. OverloadCandidateSet& CandidateSet,
  5313. SourceRange OpRange) {
  5314. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  5315. // C++ [over.match.oper]p3:
  5316. // For a unary operator @ with an operand of a type whose
  5317. // cv-unqualified version is T1, and for a binary operator @ with
  5318. // a left operand of a type whose cv-unqualified version is T1 and
  5319. // a right operand of a type whose cv-unqualified version is T2,
  5320. // three sets of candidate functions, designated member
  5321. // candidates, non-member candidates and built-in candidates, are
  5322. // constructed as follows:
  5323. QualType T1 = Args[0]->getType();
  5324. // -- If T1 is a class type, the set of member candidates is the
  5325. // result of the qualified lookup of T1::operator@
  5326. // (13.3.1.1.1); otherwise, the set of member candidates is
  5327. // empty.
  5328. if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
  5329. // Complete the type if it can be completed. Otherwise, we're done.
  5330. if (RequireCompleteType(OpLoc, T1, 0))
  5331. return;
  5332. LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
  5333. LookupQualifiedName(Operators, T1Rec->getDecl());
  5334. Operators.suppressDiagnostics();
  5335. for (LookupResult::iterator Oper = Operators.begin(),
  5336. OperEnd = Operators.end();
  5337. Oper != OperEnd;
  5338. ++Oper)
  5339. AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
  5340. Args[0]->Classify(Context), Args + 1, NumArgs - 1,
  5341. CandidateSet,
  5342. /* SuppressUserConversions = */ false);
  5343. }
  5344. }
  5345. /// AddBuiltinCandidate - Add a candidate for a built-in
  5346. /// operator. ResultTy and ParamTys are the result and parameter types
  5347. /// of the built-in candidate, respectively. Args and NumArgs are the
  5348. /// arguments being passed to the candidate. IsAssignmentOperator
  5349. /// should be true when this built-in candidate is an assignment
  5350. /// operator. NumContextualBoolArguments is the number of arguments
  5351. /// (at the beginning of the argument list) that will be contextually
  5352. /// converted to bool.
  5353. void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
  5354. Expr **Args, unsigned NumArgs,
  5355. OverloadCandidateSet& CandidateSet,
  5356. bool IsAssignmentOperator,
  5357. unsigned NumContextualBoolArguments) {
  5358. // Overload resolution is always an unevaluated context.
  5359. EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
  5360. // Add this candidate
  5361. OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
  5362. Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
  5363. Candidate.Function = 0;
  5364. Candidate.IsSurrogate = false;
  5365. Candidate.IgnoreObjectArgument = false;
  5366. Candidate.BuiltinTypes.ResultTy = ResultTy;
  5367. for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
  5368. Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
  5369. // Determine the implicit conversion sequences for each of the
  5370. // arguments.
  5371. Candidate.Viable = true;
  5372. Candidate.ExplicitCallArguments = NumArgs;
  5373. for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
  5374. // C++ [over.match.oper]p4:
  5375. // For the built-in assignment operators, conversions of the
  5376. // left operand are restricted as follows:
  5377. // -- no temporaries are introduced to hold the left operand, and
  5378. // -- no user-defined conversions are applied to the left
  5379. // operand to achieve a type match with the left-most
  5380. // parameter of a built-in candidate.
  5381. //
  5382. // We block these conversions by turning off user-defined
  5383. // conversions, since that is the only way that initialization of
  5384. // a reference to a non-class type can occur from something that
  5385. // is not of the same type.
  5386. if (ArgIdx < NumContextualBoolArguments) {
  5387. assert(ParamTys[ArgIdx] == Context.BoolTy &&
  5388. "Contextual conversion to bool requires bool type");
  5389. Candidate.Conversions[ArgIdx]
  5390. = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
  5391. } else {
  5392. Candidate.Conversions[ArgIdx]
  5393. = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
  5394. ArgIdx == 0 && IsAssignmentOperator,
  5395. /*InOverloadResolution=*/false,
  5396. /*AllowObjCWritebackConversion=*/
  5397. getLangOpts().ObjCAutoRefCount);
  5398. }
  5399. if (Candidate.Conversions[ArgIdx].isBad()) {
  5400. Candidate.Viable = false;
  5401. Candidate.FailureKind = ovl_fail_bad_conversion;
  5402. break;
  5403. }
  5404. }
  5405. }
  5406. /// BuiltinCandidateTypeSet - A set of types that will be used for the
  5407. /// candidate operator functions for built-in operators (C++
  5408. /// [over.built]). The types are separated into pointer types and
  5409. /// enumeration types.
  5410. class BuiltinCandidateTypeSet {
  5411. /// TypeSet - A set of types.
  5412. typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
  5413. /// PointerTypes - The set of pointer types that will be used in the
  5414. /// built-in candidates.
  5415. TypeSet PointerTypes;
  5416. /// MemberPointerTypes - The set of member pointer types that will be
  5417. /// used in the built-in candidates.
  5418. TypeSet MemberPointerTypes;
  5419. /// EnumerationTypes - The set of enumeration types that will be
  5420. /// used in the built-in candidates.
  5421. TypeSet EnumerationTypes;
  5422. /// \brief The set of vector types that will be used in the built-in
  5423. /// candidates.
  5424. TypeSet VectorTypes;
  5425. /// \brief A flag indicating non-record types are viable candidates
  5426. bool HasNonRecordTypes;
  5427. /// \brief A flag indicating whether either arithmetic or enumeration types
  5428. /// were present in the candidate set.
  5429. bool HasArithmeticOrEnumeralTypes;
  5430. /// \brief A flag indicating whether the nullptr type was present in the
  5431. /// candidate set.
  5432. bool HasNullPtrType;
  5433. /// Sema - The semantic analysis instance where we are building the
  5434. /// candidate type set.
  5435. Sema &SemaRef;
  5436. /// Context - The AST context in which we will build the type sets.
  5437. ASTContext &Context;
  5438. bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  5439. const Qualifiers &VisibleQuals);
  5440. bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
  5441. public:
  5442. /// iterator - Iterates through the types that are part of the set.
  5443. typedef TypeSet::iterator iterator;
  5444. BuiltinCandidateTypeSet(Sema &SemaRef)
  5445. : HasNonRecordTypes(false),
  5446. HasArithmeticOrEnumeralTypes(false),
  5447. HasNullPtrType(false),
  5448. SemaRef(SemaRef),
  5449. Context(SemaRef.Context) { }
  5450. void AddTypesConvertedFrom(QualType Ty,
  5451. SourceLocation Loc,
  5452. bool AllowUserConversions,
  5453. bool AllowExplicitConversions,
  5454. const Qualifiers &VisibleTypeConversionsQuals);
  5455. /// pointer_begin - First pointer type found;
  5456. iterator pointer_begin() { return PointerTypes.begin(); }
  5457. /// pointer_end - Past the last pointer type found;
  5458. iterator pointer_end() { return PointerTypes.end(); }
  5459. /// member_pointer_begin - First member pointer type found;
  5460. iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
  5461. /// member_pointer_end - Past the last member pointer type found;
  5462. iterator member_pointer_end() { return MemberPointerTypes.end(); }
  5463. /// enumeration_begin - First enumeration type found;
  5464. iterator enumeration_begin() { return EnumerationTypes.begin(); }
  5465. /// enumeration_end - Past the last enumeration type found;
  5466. iterator enumeration_end() { return EnumerationTypes.end(); }
  5467. iterator vector_begin() { return VectorTypes.begin(); }
  5468. iterator vector_end() { return VectorTypes.end(); }
  5469. bool hasNonRecordTypes() { return HasNonRecordTypes; }
  5470. bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
  5471. bool hasNullPtrType() const { return HasNullPtrType; }
  5472. };
  5473. /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
  5474. /// the set of pointer types along with any more-qualified variants of
  5475. /// that type. For example, if @p Ty is "int const *", this routine
  5476. /// will add "int const *", "int const volatile *", "int const
  5477. /// restrict *", and "int const volatile restrict *" to the set of
  5478. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  5479. /// false otherwise.
  5480. ///
  5481. /// FIXME: what to do about extended qualifiers?
  5482. bool
  5483. BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
  5484. const Qualifiers &VisibleQuals) {
  5485. // Insert this type.
  5486. if (!PointerTypes.insert(Ty))
  5487. return false;
  5488. QualType PointeeTy;
  5489. const PointerType *PointerTy = Ty->getAs<PointerType>();
  5490. bool buildObjCPtr = false;
  5491. if (!PointerTy) {
  5492. const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
  5493. PointeeTy = PTy->getPointeeType();
  5494. buildObjCPtr = true;
  5495. } else {
  5496. PointeeTy = PointerTy->getPointeeType();
  5497. }
  5498. // Don't add qualified variants of arrays. For one, they're not allowed
  5499. // (the qualifier would sink to the element type), and for another, the
  5500. // only overload situation where it matters is subscript or pointer +- int,
  5501. // and those shouldn't have qualifier variants anyway.
  5502. if (PointeeTy->isArrayType())
  5503. return true;
  5504. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  5505. bool hasVolatile = VisibleQuals.hasVolatile();
  5506. bool hasRestrict = VisibleQuals.hasRestrict();
  5507. // Iterate through all strict supersets of BaseCVR.
  5508. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  5509. if ((CVR | BaseCVR) != CVR) continue;
  5510. // Skip over volatile if no volatile found anywhere in the types.
  5511. if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
  5512. // Skip over restrict if no restrict found anywhere in the types, or if
  5513. // the type cannot be restrict-qualified.
  5514. if ((CVR & Qualifiers::Restrict) &&
  5515. (!hasRestrict ||
  5516. (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
  5517. continue;
  5518. // Build qualified pointee type.
  5519. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  5520. // Build qualified pointer type.
  5521. QualType QPointerTy;
  5522. if (!buildObjCPtr)
  5523. QPointerTy = Context.getPointerType(QPointeeTy);
  5524. else
  5525. QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
  5526. // Insert qualified pointer type.
  5527. PointerTypes.insert(QPointerTy);
  5528. }
  5529. return true;
  5530. }
  5531. /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
  5532. /// to the set of pointer types along with any more-qualified variants of
  5533. /// that type. For example, if @p Ty is "int const *", this routine
  5534. /// will add "int const *", "int const volatile *", "int const
  5535. /// restrict *", and "int const volatile restrict *" to the set of
  5536. /// pointer types. Returns true if the add of @p Ty itself succeeded,
  5537. /// false otherwise.
  5538. ///
  5539. /// FIXME: what to do about extended qualifiers?
  5540. bool
  5541. BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
  5542. QualType Ty) {
  5543. // Insert this type.
  5544. if (!MemberPointerTypes.insert(Ty))
  5545. return false;
  5546. const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
  5547. assert(PointerTy && "type was not a member pointer type!");
  5548. QualType PointeeTy = PointerTy->getPointeeType();
  5549. // Don't add qualified variants of arrays. For one, they're not allowed
  5550. // (the qualifier would sink to the element type), and for another, the
  5551. // only overload situation where it matters is subscript or pointer +- int,
  5552. // and those shouldn't have qualifier variants anyway.
  5553. if (PointeeTy->isArrayType())
  5554. return true;
  5555. const Type *ClassTy = PointerTy->getClass();
  5556. // Iterate through all strict supersets of the pointee type's CVR
  5557. // qualifiers.
  5558. unsigned BaseCVR = PointeeTy.getCVRQualifiers();
  5559. for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
  5560. if ((CVR | BaseCVR) != CVR) continue;
  5561. QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
  5562. MemberPointerTypes.insert(
  5563. Context.getMemberPointerType(QPointeeTy, ClassTy));
  5564. }
  5565. return true;
  5566. }
  5567. /// AddTypesConvertedFrom - Add each of the types to which the type @p
  5568. /// Ty can be implicit converted to the given set of @p Types. We're
  5569. /// primarily interested in pointer types and enumeration types. We also
  5570. /// take member pointer types, for the conditional operator.
  5571. /// AllowUserConversions is true if we should look at the conversion
  5572. /// functions of a class type, and AllowExplicitConversions if we
  5573. /// should also include the explicit conversion functions of a class
  5574. /// type.
  5575. void
  5576. BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
  5577. SourceLocation Loc,
  5578. bool AllowUserConversions,
  5579. bool AllowExplicitConversions,
  5580. const Qualifiers &VisibleQuals) {
  5581. // Only deal with canonical types.
  5582. Ty = Context.getCanonicalType(Ty);
  5583. // Look through reference types; they aren't part of the type of an
  5584. // expression for the purposes of conversions.
  5585. if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
  5586. Ty = RefTy->getPointeeType();
  5587. // If we're dealing with an array type, decay to the pointer.
  5588. if (Ty->isArrayType())
  5589. Ty = SemaRef.Context.getArrayDecayedType(Ty);
  5590. // Otherwise, we don't care about qualifiers on the type.
  5591. Ty = Ty.getLocalUnqualifiedType();
  5592. // Flag if we ever add a non-record type.
  5593. const RecordType *TyRec = Ty->getAs<RecordType>();
  5594. HasNonRecordTypes = HasNonRecordTypes || !TyRec;
  5595. // Flag if we encounter an arithmetic type.
  5596. HasArithmeticOrEnumeralTypes =
  5597. HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
  5598. if (Ty->isObjCIdType() || Ty->isObjCClassType())
  5599. PointerTypes.insert(Ty);
  5600. else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
  5601. // Insert our type, and its more-qualified variants, into the set
  5602. // of types.
  5603. if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
  5604. return;
  5605. } else if (Ty->isMemberPointerType()) {
  5606. // Member pointers are far easier, since the pointee can't be converted.
  5607. if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
  5608. return;
  5609. } else if (Ty->isEnumeralType()) {
  5610. HasArithmeticOrEnumeralTypes = true;
  5611. EnumerationTypes.insert(Ty);
  5612. } else if (Ty->isVectorType()) {
  5613. // We treat vector types as arithmetic types in many contexts as an
  5614. // extension.
  5615. HasArithmeticOrEnumeralTypes = true;
  5616. VectorTypes.insert(Ty);
  5617. } else if (Ty->isNullPtrType()) {
  5618. HasNullPtrType = true;
  5619. } else if (AllowUserConversions && TyRec) {
  5620. // No conversion functions in incomplete types.
  5621. if (SemaRef.RequireCompleteType(Loc, Ty, 0))
  5622. return;
  5623. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  5624. const UnresolvedSetImpl *Conversions
  5625. = ClassDecl->getVisibleConversionFunctions();
  5626. for (UnresolvedSetImpl::iterator I = Conversions->begin(),
  5627. E = Conversions->end(); I != E; ++I) {
  5628. NamedDecl *D = I.getDecl();
  5629. if (isa<UsingShadowDecl>(D))
  5630. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  5631. // Skip conversion function templates; they don't tell us anything
  5632. // about which builtin types we can convert to.
  5633. if (isa<FunctionTemplateDecl>(D))
  5634. continue;
  5635. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  5636. if (AllowExplicitConversions || !Conv->isExplicit()) {
  5637. AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
  5638. VisibleQuals);
  5639. }
  5640. }
  5641. }
  5642. }
  5643. /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
  5644. /// the volatile- and non-volatile-qualified assignment operators for the
  5645. /// given type to the candidate set.
  5646. static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
  5647. QualType T,
  5648. Expr **Args,
  5649. unsigned NumArgs,
  5650. OverloadCandidateSet &CandidateSet) {
  5651. QualType ParamTypes[2];
  5652. // T& operator=(T&, T)
  5653. ParamTypes[0] = S.Context.getLValueReferenceType(T);
  5654. ParamTypes[1] = T;
  5655. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
  5656. /*IsAssignmentOperator=*/true);
  5657. if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
  5658. // volatile T& operator=(volatile T&, T)
  5659. ParamTypes[0]
  5660. = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
  5661. ParamTypes[1] = T;
  5662. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
  5663. /*IsAssignmentOperator=*/true);
  5664. }
  5665. }
  5666. /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
  5667. /// if any, found in visible type conversion functions found in ArgExpr's type.
  5668. static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
  5669. Qualifiers VRQuals;
  5670. const RecordType *TyRec;
  5671. if (const MemberPointerType *RHSMPType =
  5672. ArgExpr->getType()->getAs<MemberPointerType>())
  5673. TyRec = RHSMPType->getClass()->getAs<RecordType>();
  5674. else
  5675. TyRec = ArgExpr->getType()->getAs<RecordType>();
  5676. if (!TyRec) {
  5677. // Just to be safe, assume the worst case.
  5678. VRQuals.addVolatile();
  5679. VRQuals.addRestrict();
  5680. return VRQuals;
  5681. }
  5682. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
  5683. if (!ClassDecl->hasDefinition())
  5684. return VRQuals;
  5685. const UnresolvedSetImpl *Conversions =
  5686. ClassDecl->getVisibleConversionFunctions();
  5687. for (UnresolvedSetImpl::iterator I = Conversions->begin(),
  5688. E = Conversions->end(); I != E; ++I) {
  5689. NamedDecl *D = I.getDecl();
  5690. if (isa<UsingShadowDecl>(D))
  5691. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  5692. if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
  5693. QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
  5694. if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
  5695. CanTy = ResTypeRef->getPointeeType();
  5696. // Need to go down the pointer/mempointer chain and add qualifiers
  5697. // as see them.
  5698. bool done = false;
  5699. while (!done) {
  5700. if (CanTy.isRestrictQualified())
  5701. VRQuals.addRestrict();
  5702. if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
  5703. CanTy = ResTypePtr->getPointeeType();
  5704. else if (const MemberPointerType *ResTypeMPtr =
  5705. CanTy->getAs<MemberPointerType>())
  5706. CanTy = ResTypeMPtr->getPointeeType();
  5707. else
  5708. done = true;
  5709. if (CanTy.isVolatileQualified())
  5710. VRQuals.addVolatile();
  5711. if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
  5712. return VRQuals;
  5713. }
  5714. }
  5715. }
  5716. return VRQuals;
  5717. }
  5718. namespace {
  5719. /// \brief Helper class to manage the addition of builtin operator overload
  5720. /// candidates. It provides shared state and utility methods used throughout
  5721. /// the process, as well as a helper method to add each group of builtin
  5722. /// operator overloads from the standard to a candidate set.
  5723. class BuiltinOperatorOverloadBuilder {
  5724. // Common instance state available to all overload candidate addition methods.
  5725. Sema &S;
  5726. Expr **Args;
  5727. unsigned NumArgs;
  5728. Qualifiers VisibleTypeConversionsQuals;
  5729. bool HasArithmeticOrEnumeralCandidateType;
  5730. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
  5731. OverloadCandidateSet &CandidateSet;
  5732. // Define some constants used to index and iterate over the arithemetic types
  5733. // provided via the getArithmeticType() method below.
  5734. // The "promoted arithmetic types" are the arithmetic
  5735. // types are that preserved by promotion (C++ [over.built]p2).
  5736. static const unsigned FirstIntegralType = 3;
  5737. static const unsigned LastIntegralType = 20;
  5738. static const unsigned FirstPromotedIntegralType = 3,
  5739. LastPromotedIntegralType = 11;
  5740. static const unsigned FirstPromotedArithmeticType = 0,
  5741. LastPromotedArithmeticType = 11;
  5742. static const unsigned NumArithmeticTypes = 20;
  5743. /// \brief Get the canonical type for a given arithmetic type index.
  5744. CanQualType getArithmeticType(unsigned index) {
  5745. assert(index < NumArithmeticTypes);
  5746. static CanQualType ASTContext::* const
  5747. ArithmeticTypes[NumArithmeticTypes] = {
  5748. // Start of promoted types.
  5749. &ASTContext::FloatTy,
  5750. &ASTContext::DoubleTy,
  5751. &ASTContext::LongDoubleTy,
  5752. // Start of integral types.
  5753. &ASTContext::IntTy,
  5754. &ASTContext::LongTy,
  5755. &ASTContext::LongLongTy,
  5756. &ASTContext::Int128Ty,
  5757. &ASTContext::UnsignedIntTy,
  5758. &ASTContext::UnsignedLongTy,
  5759. &ASTContext::UnsignedLongLongTy,
  5760. &ASTContext::UnsignedInt128Ty,
  5761. // End of promoted types.
  5762. &ASTContext::BoolTy,
  5763. &ASTContext::CharTy,
  5764. &ASTContext::WCharTy,
  5765. &ASTContext::Char16Ty,
  5766. &ASTContext::Char32Ty,
  5767. &ASTContext::SignedCharTy,
  5768. &ASTContext::ShortTy,
  5769. &ASTContext::UnsignedCharTy,
  5770. &ASTContext::UnsignedShortTy,
  5771. // End of integral types.
  5772. // FIXME: What about complex? What about half?
  5773. };
  5774. return S.Context.*ArithmeticTypes[index];
  5775. }
  5776. /// \brief Gets the canonical type resulting from the usual arithemetic
  5777. /// converions for the given arithmetic types.
  5778. CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
  5779. // Accelerator table for performing the usual arithmetic conversions.
  5780. // The rules are basically:
  5781. // - if either is floating-point, use the wider floating-point
  5782. // - if same signedness, use the higher rank
  5783. // - if same size, use unsigned of the higher rank
  5784. // - use the larger type
  5785. // These rules, together with the axiom that higher ranks are
  5786. // never smaller, are sufficient to precompute all of these results
  5787. // *except* when dealing with signed types of higher rank.
  5788. // (we could precompute SLL x UI for all known platforms, but it's
  5789. // better not to make any assumptions).
  5790. // We assume that int128 has a higher rank than long long on all platforms.
  5791. enum PromotedType {
  5792. Dep=-1,
  5793. Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
  5794. };
  5795. static const PromotedType ConversionsTable[LastPromotedArithmeticType]
  5796. [LastPromotedArithmeticType] = {
  5797. /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
  5798. /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
  5799. /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
  5800. /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
  5801. /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
  5802. /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
  5803. /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
  5804. /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
  5805. /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
  5806. /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
  5807. /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
  5808. };
  5809. assert(L < LastPromotedArithmeticType);
  5810. assert(R < LastPromotedArithmeticType);
  5811. int Idx = ConversionsTable[L][R];
  5812. // Fast path: the table gives us a concrete answer.
  5813. if (Idx != Dep) return getArithmeticType(Idx);
  5814. // Slow path: we need to compare widths.
  5815. // An invariant is that the signed type has higher rank.
  5816. CanQualType LT = getArithmeticType(L),
  5817. RT = getArithmeticType(R);
  5818. unsigned LW = S.Context.getIntWidth(LT),
  5819. RW = S.Context.getIntWidth(RT);
  5820. // If they're different widths, use the signed type.
  5821. if (LW > RW) return LT;
  5822. else if (LW < RW) return RT;
  5823. // Otherwise, use the unsigned type of the signed type's rank.
  5824. if (L == SL || R == SL) return S.Context.UnsignedLongTy;
  5825. assert(L == SLL || R == SLL);
  5826. return S.Context.UnsignedLongLongTy;
  5827. }
  5828. /// \brief Helper method to factor out the common pattern of adding overloads
  5829. /// for '++' and '--' builtin operators.
  5830. void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
  5831. bool HasVolatile,
  5832. bool HasRestrict) {
  5833. QualType ParamTypes[2] = {
  5834. S.Context.getLValueReferenceType(CandidateTy),
  5835. S.Context.IntTy
  5836. };
  5837. // Non-volatile version.
  5838. if (NumArgs == 1)
  5839. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
  5840. else
  5841. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
  5842. // Use a heuristic to reduce number of builtin candidates in the set:
  5843. // add volatile version only if there are conversions to a volatile type.
  5844. if (HasVolatile) {
  5845. ParamTypes[0] =
  5846. S.Context.getLValueReferenceType(
  5847. S.Context.getVolatileType(CandidateTy));
  5848. if (NumArgs == 1)
  5849. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
  5850. else
  5851. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
  5852. }
  5853. // Add restrict version only if there are conversions to a restrict type
  5854. // and our candidate type is a non-restrict-qualified pointer.
  5855. if (HasRestrict && CandidateTy->isAnyPointerType() &&
  5856. !CandidateTy.isRestrictQualified()) {
  5857. ParamTypes[0]
  5858. = S.Context.getLValueReferenceType(
  5859. S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
  5860. if (NumArgs == 1)
  5861. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
  5862. else
  5863. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
  5864. if (HasVolatile) {
  5865. ParamTypes[0]
  5866. = S.Context.getLValueReferenceType(
  5867. S.Context.getCVRQualifiedType(CandidateTy,
  5868. (Qualifiers::Volatile |
  5869. Qualifiers::Restrict)));
  5870. if (NumArgs == 1)
  5871. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
  5872. CandidateSet);
  5873. else
  5874. S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
  5875. }
  5876. }
  5877. }
  5878. public:
  5879. BuiltinOperatorOverloadBuilder(
  5880. Sema &S, Expr **Args, unsigned NumArgs,
  5881. Qualifiers VisibleTypeConversionsQuals,
  5882. bool HasArithmeticOrEnumeralCandidateType,
  5883. SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
  5884. OverloadCandidateSet &CandidateSet)
  5885. : S(S), Args(Args), NumArgs(NumArgs),
  5886. VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
  5887. HasArithmeticOrEnumeralCandidateType(
  5888. HasArithmeticOrEnumeralCandidateType),
  5889. CandidateTypes(CandidateTypes),
  5890. CandidateSet(CandidateSet) {
  5891. // Validate some of our static helper constants in debug builds.
  5892. assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
  5893. "Invalid first promoted integral type");
  5894. assert(getArithmeticType(LastPromotedIntegralType - 1)
  5895. == S.Context.UnsignedInt128Ty &&
  5896. "Invalid last promoted integral type");
  5897. assert(getArithmeticType(FirstPromotedArithmeticType)
  5898. == S.Context.FloatTy &&
  5899. "Invalid first promoted arithmetic type");
  5900. assert(getArithmeticType(LastPromotedArithmeticType - 1)
  5901. == S.Context.UnsignedInt128Ty &&
  5902. "Invalid last promoted arithmetic type");
  5903. }
  5904. // C++ [over.built]p3:
  5905. //
  5906. // For every pair (T, VQ), where T is an arithmetic type, and VQ
  5907. // is either volatile or empty, there exist candidate operator
  5908. // functions of the form
  5909. //
  5910. // VQ T& operator++(VQ T&);
  5911. // T operator++(VQ T&, int);
  5912. //
  5913. // C++ [over.built]p4:
  5914. //
  5915. // For every pair (T, VQ), where T is an arithmetic type other
  5916. // than bool, and VQ is either volatile or empty, there exist
  5917. // candidate operator functions of the form
  5918. //
  5919. // VQ T& operator--(VQ T&);
  5920. // T operator--(VQ T&, int);
  5921. void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
  5922. if (!HasArithmeticOrEnumeralCandidateType)
  5923. return;
  5924. for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
  5925. Arith < NumArithmeticTypes; ++Arith) {
  5926. addPlusPlusMinusMinusStyleOverloads(
  5927. getArithmeticType(Arith),
  5928. VisibleTypeConversionsQuals.hasVolatile(),
  5929. VisibleTypeConversionsQuals.hasRestrict());
  5930. }
  5931. }
  5932. // C++ [over.built]p5:
  5933. //
  5934. // For every pair (T, VQ), where T is a cv-qualified or
  5935. // cv-unqualified object type, and VQ is either volatile or
  5936. // empty, there exist candidate operator functions of the form
  5937. //
  5938. // T*VQ& operator++(T*VQ&);
  5939. // T*VQ& operator--(T*VQ&);
  5940. // T* operator++(T*VQ&, int);
  5941. // T* operator--(T*VQ&, int);
  5942. void addPlusPlusMinusMinusPointerOverloads() {
  5943. for (BuiltinCandidateTypeSet::iterator
  5944. Ptr = CandidateTypes[0].pointer_begin(),
  5945. PtrEnd = CandidateTypes[0].pointer_end();
  5946. Ptr != PtrEnd; ++Ptr) {
  5947. // Skip pointer types that aren't pointers to object types.
  5948. if (!(*Ptr)->getPointeeType()->isObjectType())
  5949. continue;
  5950. addPlusPlusMinusMinusStyleOverloads(*Ptr,
  5951. (!(*Ptr).isVolatileQualified() &&
  5952. VisibleTypeConversionsQuals.hasVolatile()),
  5953. (!(*Ptr).isRestrictQualified() &&
  5954. VisibleTypeConversionsQuals.hasRestrict()));
  5955. }
  5956. }
  5957. // C++ [over.built]p6:
  5958. // For every cv-qualified or cv-unqualified object type T, there
  5959. // exist candidate operator functions of the form
  5960. //
  5961. // T& operator*(T*);
  5962. //
  5963. // C++ [over.built]p7:
  5964. // For every function type T that does not have cv-qualifiers or a
  5965. // ref-qualifier, there exist candidate operator functions of the form
  5966. // T& operator*(T*);
  5967. void addUnaryStarPointerOverloads() {
  5968. for (BuiltinCandidateTypeSet::iterator
  5969. Ptr = CandidateTypes[0].pointer_begin(),
  5970. PtrEnd = CandidateTypes[0].pointer_end();
  5971. Ptr != PtrEnd; ++Ptr) {
  5972. QualType ParamTy = *Ptr;
  5973. QualType PointeeTy = ParamTy->getPointeeType();
  5974. if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
  5975. continue;
  5976. if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
  5977. if (Proto->getTypeQuals() || Proto->getRefQualifier())
  5978. continue;
  5979. S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
  5980. &ParamTy, Args, 1, CandidateSet);
  5981. }
  5982. }
  5983. // C++ [over.built]p9:
  5984. // For every promoted arithmetic type T, there exist candidate
  5985. // operator functions of the form
  5986. //
  5987. // T operator+(T);
  5988. // T operator-(T);
  5989. void addUnaryPlusOrMinusArithmeticOverloads() {
  5990. if (!HasArithmeticOrEnumeralCandidateType)
  5991. return;
  5992. for (unsigned Arith = FirstPromotedArithmeticType;
  5993. Arith < LastPromotedArithmeticType; ++Arith) {
  5994. QualType ArithTy = getArithmeticType(Arith);
  5995. S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
  5996. }
  5997. // Extension: We also add these operators for vector types.
  5998. for (BuiltinCandidateTypeSet::iterator
  5999. Vec = CandidateTypes[0].vector_begin(),
  6000. VecEnd = CandidateTypes[0].vector_end();
  6001. Vec != VecEnd; ++Vec) {
  6002. QualType VecTy = *Vec;
  6003. S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
  6004. }
  6005. }
  6006. // C++ [over.built]p8:
  6007. // For every type T, there exist candidate operator functions of
  6008. // the form
  6009. //
  6010. // T* operator+(T*);
  6011. void addUnaryPlusPointerOverloads() {
  6012. for (BuiltinCandidateTypeSet::iterator
  6013. Ptr = CandidateTypes[0].pointer_begin(),
  6014. PtrEnd = CandidateTypes[0].pointer_end();
  6015. Ptr != PtrEnd; ++Ptr) {
  6016. QualType ParamTy = *Ptr;
  6017. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
  6018. }
  6019. }
  6020. // C++ [over.built]p10:
  6021. // For every promoted integral type T, there exist candidate
  6022. // operator functions of the form
  6023. //
  6024. // T operator~(T);
  6025. void addUnaryTildePromotedIntegralOverloads() {
  6026. if (!HasArithmeticOrEnumeralCandidateType)
  6027. return;
  6028. for (unsigned Int = FirstPromotedIntegralType;
  6029. Int < LastPromotedIntegralType; ++Int) {
  6030. QualType IntTy = getArithmeticType(Int);
  6031. S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
  6032. }
  6033. // Extension: We also add this operator for vector types.
  6034. for (BuiltinCandidateTypeSet::iterator
  6035. Vec = CandidateTypes[0].vector_begin(),
  6036. VecEnd = CandidateTypes[0].vector_end();
  6037. Vec != VecEnd; ++Vec) {
  6038. QualType VecTy = *Vec;
  6039. S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
  6040. }
  6041. }
  6042. // C++ [over.match.oper]p16:
  6043. // For every pointer to member type T, there exist candidate operator
  6044. // functions of the form
  6045. //
  6046. // bool operator==(T,T);
  6047. // bool operator!=(T,T);
  6048. void addEqualEqualOrNotEqualMemberPointerOverloads() {
  6049. /// Set of (canonical) types that we've already handled.
  6050. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6051. for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
  6052. for (BuiltinCandidateTypeSet::iterator
  6053. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  6054. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  6055. MemPtr != MemPtrEnd;
  6056. ++MemPtr) {
  6057. // Don't add the same builtin candidate twice.
  6058. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
  6059. continue;
  6060. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  6061. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
  6062. CandidateSet);
  6063. }
  6064. }
  6065. }
  6066. // C++ [over.built]p15:
  6067. //
  6068. // For every T, where T is an enumeration type, a pointer type, or
  6069. // std::nullptr_t, there exist candidate operator functions of the form
  6070. //
  6071. // bool operator<(T, T);
  6072. // bool operator>(T, T);
  6073. // bool operator<=(T, T);
  6074. // bool operator>=(T, T);
  6075. // bool operator==(T, T);
  6076. // bool operator!=(T, T);
  6077. void addRelationalPointerOrEnumeralOverloads() {
  6078. // C++ [over.built]p1:
  6079. // If there is a user-written candidate with the same name and parameter
  6080. // types as a built-in candidate operator function, the built-in operator
  6081. // function is hidden and is not included in the set of candidate
  6082. // functions.
  6083. //
  6084. // The text is actually in a note, but if we don't implement it then we end
  6085. // up with ambiguities when the user provides an overloaded operator for
  6086. // an enumeration type. Note that only enumeration types have this problem,
  6087. // so we track which enumeration types we've seen operators for. Also, the
  6088. // only other overloaded operator with enumeration argumenst, operator=,
  6089. // cannot be overloaded for enumeration types, so this is the only place
  6090. // where we must suppress candidates like this.
  6091. llvm::DenseSet<std::pair<CanQualType, CanQualType> >
  6092. UserDefinedBinaryOperators;
  6093. for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
  6094. if (CandidateTypes[ArgIdx].enumeration_begin() !=
  6095. CandidateTypes[ArgIdx].enumeration_end()) {
  6096. for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
  6097. CEnd = CandidateSet.end();
  6098. C != CEnd; ++C) {
  6099. if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
  6100. continue;
  6101. QualType FirstParamType =
  6102. C->Function->getParamDecl(0)->getType().getUnqualifiedType();
  6103. QualType SecondParamType =
  6104. C->Function->getParamDecl(1)->getType().getUnqualifiedType();
  6105. // Skip if either parameter isn't of enumeral type.
  6106. if (!FirstParamType->isEnumeralType() ||
  6107. !SecondParamType->isEnumeralType())
  6108. continue;
  6109. // Add this operator to the set of known user-defined operators.
  6110. UserDefinedBinaryOperators.insert(
  6111. std::make_pair(S.Context.getCanonicalType(FirstParamType),
  6112. S.Context.getCanonicalType(SecondParamType)));
  6113. }
  6114. }
  6115. }
  6116. /// Set of (canonical) types that we've already handled.
  6117. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6118. for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
  6119. for (BuiltinCandidateTypeSet::iterator
  6120. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  6121. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  6122. Ptr != PtrEnd; ++Ptr) {
  6123. // Don't add the same builtin candidate twice.
  6124. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
  6125. continue;
  6126. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6127. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
  6128. CandidateSet);
  6129. }
  6130. for (BuiltinCandidateTypeSet::iterator
  6131. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  6132. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  6133. Enum != EnumEnd; ++Enum) {
  6134. CanQualType CanonType = S.Context.getCanonicalType(*Enum);
  6135. // Don't add the same builtin candidate twice, or if a user defined
  6136. // candidate exists.
  6137. if (!AddedTypes.insert(CanonType) ||
  6138. UserDefinedBinaryOperators.count(std::make_pair(CanonType,
  6139. CanonType)))
  6140. continue;
  6141. QualType ParamTypes[2] = { *Enum, *Enum };
  6142. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
  6143. CandidateSet);
  6144. }
  6145. if (CandidateTypes[ArgIdx].hasNullPtrType()) {
  6146. CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
  6147. if (AddedTypes.insert(NullPtrTy) &&
  6148. !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
  6149. NullPtrTy))) {
  6150. QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
  6151. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
  6152. CandidateSet);
  6153. }
  6154. }
  6155. }
  6156. }
  6157. // C++ [over.built]p13:
  6158. //
  6159. // For every cv-qualified or cv-unqualified object type T
  6160. // there exist candidate operator functions of the form
  6161. //
  6162. // T* operator+(T*, ptrdiff_t);
  6163. // T& operator[](T*, ptrdiff_t); [BELOW]
  6164. // T* operator-(T*, ptrdiff_t);
  6165. // T* operator+(ptrdiff_t, T*);
  6166. // T& operator[](ptrdiff_t, T*); [BELOW]
  6167. //
  6168. // C++ [over.built]p14:
  6169. //
  6170. // For every T, where T is a pointer to object type, there
  6171. // exist candidate operator functions of the form
  6172. //
  6173. // ptrdiff_t operator-(T, T);
  6174. void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
  6175. /// Set of (canonical) types that we've already handled.
  6176. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6177. for (int Arg = 0; Arg < 2; ++Arg) {
  6178. QualType AsymetricParamTypes[2] = {
  6179. S.Context.getPointerDiffType(),
  6180. S.Context.getPointerDiffType(),
  6181. };
  6182. for (BuiltinCandidateTypeSet::iterator
  6183. Ptr = CandidateTypes[Arg].pointer_begin(),
  6184. PtrEnd = CandidateTypes[Arg].pointer_end();
  6185. Ptr != PtrEnd; ++Ptr) {
  6186. QualType PointeeTy = (*Ptr)->getPointeeType();
  6187. if (!PointeeTy->isObjectType())
  6188. continue;
  6189. AsymetricParamTypes[Arg] = *Ptr;
  6190. if (Arg == 0 || Op == OO_Plus) {
  6191. // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
  6192. // T* operator+(ptrdiff_t, T*);
  6193. S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
  6194. CandidateSet);
  6195. }
  6196. if (Op == OO_Minus) {
  6197. // ptrdiff_t operator-(T, T);
  6198. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
  6199. continue;
  6200. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6201. S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
  6202. Args, 2, CandidateSet);
  6203. }
  6204. }
  6205. }
  6206. }
  6207. // C++ [over.built]p12:
  6208. //
  6209. // For every pair of promoted arithmetic types L and R, there
  6210. // exist candidate operator functions of the form
  6211. //
  6212. // LR operator*(L, R);
  6213. // LR operator/(L, R);
  6214. // LR operator+(L, R);
  6215. // LR operator-(L, R);
  6216. // bool operator<(L, R);
  6217. // bool operator>(L, R);
  6218. // bool operator<=(L, R);
  6219. // bool operator>=(L, R);
  6220. // bool operator==(L, R);
  6221. // bool operator!=(L, R);
  6222. //
  6223. // where LR is the result of the usual arithmetic conversions
  6224. // between types L and R.
  6225. //
  6226. // C++ [over.built]p24:
  6227. //
  6228. // For every pair of promoted arithmetic types L and R, there exist
  6229. // candidate operator functions of the form
  6230. //
  6231. // LR operator?(bool, L, R);
  6232. //
  6233. // where LR is the result of the usual arithmetic conversions
  6234. // between types L and R.
  6235. // Our candidates ignore the first parameter.
  6236. void addGenericBinaryArithmeticOverloads(bool isComparison) {
  6237. if (!HasArithmeticOrEnumeralCandidateType)
  6238. return;
  6239. for (unsigned Left = FirstPromotedArithmeticType;
  6240. Left < LastPromotedArithmeticType; ++Left) {
  6241. for (unsigned Right = FirstPromotedArithmeticType;
  6242. Right < LastPromotedArithmeticType; ++Right) {
  6243. QualType LandR[2] = { getArithmeticType(Left),
  6244. getArithmeticType(Right) };
  6245. QualType Result =
  6246. isComparison ? S.Context.BoolTy
  6247. : getUsualArithmeticConversions(Left, Right);
  6248. S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
  6249. }
  6250. }
  6251. // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
  6252. // conditional operator for vector types.
  6253. for (BuiltinCandidateTypeSet::iterator
  6254. Vec1 = CandidateTypes[0].vector_begin(),
  6255. Vec1End = CandidateTypes[0].vector_end();
  6256. Vec1 != Vec1End; ++Vec1) {
  6257. for (BuiltinCandidateTypeSet::iterator
  6258. Vec2 = CandidateTypes[1].vector_begin(),
  6259. Vec2End = CandidateTypes[1].vector_end();
  6260. Vec2 != Vec2End; ++Vec2) {
  6261. QualType LandR[2] = { *Vec1, *Vec2 };
  6262. QualType Result = S.Context.BoolTy;
  6263. if (!isComparison) {
  6264. if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
  6265. Result = *Vec1;
  6266. else
  6267. Result = *Vec2;
  6268. }
  6269. S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
  6270. }
  6271. }
  6272. }
  6273. // C++ [over.built]p17:
  6274. //
  6275. // For every pair of promoted integral types L and R, there
  6276. // exist candidate operator functions of the form
  6277. //
  6278. // LR operator%(L, R);
  6279. // LR operator&(L, R);
  6280. // LR operator^(L, R);
  6281. // LR operator|(L, R);
  6282. // L operator<<(L, R);
  6283. // L operator>>(L, R);
  6284. //
  6285. // where LR is the result of the usual arithmetic conversions
  6286. // between types L and R.
  6287. void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
  6288. if (!HasArithmeticOrEnumeralCandidateType)
  6289. return;
  6290. for (unsigned Left = FirstPromotedIntegralType;
  6291. Left < LastPromotedIntegralType; ++Left) {
  6292. for (unsigned Right = FirstPromotedIntegralType;
  6293. Right < LastPromotedIntegralType; ++Right) {
  6294. QualType LandR[2] = { getArithmeticType(Left),
  6295. getArithmeticType(Right) };
  6296. QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
  6297. ? LandR[0]
  6298. : getUsualArithmeticConversions(Left, Right);
  6299. S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
  6300. }
  6301. }
  6302. }
  6303. // C++ [over.built]p20:
  6304. //
  6305. // For every pair (T, VQ), where T is an enumeration or
  6306. // pointer to member type and VQ is either volatile or
  6307. // empty, there exist candidate operator functions of the form
  6308. //
  6309. // VQ T& operator=(VQ T&, T);
  6310. void addAssignmentMemberPointerOrEnumeralOverloads() {
  6311. /// Set of (canonical) types that we've already handled.
  6312. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6313. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  6314. for (BuiltinCandidateTypeSet::iterator
  6315. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  6316. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  6317. Enum != EnumEnd; ++Enum) {
  6318. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
  6319. continue;
  6320. AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
  6321. CandidateSet);
  6322. }
  6323. for (BuiltinCandidateTypeSet::iterator
  6324. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  6325. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  6326. MemPtr != MemPtrEnd; ++MemPtr) {
  6327. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
  6328. continue;
  6329. AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
  6330. CandidateSet);
  6331. }
  6332. }
  6333. }
  6334. // C++ [over.built]p19:
  6335. //
  6336. // For every pair (T, VQ), where T is any type and VQ is either
  6337. // volatile or empty, there exist candidate operator functions
  6338. // of the form
  6339. //
  6340. // T*VQ& operator=(T*VQ&, T*);
  6341. //
  6342. // C++ [over.built]p21:
  6343. //
  6344. // For every pair (T, VQ), where T is a cv-qualified or
  6345. // cv-unqualified object type and VQ is either volatile or
  6346. // empty, there exist candidate operator functions of the form
  6347. //
  6348. // T*VQ& operator+=(T*VQ&, ptrdiff_t);
  6349. // T*VQ& operator-=(T*VQ&, ptrdiff_t);
  6350. void addAssignmentPointerOverloads(bool isEqualOp) {
  6351. /// Set of (canonical) types that we've already handled.
  6352. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6353. for (BuiltinCandidateTypeSet::iterator
  6354. Ptr = CandidateTypes[0].pointer_begin(),
  6355. PtrEnd = CandidateTypes[0].pointer_end();
  6356. Ptr != PtrEnd; ++Ptr) {
  6357. // If this is operator=, keep track of the builtin candidates we added.
  6358. if (isEqualOp)
  6359. AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
  6360. else if (!(*Ptr)->getPointeeType()->isObjectType())
  6361. continue;
  6362. // non-volatile version
  6363. QualType ParamTypes[2] = {
  6364. S.Context.getLValueReferenceType(*Ptr),
  6365. isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
  6366. };
  6367. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
  6368. /*IsAssigmentOperator=*/ isEqualOp);
  6369. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  6370. VisibleTypeConversionsQuals.hasVolatile();
  6371. if (NeedVolatile) {
  6372. // volatile version
  6373. ParamTypes[0] =
  6374. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  6375. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
  6376. /*IsAssigmentOperator=*/isEqualOp);
  6377. }
  6378. if (!(*Ptr).isRestrictQualified() &&
  6379. VisibleTypeConversionsQuals.hasRestrict()) {
  6380. // restrict version
  6381. ParamTypes[0]
  6382. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  6383. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
  6384. /*IsAssigmentOperator=*/isEqualOp);
  6385. if (NeedVolatile) {
  6386. // volatile restrict version
  6387. ParamTypes[0]
  6388. = S.Context.getLValueReferenceType(
  6389. S.Context.getCVRQualifiedType(*Ptr,
  6390. (Qualifiers::Volatile |
  6391. Qualifiers::Restrict)));
  6392. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
  6393. CandidateSet,
  6394. /*IsAssigmentOperator=*/isEqualOp);
  6395. }
  6396. }
  6397. }
  6398. if (isEqualOp) {
  6399. for (BuiltinCandidateTypeSet::iterator
  6400. Ptr = CandidateTypes[1].pointer_begin(),
  6401. PtrEnd = CandidateTypes[1].pointer_end();
  6402. Ptr != PtrEnd; ++Ptr) {
  6403. // Make sure we don't add the same candidate twice.
  6404. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
  6405. continue;
  6406. QualType ParamTypes[2] = {
  6407. S.Context.getLValueReferenceType(*Ptr),
  6408. *Ptr,
  6409. };
  6410. // non-volatile version
  6411. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
  6412. /*IsAssigmentOperator=*/true);
  6413. bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
  6414. VisibleTypeConversionsQuals.hasVolatile();
  6415. if (NeedVolatile) {
  6416. // volatile version
  6417. ParamTypes[0] =
  6418. S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
  6419. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
  6420. CandidateSet, /*IsAssigmentOperator=*/true);
  6421. }
  6422. if (!(*Ptr).isRestrictQualified() &&
  6423. VisibleTypeConversionsQuals.hasRestrict()) {
  6424. // restrict version
  6425. ParamTypes[0]
  6426. = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
  6427. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
  6428. CandidateSet, /*IsAssigmentOperator=*/true);
  6429. if (NeedVolatile) {
  6430. // volatile restrict version
  6431. ParamTypes[0]
  6432. = S.Context.getLValueReferenceType(
  6433. S.Context.getCVRQualifiedType(*Ptr,
  6434. (Qualifiers::Volatile |
  6435. Qualifiers::Restrict)));
  6436. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
  6437. CandidateSet, /*IsAssigmentOperator=*/true);
  6438. }
  6439. }
  6440. }
  6441. }
  6442. }
  6443. // C++ [over.built]p18:
  6444. //
  6445. // For every triple (L, VQ, R), where L is an arithmetic type,
  6446. // VQ is either volatile or empty, and R is a promoted
  6447. // arithmetic type, there exist candidate operator functions of
  6448. // the form
  6449. //
  6450. // VQ L& operator=(VQ L&, R);
  6451. // VQ L& operator*=(VQ L&, R);
  6452. // VQ L& operator/=(VQ L&, R);
  6453. // VQ L& operator+=(VQ L&, R);
  6454. // VQ L& operator-=(VQ L&, R);
  6455. void addAssignmentArithmeticOverloads(bool isEqualOp) {
  6456. if (!HasArithmeticOrEnumeralCandidateType)
  6457. return;
  6458. for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
  6459. for (unsigned Right = FirstPromotedArithmeticType;
  6460. Right < LastPromotedArithmeticType; ++Right) {
  6461. QualType ParamTypes[2];
  6462. ParamTypes[1] = getArithmeticType(Right);
  6463. // Add this built-in operator as a candidate (VQ is empty).
  6464. ParamTypes[0] =
  6465. S.Context.getLValueReferenceType(getArithmeticType(Left));
  6466. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
  6467. /*IsAssigmentOperator=*/isEqualOp);
  6468. // Add this built-in operator as a candidate (VQ is 'volatile').
  6469. if (VisibleTypeConversionsQuals.hasVolatile()) {
  6470. ParamTypes[0] =
  6471. S.Context.getVolatileType(getArithmeticType(Left));
  6472. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  6473. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
  6474. CandidateSet,
  6475. /*IsAssigmentOperator=*/isEqualOp);
  6476. }
  6477. }
  6478. }
  6479. // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
  6480. for (BuiltinCandidateTypeSet::iterator
  6481. Vec1 = CandidateTypes[0].vector_begin(),
  6482. Vec1End = CandidateTypes[0].vector_end();
  6483. Vec1 != Vec1End; ++Vec1) {
  6484. for (BuiltinCandidateTypeSet::iterator
  6485. Vec2 = CandidateTypes[1].vector_begin(),
  6486. Vec2End = CandidateTypes[1].vector_end();
  6487. Vec2 != Vec2End; ++Vec2) {
  6488. QualType ParamTypes[2];
  6489. ParamTypes[1] = *Vec2;
  6490. // Add this built-in operator as a candidate (VQ is empty).
  6491. ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
  6492. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
  6493. /*IsAssigmentOperator=*/isEqualOp);
  6494. // Add this built-in operator as a candidate (VQ is 'volatile').
  6495. if (VisibleTypeConversionsQuals.hasVolatile()) {
  6496. ParamTypes[0] = S.Context.getVolatileType(*Vec1);
  6497. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  6498. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
  6499. CandidateSet,
  6500. /*IsAssigmentOperator=*/isEqualOp);
  6501. }
  6502. }
  6503. }
  6504. }
  6505. // C++ [over.built]p22:
  6506. //
  6507. // For every triple (L, VQ, R), where L is an integral type, VQ
  6508. // is either volatile or empty, and R is a promoted integral
  6509. // type, there exist candidate operator functions of the form
  6510. //
  6511. // VQ L& operator%=(VQ L&, R);
  6512. // VQ L& operator<<=(VQ L&, R);
  6513. // VQ L& operator>>=(VQ L&, R);
  6514. // VQ L& operator&=(VQ L&, R);
  6515. // VQ L& operator^=(VQ L&, R);
  6516. // VQ L& operator|=(VQ L&, R);
  6517. void addAssignmentIntegralOverloads() {
  6518. if (!HasArithmeticOrEnumeralCandidateType)
  6519. return;
  6520. for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
  6521. for (unsigned Right = FirstPromotedIntegralType;
  6522. Right < LastPromotedIntegralType; ++Right) {
  6523. QualType ParamTypes[2];
  6524. ParamTypes[1] = getArithmeticType(Right);
  6525. // Add this built-in operator as a candidate (VQ is empty).
  6526. ParamTypes[0] =
  6527. S.Context.getLValueReferenceType(getArithmeticType(Left));
  6528. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
  6529. if (VisibleTypeConversionsQuals.hasVolatile()) {
  6530. // Add this built-in operator as a candidate (VQ is 'volatile').
  6531. ParamTypes[0] = getArithmeticType(Left);
  6532. ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
  6533. ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
  6534. S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
  6535. CandidateSet);
  6536. }
  6537. }
  6538. }
  6539. }
  6540. // C++ [over.operator]p23:
  6541. //
  6542. // There also exist candidate operator functions of the form
  6543. //
  6544. // bool operator!(bool);
  6545. // bool operator&&(bool, bool);
  6546. // bool operator||(bool, bool);
  6547. void addExclaimOverload() {
  6548. QualType ParamTy = S.Context.BoolTy;
  6549. S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
  6550. /*IsAssignmentOperator=*/false,
  6551. /*NumContextualBoolArguments=*/1);
  6552. }
  6553. void addAmpAmpOrPipePipeOverload() {
  6554. QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
  6555. S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
  6556. /*IsAssignmentOperator=*/false,
  6557. /*NumContextualBoolArguments=*/2);
  6558. }
  6559. // C++ [over.built]p13:
  6560. //
  6561. // For every cv-qualified or cv-unqualified object type T there
  6562. // exist candidate operator functions of the form
  6563. //
  6564. // T* operator+(T*, ptrdiff_t); [ABOVE]
  6565. // T& operator[](T*, ptrdiff_t);
  6566. // T* operator-(T*, ptrdiff_t); [ABOVE]
  6567. // T* operator+(ptrdiff_t, T*); [ABOVE]
  6568. // T& operator[](ptrdiff_t, T*);
  6569. void addSubscriptOverloads() {
  6570. for (BuiltinCandidateTypeSet::iterator
  6571. Ptr = CandidateTypes[0].pointer_begin(),
  6572. PtrEnd = CandidateTypes[0].pointer_end();
  6573. Ptr != PtrEnd; ++Ptr) {
  6574. QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
  6575. QualType PointeeType = (*Ptr)->getPointeeType();
  6576. if (!PointeeType->isObjectType())
  6577. continue;
  6578. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  6579. // T& operator[](T*, ptrdiff_t)
  6580. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
  6581. }
  6582. for (BuiltinCandidateTypeSet::iterator
  6583. Ptr = CandidateTypes[1].pointer_begin(),
  6584. PtrEnd = CandidateTypes[1].pointer_end();
  6585. Ptr != PtrEnd; ++Ptr) {
  6586. QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
  6587. QualType PointeeType = (*Ptr)->getPointeeType();
  6588. if (!PointeeType->isObjectType())
  6589. continue;
  6590. QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
  6591. // T& operator[](ptrdiff_t, T*)
  6592. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
  6593. }
  6594. }
  6595. // C++ [over.built]p11:
  6596. // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
  6597. // C1 is the same type as C2 or is a derived class of C2, T is an object
  6598. // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
  6599. // there exist candidate operator functions of the form
  6600. //
  6601. // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
  6602. //
  6603. // where CV12 is the union of CV1 and CV2.
  6604. void addArrowStarOverloads() {
  6605. for (BuiltinCandidateTypeSet::iterator
  6606. Ptr = CandidateTypes[0].pointer_begin(),
  6607. PtrEnd = CandidateTypes[0].pointer_end();
  6608. Ptr != PtrEnd; ++Ptr) {
  6609. QualType C1Ty = (*Ptr);
  6610. QualType C1;
  6611. QualifierCollector Q1;
  6612. C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
  6613. if (!isa<RecordType>(C1))
  6614. continue;
  6615. // heuristic to reduce number of builtin candidates in the set.
  6616. // Add volatile/restrict version only if there are conversions to a
  6617. // volatile/restrict type.
  6618. if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
  6619. continue;
  6620. if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
  6621. continue;
  6622. for (BuiltinCandidateTypeSet::iterator
  6623. MemPtr = CandidateTypes[1].member_pointer_begin(),
  6624. MemPtrEnd = CandidateTypes[1].member_pointer_end();
  6625. MemPtr != MemPtrEnd; ++MemPtr) {
  6626. const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
  6627. QualType C2 = QualType(mptr->getClass(), 0);
  6628. C2 = C2.getUnqualifiedType();
  6629. if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
  6630. break;
  6631. QualType ParamTypes[2] = { *Ptr, *MemPtr };
  6632. // build CV12 T&
  6633. QualType T = mptr->getPointeeType();
  6634. if (!VisibleTypeConversionsQuals.hasVolatile() &&
  6635. T.isVolatileQualified())
  6636. continue;
  6637. if (!VisibleTypeConversionsQuals.hasRestrict() &&
  6638. T.isRestrictQualified())
  6639. continue;
  6640. T = Q1.apply(S.Context, T);
  6641. QualType ResultTy = S.Context.getLValueReferenceType(T);
  6642. S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
  6643. }
  6644. }
  6645. }
  6646. // Note that we don't consider the first argument, since it has been
  6647. // contextually converted to bool long ago. The candidates below are
  6648. // therefore added as binary.
  6649. //
  6650. // C++ [over.built]p25:
  6651. // For every type T, where T is a pointer, pointer-to-member, or scoped
  6652. // enumeration type, there exist candidate operator functions of the form
  6653. //
  6654. // T operator?(bool, T, T);
  6655. //
  6656. void addConditionalOperatorOverloads() {
  6657. /// Set of (canonical) types that we've already handled.
  6658. llvm::SmallPtrSet<QualType, 8> AddedTypes;
  6659. for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
  6660. for (BuiltinCandidateTypeSet::iterator
  6661. Ptr = CandidateTypes[ArgIdx].pointer_begin(),
  6662. PtrEnd = CandidateTypes[ArgIdx].pointer_end();
  6663. Ptr != PtrEnd; ++Ptr) {
  6664. if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
  6665. continue;
  6666. QualType ParamTypes[2] = { *Ptr, *Ptr };
  6667. S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
  6668. }
  6669. for (BuiltinCandidateTypeSet::iterator
  6670. MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
  6671. MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
  6672. MemPtr != MemPtrEnd; ++MemPtr) {
  6673. if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
  6674. continue;
  6675. QualType ParamTypes[2] = { *MemPtr, *MemPtr };
  6676. S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
  6677. }
  6678. if (S.getLangOpts().CPlusPlus0x) {
  6679. for (BuiltinCandidateTypeSet::iterator
  6680. Enum = CandidateTypes[ArgIdx].enumeration_begin(),
  6681. EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
  6682. Enum != EnumEnd; ++Enum) {
  6683. if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
  6684. continue;
  6685. if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
  6686. continue;
  6687. QualType ParamTypes[2] = { *Enum, *Enum };
  6688. S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
  6689. }
  6690. }
  6691. }
  6692. }
  6693. };
  6694. } // end anonymous namespace
  6695. /// AddBuiltinOperatorCandidates - Add the appropriate built-in
  6696. /// operator overloads to the candidate set (C++ [over.built]), based
  6697. /// on the operator @p Op and the arguments given. For example, if the
  6698. /// operator is a binary '+', this routine might add "int
  6699. /// operator+(int, int)" to cover integer addition.
  6700. void
  6701. Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
  6702. SourceLocation OpLoc,
  6703. Expr **Args, unsigned NumArgs,
  6704. OverloadCandidateSet& CandidateSet) {
  6705. // Find all of the types that the arguments can convert to, but only
  6706. // if the operator we're looking at has built-in operator candidates
  6707. // that make use of these types. Also record whether we encounter non-record
  6708. // candidate types or either arithmetic or enumeral candidate types.
  6709. Qualifiers VisibleTypeConversionsQuals;
  6710. VisibleTypeConversionsQuals.addConst();
  6711. for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
  6712. VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
  6713. bool HasNonRecordCandidateType = false;
  6714. bool HasArithmeticOrEnumeralCandidateType = false;
  6715. SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
  6716. for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
  6717. CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
  6718. CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
  6719. OpLoc,
  6720. true,
  6721. (Op == OO_Exclaim ||
  6722. Op == OO_AmpAmp ||
  6723. Op == OO_PipePipe),
  6724. VisibleTypeConversionsQuals);
  6725. HasNonRecordCandidateType = HasNonRecordCandidateType ||
  6726. CandidateTypes[ArgIdx].hasNonRecordTypes();
  6727. HasArithmeticOrEnumeralCandidateType =
  6728. HasArithmeticOrEnumeralCandidateType ||
  6729. CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
  6730. }
  6731. // Exit early when no non-record types have been added to the candidate set
  6732. // for any of the arguments to the operator.
  6733. //
  6734. // We can't exit early for !, ||, or &&, since there we have always have
  6735. // 'bool' overloads.
  6736. if (!HasNonRecordCandidateType &&
  6737. !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
  6738. return;
  6739. // Setup an object to manage the common state for building overloads.
  6740. BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
  6741. VisibleTypeConversionsQuals,
  6742. HasArithmeticOrEnumeralCandidateType,
  6743. CandidateTypes, CandidateSet);
  6744. // Dispatch over the operation to add in only those overloads which apply.
  6745. switch (Op) {
  6746. case OO_None:
  6747. case NUM_OVERLOADED_OPERATORS:
  6748. llvm_unreachable("Expected an overloaded operator");
  6749. case OO_New:
  6750. case OO_Delete:
  6751. case OO_Array_New:
  6752. case OO_Array_Delete:
  6753. case OO_Call:
  6754. llvm_unreachable(
  6755. "Special operators don't use AddBuiltinOperatorCandidates");
  6756. case OO_Comma:
  6757. case OO_Arrow:
  6758. // C++ [over.match.oper]p3:
  6759. // -- For the operator ',', the unary operator '&', or the
  6760. // operator '->', the built-in candidates set is empty.
  6761. break;
  6762. case OO_Plus: // '+' is either unary or binary
  6763. if (NumArgs == 1)
  6764. OpBuilder.addUnaryPlusPointerOverloads();
  6765. // Fall through.
  6766. case OO_Minus: // '-' is either unary or binary
  6767. if (NumArgs == 1) {
  6768. OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
  6769. } else {
  6770. OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
  6771. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  6772. }
  6773. break;
  6774. case OO_Star: // '*' is either unary or binary
  6775. if (NumArgs == 1)
  6776. OpBuilder.addUnaryStarPointerOverloads();
  6777. else
  6778. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  6779. break;
  6780. case OO_Slash:
  6781. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  6782. break;
  6783. case OO_PlusPlus:
  6784. case OO_MinusMinus:
  6785. OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
  6786. OpBuilder.addPlusPlusMinusMinusPointerOverloads();
  6787. break;
  6788. case OO_EqualEqual:
  6789. case OO_ExclaimEqual:
  6790. OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
  6791. // Fall through.
  6792. case OO_Less:
  6793. case OO_Greater:
  6794. case OO_LessEqual:
  6795. case OO_GreaterEqual:
  6796. OpBuilder.addRelationalPointerOrEnumeralOverloads();
  6797. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
  6798. break;
  6799. case OO_Percent:
  6800. case OO_Caret:
  6801. case OO_Pipe:
  6802. case OO_LessLess:
  6803. case OO_GreaterGreater:
  6804. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  6805. break;
  6806. case OO_Amp: // '&' is either unary or binary
  6807. if (NumArgs == 1)
  6808. // C++ [over.match.oper]p3:
  6809. // -- For the operator ',', the unary operator '&', or the
  6810. // operator '->', the built-in candidates set is empty.
  6811. break;
  6812. OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
  6813. break;
  6814. case OO_Tilde:
  6815. OpBuilder.addUnaryTildePromotedIntegralOverloads();
  6816. break;
  6817. case OO_Equal:
  6818. OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
  6819. // Fall through.
  6820. case OO_PlusEqual:
  6821. case OO_MinusEqual:
  6822. OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
  6823. // Fall through.
  6824. case OO_StarEqual:
  6825. case OO_SlashEqual:
  6826. OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
  6827. break;
  6828. case OO_PercentEqual:
  6829. case OO_LessLessEqual:
  6830. case OO_GreaterGreaterEqual:
  6831. case OO_AmpEqual:
  6832. case OO_CaretEqual:
  6833. case OO_PipeEqual:
  6834. OpBuilder.addAssignmentIntegralOverloads();
  6835. break;
  6836. case OO_Exclaim:
  6837. OpBuilder.addExclaimOverload();
  6838. break;
  6839. case OO_AmpAmp:
  6840. case OO_PipePipe:
  6841. OpBuilder.addAmpAmpOrPipePipeOverload();
  6842. break;
  6843. case OO_Subscript:
  6844. OpBuilder.addSubscriptOverloads();
  6845. break;
  6846. case OO_ArrowStar:
  6847. OpBuilder.addArrowStarOverloads();
  6848. break;
  6849. case OO_Conditional:
  6850. OpBuilder.addConditionalOperatorOverloads();
  6851. OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
  6852. break;
  6853. }
  6854. }
  6855. /// \brief Add function candidates found via argument-dependent lookup
  6856. /// to the set of overloading candidates.
  6857. ///
  6858. /// This routine performs argument-dependent name lookup based on the
  6859. /// given function name (which may also be an operator name) and adds
  6860. /// all of the overload candidates found by ADL to the overload
  6861. /// candidate set (C++ [basic.lookup.argdep]).
  6862. void
  6863. Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
  6864. bool Operator, SourceLocation Loc,
  6865. llvm::ArrayRef<Expr *> Args,
  6866. TemplateArgumentListInfo *ExplicitTemplateArgs,
  6867. OverloadCandidateSet& CandidateSet,
  6868. bool PartialOverloading,
  6869. bool StdNamespaceIsAssociated) {
  6870. ADLResult Fns;
  6871. // FIXME: This approach for uniquing ADL results (and removing
  6872. // redundant candidates from the set) relies on pointer-equality,
  6873. // which means we need to key off the canonical decl. However,
  6874. // always going back to the canonical decl might not get us the
  6875. // right set of default arguments. What default arguments are
  6876. // we supposed to consider on ADL candidates, anyway?
  6877. // FIXME: Pass in the explicit template arguments?
  6878. ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
  6879. StdNamespaceIsAssociated);
  6880. // Erase all of the candidates we already knew about.
  6881. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  6882. CandEnd = CandidateSet.end();
  6883. Cand != CandEnd; ++Cand)
  6884. if (Cand->Function) {
  6885. Fns.erase(Cand->Function);
  6886. if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
  6887. Fns.erase(FunTmpl);
  6888. }
  6889. // For each of the ADL candidates we found, add it to the overload
  6890. // set.
  6891. for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  6892. DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
  6893. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  6894. if (ExplicitTemplateArgs)
  6895. continue;
  6896. AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
  6897. PartialOverloading);
  6898. } else
  6899. AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
  6900. FoundDecl, ExplicitTemplateArgs,
  6901. Args, CandidateSet);
  6902. }
  6903. }
  6904. /// isBetterOverloadCandidate - Determines whether the first overload
  6905. /// candidate is a better candidate than the second (C++ 13.3.3p1).
  6906. bool
  6907. isBetterOverloadCandidate(Sema &S,
  6908. const OverloadCandidate &Cand1,
  6909. const OverloadCandidate &Cand2,
  6910. SourceLocation Loc,
  6911. bool UserDefinedConversion) {
  6912. // Define viable functions to be better candidates than non-viable
  6913. // functions.
  6914. if (!Cand2.Viable)
  6915. return Cand1.Viable;
  6916. else if (!Cand1.Viable)
  6917. return false;
  6918. // C++ [over.match.best]p1:
  6919. //
  6920. // -- if F is a static member function, ICS1(F) is defined such
  6921. // that ICS1(F) is neither better nor worse than ICS1(G) for
  6922. // any function G, and, symmetrically, ICS1(G) is neither
  6923. // better nor worse than ICS1(F).
  6924. unsigned StartArg = 0;
  6925. if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
  6926. StartArg = 1;
  6927. // C++ [over.match.best]p1:
  6928. // A viable function F1 is defined to be a better function than another
  6929. // viable function F2 if for all arguments i, ICSi(F1) is not a worse
  6930. // conversion sequence than ICSi(F2), and then...
  6931. unsigned NumArgs = Cand1.NumConversions;
  6932. assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
  6933. bool HasBetterConversion = false;
  6934. for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
  6935. switch (CompareImplicitConversionSequences(S,
  6936. Cand1.Conversions[ArgIdx],
  6937. Cand2.Conversions[ArgIdx])) {
  6938. case ImplicitConversionSequence::Better:
  6939. // Cand1 has a better conversion sequence.
  6940. HasBetterConversion = true;
  6941. break;
  6942. case ImplicitConversionSequence::Worse:
  6943. // Cand1 can't be better than Cand2.
  6944. return false;
  6945. case ImplicitConversionSequence::Indistinguishable:
  6946. // Do nothing.
  6947. break;
  6948. }
  6949. }
  6950. // -- for some argument j, ICSj(F1) is a better conversion sequence than
  6951. // ICSj(F2), or, if not that,
  6952. if (HasBetterConversion)
  6953. return true;
  6954. // - F1 is a non-template function and F2 is a function template
  6955. // specialization, or, if not that,
  6956. if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
  6957. Cand2.Function && Cand2.Function->getPrimaryTemplate())
  6958. return true;
  6959. // -- F1 and F2 are function template specializations, and the function
  6960. // template for F1 is more specialized than the template for F2
  6961. // according to the partial ordering rules described in 14.5.5.2, or,
  6962. // if not that,
  6963. if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
  6964. Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
  6965. if (FunctionTemplateDecl *BetterTemplate
  6966. = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
  6967. Cand2.Function->getPrimaryTemplate(),
  6968. Loc,
  6969. isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
  6970. : TPOC_Call,
  6971. Cand1.ExplicitCallArguments))
  6972. return BetterTemplate == Cand1.Function->getPrimaryTemplate();
  6973. }
  6974. // -- the context is an initialization by user-defined conversion
  6975. // (see 8.5, 13.3.1.5) and the standard conversion sequence
  6976. // from the return type of F1 to the destination type (i.e.,
  6977. // the type of the entity being initialized) is a better
  6978. // conversion sequence than the standard conversion sequence
  6979. // from the return type of F2 to the destination type.
  6980. if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
  6981. isa<CXXConversionDecl>(Cand1.Function) &&
  6982. isa<CXXConversionDecl>(Cand2.Function)) {
  6983. // First check whether we prefer one of the conversion functions over the
  6984. // other. This only distinguishes the results in non-standard, extension
  6985. // cases such as the conversion from a lambda closure type to a function
  6986. // pointer or block.
  6987. ImplicitConversionSequence::CompareKind FuncResult
  6988. = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
  6989. if (FuncResult != ImplicitConversionSequence::Indistinguishable)
  6990. return FuncResult;
  6991. switch (CompareStandardConversionSequences(S,
  6992. Cand1.FinalConversion,
  6993. Cand2.FinalConversion)) {
  6994. case ImplicitConversionSequence::Better:
  6995. // Cand1 has a better conversion sequence.
  6996. return true;
  6997. case ImplicitConversionSequence::Worse:
  6998. // Cand1 can't be better than Cand2.
  6999. return false;
  7000. case ImplicitConversionSequence::Indistinguishable:
  7001. // Do nothing
  7002. break;
  7003. }
  7004. }
  7005. return false;
  7006. }
  7007. /// \brief Computes the best viable function (C++ 13.3.3)
  7008. /// within an overload candidate set.
  7009. ///
  7010. /// \param Loc The location of the function name (or operator symbol) for
  7011. /// which overload resolution occurs.
  7012. ///
  7013. /// \param Best If overload resolution was successful or found a deleted
  7014. /// function, \p Best points to the candidate function found.
  7015. ///
  7016. /// \returns The result of overload resolution.
  7017. OverloadingResult
  7018. OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
  7019. iterator &Best,
  7020. bool UserDefinedConversion) {
  7021. // Find the best viable function.
  7022. Best = end();
  7023. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7024. if (Cand->Viable)
  7025. if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
  7026. UserDefinedConversion))
  7027. Best = Cand;
  7028. }
  7029. // If we didn't find any viable functions, abort.
  7030. if (Best == end())
  7031. return OR_No_Viable_Function;
  7032. // Make sure that this function is better than every other viable
  7033. // function. If not, we have an ambiguity.
  7034. for (iterator Cand = begin(); Cand != end(); ++Cand) {
  7035. if (Cand->Viable &&
  7036. Cand != Best &&
  7037. !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
  7038. UserDefinedConversion)) {
  7039. Best = end();
  7040. return OR_Ambiguous;
  7041. }
  7042. }
  7043. // Best is the best viable function.
  7044. if (Best->Function &&
  7045. (Best->Function->isDeleted() ||
  7046. S.isFunctionConsideredUnavailable(Best->Function)))
  7047. return OR_Deleted;
  7048. return OR_Success;
  7049. }
  7050. namespace {
  7051. enum OverloadCandidateKind {
  7052. oc_function,
  7053. oc_method,
  7054. oc_constructor,
  7055. oc_function_template,
  7056. oc_method_template,
  7057. oc_constructor_template,
  7058. oc_implicit_default_constructor,
  7059. oc_implicit_copy_constructor,
  7060. oc_implicit_move_constructor,
  7061. oc_implicit_copy_assignment,
  7062. oc_implicit_move_assignment,
  7063. oc_implicit_inherited_constructor
  7064. };
  7065. OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
  7066. FunctionDecl *Fn,
  7067. std::string &Description) {
  7068. bool isTemplate = false;
  7069. if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
  7070. isTemplate = true;
  7071. Description = S.getTemplateArgumentBindingsText(
  7072. FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
  7073. }
  7074. if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
  7075. if (!Ctor->isImplicit())
  7076. return isTemplate ? oc_constructor_template : oc_constructor;
  7077. if (Ctor->getInheritedConstructor())
  7078. return oc_implicit_inherited_constructor;
  7079. if (Ctor->isDefaultConstructor())
  7080. return oc_implicit_default_constructor;
  7081. if (Ctor->isMoveConstructor())
  7082. return oc_implicit_move_constructor;
  7083. assert(Ctor->isCopyConstructor() &&
  7084. "unexpected sort of implicit constructor");
  7085. return oc_implicit_copy_constructor;
  7086. }
  7087. if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
  7088. // This actually gets spelled 'candidate function' for now, but
  7089. // it doesn't hurt to split it out.
  7090. if (!Meth->isImplicit())
  7091. return isTemplate ? oc_method_template : oc_method;
  7092. if (Meth->isMoveAssignmentOperator())
  7093. return oc_implicit_move_assignment;
  7094. if (Meth->isCopyAssignmentOperator())
  7095. return oc_implicit_copy_assignment;
  7096. assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
  7097. return oc_method;
  7098. }
  7099. return isTemplate ? oc_function_template : oc_function;
  7100. }
  7101. void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
  7102. const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
  7103. if (!Ctor) return;
  7104. Ctor = Ctor->getInheritedConstructor();
  7105. if (!Ctor) return;
  7106. S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
  7107. }
  7108. } // end anonymous namespace
  7109. // Notes the location of an overload candidate.
  7110. void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
  7111. std::string FnDesc;
  7112. OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
  7113. PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
  7114. << (unsigned) K << FnDesc;
  7115. HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
  7116. Diag(Fn->getLocation(), PD);
  7117. MaybeEmitInheritedConstructorNote(*this, Fn);
  7118. }
  7119. //Notes the location of all overload candidates designated through
  7120. // OverloadedExpr
  7121. void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
  7122. assert(OverloadedExpr->getType() == Context.OverloadTy);
  7123. OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
  7124. OverloadExpr *OvlExpr = Ovl.Expression;
  7125. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  7126. IEnd = OvlExpr->decls_end();
  7127. I != IEnd; ++I) {
  7128. if (FunctionTemplateDecl *FunTmpl =
  7129. dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
  7130. NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
  7131. } else if (FunctionDecl *Fun
  7132. = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
  7133. NoteOverloadCandidate(Fun, DestType);
  7134. }
  7135. }
  7136. }
  7137. /// Diagnoses an ambiguous conversion. The partial diagnostic is the
  7138. /// "lead" diagnostic; it will be given two arguments, the source and
  7139. /// target types of the conversion.
  7140. void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
  7141. Sema &S,
  7142. SourceLocation CaretLoc,
  7143. const PartialDiagnostic &PDiag) const {
  7144. S.Diag(CaretLoc, PDiag)
  7145. << Ambiguous.getFromType() << Ambiguous.getToType();
  7146. for (AmbiguousConversionSequence::const_iterator
  7147. I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
  7148. S.NoteOverloadCandidate(*I);
  7149. }
  7150. }
  7151. namespace {
  7152. void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
  7153. const ImplicitConversionSequence &Conv = Cand->Conversions[I];
  7154. assert(Conv.isBad());
  7155. assert(Cand->Function && "for now, candidate must be a function");
  7156. FunctionDecl *Fn = Cand->Function;
  7157. // There's a conversion slot for the object argument if this is a
  7158. // non-constructor method. Note that 'I' corresponds the
  7159. // conversion-slot index.
  7160. bool isObjectArgument = false;
  7161. if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
  7162. if (I == 0)
  7163. isObjectArgument = true;
  7164. else
  7165. I--;
  7166. }
  7167. std::string FnDesc;
  7168. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  7169. Expr *FromExpr = Conv.Bad.FromExpr;
  7170. QualType FromTy = Conv.Bad.getFromType();
  7171. QualType ToTy = Conv.Bad.getToType();
  7172. if (FromTy == S.Context.OverloadTy) {
  7173. assert(FromExpr && "overload set argument came from implicit argument?");
  7174. Expr *E = FromExpr->IgnoreParens();
  7175. if (isa<UnaryOperator>(E))
  7176. E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
  7177. DeclarationName Name = cast<OverloadExpr>(E)->getName();
  7178. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
  7179. << (unsigned) FnKind << FnDesc
  7180. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7181. << ToTy << Name << I+1;
  7182. MaybeEmitInheritedConstructorNote(S, Fn);
  7183. return;
  7184. }
  7185. // Do some hand-waving analysis to see if the non-viability is due
  7186. // to a qualifier mismatch.
  7187. CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
  7188. CanQualType CToTy = S.Context.getCanonicalType(ToTy);
  7189. if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
  7190. CToTy = RT->getPointeeType();
  7191. else {
  7192. // TODO: detect and diagnose the full richness of const mismatches.
  7193. if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
  7194. if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
  7195. CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
  7196. }
  7197. if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
  7198. !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
  7199. Qualifiers FromQs = CFromTy.getQualifiers();
  7200. Qualifiers ToQs = CToTy.getQualifiers();
  7201. if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
  7202. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
  7203. << (unsigned) FnKind << FnDesc
  7204. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7205. << FromTy
  7206. << FromQs.getAddressSpace() << ToQs.getAddressSpace()
  7207. << (unsigned) isObjectArgument << I+1;
  7208. MaybeEmitInheritedConstructorNote(S, Fn);
  7209. return;
  7210. }
  7211. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  7212. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
  7213. << (unsigned) FnKind << FnDesc
  7214. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7215. << FromTy
  7216. << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
  7217. << (unsigned) isObjectArgument << I+1;
  7218. MaybeEmitInheritedConstructorNote(S, Fn);
  7219. return;
  7220. }
  7221. if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
  7222. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
  7223. << (unsigned) FnKind << FnDesc
  7224. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7225. << FromTy
  7226. << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
  7227. << (unsigned) isObjectArgument << I+1;
  7228. MaybeEmitInheritedConstructorNote(S, Fn);
  7229. return;
  7230. }
  7231. unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
  7232. assert(CVR && "unexpected qualifiers mismatch");
  7233. if (isObjectArgument) {
  7234. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
  7235. << (unsigned) FnKind << FnDesc
  7236. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7237. << FromTy << (CVR - 1);
  7238. } else {
  7239. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
  7240. << (unsigned) FnKind << FnDesc
  7241. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7242. << FromTy << (CVR - 1) << I+1;
  7243. }
  7244. MaybeEmitInheritedConstructorNote(S, Fn);
  7245. return;
  7246. }
  7247. // Special diagnostic for failure to convert an initializer list, since
  7248. // telling the user that it has type void is not useful.
  7249. if (FromExpr && isa<InitListExpr>(FromExpr)) {
  7250. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
  7251. << (unsigned) FnKind << FnDesc
  7252. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7253. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  7254. MaybeEmitInheritedConstructorNote(S, Fn);
  7255. return;
  7256. }
  7257. // Diagnose references or pointers to incomplete types differently,
  7258. // since it's far from impossible that the incompleteness triggered
  7259. // the failure.
  7260. QualType TempFromTy = FromTy.getNonReferenceType();
  7261. if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
  7262. TempFromTy = PTy->getPointeeType();
  7263. if (TempFromTy->isIncompleteType()) {
  7264. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
  7265. << (unsigned) FnKind << FnDesc
  7266. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7267. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  7268. MaybeEmitInheritedConstructorNote(S, Fn);
  7269. return;
  7270. }
  7271. // Diagnose base -> derived pointer conversions.
  7272. unsigned BaseToDerivedConversion = 0;
  7273. if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
  7274. if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
  7275. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  7276. FromPtrTy->getPointeeType()) &&
  7277. !FromPtrTy->getPointeeType()->isIncompleteType() &&
  7278. !ToPtrTy->getPointeeType()->isIncompleteType() &&
  7279. S.IsDerivedFrom(ToPtrTy->getPointeeType(),
  7280. FromPtrTy->getPointeeType()))
  7281. BaseToDerivedConversion = 1;
  7282. }
  7283. } else if (const ObjCObjectPointerType *FromPtrTy
  7284. = FromTy->getAs<ObjCObjectPointerType>()) {
  7285. if (const ObjCObjectPointerType *ToPtrTy
  7286. = ToTy->getAs<ObjCObjectPointerType>())
  7287. if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
  7288. if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
  7289. if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
  7290. FromPtrTy->getPointeeType()) &&
  7291. FromIface->isSuperClassOf(ToIface))
  7292. BaseToDerivedConversion = 2;
  7293. } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
  7294. if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
  7295. !FromTy->isIncompleteType() &&
  7296. !ToRefTy->getPointeeType()->isIncompleteType() &&
  7297. S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
  7298. BaseToDerivedConversion = 3;
  7299. } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
  7300. ToTy.getNonReferenceType().getCanonicalType() ==
  7301. FromTy.getNonReferenceType().getCanonicalType()) {
  7302. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
  7303. << (unsigned) FnKind << FnDesc
  7304. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7305. << (unsigned) isObjectArgument << I + 1;
  7306. MaybeEmitInheritedConstructorNote(S, Fn);
  7307. return;
  7308. }
  7309. }
  7310. if (BaseToDerivedConversion) {
  7311. S.Diag(Fn->getLocation(),
  7312. diag::note_ovl_candidate_bad_base_to_derived_conv)
  7313. << (unsigned) FnKind << FnDesc
  7314. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7315. << (BaseToDerivedConversion - 1)
  7316. << FromTy << ToTy << I+1;
  7317. MaybeEmitInheritedConstructorNote(S, Fn);
  7318. return;
  7319. }
  7320. if (isa<ObjCObjectPointerType>(CFromTy) &&
  7321. isa<PointerType>(CToTy)) {
  7322. Qualifiers FromQs = CFromTy.getQualifiers();
  7323. Qualifiers ToQs = CToTy.getQualifiers();
  7324. if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
  7325. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
  7326. << (unsigned) FnKind << FnDesc
  7327. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7328. << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
  7329. MaybeEmitInheritedConstructorNote(S, Fn);
  7330. return;
  7331. }
  7332. }
  7333. // Emit the generic diagnostic and, optionally, add the hints to it.
  7334. PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
  7335. FDiag << (unsigned) FnKind << FnDesc
  7336. << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
  7337. << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
  7338. << (unsigned) (Cand->Fix.Kind);
  7339. // If we can fix the conversion, suggest the FixIts.
  7340. for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
  7341. HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
  7342. FDiag << *HI;
  7343. S.Diag(Fn->getLocation(), FDiag);
  7344. MaybeEmitInheritedConstructorNote(S, Fn);
  7345. }
  7346. void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
  7347. unsigned NumFormalArgs) {
  7348. // TODO: treat calls to a missing default constructor as a special case
  7349. FunctionDecl *Fn = Cand->Function;
  7350. const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
  7351. unsigned MinParams = Fn->getMinRequiredArguments();
  7352. // With invalid overloaded operators, it's possible that we think we
  7353. // have an arity mismatch when it fact it looks like we have the
  7354. // right number of arguments, because only overloaded operators have
  7355. // the weird behavior of overloading member and non-member functions.
  7356. // Just don't report anything.
  7357. if (Fn->isInvalidDecl() &&
  7358. Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  7359. return;
  7360. // at least / at most / exactly
  7361. unsigned mode, modeCount;
  7362. if (NumFormalArgs < MinParams) {
  7363. assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
  7364. (Cand->FailureKind == ovl_fail_bad_deduction &&
  7365. Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
  7366. if (MinParams != FnTy->getNumArgs() ||
  7367. FnTy->isVariadic() || FnTy->isTemplateVariadic())
  7368. mode = 0; // "at least"
  7369. else
  7370. mode = 2; // "exactly"
  7371. modeCount = MinParams;
  7372. } else {
  7373. assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
  7374. (Cand->FailureKind == ovl_fail_bad_deduction &&
  7375. Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
  7376. if (MinParams != FnTy->getNumArgs())
  7377. mode = 1; // "at most"
  7378. else
  7379. mode = 2; // "exactly"
  7380. modeCount = FnTy->getNumArgs();
  7381. }
  7382. std::string Description;
  7383. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
  7384. if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
  7385. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
  7386. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
  7387. << Fn->getParamDecl(0) << NumFormalArgs;
  7388. else
  7389. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
  7390. << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
  7391. << modeCount << NumFormalArgs;
  7392. MaybeEmitInheritedConstructorNote(S, Fn);
  7393. }
  7394. /// Diagnose a failed template-argument deduction.
  7395. void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
  7396. unsigned NumArgs) {
  7397. FunctionDecl *Fn = Cand->Function; // pattern
  7398. TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
  7399. NamedDecl *ParamD;
  7400. (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
  7401. (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
  7402. (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
  7403. switch (Cand->DeductionFailure.Result) {
  7404. case Sema::TDK_Success:
  7405. llvm_unreachable("TDK_success while diagnosing bad deduction");
  7406. case Sema::TDK_Incomplete: {
  7407. assert(ParamD && "no parameter found for incomplete deduction result");
  7408. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
  7409. << ParamD->getDeclName();
  7410. MaybeEmitInheritedConstructorNote(S, Fn);
  7411. return;
  7412. }
  7413. case Sema::TDK_Underqualified: {
  7414. assert(ParamD && "no parameter found for bad qualifiers deduction result");
  7415. TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
  7416. QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
  7417. // Param will have been canonicalized, but it should just be a
  7418. // qualified version of ParamD, so move the qualifiers to that.
  7419. QualifierCollector Qs;
  7420. Qs.strip(Param);
  7421. QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
  7422. assert(S.Context.hasSameType(Param, NonCanonParam));
  7423. // Arg has also been canonicalized, but there's nothing we can do
  7424. // about that. It also doesn't matter as much, because it won't
  7425. // have any template parameters in it (because deduction isn't
  7426. // done on dependent types).
  7427. QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
  7428. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
  7429. << ParamD->getDeclName() << Arg << NonCanonParam;
  7430. MaybeEmitInheritedConstructorNote(S, Fn);
  7431. return;
  7432. }
  7433. case Sema::TDK_Inconsistent: {
  7434. assert(ParamD && "no parameter found for inconsistent deduction result");
  7435. int which = 0;
  7436. if (isa<TemplateTypeParmDecl>(ParamD))
  7437. which = 0;
  7438. else if (isa<NonTypeTemplateParmDecl>(ParamD))
  7439. which = 1;
  7440. else {
  7441. which = 2;
  7442. }
  7443. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
  7444. << which << ParamD->getDeclName()
  7445. << *Cand->DeductionFailure.getFirstArg()
  7446. << *Cand->DeductionFailure.getSecondArg();
  7447. MaybeEmitInheritedConstructorNote(S, Fn);
  7448. return;
  7449. }
  7450. case Sema::TDK_InvalidExplicitArguments:
  7451. assert(ParamD && "no parameter found for invalid explicit arguments");
  7452. if (ParamD->getDeclName())
  7453. S.Diag(Fn->getLocation(),
  7454. diag::note_ovl_candidate_explicit_arg_mismatch_named)
  7455. << ParamD->getDeclName();
  7456. else {
  7457. int index = 0;
  7458. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
  7459. index = TTP->getIndex();
  7460. else if (NonTypeTemplateParmDecl *NTTP
  7461. = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
  7462. index = NTTP->getIndex();
  7463. else
  7464. index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
  7465. S.Diag(Fn->getLocation(),
  7466. diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
  7467. << (index + 1);
  7468. }
  7469. MaybeEmitInheritedConstructorNote(S, Fn);
  7470. return;
  7471. case Sema::TDK_TooManyArguments:
  7472. case Sema::TDK_TooFewArguments:
  7473. DiagnoseArityMismatch(S, Cand, NumArgs);
  7474. return;
  7475. case Sema::TDK_InstantiationDepth:
  7476. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
  7477. MaybeEmitInheritedConstructorNote(S, Fn);
  7478. return;
  7479. case Sema::TDK_SubstitutionFailure: {
  7480. // Format the template argument list into the argument string.
  7481. llvm::SmallString<128> TemplateArgString;
  7482. if (TemplateArgumentList *Args =
  7483. Cand->DeductionFailure.getTemplateArgumentList()) {
  7484. TemplateArgString = " ";
  7485. TemplateArgString += S.getTemplateArgumentBindingsText(
  7486. Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
  7487. }
  7488. // If this candidate was disabled by enable_if, say so.
  7489. PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
  7490. if (PDiag && PDiag->second.getDiagID() ==
  7491. diag::err_typename_nested_not_found_enable_if) {
  7492. // FIXME: Use the source range of the condition, and the fully-qualified
  7493. // name of the enable_if template. These are both present in PDiag.
  7494. S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
  7495. << "'enable_if'" << TemplateArgString;
  7496. return;
  7497. }
  7498. // Format the SFINAE diagnostic into the argument string.
  7499. // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
  7500. // formatted message in another diagnostic.
  7501. llvm::SmallString<128> SFINAEArgString;
  7502. SourceRange R;
  7503. if (PDiag) {
  7504. SFINAEArgString = ": ";
  7505. R = SourceRange(PDiag->first, PDiag->first);
  7506. PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
  7507. }
  7508. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
  7509. << TemplateArgString << SFINAEArgString << R;
  7510. MaybeEmitInheritedConstructorNote(S, Fn);
  7511. return;
  7512. }
  7513. // TODO: diagnose these individually, then kill off
  7514. // note_ovl_candidate_bad_deduction, which is uselessly vague.
  7515. case Sema::TDK_NonDeducedMismatch:
  7516. case Sema::TDK_FailedOverloadResolution:
  7517. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
  7518. MaybeEmitInheritedConstructorNote(S, Fn);
  7519. return;
  7520. }
  7521. }
  7522. /// CUDA: diagnose an invalid call across targets.
  7523. void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
  7524. FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
  7525. FunctionDecl *Callee = Cand->Function;
  7526. Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
  7527. CalleeTarget = S.IdentifyCUDATarget(Callee);
  7528. std::string FnDesc;
  7529. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
  7530. S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
  7531. << (unsigned) FnKind << CalleeTarget << CallerTarget;
  7532. }
  7533. /// Generates a 'note' diagnostic for an overload candidate. We've
  7534. /// already generated a primary error at the call site.
  7535. ///
  7536. /// It really does need to be a single diagnostic with its caret
  7537. /// pointed at the candidate declaration. Yes, this creates some
  7538. /// major challenges of technical writing. Yes, this makes pointing
  7539. /// out problems with specific arguments quite awkward. It's still
  7540. /// better than generating twenty screens of text for every failed
  7541. /// overload.
  7542. ///
  7543. /// It would be great to be able to express per-candidate problems
  7544. /// more richly for those diagnostic clients that cared, but we'd
  7545. /// still have to be just as careful with the default diagnostics.
  7546. void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
  7547. unsigned NumArgs) {
  7548. FunctionDecl *Fn = Cand->Function;
  7549. // Note deleted candidates, but only if they're viable.
  7550. if (Cand->Viable && (Fn->isDeleted() ||
  7551. S.isFunctionConsideredUnavailable(Fn))) {
  7552. std::string FnDesc;
  7553. OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
  7554. S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
  7555. << FnKind << FnDesc
  7556. << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
  7557. MaybeEmitInheritedConstructorNote(S, Fn);
  7558. return;
  7559. }
  7560. // We don't really have anything else to say about viable candidates.
  7561. if (Cand->Viable) {
  7562. S.NoteOverloadCandidate(Fn);
  7563. return;
  7564. }
  7565. switch (Cand->FailureKind) {
  7566. case ovl_fail_too_many_arguments:
  7567. case ovl_fail_too_few_arguments:
  7568. return DiagnoseArityMismatch(S, Cand, NumArgs);
  7569. case ovl_fail_bad_deduction:
  7570. return DiagnoseBadDeduction(S, Cand, NumArgs);
  7571. case ovl_fail_trivial_conversion:
  7572. case ovl_fail_bad_final_conversion:
  7573. case ovl_fail_final_conversion_not_exact:
  7574. return S.NoteOverloadCandidate(Fn);
  7575. case ovl_fail_bad_conversion: {
  7576. unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
  7577. for (unsigned N = Cand->NumConversions; I != N; ++I)
  7578. if (Cand->Conversions[I].isBad())
  7579. return DiagnoseBadConversion(S, Cand, I);
  7580. // FIXME: this currently happens when we're called from SemaInit
  7581. // when user-conversion overload fails. Figure out how to handle
  7582. // those conditions and diagnose them well.
  7583. return S.NoteOverloadCandidate(Fn);
  7584. }
  7585. case ovl_fail_bad_target:
  7586. return DiagnoseBadTarget(S, Cand);
  7587. }
  7588. }
  7589. void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
  7590. // Desugar the type of the surrogate down to a function type,
  7591. // retaining as many typedefs as possible while still showing
  7592. // the function type (and, therefore, its parameter types).
  7593. QualType FnType = Cand->Surrogate->getConversionType();
  7594. bool isLValueReference = false;
  7595. bool isRValueReference = false;
  7596. bool isPointer = false;
  7597. if (const LValueReferenceType *FnTypeRef =
  7598. FnType->getAs<LValueReferenceType>()) {
  7599. FnType = FnTypeRef->getPointeeType();
  7600. isLValueReference = true;
  7601. } else if (const RValueReferenceType *FnTypeRef =
  7602. FnType->getAs<RValueReferenceType>()) {
  7603. FnType = FnTypeRef->getPointeeType();
  7604. isRValueReference = true;
  7605. }
  7606. if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
  7607. FnType = FnTypePtr->getPointeeType();
  7608. isPointer = true;
  7609. }
  7610. // Desugar down to a function type.
  7611. FnType = QualType(FnType->getAs<FunctionType>(), 0);
  7612. // Reconstruct the pointer/reference as appropriate.
  7613. if (isPointer) FnType = S.Context.getPointerType(FnType);
  7614. if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
  7615. if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
  7616. S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
  7617. << FnType;
  7618. MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
  7619. }
  7620. void NoteBuiltinOperatorCandidate(Sema &S,
  7621. const char *Opc,
  7622. SourceLocation OpLoc,
  7623. OverloadCandidate *Cand) {
  7624. assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
  7625. std::string TypeStr("operator");
  7626. TypeStr += Opc;
  7627. TypeStr += "(";
  7628. TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
  7629. if (Cand->NumConversions == 1) {
  7630. TypeStr += ")";
  7631. S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
  7632. } else {
  7633. TypeStr += ", ";
  7634. TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
  7635. TypeStr += ")";
  7636. S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
  7637. }
  7638. }
  7639. void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
  7640. OverloadCandidate *Cand) {
  7641. unsigned NoOperands = Cand->NumConversions;
  7642. for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
  7643. const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
  7644. if (ICS.isBad()) break; // all meaningless after first invalid
  7645. if (!ICS.isAmbiguous()) continue;
  7646. ICS.DiagnoseAmbiguousConversion(S, OpLoc,
  7647. S.PDiag(diag::note_ambiguous_type_conversion));
  7648. }
  7649. }
  7650. SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
  7651. if (Cand->Function)
  7652. return Cand->Function->getLocation();
  7653. if (Cand->IsSurrogate)
  7654. return Cand->Surrogate->getLocation();
  7655. return SourceLocation();
  7656. }
  7657. static unsigned
  7658. RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
  7659. switch ((Sema::TemplateDeductionResult)DFI.Result) {
  7660. case Sema::TDK_Success:
  7661. llvm_unreachable("TDK_success while diagnosing bad deduction");
  7662. case Sema::TDK_Incomplete:
  7663. return 1;
  7664. case Sema::TDK_Underqualified:
  7665. case Sema::TDK_Inconsistent:
  7666. return 2;
  7667. case Sema::TDK_SubstitutionFailure:
  7668. case Sema::TDK_NonDeducedMismatch:
  7669. return 3;
  7670. case Sema::TDK_InstantiationDepth:
  7671. case Sema::TDK_FailedOverloadResolution:
  7672. return 4;
  7673. case Sema::TDK_InvalidExplicitArguments:
  7674. return 5;
  7675. case Sema::TDK_TooManyArguments:
  7676. case Sema::TDK_TooFewArguments:
  7677. return 6;
  7678. }
  7679. llvm_unreachable("Unhandled deduction result");
  7680. }
  7681. struct CompareOverloadCandidatesForDisplay {
  7682. Sema &S;
  7683. CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
  7684. bool operator()(const OverloadCandidate *L,
  7685. const OverloadCandidate *R) {
  7686. // Fast-path this check.
  7687. if (L == R) return false;
  7688. // Order first by viability.
  7689. if (L->Viable) {
  7690. if (!R->Viable) return true;
  7691. // TODO: introduce a tri-valued comparison for overload
  7692. // candidates. Would be more worthwhile if we had a sort
  7693. // that could exploit it.
  7694. if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
  7695. if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
  7696. } else if (R->Viable)
  7697. return false;
  7698. assert(L->Viable == R->Viable);
  7699. // Criteria by which we can sort non-viable candidates:
  7700. if (!L->Viable) {
  7701. // 1. Arity mismatches come after other candidates.
  7702. if (L->FailureKind == ovl_fail_too_many_arguments ||
  7703. L->FailureKind == ovl_fail_too_few_arguments)
  7704. return false;
  7705. if (R->FailureKind == ovl_fail_too_many_arguments ||
  7706. R->FailureKind == ovl_fail_too_few_arguments)
  7707. return true;
  7708. // 2. Bad conversions come first and are ordered by the number
  7709. // of bad conversions and quality of good conversions.
  7710. if (L->FailureKind == ovl_fail_bad_conversion) {
  7711. if (R->FailureKind != ovl_fail_bad_conversion)
  7712. return true;
  7713. // The conversion that can be fixed with a smaller number of changes,
  7714. // comes first.
  7715. unsigned numLFixes = L->Fix.NumConversionsFixed;
  7716. unsigned numRFixes = R->Fix.NumConversionsFixed;
  7717. numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
  7718. numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
  7719. if (numLFixes != numRFixes) {
  7720. if (numLFixes < numRFixes)
  7721. return true;
  7722. else
  7723. return false;
  7724. }
  7725. // If there's any ordering between the defined conversions...
  7726. // FIXME: this might not be transitive.
  7727. assert(L->NumConversions == R->NumConversions);
  7728. int leftBetter = 0;
  7729. unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
  7730. for (unsigned E = L->NumConversions; I != E; ++I) {
  7731. switch (CompareImplicitConversionSequences(S,
  7732. L->Conversions[I],
  7733. R->Conversions[I])) {
  7734. case ImplicitConversionSequence::Better:
  7735. leftBetter++;
  7736. break;
  7737. case ImplicitConversionSequence::Worse:
  7738. leftBetter--;
  7739. break;
  7740. case ImplicitConversionSequence::Indistinguishable:
  7741. break;
  7742. }
  7743. }
  7744. if (leftBetter > 0) return true;
  7745. if (leftBetter < 0) return false;
  7746. } else if (R->FailureKind == ovl_fail_bad_conversion)
  7747. return false;
  7748. if (L->FailureKind == ovl_fail_bad_deduction) {
  7749. if (R->FailureKind != ovl_fail_bad_deduction)
  7750. return true;
  7751. if (L->DeductionFailure.Result != R->DeductionFailure.Result)
  7752. return RankDeductionFailure(L->DeductionFailure)
  7753. < RankDeductionFailure(R->DeductionFailure);
  7754. } else if (R->FailureKind == ovl_fail_bad_deduction)
  7755. return false;
  7756. // TODO: others?
  7757. }
  7758. // Sort everything else by location.
  7759. SourceLocation LLoc = GetLocationForCandidate(L);
  7760. SourceLocation RLoc = GetLocationForCandidate(R);
  7761. // Put candidates without locations (e.g. builtins) at the end.
  7762. if (LLoc.isInvalid()) return false;
  7763. if (RLoc.isInvalid()) return true;
  7764. return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
  7765. }
  7766. };
  7767. /// CompleteNonViableCandidate - Normally, overload resolution only
  7768. /// computes up to the first. Produces the FixIt set if possible.
  7769. void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
  7770. llvm::ArrayRef<Expr *> Args) {
  7771. assert(!Cand->Viable);
  7772. // Don't do anything on failures other than bad conversion.
  7773. if (Cand->FailureKind != ovl_fail_bad_conversion) return;
  7774. // We only want the FixIts if all the arguments can be corrected.
  7775. bool Unfixable = false;
  7776. // Use a implicit copy initialization to check conversion fixes.
  7777. Cand->Fix.setConversionChecker(TryCopyInitialization);
  7778. // Skip forward to the first bad conversion.
  7779. unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
  7780. unsigned ConvCount = Cand->NumConversions;
  7781. while (true) {
  7782. assert(ConvIdx != ConvCount && "no bad conversion in candidate");
  7783. ConvIdx++;
  7784. if (Cand->Conversions[ConvIdx - 1].isBad()) {
  7785. Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
  7786. break;
  7787. }
  7788. }
  7789. if (ConvIdx == ConvCount)
  7790. return;
  7791. assert(!Cand->Conversions[ConvIdx].isInitialized() &&
  7792. "remaining conversion is initialized?");
  7793. // FIXME: this should probably be preserved from the overload
  7794. // operation somehow.
  7795. bool SuppressUserConversions = false;
  7796. const FunctionProtoType* Proto;
  7797. unsigned ArgIdx = ConvIdx;
  7798. if (Cand->IsSurrogate) {
  7799. QualType ConvType
  7800. = Cand->Surrogate->getConversionType().getNonReferenceType();
  7801. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  7802. ConvType = ConvPtrType->getPointeeType();
  7803. Proto = ConvType->getAs<FunctionProtoType>();
  7804. ArgIdx--;
  7805. } else if (Cand->Function) {
  7806. Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
  7807. if (isa<CXXMethodDecl>(Cand->Function) &&
  7808. !isa<CXXConstructorDecl>(Cand->Function))
  7809. ArgIdx--;
  7810. } else {
  7811. // Builtin binary operator with a bad first conversion.
  7812. assert(ConvCount <= 3);
  7813. for (; ConvIdx != ConvCount; ++ConvIdx)
  7814. Cand->Conversions[ConvIdx]
  7815. = TryCopyInitialization(S, Args[ConvIdx],
  7816. Cand->BuiltinTypes.ParamTypes[ConvIdx],
  7817. SuppressUserConversions,
  7818. /*InOverloadResolution*/ true,
  7819. /*AllowObjCWritebackConversion=*/
  7820. S.getLangOpts().ObjCAutoRefCount);
  7821. return;
  7822. }
  7823. // Fill in the rest of the conversions.
  7824. unsigned NumArgsInProto = Proto->getNumArgs();
  7825. for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
  7826. if (ArgIdx < NumArgsInProto) {
  7827. Cand->Conversions[ConvIdx]
  7828. = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
  7829. SuppressUserConversions,
  7830. /*InOverloadResolution=*/true,
  7831. /*AllowObjCWritebackConversion=*/
  7832. S.getLangOpts().ObjCAutoRefCount);
  7833. // Store the FixIt in the candidate if it exists.
  7834. if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
  7835. Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
  7836. }
  7837. else
  7838. Cand->Conversions[ConvIdx].setEllipsis();
  7839. }
  7840. }
  7841. } // end anonymous namespace
  7842. /// PrintOverloadCandidates - When overload resolution fails, prints
  7843. /// diagnostic messages containing the candidates in the candidate
  7844. /// set.
  7845. void OverloadCandidateSet::NoteCandidates(Sema &S,
  7846. OverloadCandidateDisplayKind OCD,
  7847. llvm::ArrayRef<Expr *> Args,
  7848. const char *Opc,
  7849. SourceLocation OpLoc) {
  7850. // Sort the candidates by viability and position. Sorting directly would
  7851. // be prohibitive, so we make a set of pointers and sort those.
  7852. SmallVector<OverloadCandidate*, 32> Cands;
  7853. if (OCD == OCD_AllCandidates) Cands.reserve(size());
  7854. for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
  7855. if (Cand->Viable)
  7856. Cands.push_back(Cand);
  7857. else if (OCD == OCD_AllCandidates) {
  7858. CompleteNonViableCandidate(S, Cand, Args);
  7859. if (Cand->Function || Cand->IsSurrogate)
  7860. Cands.push_back(Cand);
  7861. // Otherwise, this a non-viable builtin candidate. We do not, in general,
  7862. // want to list every possible builtin candidate.
  7863. }
  7864. }
  7865. std::sort(Cands.begin(), Cands.end(),
  7866. CompareOverloadCandidatesForDisplay(S));
  7867. bool ReportedAmbiguousConversions = false;
  7868. SmallVectorImpl<OverloadCandidate*>::iterator I, E;
  7869. const DiagnosticsEngine::OverloadsShown ShowOverloads =
  7870. S.Diags.getShowOverloads();
  7871. unsigned CandsShown = 0;
  7872. for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
  7873. OverloadCandidate *Cand = *I;
  7874. // Set an arbitrary limit on the number of candidate functions we'll spam
  7875. // the user with. FIXME: This limit should depend on details of the
  7876. // candidate list.
  7877. if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
  7878. break;
  7879. }
  7880. ++CandsShown;
  7881. if (Cand->Function)
  7882. NoteFunctionCandidate(S, Cand, Args.size());
  7883. else if (Cand->IsSurrogate)
  7884. NoteSurrogateCandidate(S, Cand);
  7885. else {
  7886. assert(Cand->Viable &&
  7887. "Non-viable built-in candidates are not added to Cands.");
  7888. // Generally we only see ambiguities including viable builtin
  7889. // operators if overload resolution got screwed up by an
  7890. // ambiguous user-defined conversion.
  7891. //
  7892. // FIXME: It's quite possible for different conversions to see
  7893. // different ambiguities, though.
  7894. if (!ReportedAmbiguousConversions) {
  7895. NoteAmbiguousUserConversions(S, OpLoc, Cand);
  7896. ReportedAmbiguousConversions = true;
  7897. }
  7898. // If this is a viable builtin, print it.
  7899. NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
  7900. }
  7901. }
  7902. if (I != E)
  7903. S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
  7904. }
  7905. // [PossiblyAFunctionType] --> [Return]
  7906. // NonFunctionType --> NonFunctionType
  7907. // R (A) --> R(A)
  7908. // R (*)(A) --> R (A)
  7909. // R (&)(A) --> R (A)
  7910. // R (S::*)(A) --> R (A)
  7911. QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
  7912. QualType Ret = PossiblyAFunctionType;
  7913. if (const PointerType *ToTypePtr =
  7914. PossiblyAFunctionType->getAs<PointerType>())
  7915. Ret = ToTypePtr->getPointeeType();
  7916. else if (const ReferenceType *ToTypeRef =
  7917. PossiblyAFunctionType->getAs<ReferenceType>())
  7918. Ret = ToTypeRef->getPointeeType();
  7919. else if (const MemberPointerType *MemTypePtr =
  7920. PossiblyAFunctionType->getAs<MemberPointerType>())
  7921. Ret = MemTypePtr->getPointeeType();
  7922. Ret =
  7923. Context.getCanonicalType(Ret).getUnqualifiedType();
  7924. return Ret;
  7925. }
  7926. // A helper class to help with address of function resolution
  7927. // - allows us to avoid passing around all those ugly parameters
  7928. class AddressOfFunctionResolver
  7929. {
  7930. Sema& S;
  7931. Expr* SourceExpr;
  7932. const QualType& TargetType;
  7933. QualType TargetFunctionType; // Extracted function type from target type
  7934. bool Complain;
  7935. //DeclAccessPair& ResultFunctionAccessPair;
  7936. ASTContext& Context;
  7937. bool TargetTypeIsNonStaticMemberFunction;
  7938. bool FoundNonTemplateFunction;
  7939. OverloadExpr::FindResult OvlExprInfo;
  7940. OverloadExpr *OvlExpr;
  7941. TemplateArgumentListInfo OvlExplicitTemplateArgs;
  7942. SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
  7943. public:
  7944. AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
  7945. const QualType& TargetType, bool Complain)
  7946. : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
  7947. Complain(Complain), Context(S.getASTContext()),
  7948. TargetTypeIsNonStaticMemberFunction(
  7949. !!TargetType->getAs<MemberPointerType>()),
  7950. FoundNonTemplateFunction(false),
  7951. OvlExprInfo(OverloadExpr::find(SourceExpr)),
  7952. OvlExpr(OvlExprInfo.Expression)
  7953. {
  7954. ExtractUnqualifiedFunctionTypeFromTargetType();
  7955. if (!TargetFunctionType->isFunctionType()) {
  7956. if (OvlExpr->hasExplicitTemplateArgs()) {
  7957. DeclAccessPair dap;
  7958. if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
  7959. OvlExpr, false, &dap) ) {
  7960. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  7961. if (!Method->isStatic()) {
  7962. // If the target type is a non-function type and the function
  7963. // found is a non-static member function, pretend as if that was
  7964. // the target, it's the only possible type to end up with.
  7965. TargetTypeIsNonStaticMemberFunction = true;
  7966. // And skip adding the function if its not in the proper form.
  7967. // We'll diagnose this due to an empty set of functions.
  7968. if (!OvlExprInfo.HasFormOfMemberPointer)
  7969. return;
  7970. }
  7971. }
  7972. Matches.push_back(std::make_pair(dap,Fn));
  7973. }
  7974. }
  7975. return;
  7976. }
  7977. if (OvlExpr->hasExplicitTemplateArgs())
  7978. OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
  7979. if (FindAllFunctionsThatMatchTargetTypeExactly()) {
  7980. // C++ [over.over]p4:
  7981. // If more than one function is selected, [...]
  7982. if (Matches.size() > 1) {
  7983. if (FoundNonTemplateFunction)
  7984. EliminateAllTemplateMatches();
  7985. else
  7986. EliminateAllExceptMostSpecializedTemplate();
  7987. }
  7988. }
  7989. }
  7990. private:
  7991. bool isTargetTypeAFunction() const {
  7992. return TargetFunctionType->isFunctionType();
  7993. }
  7994. // [ToType] [Return]
  7995. // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
  7996. // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
  7997. // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
  7998. void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
  7999. TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
  8000. }
  8001. // return true if any matching specializations were found
  8002. bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
  8003. const DeclAccessPair& CurAccessFunPair) {
  8004. if (CXXMethodDecl *Method
  8005. = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
  8006. // Skip non-static function templates when converting to pointer, and
  8007. // static when converting to member pointer.
  8008. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  8009. return false;
  8010. }
  8011. else if (TargetTypeIsNonStaticMemberFunction)
  8012. return false;
  8013. // C++ [over.over]p2:
  8014. // If the name is a function template, template argument deduction is
  8015. // done (14.8.2.2), and if the argument deduction succeeds, the
  8016. // resulting template argument list is used to generate a single
  8017. // function template specialization, which is added to the set of
  8018. // overloaded functions considered.
  8019. FunctionDecl *Specialization = 0;
  8020. TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
  8021. if (Sema::TemplateDeductionResult Result
  8022. = S.DeduceTemplateArguments(FunctionTemplate,
  8023. &OvlExplicitTemplateArgs,
  8024. TargetFunctionType, Specialization,
  8025. Info)) {
  8026. // FIXME: make a note of the failed deduction for diagnostics.
  8027. (void)Result;
  8028. return false;
  8029. }
  8030. // Template argument deduction ensures that we have an exact match.
  8031. // This function template specicalization works.
  8032. Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
  8033. assert(TargetFunctionType
  8034. == Context.getCanonicalType(Specialization->getType()));
  8035. Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
  8036. return true;
  8037. }
  8038. bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
  8039. const DeclAccessPair& CurAccessFunPair) {
  8040. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  8041. // Skip non-static functions when converting to pointer, and static
  8042. // when converting to member pointer.
  8043. if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
  8044. return false;
  8045. }
  8046. else if (TargetTypeIsNonStaticMemberFunction)
  8047. return false;
  8048. if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
  8049. if (S.getLangOpts().CUDA)
  8050. if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
  8051. if (S.CheckCUDATarget(Caller, FunDecl))
  8052. return false;
  8053. QualType ResultTy;
  8054. if (Context.hasSameUnqualifiedType(TargetFunctionType,
  8055. FunDecl->getType()) ||
  8056. S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
  8057. ResultTy)) {
  8058. Matches.push_back(std::make_pair(CurAccessFunPair,
  8059. cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
  8060. FoundNonTemplateFunction = true;
  8061. return true;
  8062. }
  8063. }
  8064. return false;
  8065. }
  8066. bool FindAllFunctionsThatMatchTargetTypeExactly() {
  8067. bool Ret = false;
  8068. // If the overload expression doesn't have the form of a pointer to
  8069. // member, don't try to convert it to a pointer-to-member type.
  8070. if (IsInvalidFormOfPointerToMemberFunction())
  8071. return false;
  8072. for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
  8073. E = OvlExpr->decls_end();
  8074. I != E; ++I) {
  8075. // Look through any using declarations to find the underlying function.
  8076. NamedDecl *Fn = (*I)->getUnderlyingDecl();
  8077. // C++ [over.over]p3:
  8078. // Non-member functions and static member functions match
  8079. // targets of type "pointer-to-function" or "reference-to-function."
  8080. // Nonstatic member functions match targets of
  8081. // type "pointer-to-member-function."
  8082. // Note that according to DR 247, the containing class does not matter.
  8083. if (FunctionTemplateDecl *FunctionTemplate
  8084. = dyn_cast<FunctionTemplateDecl>(Fn)) {
  8085. if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
  8086. Ret = true;
  8087. }
  8088. // If we have explicit template arguments supplied, skip non-templates.
  8089. else if (!OvlExpr->hasExplicitTemplateArgs() &&
  8090. AddMatchingNonTemplateFunction(Fn, I.getPair()))
  8091. Ret = true;
  8092. }
  8093. assert(Ret || Matches.empty());
  8094. return Ret;
  8095. }
  8096. void EliminateAllExceptMostSpecializedTemplate() {
  8097. // [...] and any given function template specialization F1 is
  8098. // eliminated if the set contains a second function template
  8099. // specialization whose function template is more specialized
  8100. // than the function template of F1 according to the partial
  8101. // ordering rules of 14.5.5.2.
  8102. // The algorithm specified above is quadratic. We instead use a
  8103. // two-pass algorithm (similar to the one used to identify the
  8104. // best viable function in an overload set) that identifies the
  8105. // best function template (if it exists).
  8106. UnresolvedSet<4> MatchesCopy; // TODO: avoid!
  8107. for (unsigned I = 0, E = Matches.size(); I != E; ++I)
  8108. MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
  8109. UnresolvedSetIterator Result =
  8110. S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
  8111. TPOC_Other, 0, SourceExpr->getLocStart(),
  8112. S.PDiag(),
  8113. S.PDiag(diag::err_addr_ovl_ambiguous)
  8114. << Matches[0].second->getDeclName(),
  8115. S.PDiag(diag::note_ovl_candidate)
  8116. << (unsigned) oc_function_template,
  8117. Complain, TargetFunctionType);
  8118. if (Result != MatchesCopy.end()) {
  8119. // Make it the first and only element
  8120. Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
  8121. Matches[0].second = cast<FunctionDecl>(*Result);
  8122. Matches.resize(1);
  8123. }
  8124. }
  8125. void EliminateAllTemplateMatches() {
  8126. // [...] any function template specializations in the set are
  8127. // eliminated if the set also contains a non-template function, [...]
  8128. for (unsigned I = 0, N = Matches.size(); I != N; ) {
  8129. if (Matches[I].second->getPrimaryTemplate() == 0)
  8130. ++I;
  8131. else {
  8132. Matches[I] = Matches[--N];
  8133. Matches.set_size(N);
  8134. }
  8135. }
  8136. }
  8137. public:
  8138. void ComplainNoMatchesFound() const {
  8139. assert(Matches.empty());
  8140. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
  8141. << OvlExpr->getName() << TargetFunctionType
  8142. << OvlExpr->getSourceRange();
  8143. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  8144. }
  8145. bool IsInvalidFormOfPointerToMemberFunction() const {
  8146. return TargetTypeIsNonStaticMemberFunction &&
  8147. !OvlExprInfo.HasFormOfMemberPointer;
  8148. }
  8149. void ComplainIsInvalidFormOfPointerToMemberFunction() const {
  8150. // TODO: Should we condition this on whether any functions might
  8151. // have matched, or is it more appropriate to do that in callers?
  8152. // TODO: a fixit wouldn't hurt.
  8153. S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
  8154. << TargetType << OvlExpr->getSourceRange();
  8155. }
  8156. void ComplainOfInvalidConversion() const {
  8157. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
  8158. << OvlExpr->getName() << TargetType;
  8159. }
  8160. void ComplainMultipleMatchesFound() const {
  8161. assert(Matches.size() > 1);
  8162. S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
  8163. << OvlExpr->getName()
  8164. << OvlExpr->getSourceRange();
  8165. S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
  8166. }
  8167. bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
  8168. int getNumMatches() const { return Matches.size(); }
  8169. FunctionDecl* getMatchingFunctionDecl() const {
  8170. if (Matches.size() != 1) return 0;
  8171. return Matches[0].second;
  8172. }
  8173. const DeclAccessPair* getMatchingFunctionAccessPair() const {
  8174. if (Matches.size() != 1) return 0;
  8175. return &Matches[0].first;
  8176. }
  8177. };
  8178. /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
  8179. /// an overloaded function (C++ [over.over]), where @p From is an
  8180. /// expression with overloaded function type and @p ToType is the type
  8181. /// we're trying to resolve to. For example:
  8182. ///
  8183. /// @code
  8184. /// int f(double);
  8185. /// int f(int);
  8186. ///
  8187. /// int (*pfd)(double) = f; // selects f(double)
  8188. /// @endcode
  8189. ///
  8190. /// This routine returns the resulting FunctionDecl if it could be
  8191. /// resolved, and NULL otherwise. When @p Complain is true, this
  8192. /// routine will emit diagnostics if there is an error.
  8193. FunctionDecl *
  8194. Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
  8195. QualType TargetType,
  8196. bool Complain,
  8197. DeclAccessPair &FoundResult,
  8198. bool *pHadMultipleCandidates) {
  8199. assert(AddressOfExpr->getType() == Context.OverloadTy);
  8200. AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
  8201. Complain);
  8202. int NumMatches = Resolver.getNumMatches();
  8203. FunctionDecl* Fn = 0;
  8204. if (NumMatches == 0 && Complain) {
  8205. if (Resolver.IsInvalidFormOfPointerToMemberFunction())
  8206. Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
  8207. else
  8208. Resolver.ComplainNoMatchesFound();
  8209. }
  8210. else if (NumMatches > 1 && Complain)
  8211. Resolver.ComplainMultipleMatchesFound();
  8212. else if (NumMatches == 1) {
  8213. Fn = Resolver.getMatchingFunctionDecl();
  8214. assert(Fn);
  8215. FoundResult = *Resolver.getMatchingFunctionAccessPair();
  8216. MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
  8217. if (Complain)
  8218. CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
  8219. }
  8220. if (pHadMultipleCandidates)
  8221. *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
  8222. return Fn;
  8223. }
  8224. /// \brief Given an expression that refers to an overloaded function, try to
  8225. /// resolve that overloaded function expression down to a single function.
  8226. ///
  8227. /// This routine can only resolve template-ids that refer to a single function
  8228. /// template, where that template-id refers to a single template whose template
  8229. /// arguments are either provided by the template-id or have defaults,
  8230. /// as described in C++0x [temp.arg.explicit]p3.
  8231. FunctionDecl *
  8232. Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
  8233. bool Complain,
  8234. DeclAccessPair *FoundResult) {
  8235. // C++ [over.over]p1:
  8236. // [...] [Note: any redundant set of parentheses surrounding the
  8237. // overloaded function name is ignored (5.1). ]
  8238. // C++ [over.over]p1:
  8239. // [...] The overloaded function name can be preceded by the &
  8240. // operator.
  8241. // If we didn't actually find any template-ids, we're done.
  8242. if (!ovl->hasExplicitTemplateArgs())
  8243. return 0;
  8244. TemplateArgumentListInfo ExplicitTemplateArgs;
  8245. ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
  8246. // Look through all of the overloaded functions, searching for one
  8247. // whose type matches exactly.
  8248. FunctionDecl *Matched = 0;
  8249. for (UnresolvedSetIterator I = ovl->decls_begin(),
  8250. E = ovl->decls_end(); I != E; ++I) {
  8251. // C++0x [temp.arg.explicit]p3:
  8252. // [...] In contexts where deduction is done and fails, or in contexts
  8253. // where deduction is not done, if a template argument list is
  8254. // specified and it, along with any default template arguments,
  8255. // identifies a single function template specialization, then the
  8256. // template-id is an lvalue for the function template specialization.
  8257. FunctionTemplateDecl *FunctionTemplate
  8258. = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
  8259. // C++ [over.over]p2:
  8260. // If the name is a function template, template argument deduction is
  8261. // done (14.8.2.2), and if the argument deduction succeeds, the
  8262. // resulting template argument list is used to generate a single
  8263. // function template specialization, which is added to the set of
  8264. // overloaded functions considered.
  8265. FunctionDecl *Specialization = 0;
  8266. TemplateDeductionInfo Info(Context, ovl->getNameLoc());
  8267. if (TemplateDeductionResult Result
  8268. = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
  8269. Specialization, Info)) {
  8270. // FIXME: make a note of the failed deduction for diagnostics.
  8271. (void)Result;
  8272. continue;
  8273. }
  8274. assert(Specialization && "no specialization and no error?");
  8275. // Multiple matches; we can't resolve to a single declaration.
  8276. if (Matched) {
  8277. if (Complain) {
  8278. Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
  8279. << ovl->getName();
  8280. NoteAllOverloadCandidates(ovl);
  8281. }
  8282. return 0;
  8283. }
  8284. Matched = Specialization;
  8285. if (FoundResult) *FoundResult = I.getPair();
  8286. }
  8287. return Matched;
  8288. }
  8289. // Resolve and fix an overloaded expression that can be resolved
  8290. // because it identifies a single function template specialization.
  8291. //
  8292. // Last three arguments should only be supplied if Complain = true
  8293. //
  8294. // Return true if it was logically possible to so resolve the
  8295. // expression, regardless of whether or not it succeeded. Always
  8296. // returns true if 'complain' is set.
  8297. bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
  8298. ExprResult &SrcExpr, bool doFunctionPointerConverion,
  8299. bool complain, const SourceRange& OpRangeForComplaining,
  8300. QualType DestTypeForComplaining,
  8301. unsigned DiagIDForComplaining) {
  8302. assert(SrcExpr.get()->getType() == Context.OverloadTy);
  8303. OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
  8304. DeclAccessPair found;
  8305. ExprResult SingleFunctionExpression;
  8306. if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
  8307. ovl.Expression, /*complain*/ false, &found)) {
  8308. if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
  8309. SrcExpr = ExprError();
  8310. return true;
  8311. }
  8312. // It is only correct to resolve to an instance method if we're
  8313. // resolving a form that's permitted to be a pointer to member.
  8314. // Otherwise we'll end up making a bound member expression, which
  8315. // is illegal in all the contexts we resolve like this.
  8316. if (!ovl.HasFormOfMemberPointer &&
  8317. isa<CXXMethodDecl>(fn) &&
  8318. cast<CXXMethodDecl>(fn)->isInstance()) {
  8319. if (!complain) return false;
  8320. Diag(ovl.Expression->getExprLoc(),
  8321. diag::err_bound_member_function)
  8322. << 0 << ovl.Expression->getSourceRange();
  8323. // TODO: I believe we only end up here if there's a mix of
  8324. // static and non-static candidates (otherwise the expression
  8325. // would have 'bound member' type, not 'overload' type).
  8326. // Ideally we would note which candidate was chosen and why
  8327. // the static candidates were rejected.
  8328. SrcExpr = ExprError();
  8329. return true;
  8330. }
  8331. // Fix the expression to refer to 'fn'.
  8332. SingleFunctionExpression =
  8333. Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
  8334. // If desired, do function-to-pointer decay.
  8335. if (doFunctionPointerConverion) {
  8336. SingleFunctionExpression =
  8337. DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
  8338. if (SingleFunctionExpression.isInvalid()) {
  8339. SrcExpr = ExprError();
  8340. return true;
  8341. }
  8342. }
  8343. }
  8344. if (!SingleFunctionExpression.isUsable()) {
  8345. if (complain) {
  8346. Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
  8347. << ovl.Expression->getName()
  8348. << DestTypeForComplaining
  8349. << OpRangeForComplaining
  8350. << ovl.Expression->getQualifierLoc().getSourceRange();
  8351. NoteAllOverloadCandidates(SrcExpr.get());
  8352. SrcExpr = ExprError();
  8353. return true;
  8354. }
  8355. return false;
  8356. }
  8357. SrcExpr = SingleFunctionExpression;
  8358. return true;
  8359. }
  8360. /// \brief Add a single candidate to the overload set.
  8361. static void AddOverloadedCallCandidate(Sema &S,
  8362. DeclAccessPair FoundDecl,
  8363. TemplateArgumentListInfo *ExplicitTemplateArgs,
  8364. llvm::ArrayRef<Expr *> Args,
  8365. OverloadCandidateSet &CandidateSet,
  8366. bool PartialOverloading,
  8367. bool KnownValid) {
  8368. NamedDecl *Callee = FoundDecl.getDecl();
  8369. if (isa<UsingShadowDecl>(Callee))
  8370. Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
  8371. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
  8372. if (ExplicitTemplateArgs) {
  8373. assert(!KnownValid && "Explicit template arguments?");
  8374. return;
  8375. }
  8376. S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
  8377. PartialOverloading);
  8378. return;
  8379. }
  8380. if (FunctionTemplateDecl *FuncTemplate
  8381. = dyn_cast<FunctionTemplateDecl>(Callee)) {
  8382. S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
  8383. ExplicitTemplateArgs, Args, CandidateSet);
  8384. return;
  8385. }
  8386. assert(!KnownValid && "unhandled case in overloaded call candidate");
  8387. }
  8388. /// \brief Add the overload candidates named by callee and/or found by argument
  8389. /// dependent lookup to the given overload set.
  8390. void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
  8391. llvm::ArrayRef<Expr *> Args,
  8392. OverloadCandidateSet &CandidateSet,
  8393. bool PartialOverloading) {
  8394. #ifndef NDEBUG
  8395. // Verify that ArgumentDependentLookup is consistent with the rules
  8396. // in C++0x [basic.lookup.argdep]p3:
  8397. //
  8398. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  8399. // and let Y be the lookup set produced by argument dependent
  8400. // lookup (defined as follows). If X contains
  8401. //
  8402. // -- a declaration of a class member, or
  8403. //
  8404. // -- a block-scope function declaration that is not a
  8405. // using-declaration, or
  8406. //
  8407. // -- a declaration that is neither a function or a function
  8408. // template
  8409. //
  8410. // then Y is empty.
  8411. if (ULE->requiresADL()) {
  8412. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  8413. E = ULE->decls_end(); I != E; ++I) {
  8414. assert(!(*I)->getDeclContext()->isRecord());
  8415. assert(isa<UsingShadowDecl>(*I) ||
  8416. !(*I)->getDeclContext()->isFunctionOrMethod());
  8417. assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
  8418. }
  8419. }
  8420. #endif
  8421. // It would be nice to avoid this copy.
  8422. TemplateArgumentListInfo TABuffer;
  8423. TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
  8424. if (ULE->hasExplicitTemplateArgs()) {
  8425. ULE->copyTemplateArgumentsInto(TABuffer);
  8426. ExplicitTemplateArgs = &TABuffer;
  8427. }
  8428. for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
  8429. E = ULE->decls_end(); I != E; ++I)
  8430. AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
  8431. CandidateSet, PartialOverloading,
  8432. /*KnownValid*/ true);
  8433. if (ULE->requiresADL())
  8434. AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
  8435. ULE->getExprLoc(),
  8436. Args, ExplicitTemplateArgs,
  8437. CandidateSet, PartialOverloading,
  8438. ULE->isStdAssociatedNamespace());
  8439. }
  8440. /// Attempt to recover from an ill-formed use of a non-dependent name in a
  8441. /// template, where the non-dependent name was declared after the template
  8442. /// was defined. This is common in code written for a compilers which do not
  8443. /// correctly implement two-stage name lookup.
  8444. ///
  8445. /// Returns true if a viable candidate was found and a diagnostic was issued.
  8446. static bool
  8447. DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
  8448. const CXXScopeSpec &SS, LookupResult &R,
  8449. TemplateArgumentListInfo *ExplicitTemplateArgs,
  8450. llvm::ArrayRef<Expr *> Args) {
  8451. if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
  8452. return false;
  8453. for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
  8454. if (DC->isTransparentContext())
  8455. continue;
  8456. SemaRef.LookupQualifiedName(R, DC);
  8457. if (!R.empty()) {
  8458. R.suppressDiagnostics();
  8459. if (isa<CXXRecordDecl>(DC)) {
  8460. // Don't diagnose names we find in classes; we get much better
  8461. // diagnostics for these from DiagnoseEmptyLookup.
  8462. R.clear();
  8463. return false;
  8464. }
  8465. OverloadCandidateSet Candidates(FnLoc);
  8466. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  8467. AddOverloadedCallCandidate(SemaRef, I.getPair(),
  8468. ExplicitTemplateArgs, Args,
  8469. Candidates, false, /*KnownValid*/ false);
  8470. OverloadCandidateSet::iterator Best;
  8471. if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
  8472. // No viable functions. Don't bother the user with notes for functions
  8473. // which don't work and shouldn't be found anyway.
  8474. R.clear();
  8475. return false;
  8476. }
  8477. // Find the namespaces where ADL would have looked, and suggest
  8478. // declaring the function there instead.
  8479. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  8480. Sema::AssociatedClassSet AssociatedClasses;
  8481. SemaRef.FindAssociatedClassesAndNamespaces(Args,
  8482. AssociatedNamespaces,
  8483. AssociatedClasses);
  8484. // Never suggest declaring a function within namespace 'std'.
  8485. Sema::AssociatedNamespaceSet SuggestedNamespaces;
  8486. if (DeclContext *Std = SemaRef.getStdNamespace()) {
  8487. for (Sema::AssociatedNamespaceSet::iterator
  8488. it = AssociatedNamespaces.begin(),
  8489. end = AssociatedNamespaces.end(); it != end; ++it) {
  8490. if (!Std->Encloses(*it))
  8491. SuggestedNamespaces.insert(*it);
  8492. }
  8493. } else {
  8494. // Lacking the 'std::' namespace, use all of the associated namespaces.
  8495. SuggestedNamespaces = AssociatedNamespaces;
  8496. }
  8497. SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
  8498. << R.getLookupName();
  8499. if (SuggestedNamespaces.empty()) {
  8500. SemaRef.Diag(Best->Function->getLocation(),
  8501. diag::note_not_found_by_two_phase_lookup)
  8502. << R.getLookupName() << 0;
  8503. } else if (SuggestedNamespaces.size() == 1) {
  8504. SemaRef.Diag(Best->Function->getLocation(),
  8505. diag::note_not_found_by_two_phase_lookup)
  8506. << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
  8507. } else {
  8508. // FIXME: It would be useful to list the associated namespaces here,
  8509. // but the diagnostics infrastructure doesn't provide a way to produce
  8510. // a localized representation of a list of items.
  8511. SemaRef.Diag(Best->Function->getLocation(),
  8512. diag::note_not_found_by_two_phase_lookup)
  8513. << R.getLookupName() << 2;
  8514. }
  8515. // Try to recover by calling this function.
  8516. return true;
  8517. }
  8518. R.clear();
  8519. }
  8520. return false;
  8521. }
  8522. /// Attempt to recover from ill-formed use of a non-dependent operator in a
  8523. /// template, where the non-dependent operator was declared after the template
  8524. /// was defined.
  8525. ///
  8526. /// Returns true if a viable candidate was found and a diagnostic was issued.
  8527. static bool
  8528. DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
  8529. SourceLocation OpLoc,
  8530. llvm::ArrayRef<Expr *> Args) {
  8531. DeclarationName OpName =
  8532. SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
  8533. LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
  8534. return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
  8535. /*ExplicitTemplateArgs=*/0, Args);
  8536. }
  8537. namespace {
  8538. // Callback to limit the allowed keywords and to only accept typo corrections
  8539. // that are keywords or whose decls refer to functions (or template functions)
  8540. // that accept the given number of arguments.
  8541. class RecoveryCallCCC : public CorrectionCandidateCallback {
  8542. public:
  8543. RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
  8544. : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
  8545. WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
  8546. WantRemainingKeywords = false;
  8547. }
  8548. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  8549. if (!candidate.getCorrectionDecl())
  8550. return candidate.isKeyword();
  8551. for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
  8552. DIEnd = candidate.end(); DI != DIEnd; ++DI) {
  8553. FunctionDecl *FD = 0;
  8554. NamedDecl *ND = (*DI)->getUnderlyingDecl();
  8555. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  8556. FD = FTD->getTemplatedDecl();
  8557. if (!HasExplicitTemplateArgs && !FD) {
  8558. if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
  8559. // If the Decl is neither a function nor a template function,
  8560. // determine if it is a pointer or reference to a function. If so,
  8561. // check against the number of arguments expected for the pointee.
  8562. QualType ValType = cast<ValueDecl>(ND)->getType();
  8563. if (ValType->isAnyPointerType() || ValType->isReferenceType())
  8564. ValType = ValType->getPointeeType();
  8565. if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
  8566. if (FPT->getNumArgs() == NumArgs)
  8567. return true;
  8568. }
  8569. }
  8570. if (FD && FD->getNumParams() >= NumArgs &&
  8571. FD->getMinRequiredArguments() <= NumArgs)
  8572. return true;
  8573. }
  8574. return false;
  8575. }
  8576. private:
  8577. unsigned NumArgs;
  8578. bool HasExplicitTemplateArgs;
  8579. };
  8580. // Callback that effectively disabled typo correction
  8581. class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
  8582. public:
  8583. NoTypoCorrectionCCC() {
  8584. WantTypeSpecifiers = false;
  8585. WantExpressionKeywords = false;
  8586. WantCXXNamedCasts = false;
  8587. WantRemainingKeywords = false;
  8588. }
  8589. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  8590. return false;
  8591. }
  8592. };
  8593. }
  8594. /// Attempts to recover from a call where no functions were found.
  8595. ///
  8596. /// Returns true if new candidates were found.
  8597. static ExprResult
  8598. BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  8599. UnresolvedLookupExpr *ULE,
  8600. SourceLocation LParenLoc,
  8601. llvm::MutableArrayRef<Expr *> Args,
  8602. SourceLocation RParenLoc,
  8603. bool EmptyLookup, bool AllowTypoCorrection) {
  8604. CXXScopeSpec SS;
  8605. SS.Adopt(ULE->getQualifierLoc());
  8606. SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
  8607. TemplateArgumentListInfo TABuffer;
  8608. TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
  8609. if (ULE->hasExplicitTemplateArgs()) {
  8610. ULE->copyTemplateArgumentsInto(TABuffer);
  8611. ExplicitTemplateArgs = &TABuffer;
  8612. }
  8613. LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
  8614. Sema::LookupOrdinaryName);
  8615. RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
  8616. NoTypoCorrectionCCC RejectAll;
  8617. CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
  8618. (CorrectionCandidateCallback*)&Validator :
  8619. (CorrectionCandidateCallback*)&RejectAll;
  8620. if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
  8621. ExplicitTemplateArgs, Args) &&
  8622. (!EmptyLookup ||
  8623. SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
  8624. ExplicitTemplateArgs, Args)))
  8625. return ExprError();
  8626. assert(!R.empty() && "lookup results empty despite recovery");
  8627. // Build an implicit member call if appropriate. Just drop the
  8628. // casts and such from the call, we don't really care.
  8629. ExprResult NewFn = ExprError();
  8630. if ((*R.begin())->isCXXClassMember())
  8631. NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  8632. R, ExplicitTemplateArgs);
  8633. else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
  8634. NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
  8635. ExplicitTemplateArgs);
  8636. else
  8637. NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
  8638. if (NewFn.isInvalid())
  8639. return ExprError();
  8640. // This shouldn't cause an infinite loop because we're giving it
  8641. // an expression with viable lookup results, which should never
  8642. // end up here.
  8643. return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
  8644. MultiExprArg(Args.data(), Args.size()),
  8645. RParenLoc);
  8646. }
  8647. /// \brief Constructs and populates an OverloadedCandidateSet from
  8648. /// the given function.
  8649. /// \returns true when an the ExprResult output parameter has been set.
  8650. bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
  8651. UnresolvedLookupExpr *ULE,
  8652. Expr **Args, unsigned NumArgs,
  8653. SourceLocation RParenLoc,
  8654. OverloadCandidateSet *CandidateSet,
  8655. ExprResult *Result) {
  8656. #ifndef NDEBUG
  8657. if (ULE->requiresADL()) {
  8658. // To do ADL, we must have found an unqualified name.
  8659. assert(!ULE->getQualifier() && "qualified name with ADL");
  8660. // We don't perform ADL for implicit declarations of builtins.
  8661. // Verify that this was correctly set up.
  8662. FunctionDecl *F;
  8663. if (ULE->decls_begin() + 1 == ULE->decls_end() &&
  8664. (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
  8665. F->getBuiltinID() && F->isImplicit())
  8666. llvm_unreachable("performing ADL for builtin");
  8667. // We don't perform ADL in C.
  8668. assert(getLangOpts().CPlusPlus && "ADL enabled in C");
  8669. } else
  8670. assert(!ULE->isStdAssociatedNamespace() &&
  8671. "std is associated namespace but not doing ADL");
  8672. #endif
  8673. UnbridgedCastsSet UnbridgedCasts;
  8674. if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
  8675. *Result = ExprError();
  8676. return true;
  8677. }
  8678. // Add the functions denoted by the callee to the set of candidate
  8679. // functions, including those from argument-dependent lookup.
  8680. AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
  8681. *CandidateSet);
  8682. // If we found nothing, try to recover.
  8683. // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
  8684. // out if it fails.
  8685. if (CandidateSet->empty()) {
  8686. // In Microsoft mode, if we are inside a template class member function then
  8687. // create a type dependent CallExpr. The goal is to postpone name lookup
  8688. // to instantiation time to be able to search into type dependent base
  8689. // classes.
  8690. if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
  8691. (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
  8692. CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
  8693. Context.DependentTy, VK_RValue,
  8694. RParenLoc);
  8695. CE->setTypeDependent(true);
  8696. *Result = Owned(CE);
  8697. return true;
  8698. }
  8699. return false;
  8700. }
  8701. UnbridgedCasts.restore();
  8702. return false;
  8703. }
  8704. /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
  8705. /// the completed call expression. If overload resolution fails, emits
  8706. /// diagnostics and returns ExprError()
  8707. static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
  8708. UnresolvedLookupExpr *ULE,
  8709. SourceLocation LParenLoc,
  8710. Expr **Args, unsigned NumArgs,
  8711. SourceLocation RParenLoc,
  8712. Expr *ExecConfig,
  8713. OverloadCandidateSet *CandidateSet,
  8714. OverloadCandidateSet::iterator *Best,
  8715. OverloadingResult OverloadResult,
  8716. bool AllowTypoCorrection) {
  8717. if (CandidateSet->empty())
  8718. return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  8719. llvm::MutableArrayRef<Expr *>(Args, NumArgs),
  8720. RParenLoc, /*EmptyLookup=*/true,
  8721. AllowTypoCorrection);
  8722. switch (OverloadResult) {
  8723. case OR_Success: {
  8724. FunctionDecl *FDecl = (*Best)->Function;
  8725. SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
  8726. SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
  8727. SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
  8728. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  8729. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
  8730. RParenLoc, ExecConfig);
  8731. }
  8732. case OR_No_Viable_Function: {
  8733. // Try to recover by looking for viable functions which the user might
  8734. // have meant to call.
  8735. ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
  8736. llvm::MutableArrayRef<Expr *>(Args, NumArgs),
  8737. RParenLoc,
  8738. /*EmptyLookup=*/false,
  8739. AllowTypoCorrection);
  8740. if (!Recovery.isInvalid())
  8741. return Recovery;
  8742. SemaRef.Diag(Fn->getLocStart(),
  8743. diag::err_ovl_no_viable_function_in_call)
  8744. << ULE->getName() << Fn->getSourceRange();
  8745. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
  8746. llvm::makeArrayRef(Args, NumArgs));
  8747. break;
  8748. }
  8749. case OR_Ambiguous:
  8750. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
  8751. << ULE->getName() << Fn->getSourceRange();
  8752. CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
  8753. llvm::makeArrayRef(Args, NumArgs));
  8754. break;
  8755. case OR_Deleted: {
  8756. SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
  8757. << (*Best)->Function->isDeleted()
  8758. << ULE->getName()
  8759. << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
  8760. << Fn->getSourceRange();
  8761. CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
  8762. llvm::makeArrayRef(Args, NumArgs));
  8763. // We emitted an error for the unvailable/deleted function call but keep
  8764. // the call in the AST.
  8765. FunctionDecl *FDecl = (*Best)->Function;
  8766. Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
  8767. return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
  8768. RParenLoc, ExecConfig);
  8769. }
  8770. }
  8771. // Overload resolution failed.
  8772. return ExprError();
  8773. }
  8774. /// BuildOverloadedCallExpr - Given the call expression that calls Fn
  8775. /// (which eventually refers to the declaration Func) and the call
  8776. /// arguments Args/NumArgs, attempt to resolve the function call down
  8777. /// to a specific function. If overload resolution succeeds, returns
  8778. /// the call expression produced by overload resolution.
  8779. /// Otherwise, emits diagnostics and returns ExprError.
  8780. ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
  8781. UnresolvedLookupExpr *ULE,
  8782. SourceLocation LParenLoc,
  8783. Expr **Args, unsigned NumArgs,
  8784. SourceLocation RParenLoc,
  8785. Expr *ExecConfig,
  8786. bool AllowTypoCorrection) {
  8787. OverloadCandidateSet CandidateSet(Fn->getExprLoc());
  8788. ExprResult result;
  8789. if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
  8790. &CandidateSet, &result))
  8791. return result;
  8792. OverloadCandidateSet::iterator Best;
  8793. OverloadingResult OverloadResult =
  8794. CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
  8795. return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
  8796. RParenLoc, ExecConfig, &CandidateSet,
  8797. &Best, OverloadResult,
  8798. AllowTypoCorrection);
  8799. }
  8800. static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
  8801. return Functions.size() > 1 ||
  8802. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  8803. }
  8804. /// \brief Create a unary operation that may resolve to an overloaded
  8805. /// operator.
  8806. ///
  8807. /// \param OpLoc The location of the operator itself (e.g., '*').
  8808. ///
  8809. /// \param OpcIn The UnaryOperator::Opcode that describes this
  8810. /// operator.
  8811. ///
  8812. /// \param Fns The set of non-member functions that will be
  8813. /// considered by overload resolution. The caller needs to build this
  8814. /// set based on the context using, e.g.,
  8815. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  8816. /// set should not contain any member functions; those will be added
  8817. /// by CreateOverloadedUnaryOp().
  8818. ///
  8819. /// \param Input The input argument.
  8820. ExprResult
  8821. Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
  8822. const UnresolvedSetImpl &Fns,
  8823. Expr *Input) {
  8824. UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
  8825. OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
  8826. assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
  8827. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  8828. // TODO: provide better source location info.
  8829. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  8830. if (checkPlaceholderForOverload(*this, Input))
  8831. return ExprError();
  8832. Expr *Args[2] = { Input, 0 };
  8833. unsigned NumArgs = 1;
  8834. // For post-increment and post-decrement, add the implicit '0' as
  8835. // the second argument, so that we know this is a post-increment or
  8836. // post-decrement.
  8837. if (Opc == UO_PostInc || Opc == UO_PostDec) {
  8838. llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
  8839. Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
  8840. SourceLocation());
  8841. NumArgs = 2;
  8842. }
  8843. if (Input->isTypeDependent()) {
  8844. if (Fns.empty())
  8845. return Owned(new (Context) UnaryOperator(Input,
  8846. Opc,
  8847. Context.DependentTy,
  8848. VK_RValue, OK_Ordinary,
  8849. OpLoc));
  8850. CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
  8851. UnresolvedLookupExpr *Fn
  8852. = UnresolvedLookupExpr::Create(Context, NamingClass,
  8853. NestedNameSpecifierLoc(), OpNameInfo,
  8854. /*ADL*/ true, IsOverloaded(Fns),
  8855. Fns.begin(), Fns.end());
  8856. return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
  8857. &Args[0], NumArgs,
  8858. Context.DependentTy,
  8859. VK_RValue,
  8860. OpLoc));
  8861. }
  8862. // Build an empty overload set.
  8863. OverloadCandidateSet CandidateSet(OpLoc);
  8864. // Add the candidates from the given function set.
  8865. AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
  8866. false);
  8867. // Add operator candidates that are member functions.
  8868. AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
  8869. // Add candidates from ADL.
  8870. AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
  8871. OpLoc, llvm::makeArrayRef(Args, NumArgs),
  8872. /*ExplicitTemplateArgs*/ 0,
  8873. CandidateSet);
  8874. // Add builtin operator candidates.
  8875. AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
  8876. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  8877. // Perform overload resolution.
  8878. OverloadCandidateSet::iterator Best;
  8879. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  8880. case OR_Success: {
  8881. // We found a built-in operator or an overloaded operator.
  8882. FunctionDecl *FnDecl = Best->Function;
  8883. if (FnDecl) {
  8884. // We matched an overloaded operator. Build a call to that
  8885. // operator.
  8886. MarkFunctionReferenced(OpLoc, FnDecl);
  8887. // Convert the arguments.
  8888. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  8889. CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
  8890. ExprResult InputRes =
  8891. PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
  8892. Best->FoundDecl, Method);
  8893. if (InputRes.isInvalid())
  8894. return ExprError();
  8895. Input = InputRes.take();
  8896. } else {
  8897. // Convert the arguments.
  8898. ExprResult InputInit
  8899. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  8900. Context,
  8901. FnDecl->getParamDecl(0)),
  8902. SourceLocation(),
  8903. Input);
  8904. if (InputInit.isInvalid())
  8905. return ExprError();
  8906. Input = InputInit.take();
  8907. }
  8908. DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
  8909. // Determine the result type.
  8910. QualType ResultTy = FnDecl->getResultType();
  8911. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  8912. ResultTy = ResultTy.getNonLValueExprType(Context);
  8913. // Build the actual expression node.
  8914. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  8915. HadMultipleCandidates, OpLoc);
  8916. if (FnExpr.isInvalid())
  8917. return ExprError();
  8918. Args[0] = Input;
  8919. CallExpr *TheCall =
  8920. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
  8921. Args, NumArgs, ResultTy, VK, OpLoc);
  8922. if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
  8923. FnDecl))
  8924. return ExprError();
  8925. return MaybeBindToTemporary(TheCall);
  8926. } else {
  8927. // We matched a built-in operator. Convert the arguments, then
  8928. // break out so that we will build the appropriate built-in
  8929. // operator node.
  8930. ExprResult InputRes =
  8931. PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
  8932. Best->Conversions[0], AA_Passing);
  8933. if (InputRes.isInvalid())
  8934. return ExprError();
  8935. Input = InputRes.take();
  8936. break;
  8937. }
  8938. }
  8939. case OR_No_Viable_Function:
  8940. // This is an erroneous use of an operator which can be overloaded by
  8941. // a non-member function. Check for non-member operators which were
  8942. // defined too late to be candidates.
  8943. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
  8944. llvm::makeArrayRef(Args, NumArgs)))
  8945. // FIXME: Recover by calling the found function.
  8946. return ExprError();
  8947. // No viable function; fall through to handling this as a
  8948. // built-in operator, which will produce an error message for us.
  8949. break;
  8950. case OR_Ambiguous:
  8951. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  8952. << UnaryOperator::getOpcodeStr(Opc)
  8953. << Input->getType()
  8954. << Input->getSourceRange();
  8955. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
  8956. llvm::makeArrayRef(Args, NumArgs),
  8957. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  8958. return ExprError();
  8959. case OR_Deleted:
  8960. Diag(OpLoc, diag::err_ovl_deleted_oper)
  8961. << Best->Function->isDeleted()
  8962. << UnaryOperator::getOpcodeStr(Opc)
  8963. << getDeletedOrUnavailableSuffix(Best->Function)
  8964. << Input->getSourceRange();
  8965. CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
  8966. llvm::makeArrayRef(Args, NumArgs),
  8967. UnaryOperator::getOpcodeStr(Opc), OpLoc);
  8968. return ExprError();
  8969. }
  8970. // Either we found no viable overloaded operator or we matched a
  8971. // built-in operator. In either case, fall through to trying to
  8972. // build a built-in operation.
  8973. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  8974. }
  8975. /// \brief Create a binary operation that may resolve to an overloaded
  8976. /// operator.
  8977. ///
  8978. /// \param OpLoc The location of the operator itself (e.g., '+').
  8979. ///
  8980. /// \param OpcIn The BinaryOperator::Opcode that describes this
  8981. /// operator.
  8982. ///
  8983. /// \param Fns The set of non-member functions that will be
  8984. /// considered by overload resolution. The caller needs to build this
  8985. /// set based on the context using, e.g.,
  8986. /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
  8987. /// set should not contain any member functions; those will be added
  8988. /// by CreateOverloadedBinOp().
  8989. ///
  8990. /// \param LHS Left-hand argument.
  8991. /// \param RHS Right-hand argument.
  8992. ExprResult
  8993. Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
  8994. unsigned OpcIn,
  8995. const UnresolvedSetImpl &Fns,
  8996. Expr *LHS, Expr *RHS) {
  8997. Expr *Args[2] = { LHS, RHS };
  8998. LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
  8999. BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
  9000. OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
  9001. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  9002. // If either side is type-dependent, create an appropriate dependent
  9003. // expression.
  9004. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  9005. if (Fns.empty()) {
  9006. // If there are no functions to store, just build a dependent
  9007. // BinaryOperator or CompoundAssignment.
  9008. if (Opc <= BO_Assign || Opc > BO_OrAssign)
  9009. return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
  9010. Context.DependentTy,
  9011. VK_RValue, OK_Ordinary,
  9012. OpLoc));
  9013. return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
  9014. Context.DependentTy,
  9015. VK_LValue,
  9016. OK_Ordinary,
  9017. Context.DependentTy,
  9018. Context.DependentTy,
  9019. OpLoc));
  9020. }
  9021. // FIXME: save results of ADL from here?
  9022. CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
  9023. // TODO: provide better source location info in DNLoc component.
  9024. DeclarationNameInfo OpNameInfo(OpName, OpLoc);
  9025. UnresolvedLookupExpr *Fn
  9026. = UnresolvedLookupExpr::Create(Context, NamingClass,
  9027. NestedNameSpecifierLoc(), OpNameInfo,
  9028. /*ADL*/ true, IsOverloaded(Fns),
  9029. Fns.begin(), Fns.end());
  9030. return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
  9031. Args, 2,
  9032. Context.DependentTy,
  9033. VK_RValue,
  9034. OpLoc));
  9035. }
  9036. // Always do placeholder-like conversions on the RHS.
  9037. if (checkPlaceholderForOverload(*this, Args[1]))
  9038. return ExprError();
  9039. // Do placeholder-like conversion on the LHS; note that we should
  9040. // not get here with a PseudoObject LHS.
  9041. assert(Args[0]->getObjectKind() != OK_ObjCProperty);
  9042. if (checkPlaceholderForOverload(*this, Args[0]))
  9043. return ExprError();
  9044. // If this is the assignment operator, we only perform overload resolution
  9045. // if the left-hand side is a class or enumeration type. This is actually
  9046. // a hack. The standard requires that we do overload resolution between the
  9047. // various built-in candidates, but as DR507 points out, this can lead to
  9048. // problems. So we do it this way, which pretty much follows what GCC does.
  9049. // Note that we go the traditional code path for compound assignment forms.
  9050. if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
  9051. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  9052. // If this is the .* operator, which is not overloadable, just
  9053. // create a built-in binary operator.
  9054. if (Opc == BO_PtrMemD)
  9055. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  9056. // Build an empty overload set.
  9057. OverloadCandidateSet CandidateSet(OpLoc);
  9058. // Add the candidates from the given function set.
  9059. AddFunctionCandidates(Fns, Args, CandidateSet, false);
  9060. // Add operator candidates that are member functions.
  9061. AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
  9062. // Add candidates from ADL.
  9063. AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
  9064. OpLoc, Args,
  9065. /*ExplicitTemplateArgs*/ 0,
  9066. CandidateSet);
  9067. // Add builtin operator candidates.
  9068. AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
  9069. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  9070. // Perform overload resolution.
  9071. OverloadCandidateSet::iterator Best;
  9072. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  9073. case OR_Success: {
  9074. // We found a built-in operator or an overloaded operator.
  9075. FunctionDecl *FnDecl = Best->Function;
  9076. if (FnDecl) {
  9077. // We matched an overloaded operator. Build a call to that
  9078. // operator.
  9079. MarkFunctionReferenced(OpLoc, FnDecl);
  9080. // Convert the arguments.
  9081. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
  9082. // Best->Access is only meaningful for class members.
  9083. CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
  9084. ExprResult Arg1 =
  9085. PerformCopyInitialization(
  9086. InitializedEntity::InitializeParameter(Context,
  9087. FnDecl->getParamDecl(0)),
  9088. SourceLocation(), Owned(Args[1]));
  9089. if (Arg1.isInvalid())
  9090. return ExprError();
  9091. ExprResult Arg0 =
  9092. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
  9093. Best->FoundDecl, Method);
  9094. if (Arg0.isInvalid())
  9095. return ExprError();
  9096. Args[0] = Arg0.takeAs<Expr>();
  9097. Args[1] = RHS = Arg1.takeAs<Expr>();
  9098. } else {
  9099. // Convert the arguments.
  9100. ExprResult Arg0 = PerformCopyInitialization(
  9101. InitializedEntity::InitializeParameter(Context,
  9102. FnDecl->getParamDecl(0)),
  9103. SourceLocation(), Owned(Args[0]));
  9104. if (Arg0.isInvalid())
  9105. return ExprError();
  9106. ExprResult Arg1 =
  9107. PerformCopyInitialization(
  9108. InitializedEntity::InitializeParameter(Context,
  9109. FnDecl->getParamDecl(1)),
  9110. SourceLocation(), Owned(Args[1]));
  9111. if (Arg1.isInvalid())
  9112. return ExprError();
  9113. Args[0] = LHS = Arg0.takeAs<Expr>();
  9114. Args[1] = RHS = Arg1.takeAs<Expr>();
  9115. }
  9116. DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
  9117. // Determine the result type.
  9118. QualType ResultTy = FnDecl->getResultType();
  9119. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  9120. ResultTy = ResultTy.getNonLValueExprType(Context);
  9121. // Build the actual expression node.
  9122. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  9123. HadMultipleCandidates, OpLoc);
  9124. if (FnExpr.isInvalid())
  9125. return ExprError();
  9126. CXXOperatorCallExpr *TheCall =
  9127. new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
  9128. Args, 2, ResultTy, VK, OpLoc);
  9129. if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
  9130. FnDecl))
  9131. return ExprError();
  9132. return MaybeBindToTemporary(TheCall);
  9133. } else {
  9134. // We matched a built-in operator. Convert the arguments, then
  9135. // break out so that we will build the appropriate built-in
  9136. // operator node.
  9137. ExprResult ArgsRes0 =
  9138. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  9139. Best->Conversions[0], AA_Passing);
  9140. if (ArgsRes0.isInvalid())
  9141. return ExprError();
  9142. Args[0] = ArgsRes0.take();
  9143. ExprResult ArgsRes1 =
  9144. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  9145. Best->Conversions[1], AA_Passing);
  9146. if (ArgsRes1.isInvalid())
  9147. return ExprError();
  9148. Args[1] = ArgsRes1.take();
  9149. break;
  9150. }
  9151. }
  9152. case OR_No_Viable_Function: {
  9153. // C++ [over.match.oper]p9:
  9154. // If the operator is the operator , [...] and there are no
  9155. // viable functions, then the operator is assumed to be the
  9156. // built-in operator and interpreted according to clause 5.
  9157. if (Opc == BO_Comma)
  9158. break;
  9159. // For class as left operand for assignment or compound assigment
  9160. // operator do not fall through to handling in built-in, but report that
  9161. // no overloaded assignment operator found
  9162. ExprResult Result = ExprError();
  9163. if (Args[0]->getType()->isRecordType() &&
  9164. Opc >= BO_Assign && Opc <= BO_OrAssign) {
  9165. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  9166. << BinaryOperator::getOpcodeStr(Opc)
  9167. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  9168. } else {
  9169. // This is an erroneous use of an operator which can be overloaded by
  9170. // a non-member function. Check for non-member operators which were
  9171. // defined too late to be candidates.
  9172. if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
  9173. // FIXME: Recover by calling the found function.
  9174. return ExprError();
  9175. // No viable function; try to create a built-in operation, which will
  9176. // produce an error. Then, show the non-viable candidates.
  9177. Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  9178. }
  9179. assert(Result.isInvalid() &&
  9180. "C++ binary operator overloading is missing candidates!");
  9181. if (Result.isInvalid())
  9182. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  9183. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  9184. return Result;
  9185. }
  9186. case OR_Ambiguous:
  9187. Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
  9188. << BinaryOperator::getOpcodeStr(Opc)
  9189. << Args[0]->getType() << Args[1]->getType()
  9190. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  9191. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  9192. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  9193. return ExprError();
  9194. case OR_Deleted:
  9195. if (isImplicitlyDeleted(Best->Function)) {
  9196. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  9197. Diag(OpLoc, diag::err_ovl_deleted_special_oper)
  9198. << getSpecialMember(Method)
  9199. << BinaryOperator::getOpcodeStr(Opc)
  9200. << getDeletedOrUnavailableSuffix(Best->Function);
  9201. if (getSpecialMember(Method) != CXXInvalid) {
  9202. // The user probably meant to call this special member. Just
  9203. // explain why it's deleted.
  9204. NoteDeletedFunction(Method);
  9205. return ExprError();
  9206. }
  9207. } else {
  9208. Diag(OpLoc, diag::err_ovl_deleted_oper)
  9209. << Best->Function->isDeleted()
  9210. << BinaryOperator::getOpcodeStr(Opc)
  9211. << getDeletedOrUnavailableSuffix(Best->Function)
  9212. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  9213. }
  9214. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  9215. BinaryOperator::getOpcodeStr(Opc), OpLoc);
  9216. return ExprError();
  9217. }
  9218. // We matched a built-in operator; build it.
  9219. return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
  9220. }
  9221. ExprResult
  9222. Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
  9223. SourceLocation RLoc,
  9224. Expr *Base, Expr *Idx) {
  9225. Expr *Args[2] = { Base, Idx };
  9226. DeclarationName OpName =
  9227. Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
  9228. // If either side is type-dependent, create an appropriate dependent
  9229. // expression.
  9230. if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
  9231. CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
  9232. // CHECKME: no 'operator' keyword?
  9233. DeclarationNameInfo OpNameInfo(OpName, LLoc);
  9234. OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  9235. UnresolvedLookupExpr *Fn
  9236. = UnresolvedLookupExpr::Create(Context, NamingClass,
  9237. NestedNameSpecifierLoc(), OpNameInfo,
  9238. /*ADL*/ true, /*Overloaded*/ false,
  9239. UnresolvedSetIterator(),
  9240. UnresolvedSetIterator());
  9241. // Can't add any actual overloads yet
  9242. return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
  9243. Args, 2,
  9244. Context.DependentTy,
  9245. VK_RValue,
  9246. RLoc));
  9247. }
  9248. // Handle placeholders on both operands.
  9249. if (checkPlaceholderForOverload(*this, Args[0]))
  9250. return ExprError();
  9251. if (checkPlaceholderForOverload(*this, Args[1]))
  9252. return ExprError();
  9253. // Build an empty overload set.
  9254. OverloadCandidateSet CandidateSet(LLoc);
  9255. // Subscript can only be overloaded as a member function.
  9256. // Add operator candidates that are member functions.
  9257. AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
  9258. // Add builtin operator candidates.
  9259. AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
  9260. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  9261. // Perform overload resolution.
  9262. OverloadCandidateSet::iterator Best;
  9263. switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
  9264. case OR_Success: {
  9265. // We found a built-in operator or an overloaded operator.
  9266. FunctionDecl *FnDecl = Best->Function;
  9267. if (FnDecl) {
  9268. // We matched an overloaded operator. Build a call to that
  9269. // operator.
  9270. MarkFunctionReferenced(LLoc, FnDecl);
  9271. CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
  9272. DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
  9273. // Convert the arguments.
  9274. CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
  9275. ExprResult Arg0 =
  9276. PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
  9277. Best->FoundDecl, Method);
  9278. if (Arg0.isInvalid())
  9279. return ExprError();
  9280. Args[0] = Arg0.take();
  9281. // Convert the arguments.
  9282. ExprResult InputInit
  9283. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  9284. Context,
  9285. FnDecl->getParamDecl(0)),
  9286. SourceLocation(),
  9287. Owned(Args[1]));
  9288. if (InputInit.isInvalid())
  9289. return ExprError();
  9290. Args[1] = InputInit.takeAs<Expr>();
  9291. // Determine the result type
  9292. QualType ResultTy = FnDecl->getResultType();
  9293. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  9294. ResultTy = ResultTy.getNonLValueExprType(Context);
  9295. // Build the actual expression node.
  9296. DeclarationNameInfo OpLocInfo(OpName, LLoc);
  9297. OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
  9298. ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
  9299. HadMultipleCandidates,
  9300. OpLocInfo.getLoc(),
  9301. OpLocInfo.getInfo());
  9302. if (FnExpr.isInvalid())
  9303. return ExprError();
  9304. CXXOperatorCallExpr *TheCall =
  9305. new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
  9306. FnExpr.take(), Args, 2,
  9307. ResultTy, VK, RLoc);
  9308. if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
  9309. FnDecl))
  9310. return ExprError();
  9311. return MaybeBindToTemporary(TheCall);
  9312. } else {
  9313. // We matched a built-in operator. Convert the arguments, then
  9314. // break out so that we will build the appropriate built-in
  9315. // operator node.
  9316. ExprResult ArgsRes0 =
  9317. PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
  9318. Best->Conversions[0], AA_Passing);
  9319. if (ArgsRes0.isInvalid())
  9320. return ExprError();
  9321. Args[0] = ArgsRes0.take();
  9322. ExprResult ArgsRes1 =
  9323. PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
  9324. Best->Conversions[1], AA_Passing);
  9325. if (ArgsRes1.isInvalid())
  9326. return ExprError();
  9327. Args[1] = ArgsRes1.take();
  9328. break;
  9329. }
  9330. }
  9331. case OR_No_Viable_Function: {
  9332. if (CandidateSet.empty())
  9333. Diag(LLoc, diag::err_ovl_no_oper)
  9334. << Args[0]->getType() << /*subscript*/ 0
  9335. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  9336. else
  9337. Diag(LLoc, diag::err_ovl_no_viable_subscript)
  9338. << Args[0]->getType()
  9339. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  9340. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  9341. "[]", LLoc);
  9342. return ExprError();
  9343. }
  9344. case OR_Ambiguous:
  9345. Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
  9346. << "[]"
  9347. << Args[0]->getType() << Args[1]->getType()
  9348. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  9349. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
  9350. "[]", LLoc);
  9351. return ExprError();
  9352. case OR_Deleted:
  9353. Diag(LLoc, diag::err_ovl_deleted_oper)
  9354. << Best->Function->isDeleted() << "[]"
  9355. << getDeletedOrUnavailableSuffix(Best->Function)
  9356. << Args[0]->getSourceRange() << Args[1]->getSourceRange();
  9357. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
  9358. "[]", LLoc);
  9359. return ExprError();
  9360. }
  9361. // We matched a built-in operator; build it.
  9362. return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
  9363. }
  9364. /// BuildCallToMemberFunction - Build a call to a member
  9365. /// function. MemExpr is the expression that refers to the member
  9366. /// function (and includes the object parameter), Args/NumArgs are the
  9367. /// arguments to the function call (not including the object
  9368. /// parameter). The caller needs to validate that the member
  9369. /// expression refers to a non-static member function or an overloaded
  9370. /// member function.
  9371. ExprResult
  9372. Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
  9373. SourceLocation LParenLoc, Expr **Args,
  9374. unsigned NumArgs, SourceLocation RParenLoc) {
  9375. assert(MemExprE->getType() == Context.BoundMemberTy ||
  9376. MemExprE->getType() == Context.OverloadTy);
  9377. // Dig out the member expression. This holds both the object
  9378. // argument and the member function we're referring to.
  9379. Expr *NakedMemExpr = MemExprE->IgnoreParens();
  9380. // Determine whether this is a call to a pointer-to-member function.
  9381. if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
  9382. assert(op->getType() == Context.BoundMemberTy);
  9383. assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
  9384. QualType fnType =
  9385. op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
  9386. const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
  9387. QualType resultType = proto->getCallResultType(Context);
  9388. ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
  9389. // Check that the object type isn't more qualified than the
  9390. // member function we're calling.
  9391. Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
  9392. QualType objectType = op->getLHS()->getType();
  9393. if (op->getOpcode() == BO_PtrMemI)
  9394. objectType = objectType->castAs<PointerType>()->getPointeeType();
  9395. Qualifiers objectQuals = objectType.getQualifiers();
  9396. Qualifiers difference = objectQuals - funcQuals;
  9397. difference.removeObjCGCAttr();
  9398. difference.removeAddressSpace();
  9399. if (difference) {
  9400. std::string qualsString = difference.getAsString();
  9401. Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
  9402. << fnType.getUnqualifiedType()
  9403. << qualsString
  9404. << (qualsString.find(' ') == std::string::npos ? 1 : 2);
  9405. }
  9406. CXXMemberCallExpr *call
  9407. = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
  9408. resultType, valueKind, RParenLoc);
  9409. if (CheckCallReturnType(proto->getResultType(),
  9410. op->getRHS()->getLocStart(),
  9411. call, 0))
  9412. return ExprError();
  9413. if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
  9414. return ExprError();
  9415. return MaybeBindToTemporary(call);
  9416. }
  9417. UnbridgedCastsSet UnbridgedCasts;
  9418. if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
  9419. return ExprError();
  9420. MemberExpr *MemExpr;
  9421. CXXMethodDecl *Method = 0;
  9422. DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
  9423. NestedNameSpecifier *Qualifier = 0;
  9424. if (isa<MemberExpr>(NakedMemExpr)) {
  9425. MemExpr = cast<MemberExpr>(NakedMemExpr);
  9426. Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
  9427. FoundDecl = MemExpr->getFoundDecl();
  9428. Qualifier = MemExpr->getQualifier();
  9429. UnbridgedCasts.restore();
  9430. } else {
  9431. UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
  9432. Qualifier = UnresExpr->getQualifier();
  9433. QualType ObjectType = UnresExpr->getBaseType();
  9434. Expr::Classification ObjectClassification
  9435. = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
  9436. : UnresExpr->getBase()->Classify(Context);
  9437. // Add overload candidates
  9438. OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
  9439. // FIXME: avoid copy.
  9440. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
  9441. if (UnresExpr->hasExplicitTemplateArgs()) {
  9442. UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  9443. TemplateArgs = &TemplateArgsBuffer;
  9444. }
  9445. for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
  9446. E = UnresExpr->decls_end(); I != E; ++I) {
  9447. NamedDecl *Func = *I;
  9448. CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
  9449. if (isa<UsingShadowDecl>(Func))
  9450. Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
  9451. // Microsoft supports direct constructor calls.
  9452. if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
  9453. AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
  9454. llvm::makeArrayRef(Args, NumArgs), CandidateSet);
  9455. } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
  9456. // If explicit template arguments were provided, we can't call a
  9457. // non-template member function.
  9458. if (TemplateArgs)
  9459. continue;
  9460. AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
  9461. ObjectClassification,
  9462. llvm::makeArrayRef(Args, NumArgs), CandidateSet,
  9463. /*SuppressUserConversions=*/false);
  9464. } else {
  9465. AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
  9466. I.getPair(), ActingDC, TemplateArgs,
  9467. ObjectType, ObjectClassification,
  9468. llvm::makeArrayRef(Args, NumArgs),
  9469. CandidateSet,
  9470. /*SuppressUsedConversions=*/false);
  9471. }
  9472. }
  9473. DeclarationName DeclName = UnresExpr->getMemberName();
  9474. UnbridgedCasts.restore();
  9475. OverloadCandidateSet::iterator Best;
  9476. switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
  9477. Best)) {
  9478. case OR_Success:
  9479. Method = cast<CXXMethodDecl>(Best->Function);
  9480. MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
  9481. FoundDecl = Best->FoundDecl;
  9482. CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
  9483. DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
  9484. break;
  9485. case OR_No_Viable_Function:
  9486. Diag(UnresExpr->getMemberLoc(),
  9487. diag::err_ovl_no_viable_member_function_in_call)
  9488. << DeclName << MemExprE->getSourceRange();
  9489. CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
  9490. llvm::makeArrayRef(Args, NumArgs));
  9491. // FIXME: Leaking incoming expressions!
  9492. return ExprError();
  9493. case OR_Ambiguous:
  9494. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
  9495. << DeclName << MemExprE->getSourceRange();
  9496. CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
  9497. llvm::makeArrayRef(Args, NumArgs));
  9498. // FIXME: Leaking incoming expressions!
  9499. return ExprError();
  9500. case OR_Deleted:
  9501. Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
  9502. << Best->Function->isDeleted()
  9503. << DeclName
  9504. << getDeletedOrUnavailableSuffix(Best->Function)
  9505. << MemExprE->getSourceRange();
  9506. CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
  9507. llvm::makeArrayRef(Args, NumArgs));
  9508. // FIXME: Leaking incoming expressions!
  9509. return ExprError();
  9510. }
  9511. MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
  9512. // If overload resolution picked a static member, build a
  9513. // non-member call based on that function.
  9514. if (Method->isStatic()) {
  9515. return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
  9516. Args, NumArgs, RParenLoc);
  9517. }
  9518. MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
  9519. }
  9520. QualType ResultType = Method->getResultType();
  9521. ExprValueKind VK = Expr::getValueKindForType(ResultType);
  9522. ResultType = ResultType.getNonLValueExprType(Context);
  9523. assert(Method && "Member call to something that isn't a method?");
  9524. CXXMemberCallExpr *TheCall =
  9525. new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
  9526. ResultType, VK, RParenLoc);
  9527. // Check for a valid return type.
  9528. if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
  9529. TheCall, Method))
  9530. return ExprError();
  9531. // Convert the object argument (for a non-static member function call).
  9532. // We only need to do this if there was actually an overload; otherwise
  9533. // it was done at lookup.
  9534. if (!Method->isStatic()) {
  9535. ExprResult ObjectArg =
  9536. PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
  9537. FoundDecl, Method);
  9538. if (ObjectArg.isInvalid())
  9539. return ExprError();
  9540. MemExpr->setBase(ObjectArg.take());
  9541. }
  9542. // Convert the rest of the arguments
  9543. const FunctionProtoType *Proto =
  9544. Method->getType()->getAs<FunctionProtoType>();
  9545. if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
  9546. RParenLoc))
  9547. return ExprError();
  9548. DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
  9549. if (CheckFunctionCall(Method, TheCall, Proto))
  9550. return ExprError();
  9551. if ((isa<CXXConstructorDecl>(CurContext) ||
  9552. isa<CXXDestructorDecl>(CurContext)) &&
  9553. TheCall->getMethodDecl()->isPure()) {
  9554. const CXXMethodDecl *MD = TheCall->getMethodDecl();
  9555. if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
  9556. Diag(MemExpr->getLocStart(),
  9557. diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
  9558. << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
  9559. << MD->getParent()->getDeclName();
  9560. Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
  9561. }
  9562. }
  9563. return MaybeBindToTemporary(TheCall);
  9564. }
  9565. /// BuildCallToObjectOfClassType - Build a call to an object of class
  9566. /// type (C++ [over.call.object]), which can end up invoking an
  9567. /// overloaded function call operator (@c operator()) or performing a
  9568. /// user-defined conversion on the object argument.
  9569. ExprResult
  9570. Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
  9571. SourceLocation LParenLoc,
  9572. Expr **Args, unsigned NumArgs,
  9573. SourceLocation RParenLoc) {
  9574. if (checkPlaceholderForOverload(*this, Obj))
  9575. return ExprError();
  9576. ExprResult Object = Owned(Obj);
  9577. UnbridgedCastsSet UnbridgedCasts;
  9578. if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
  9579. return ExprError();
  9580. assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
  9581. const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
  9582. // C++ [over.call.object]p1:
  9583. // If the primary-expression E in the function call syntax
  9584. // evaluates to a class object of type "cv T", then the set of
  9585. // candidate functions includes at least the function call
  9586. // operators of T. The function call operators of T are obtained by
  9587. // ordinary lookup of the name operator() in the context of
  9588. // (E).operator().
  9589. OverloadCandidateSet CandidateSet(LParenLoc);
  9590. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
  9591. if (RequireCompleteType(LParenLoc, Object.get()->getType(),
  9592. diag::err_incomplete_object_call, Object.get()))
  9593. return true;
  9594. LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
  9595. LookupQualifiedName(R, Record->getDecl());
  9596. R.suppressDiagnostics();
  9597. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  9598. Oper != OperEnd; ++Oper) {
  9599. AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
  9600. Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
  9601. /*SuppressUserConversions=*/ false);
  9602. }
  9603. // C++ [over.call.object]p2:
  9604. // In addition, for each (non-explicit in C++0x) conversion function
  9605. // declared in T of the form
  9606. //
  9607. // operator conversion-type-id () cv-qualifier;
  9608. //
  9609. // where cv-qualifier is the same cv-qualification as, or a
  9610. // greater cv-qualification than, cv, and where conversion-type-id
  9611. // denotes the type "pointer to function of (P1,...,Pn) returning
  9612. // R", or the type "reference to pointer to function of
  9613. // (P1,...,Pn) returning R", or the type "reference to function
  9614. // of (P1,...,Pn) returning R", a surrogate call function [...]
  9615. // is also considered as a candidate function. Similarly,
  9616. // surrogate call functions are added to the set of candidate
  9617. // functions for each conversion function declared in an
  9618. // accessible base class provided the function is not hidden
  9619. // within T by another intervening declaration.
  9620. const UnresolvedSetImpl *Conversions
  9621. = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
  9622. for (UnresolvedSetImpl::iterator I = Conversions->begin(),
  9623. E = Conversions->end(); I != E; ++I) {
  9624. NamedDecl *D = *I;
  9625. CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
  9626. if (isa<UsingShadowDecl>(D))
  9627. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  9628. // Skip over templated conversion functions; they aren't
  9629. // surrogates.
  9630. if (isa<FunctionTemplateDecl>(D))
  9631. continue;
  9632. CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
  9633. if (!Conv->isExplicit()) {
  9634. // Strip the reference type (if any) and then the pointer type (if
  9635. // any) to get down to what might be a function type.
  9636. QualType ConvType = Conv->getConversionType().getNonReferenceType();
  9637. if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
  9638. ConvType = ConvPtrType->getPointeeType();
  9639. if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
  9640. {
  9641. AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
  9642. Object.get(), llvm::makeArrayRef(Args, NumArgs),
  9643. CandidateSet);
  9644. }
  9645. }
  9646. }
  9647. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  9648. // Perform overload resolution.
  9649. OverloadCandidateSet::iterator Best;
  9650. switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
  9651. Best)) {
  9652. case OR_Success:
  9653. // Overload resolution succeeded; we'll build the appropriate call
  9654. // below.
  9655. break;
  9656. case OR_No_Viable_Function:
  9657. if (CandidateSet.empty())
  9658. Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
  9659. << Object.get()->getType() << /*call*/ 1
  9660. << Object.get()->getSourceRange();
  9661. else
  9662. Diag(Object.get()->getLocStart(),
  9663. diag::err_ovl_no_viable_object_call)
  9664. << Object.get()->getType() << Object.get()->getSourceRange();
  9665. CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
  9666. llvm::makeArrayRef(Args, NumArgs));
  9667. break;
  9668. case OR_Ambiguous:
  9669. Diag(Object.get()->getLocStart(),
  9670. diag::err_ovl_ambiguous_object_call)
  9671. << Object.get()->getType() << Object.get()->getSourceRange();
  9672. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
  9673. llvm::makeArrayRef(Args, NumArgs));
  9674. break;
  9675. case OR_Deleted:
  9676. Diag(Object.get()->getLocStart(),
  9677. diag::err_ovl_deleted_object_call)
  9678. << Best->Function->isDeleted()
  9679. << Object.get()->getType()
  9680. << getDeletedOrUnavailableSuffix(Best->Function)
  9681. << Object.get()->getSourceRange();
  9682. CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
  9683. llvm::makeArrayRef(Args, NumArgs));
  9684. break;
  9685. }
  9686. if (Best == CandidateSet.end())
  9687. return true;
  9688. UnbridgedCasts.restore();
  9689. if (Best->Function == 0) {
  9690. // Since there is no function declaration, this is one of the
  9691. // surrogate candidates. Dig out the conversion function.
  9692. CXXConversionDecl *Conv
  9693. = cast<CXXConversionDecl>(
  9694. Best->Conversions[0].UserDefined.ConversionFunction);
  9695. CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
  9696. DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
  9697. // We selected one of the surrogate functions that converts the
  9698. // object parameter to a function pointer. Perform the conversion
  9699. // on the object argument, then let ActOnCallExpr finish the job.
  9700. // Create an implicit member expr to refer to the conversion operator.
  9701. // and then call it.
  9702. ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
  9703. Conv, HadMultipleCandidates);
  9704. if (Call.isInvalid())
  9705. return ExprError();
  9706. // Record usage of conversion in an implicit cast.
  9707. Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
  9708. CK_UserDefinedConversion,
  9709. Call.get(), 0, VK_RValue));
  9710. return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
  9711. RParenLoc);
  9712. }
  9713. MarkFunctionReferenced(LParenLoc, Best->Function);
  9714. CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
  9715. DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
  9716. // We found an overloaded operator(). Build a CXXOperatorCallExpr
  9717. // that calls this method, using Object for the implicit object
  9718. // parameter and passing along the remaining arguments.
  9719. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  9720. const FunctionProtoType *Proto =
  9721. Method->getType()->getAs<FunctionProtoType>();
  9722. unsigned NumArgsInProto = Proto->getNumArgs();
  9723. unsigned NumArgsToCheck = NumArgs;
  9724. // Build the full argument list for the method call (the
  9725. // implicit object parameter is placed at the beginning of the
  9726. // list).
  9727. Expr **MethodArgs;
  9728. if (NumArgs < NumArgsInProto) {
  9729. NumArgsToCheck = NumArgsInProto;
  9730. MethodArgs = new Expr*[NumArgsInProto + 1];
  9731. } else {
  9732. MethodArgs = new Expr*[NumArgs + 1];
  9733. }
  9734. MethodArgs[0] = Object.get();
  9735. for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
  9736. MethodArgs[ArgIdx + 1] = Args[ArgIdx];
  9737. DeclarationNameInfo OpLocInfo(
  9738. Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
  9739. OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
  9740. ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
  9741. HadMultipleCandidates,
  9742. OpLocInfo.getLoc(),
  9743. OpLocInfo.getInfo());
  9744. if (NewFn.isInvalid())
  9745. return true;
  9746. // Once we've built TheCall, all of the expressions are properly
  9747. // owned.
  9748. QualType ResultTy = Method->getResultType();
  9749. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  9750. ResultTy = ResultTy.getNonLValueExprType(Context);
  9751. CXXOperatorCallExpr *TheCall =
  9752. new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
  9753. MethodArgs, NumArgs + 1,
  9754. ResultTy, VK, RParenLoc);
  9755. delete [] MethodArgs;
  9756. if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
  9757. Method))
  9758. return true;
  9759. // We may have default arguments. If so, we need to allocate more
  9760. // slots in the call for them.
  9761. if (NumArgs < NumArgsInProto)
  9762. TheCall->setNumArgs(Context, NumArgsInProto + 1);
  9763. else if (NumArgs > NumArgsInProto)
  9764. NumArgsToCheck = NumArgsInProto;
  9765. bool IsError = false;
  9766. // Initialize the implicit object parameter.
  9767. ExprResult ObjRes =
  9768. PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
  9769. Best->FoundDecl, Method);
  9770. if (ObjRes.isInvalid())
  9771. IsError = true;
  9772. else
  9773. Object = ObjRes;
  9774. TheCall->setArg(0, Object.take());
  9775. // Check the argument types.
  9776. for (unsigned i = 0; i != NumArgsToCheck; i++) {
  9777. Expr *Arg;
  9778. if (i < NumArgs) {
  9779. Arg = Args[i];
  9780. // Pass the argument.
  9781. ExprResult InputInit
  9782. = PerformCopyInitialization(InitializedEntity::InitializeParameter(
  9783. Context,
  9784. Method->getParamDecl(i)),
  9785. SourceLocation(), Arg);
  9786. IsError |= InputInit.isInvalid();
  9787. Arg = InputInit.takeAs<Expr>();
  9788. } else {
  9789. ExprResult DefArg
  9790. = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
  9791. if (DefArg.isInvalid()) {
  9792. IsError = true;
  9793. break;
  9794. }
  9795. Arg = DefArg.takeAs<Expr>();
  9796. }
  9797. TheCall->setArg(i + 1, Arg);
  9798. }
  9799. // If this is a variadic call, handle args passed through "...".
  9800. if (Proto->isVariadic()) {
  9801. // Promote the arguments (C99 6.5.2.2p7).
  9802. for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
  9803. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
  9804. IsError |= Arg.isInvalid();
  9805. TheCall->setArg(i + 1, Arg.take());
  9806. }
  9807. }
  9808. if (IsError) return true;
  9809. DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
  9810. if (CheckFunctionCall(Method, TheCall, Proto))
  9811. return true;
  9812. return MaybeBindToTemporary(TheCall);
  9813. }
  9814. /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
  9815. /// (if one exists), where @c Base is an expression of class type and
  9816. /// @c Member is the name of the member we're trying to find.
  9817. ExprResult
  9818. Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
  9819. assert(Base->getType()->isRecordType() &&
  9820. "left-hand side must have class type");
  9821. if (checkPlaceholderForOverload(*this, Base))
  9822. return ExprError();
  9823. SourceLocation Loc = Base->getExprLoc();
  9824. // C++ [over.ref]p1:
  9825. //
  9826. // [...] An expression x->m is interpreted as (x.operator->())->m
  9827. // for a class object x of type T if T::operator->() exists and if
  9828. // the operator is selected as the best match function by the
  9829. // overload resolution mechanism (13.3).
  9830. DeclarationName OpName =
  9831. Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
  9832. OverloadCandidateSet CandidateSet(Loc);
  9833. const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
  9834. if (RequireCompleteType(Loc, Base->getType(),
  9835. diag::err_typecheck_incomplete_tag, Base))
  9836. return ExprError();
  9837. LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
  9838. LookupQualifiedName(R, BaseRecord->getDecl());
  9839. R.suppressDiagnostics();
  9840. for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
  9841. Oper != OperEnd; ++Oper) {
  9842. AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
  9843. 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
  9844. }
  9845. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  9846. // Perform overload resolution.
  9847. OverloadCandidateSet::iterator Best;
  9848. switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
  9849. case OR_Success:
  9850. // Overload resolution succeeded; we'll build the call below.
  9851. break;
  9852. case OR_No_Viable_Function:
  9853. if (CandidateSet.empty())
  9854. Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
  9855. << Base->getType() << Base->getSourceRange();
  9856. else
  9857. Diag(OpLoc, diag::err_ovl_no_viable_oper)
  9858. << "operator->" << Base->getSourceRange();
  9859. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  9860. return ExprError();
  9861. case OR_Ambiguous:
  9862. Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
  9863. << "->" << Base->getType() << Base->getSourceRange();
  9864. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
  9865. return ExprError();
  9866. case OR_Deleted:
  9867. Diag(OpLoc, diag::err_ovl_deleted_oper)
  9868. << Best->Function->isDeleted()
  9869. << "->"
  9870. << getDeletedOrUnavailableSuffix(Best->Function)
  9871. << Base->getSourceRange();
  9872. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
  9873. return ExprError();
  9874. }
  9875. MarkFunctionReferenced(OpLoc, Best->Function);
  9876. CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
  9877. DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
  9878. // Convert the object parameter.
  9879. CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
  9880. ExprResult BaseResult =
  9881. PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
  9882. Best->FoundDecl, Method);
  9883. if (BaseResult.isInvalid())
  9884. return ExprError();
  9885. Base = BaseResult.take();
  9886. // Build the operator call.
  9887. ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
  9888. HadMultipleCandidates, OpLoc);
  9889. if (FnExpr.isInvalid())
  9890. return ExprError();
  9891. QualType ResultTy = Method->getResultType();
  9892. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  9893. ResultTy = ResultTy.getNonLValueExprType(Context);
  9894. CXXOperatorCallExpr *TheCall =
  9895. new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
  9896. &Base, 1, ResultTy, VK, OpLoc);
  9897. if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
  9898. Method))
  9899. return ExprError();
  9900. return MaybeBindToTemporary(TheCall);
  9901. }
  9902. /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
  9903. /// a literal operator described by the provided lookup results.
  9904. ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
  9905. DeclarationNameInfo &SuffixInfo,
  9906. ArrayRef<Expr*> Args,
  9907. SourceLocation LitEndLoc,
  9908. TemplateArgumentListInfo *TemplateArgs) {
  9909. SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
  9910. OverloadCandidateSet CandidateSet(UDSuffixLoc);
  9911. AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
  9912. TemplateArgs);
  9913. bool HadMultipleCandidates = (CandidateSet.size() > 1);
  9914. // Perform overload resolution. This will usually be trivial, but might need
  9915. // to perform substitutions for a literal operator template.
  9916. OverloadCandidateSet::iterator Best;
  9917. switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
  9918. case OR_Success:
  9919. case OR_Deleted:
  9920. break;
  9921. case OR_No_Viable_Function:
  9922. Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
  9923. << R.getLookupName();
  9924. CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
  9925. return ExprError();
  9926. case OR_Ambiguous:
  9927. Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
  9928. CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
  9929. return ExprError();
  9930. }
  9931. FunctionDecl *FD = Best->Function;
  9932. MarkFunctionReferenced(UDSuffixLoc, FD);
  9933. DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
  9934. ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
  9935. SuffixInfo.getLoc(),
  9936. SuffixInfo.getInfo());
  9937. if (Fn.isInvalid())
  9938. return true;
  9939. // Check the argument types. This should almost always be a no-op, except
  9940. // that array-to-pointer decay is applied to string literals.
  9941. Expr *ConvArgs[2];
  9942. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  9943. ExprResult InputInit = PerformCopyInitialization(
  9944. InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
  9945. SourceLocation(), Args[ArgIdx]);
  9946. if (InputInit.isInvalid())
  9947. return true;
  9948. ConvArgs[ArgIdx] = InputInit.take();
  9949. }
  9950. QualType ResultTy = FD->getResultType();
  9951. ExprValueKind VK = Expr::getValueKindForType(ResultTy);
  9952. ResultTy = ResultTy.getNonLValueExprType(Context);
  9953. UserDefinedLiteral *UDL =
  9954. new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
  9955. ResultTy, VK, LitEndLoc, UDSuffixLoc);
  9956. if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
  9957. return ExprError();
  9958. if (CheckFunctionCall(FD, UDL, NULL))
  9959. return ExprError();
  9960. return MaybeBindToTemporary(UDL);
  9961. }
  9962. /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
  9963. /// given LookupResult is non-empty, it is assumed to describe a member which
  9964. /// will be invoked. Otherwise, the function will be found via argument
  9965. /// dependent lookup.
  9966. /// CallExpr is set to a valid expression and FRS_Success returned on success,
  9967. /// otherwise CallExpr is set to ExprError() and some non-success value
  9968. /// is returned.
  9969. Sema::ForRangeStatus
  9970. Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
  9971. SourceLocation RangeLoc, VarDecl *Decl,
  9972. BeginEndFunction BEF,
  9973. const DeclarationNameInfo &NameInfo,
  9974. LookupResult &MemberLookup,
  9975. OverloadCandidateSet *CandidateSet,
  9976. Expr *Range, ExprResult *CallExpr) {
  9977. CandidateSet->clear();
  9978. if (!MemberLookup.empty()) {
  9979. ExprResult MemberRef =
  9980. BuildMemberReferenceExpr(Range, Range->getType(), Loc,
  9981. /*IsPtr=*/false, CXXScopeSpec(),
  9982. /*TemplateKWLoc=*/SourceLocation(),
  9983. /*FirstQualifierInScope=*/0,
  9984. MemberLookup,
  9985. /*TemplateArgs=*/0);
  9986. if (MemberRef.isInvalid()) {
  9987. *CallExpr = ExprError();
  9988. Diag(Range->getLocStart(), diag::note_in_for_range)
  9989. << RangeLoc << BEF << Range->getType();
  9990. return FRS_DiagnosticIssued;
  9991. }
  9992. *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
  9993. if (CallExpr->isInvalid()) {
  9994. *CallExpr = ExprError();
  9995. Diag(Range->getLocStart(), diag::note_in_for_range)
  9996. << RangeLoc << BEF << Range->getType();
  9997. return FRS_DiagnosticIssued;
  9998. }
  9999. } else {
  10000. UnresolvedSet<0> FoundNames;
  10001. // C++11 [stmt.ranged]p1: For the purposes of this name lookup, namespace
  10002. // std is an associated namespace.
  10003. UnresolvedLookupExpr *Fn =
  10004. UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
  10005. NestedNameSpecifierLoc(), NameInfo,
  10006. /*NeedsADL=*/true, /*Overloaded=*/false,
  10007. FoundNames.begin(), FoundNames.end(),
  10008. /*LookInStdNamespace=*/true);
  10009. bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
  10010. CandidateSet, CallExpr);
  10011. if (CandidateSet->empty() || CandidateSetError) {
  10012. *CallExpr = ExprError();
  10013. return FRS_NoViableFunction;
  10014. }
  10015. OverloadCandidateSet::iterator Best;
  10016. OverloadingResult OverloadResult =
  10017. CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
  10018. if (OverloadResult == OR_No_Viable_Function) {
  10019. *CallExpr = ExprError();
  10020. return FRS_NoViableFunction;
  10021. }
  10022. *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
  10023. Loc, 0, CandidateSet, &Best,
  10024. OverloadResult,
  10025. /*AllowTypoCorrection=*/false);
  10026. if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
  10027. *CallExpr = ExprError();
  10028. Diag(Range->getLocStart(), diag::note_in_for_range)
  10029. << RangeLoc << BEF << Range->getType();
  10030. return FRS_DiagnosticIssued;
  10031. }
  10032. }
  10033. return FRS_Success;
  10034. }
  10035. /// FixOverloadedFunctionReference - E is an expression that refers to
  10036. /// a C++ overloaded function (possibly with some parentheses and
  10037. /// perhaps a '&' around it). We have resolved the overloaded function
  10038. /// to the function declaration Fn, so patch up the expression E to
  10039. /// refer (possibly indirectly) to Fn. Returns the new expr.
  10040. Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
  10041. FunctionDecl *Fn) {
  10042. if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  10043. Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
  10044. Found, Fn);
  10045. if (SubExpr == PE->getSubExpr())
  10046. return PE;
  10047. return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
  10048. }
  10049. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  10050. Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
  10051. Found, Fn);
  10052. assert(Context.hasSameType(ICE->getSubExpr()->getType(),
  10053. SubExpr->getType()) &&
  10054. "Implicit cast type cannot be determined from overload");
  10055. assert(ICE->path_empty() && "fixing up hierarchy conversion?");
  10056. if (SubExpr == ICE->getSubExpr())
  10057. return ICE;
  10058. return ImplicitCastExpr::Create(Context, ICE->getType(),
  10059. ICE->getCastKind(),
  10060. SubExpr, 0,
  10061. ICE->getValueKind());
  10062. }
  10063. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
  10064. assert(UnOp->getOpcode() == UO_AddrOf &&
  10065. "Can only take the address of an overloaded function");
  10066. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
  10067. if (Method->isStatic()) {
  10068. // Do nothing: static member functions aren't any different
  10069. // from non-member functions.
  10070. } else {
  10071. // Fix the sub expression, which really has to be an
  10072. // UnresolvedLookupExpr holding an overloaded member function
  10073. // or template.
  10074. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  10075. Found, Fn);
  10076. if (SubExpr == UnOp->getSubExpr())
  10077. return UnOp;
  10078. assert(isa<DeclRefExpr>(SubExpr)
  10079. && "fixed to something other than a decl ref");
  10080. assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
  10081. && "fixed to a member ref with no nested name qualifier");
  10082. // We have taken the address of a pointer to member
  10083. // function. Perform the computation here so that we get the
  10084. // appropriate pointer to member type.
  10085. QualType ClassType
  10086. = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
  10087. QualType MemPtrType
  10088. = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
  10089. return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
  10090. VK_RValue, OK_Ordinary,
  10091. UnOp->getOperatorLoc());
  10092. }
  10093. }
  10094. Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
  10095. Found, Fn);
  10096. if (SubExpr == UnOp->getSubExpr())
  10097. return UnOp;
  10098. return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
  10099. Context.getPointerType(SubExpr->getType()),
  10100. VK_RValue, OK_Ordinary,
  10101. UnOp->getOperatorLoc());
  10102. }
  10103. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  10104. // FIXME: avoid copy.
  10105. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
  10106. if (ULE->hasExplicitTemplateArgs()) {
  10107. ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
  10108. TemplateArgs = &TemplateArgsBuffer;
  10109. }
  10110. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  10111. ULE->getQualifierLoc(),
  10112. ULE->getTemplateKeywordLoc(),
  10113. Fn,
  10114. /*enclosing*/ false, // FIXME?
  10115. ULE->getNameLoc(),
  10116. Fn->getType(),
  10117. VK_LValue,
  10118. Found.getDecl(),
  10119. TemplateArgs);
  10120. MarkDeclRefReferenced(DRE);
  10121. DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
  10122. return DRE;
  10123. }
  10124. if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
  10125. // FIXME: avoid copy.
  10126. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
  10127. if (MemExpr->hasExplicitTemplateArgs()) {
  10128. MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
  10129. TemplateArgs = &TemplateArgsBuffer;
  10130. }
  10131. Expr *Base;
  10132. // If we're filling in a static method where we used to have an
  10133. // implicit member access, rewrite to a simple decl ref.
  10134. if (MemExpr->isImplicitAccess()) {
  10135. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  10136. DeclRefExpr *DRE = DeclRefExpr::Create(Context,
  10137. MemExpr->getQualifierLoc(),
  10138. MemExpr->getTemplateKeywordLoc(),
  10139. Fn,
  10140. /*enclosing*/ false,
  10141. MemExpr->getMemberLoc(),
  10142. Fn->getType(),
  10143. VK_LValue,
  10144. Found.getDecl(),
  10145. TemplateArgs);
  10146. MarkDeclRefReferenced(DRE);
  10147. DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
  10148. return DRE;
  10149. } else {
  10150. SourceLocation Loc = MemExpr->getMemberLoc();
  10151. if (MemExpr->getQualifier())
  10152. Loc = MemExpr->getQualifierLoc().getBeginLoc();
  10153. CheckCXXThisCapture(Loc);
  10154. Base = new (Context) CXXThisExpr(Loc,
  10155. MemExpr->getBaseType(),
  10156. /*isImplicit=*/true);
  10157. }
  10158. } else
  10159. Base = MemExpr->getBase();
  10160. ExprValueKind valueKind;
  10161. QualType type;
  10162. if (cast<CXXMethodDecl>(Fn)->isStatic()) {
  10163. valueKind = VK_LValue;
  10164. type = Fn->getType();
  10165. } else {
  10166. valueKind = VK_RValue;
  10167. type = Context.BoundMemberTy;
  10168. }
  10169. MemberExpr *ME = MemberExpr::Create(Context, Base,
  10170. MemExpr->isArrow(),
  10171. MemExpr->getQualifierLoc(),
  10172. MemExpr->getTemplateKeywordLoc(),
  10173. Fn,
  10174. Found,
  10175. MemExpr->getMemberNameInfo(),
  10176. TemplateArgs,
  10177. type, valueKind, OK_Ordinary);
  10178. ME->setHadMultipleCandidates(true);
  10179. return ME;
  10180. }
  10181. llvm_unreachable("Invalid reference to overloaded function");
  10182. }
  10183. ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
  10184. DeclAccessPair Found,
  10185. FunctionDecl *Fn) {
  10186. return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
  10187. }
  10188. } // end namespace clang