SemaLookup.cpp 220 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845
  1. //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements name lookup for C, C++, Objective-C, and
  10. // Objective-C++.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/CXXInheritance.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclLookups.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/Basic/Builtins.h"
  23. #include "clang/Basic/FileManager.h"
  24. #include "clang/Basic/LangOptions.h"
  25. #include "clang/Lex/HeaderSearch.h"
  26. #include "clang/Lex/ModuleLoader.h"
  27. #include "clang/Lex/Preprocessor.h"
  28. #include "clang/Sema/DeclSpec.h"
  29. #include "clang/Sema/Lookup.h"
  30. #include "clang/Sema/Overload.h"
  31. #include "clang/Sema/RISCVIntrinsicManager.h"
  32. #include "clang/Sema/Scope.h"
  33. #include "clang/Sema/ScopeInfo.h"
  34. #include "clang/Sema/Sema.h"
  35. #include "clang/Sema/SemaInternal.h"
  36. #include "clang/Sema/TemplateDeduction.h"
  37. #include "clang/Sema/TypoCorrection.h"
  38. #include "llvm/ADT/STLExtras.h"
  39. #include "llvm/ADT/SmallPtrSet.h"
  40. #include "llvm/ADT/TinyPtrVector.h"
  41. #include "llvm/ADT/edit_distance.h"
  42. #include "llvm/Support/Casting.h"
  43. #include "llvm/Support/ErrorHandling.h"
  44. #include <algorithm>
  45. #include <iterator>
  46. #include <list>
  47. #include <optional>
  48. #include <set>
  49. #include <utility>
  50. #include <vector>
  51. #include "OpenCLBuiltins.inc"
  52. using namespace clang;
  53. using namespace sema;
  54. namespace {
  55. class UnqualUsingEntry {
  56. const DeclContext *Nominated;
  57. const DeclContext *CommonAncestor;
  58. public:
  59. UnqualUsingEntry(const DeclContext *Nominated,
  60. const DeclContext *CommonAncestor)
  61. : Nominated(Nominated), CommonAncestor(CommonAncestor) {
  62. }
  63. const DeclContext *getCommonAncestor() const {
  64. return CommonAncestor;
  65. }
  66. const DeclContext *getNominatedNamespace() const {
  67. return Nominated;
  68. }
  69. // Sort by the pointer value of the common ancestor.
  70. struct Comparator {
  71. bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
  72. return L.getCommonAncestor() < R.getCommonAncestor();
  73. }
  74. bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
  75. return E.getCommonAncestor() < DC;
  76. }
  77. bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
  78. return DC < E.getCommonAncestor();
  79. }
  80. };
  81. };
  82. /// A collection of using directives, as used by C++ unqualified
  83. /// lookup.
  84. class UnqualUsingDirectiveSet {
  85. Sema &SemaRef;
  86. typedef SmallVector<UnqualUsingEntry, 8> ListTy;
  87. ListTy list;
  88. llvm::SmallPtrSet<DeclContext*, 8> visited;
  89. public:
  90. UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
  91. void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
  92. // C++ [namespace.udir]p1:
  93. // During unqualified name lookup, the names appear as if they
  94. // were declared in the nearest enclosing namespace which contains
  95. // both the using-directive and the nominated namespace.
  96. DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
  97. assert(InnermostFileDC && InnermostFileDC->isFileContext());
  98. for (; S; S = S->getParent()) {
  99. // C++ [namespace.udir]p1:
  100. // A using-directive shall not appear in class scope, but may
  101. // appear in namespace scope or in block scope.
  102. DeclContext *Ctx = S->getEntity();
  103. if (Ctx && Ctx->isFileContext()) {
  104. visit(Ctx, Ctx);
  105. } else if (!Ctx || Ctx->isFunctionOrMethod()) {
  106. for (auto *I : S->using_directives())
  107. if (SemaRef.isVisible(I))
  108. visit(I, InnermostFileDC);
  109. }
  110. }
  111. }
  112. // Visits a context and collect all of its using directives
  113. // recursively. Treats all using directives as if they were
  114. // declared in the context.
  115. //
  116. // A given context is only every visited once, so it is important
  117. // that contexts be visited from the inside out in order to get
  118. // the effective DCs right.
  119. void visit(DeclContext *DC, DeclContext *EffectiveDC) {
  120. if (!visited.insert(DC).second)
  121. return;
  122. addUsingDirectives(DC, EffectiveDC);
  123. }
  124. // Visits a using directive and collects all of its using
  125. // directives recursively. Treats all using directives as if they
  126. // were declared in the effective DC.
  127. void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
  128. DeclContext *NS = UD->getNominatedNamespace();
  129. if (!visited.insert(NS).second)
  130. return;
  131. addUsingDirective(UD, EffectiveDC);
  132. addUsingDirectives(NS, EffectiveDC);
  133. }
  134. // Adds all the using directives in a context (and those nominated
  135. // by its using directives, transitively) as if they appeared in
  136. // the given effective context.
  137. void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
  138. SmallVector<DeclContext*, 4> queue;
  139. while (true) {
  140. for (auto *UD : DC->using_directives()) {
  141. DeclContext *NS = UD->getNominatedNamespace();
  142. if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
  143. addUsingDirective(UD, EffectiveDC);
  144. queue.push_back(NS);
  145. }
  146. }
  147. if (queue.empty())
  148. return;
  149. DC = queue.pop_back_val();
  150. }
  151. }
  152. // Add a using directive as if it had been declared in the given
  153. // context. This helps implement C++ [namespace.udir]p3:
  154. // The using-directive is transitive: if a scope contains a
  155. // using-directive that nominates a second namespace that itself
  156. // contains using-directives, the effect is as if the
  157. // using-directives from the second namespace also appeared in
  158. // the first.
  159. void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
  160. // Find the common ancestor between the effective context and
  161. // the nominated namespace.
  162. DeclContext *Common = UD->getNominatedNamespace();
  163. while (!Common->Encloses(EffectiveDC))
  164. Common = Common->getParent();
  165. Common = Common->getPrimaryContext();
  166. list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
  167. }
  168. void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
  169. typedef ListTy::const_iterator const_iterator;
  170. const_iterator begin() const { return list.begin(); }
  171. const_iterator end() const { return list.end(); }
  172. llvm::iterator_range<const_iterator>
  173. getNamespacesFor(DeclContext *DC) const {
  174. return llvm::make_range(std::equal_range(begin(), end(),
  175. DC->getPrimaryContext(),
  176. UnqualUsingEntry::Comparator()));
  177. }
  178. };
  179. } // end anonymous namespace
  180. // Retrieve the set of identifier namespaces that correspond to a
  181. // specific kind of name lookup.
  182. static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
  183. bool CPlusPlus,
  184. bool Redeclaration) {
  185. unsigned IDNS = 0;
  186. switch (NameKind) {
  187. case Sema::LookupObjCImplicitSelfParam:
  188. case Sema::LookupOrdinaryName:
  189. case Sema::LookupRedeclarationWithLinkage:
  190. case Sema::LookupLocalFriendName:
  191. case Sema::LookupDestructorName:
  192. IDNS = Decl::IDNS_Ordinary;
  193. if (CPlusPlus) {
  194. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
  195. if (Redeclaration)
  196. IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
  197. }
  198. if (Redeclaration)
  199. IDNS |= Decl::IDNS_LocalExtern;
  200. break;
  201. case Sema::LookupOperatorName:
  202. // Operator lookup is its own crazy thing; it is not the same
  203. // as (e.g.) looking up an operator name for redeclaration.
  204. assert(!Redeclaration && "cannot do redeclaration operator lookup");
  205. IDNS = Decl::IDNS_NonMemberOperator;
  206. break;
  207. case Sema::LookupTagName:
  208. if (CPlusPlus) {
  209. IDNS = Decl::IDNS_Type;
  210. // When looking for a redeclaration of a tag name, we add:
  211. // 1) TagFriend to find undeclared friend decls
  212. // 2) Namespace because they can't "overload" with tag decls.
  213. // 3) Tag because it includes class templates, which can't
  214. // "overload" with tag decls.
  215. if (Redeclaration)
  216. IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
  217. } else {
  218. IDNS = Decl::IDNS_Tag;
  219. }
  220. break;
  221. case Sema::LookupLabel:
  222. IDNS = Decl::IDNS_Label;
  223. break;
  224. case Sema::LookupMemberName:
  225. IDNS = Decl::IDNS_Member;
  226. if (CPlusPlus)
  227. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
  228. break;
  229. case Sema::LookupNestedNameSpecifierName:
  230. IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
  231. break;
  232. case Sema::LookupNamespaceName:
  233. IDNS = Decl::IDNS_Namespace;
  234. break;
  235. case Sema::LookupUsingDeclName:
  236. assert(Redeclaration && "should only be used for redecl lookup");
  237. IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
  238. Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
  239. Decl::IDNS_LocalExtern;
  240. break;
  241. case Sema::LookupObjCProtocolName:
  242. IDNS = Decl::IDNS_ObjCProtocol;
  243. break;
  244. case Sema::LookupOMPReductionName:
  245. IDNS = Decl::IDNS_OMPReduction;
  246. break;
  247. case Sema::LookupOMPMapperName:
  248. IDNS = Decl::IDNS_OMPMapper;
  249. break;
  250. case Sema::LookupAnyName:
  251. IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
  252. | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
  253. | Decl::IDNS_Type;
  254. break;
  255. }
  256. return IDNS;
  257. }
  258. void LookupResult::configure() {
  259. IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
  260. isForRedeclaration());
  261. // If we're looking for one of the allocation or deallocation
  262. // operators, make sure that the implicitly-declared new and delete
  263. // operators can be found.
  264. switch (NameInfo.getName().getCXXOverloadedOperator()) {
  265. case OO_New:
  266. case OO_Delete:
  267. case OO_Array_New:
  268. case OO_Array_Delete:
  269. getSema().DeclareGlobalNewDelete();
  270. break;
  271. default:
  272. break;
  273. }
  274. // Compiler builtins are always visible, regardless of where they end
  275. // up being declared.
  276. if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
  277. if (unsigned BuiltinID = Id->getBuiltinID()) {
  278. if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  279. AllowHidden = true;
  280. }
  281. }
  282. }
  283. bool LookupResult::checkDebugAssumptions() const {
  284. // This function is never called by NDEBUG builds.
  285. assert(ResultKind != NotFound || Decls.size() == 0);
  286. assert(ResultKind != Found || Decls.size() == 1);
  287. assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
  288. (Decls.size() == 1 &&
  289. isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
  290. assert(ResultKind != FoundUnresolvedValue || checkUnresolved());
  291. assert(ResultKind != Ambiguous || Decls.size() > 1 ||
  292. (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
  293. Ambiguity == AmbiguousBaseSubobjectTypes)));
  294. assert((Paths != nullptr) == (ResultKind == Ambiguous &&
  295. (Ambiguity == AmbiguousBaseSubobjectTypes ||
  296. Ambiguity == AmbiguousBaseSubobjects)));
  297. return true;
  298. }
  299. // Necessary because CXXBasePaths is not complete in Sema.h
  300. void LookupResult::deletePaths(CXXBasePaths *Paths) {
  301. delete Paths;
  302. }
  303. /// Get a representative context for a declaration such that two declarations
  304. /// will have the same context if they were found within the same scope.
  305. static DeclContext *getContextForScopeMatching(Decl *D) {
  306. // For function-local declarations, use that function as the context. This
  307. // doesn't account for scopes within the function; the caller must deal with
  308. // those.
  309. DeclContext *DC = D->getLexicalDeclContext();
  310. if (DC->isFunctionOrMethod())
  311. return DC;
  312. // Otherwise, look at the semantic context of the declaration. The
  313. // declaration must have been found there.
  314. return D->getDeclContext()->getRedeclContext();
  315. }
  316. /// Determine whether \p D is a better lookup result than \p Existing,
  317. /// given that they declare the same entity.
  318. static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
  319. NamedDecl *D, NamedDecl *Existing) {
  320. // When looking up redeclarations of a using declaration, prefer a using
  321. // shadow declaration over any other declaration of the same entity.
  322. if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
  323. !isa<UsingShadowDecl>(Existing))
  324. return true;
  325. auto *DUnderlying = D->getUnderlyingDecl();
  326. auto *EUnderlying = Existing->getUnderlyingDecl();
  327. // If they have different underlying declarations, prefer a typedef over the
  328. // original type (this happens when two type declarations denote the same
  329. // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
  330. // might carry additional semantic information, such as an alignment override.
  331. // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
  332. // declaration over a typedef. Also prefer a tag over a typedef for
  333. // destructor name lookup because in some contexts we only accept a
  334. // class-name in a destructor declaration.
  335. if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
  336. assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
  337. bool HaveTag = isa<TagDecl>(EUnderlying);
  338. bool WantTag =
  339. Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName;
  340. return HaveTag != WantTag;
  341. }
  342. // Pick the function with more default arguments.
  343. // FIXME: In the presence of ambiguous default arguments, we should keep both,
  344. // so we can diagnose the ambiguity if the default argument is needed.
  345. // See C++ [over.match.best]p3.
  346. if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
  347. auto *EFD = cast<FunctionDecl>(EUnderlying);
  348. unsigned DMin = DFD->getMinRequiredArguments();
  349. unsigned EMin = EFD->getMinRequiredArguments();
  350. // If D has more default arguments, it is preferred.
  351. if (DMin != EMin)
  352. return DMin < EMin;
  353. // FIXME: When we track visibility for default function arguments, check
  354. // that we pick the declaration with more visible default arguments.
  355. }
  356. // Pick the template with more default template arguments.
  357. if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
  358. auto *ETD = cast<TemplateDecl>(EUnderlying);
  359. unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
  360. unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
  361. // If D has more default arguments, it is preferred. Note that default
  362. // arguments (and their visibility) is monotonically increasing across the
  363. // redeclaration chain, so this is a quick proxy for "is more recent".
  364. if (DMin != EMin)
  365. return DMin < EMin;
  366. // If D has more *visible* default arguments, it is preferred. Note, an
  367. // earlier default argument being visible does not imply that a later
  368. // default argument is visible, so we can't just check the first one.
  369. for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
  370. I != N; ++I) {
  371. if (!S.hasVisibleDefaultArgument(
  372. ETD->getTemplateParameters()->getParam(I)) &&
  373. S.hasVisibleDefaultArgument(
  374. DTD->getTemplateParameters()->getParam(I)))
  375. return true;
  376. }
  377. }
  378. // VarDecl can have incomplete array types, prefer the one with more complete
  379. // array type.
  380. if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
  381. VarDecl *EVD = cast<VarDecl>(EUnderlying);
  382. if (EVD->getType()->isIncompleteType() &&
  383. !DVD->getType()->isIncompleteType()) {
  384. // Prefer the decl with a more complete type if visible.
  385. return S.isVisible(DVD);
  386. }
  387. return false; // Avoid picking up a newer decl, just because it was newer.
  388. }
  389. // For most kinds of declaration, it doesn't really matter which one we pick.
  390. if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
  391. // If the existing declaration is hidden, prefer the new one. Otherwise,
  392. // keep what we've got.
  393. return !S.isVisible(Existing);
  394. }
  395. // Pick the newer declaration; it might have a more precise type.
  396. for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
  397. Prev = Prev->getPreviousDecl())
  398. if (Prev == EUnderlying)
  399. return true;
  400. return false;
  401. }
  402. /// Determine whether \p D can hide a tag declaration.
  403. static bool canHideTag(NamedDecl *D) {
  404. // C++ [basic.scope.declarative]p4:
  405. // Given a set of declarations in a single declarative region [...]
  406. // exactly one declaration shall declare a class name or enumeration name
  407. // that is not a typedef name and the other declarations shall all refer to
  408. // the same variable, non-static data member, or enumerator, or all refer
  409. // to functions and function templates; in this case the class name or
  410. // enumeration name is hidden.
  411. // C++ [basic.scope.hiding]p2:
  412. // A class name or enumeration name can be hidden by the name of a
  413. // variable, data member, function, or enumerator declared in the same
  414. // scope.
  415. // An UnresolvedUsingValueDecl always instantiates to one of these.
  416. D = D->getUnderlyingDecl();
  417. return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
  418. isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
  419. isa<UnresolvedUsingValueDecl>(D);
  420. }
  421. /// Resolves the result kind of this lookup.
  422. void LookupResult::resolveKind() {
  423. unsigned N = Decls.size();
  424. // Fast case: no possible ambiguity.
  425. if (N == 0) {
  426. assert(ResultKind == NotFound ||
  427. ResultKind == NotFoundInCurrentInstantiation);
  428. return;
  429. }
  430. // If there's a single decl, we need to examine it to decide what
  431. // kind of lookup this is.
  432. if (N == 1) {
  433. NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
  434. if (isa<FunctionTemplateDecl>(D))
  435. ResultKind = FoundOverloaded;
  436. else if (isa<UnresolvedUsingValueDecl>(D))
  437. ResultKind = FoundUnresolvedValue;
  438. return;
  439. }
  440. // Don't do any extra resolution if we've already resolved as ambiguous.
  441. if (ResultKind == Ambiguous) return;
  442. llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
  443. llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
  444. bool Ambiguous = false;
  445. bool HasTag = false, HasFunction = false;
  446. bool HasFunctionTemplate = false, HasUnresolved = false;
  447. NamedDecl *HasNonFunction = nullptr;
  448. llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
  449. unsigned UniqueTagIndex = 0;
  450. unsigned I = 0;
  451. while (I < N) {
  452. NamedDecl *D = Decls[I]->getUnderlyingDecl();
  453. D = cast<NamedDecl>(D->getCanonicalDecl());
  454. // Ignore an invalid declaration unless it's the only one left.
  455. // Also ignore HLSLBufferDecl which not have name conflict with other Decls.
  456. if ((D->isInvalidDecl() || isa<HLSLBufferDecl>(D)) && !(I == 0 && N == 1)) {
  457. Decls[I] = Decls[--N];
  458. continue;
  459. }
  460. std::optional<unsigned> ExistingI;
  461. // Redeclarations of types via typedef can occur both within a scope
  462. // and, through using declarations and directives, across scopes. There is
  463. // no ambiguity if they all refer to the same type, so unique based on the
  464. // canonical type.
  465. if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
  466. QualType T = getSema().Context.getTypeDeclType(TD);
  467. auto UniqueResult = UniqueTypes.insert(
  468. std::make_pair(getSema().Context.getCanonicalType(T), I));
  469. if (!UniqueResult.second) {
  470. // The type is not unique.
  471. ExistingI = UniqueResult.first->second;
  472. }
  473. }
  474. // For non-type declarations, check for a prior lookup result naming this
  475. // canonical declaration.
  476. if (!ExistingI) {
  477. auto UniqueResult = Unique.insert(std::make_pair(D, I));
  478. if (!UniqueResult.second) {
  479. // We've seen this entity before.
  480. ExistingI = UniqueResult.first->second;
  481. }
  482. }
  483. if (ExistingI) {
  484. // This is not a unique lookup result. Pick one of the results and
  485. // discard the other.
  486. if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
  487. Decls[*ExistingI]))
  488. Decls[*ExistingI] = Decls[I];
  489. Decls[I] = Decls[--N];
  490. continue;
  491. }
  492. // Otherwise, do some decl type analysis and then continue.
  493. if (isa<UnresolvedUsingValueDecl>(D)) {
  494. HasUnresolved = true;
  495. } else if (isa<TagDecl>(D)) {
  496. if (HasTag)
  497. Ambiguous = true;
  498. UniqueTagIndex = I;
  499. HasTag = true;
  500. } else if (isa<FunctionTemplateDecl>(D)) {
  501. HasFunction = true;
  502. HasFunctionTemplate = true;
  503. } else if (isa<FunctionDecl>(D)) {
  504. HasFunction = true;
  505. } else {
  506. if (HasNonFunction) {
  507. // If we're about to create an ambiguity between two declarations that
  508. // are equivalent, but one is an internal linkage declaration from one
  509. // module and the other is an internal linkage declaration from another
  510. // module, just skip it.
  511. if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
  512. D)) {
  513. EquivalentNonFunctions.push_back(D);
  514. Decls[I] = Decls[--N];
  515. continue;
  516. }
  517. Ambiguous = true;
  518. }
  519. HasNonFunction = D;
  520. }
  521. I++;
  522. }
  523. // C++ [basic.scope.hiding]p2:
  524. // A class name or enumeration name can be hidden by the name of
  525. // an object, function, or enumerator declared in the same
  526. // scope. If a class or enumeration name and an object, function,
  527. // or enumerator are declared in the same scope (in any order)
  528. // with the same name, the class or enumeration name is hidden
  529. // wherever the object, function, or enumerator name is visible.
  530. // But it's still an error if there are distinct tag types found,
  531. // even if they're not visible. (ref?)
  532. if (N > 1 && HideTags && HasTag && !Ambiguous &&
  533. (HasFunction || HasNonFunction || HasUnresolved)) {
  534. NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
  535. if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
  536. getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
  537. getContextForScopeMatching(OtherDecl)) &&
  538. canHideTag(OtherDecl))
  539. Decls[UniqueTagIndex] = Decls[--N];
  540. else
  541. Ambiguous = true;
  542. }
  543. // FIXME: This diagnostic should really be delayed until we're done with
  544. // the lookup result, in case the ambiguity is resolved by the caller.
  545. if (!EquivalentNonFunctions.empty() && !Ambiguous)
  546. getSema().diagnoseEquivalentInternalLinkageDeclarations(
  547. getNameLoc(), HasNonFunction, EquivalentNonFunctions);
  548. Decls.truncate(N);
  549. if (HasNonFunction && (HasFunction || HasUnresolved))
  550. Ambiguous = true;
  551. if (Ambiguous)
  552. setAmbiguous(LookupResult::AmbiguousReference);
  553. else if (HasUnresolved)
  554. ResultKind = LookupResult::FoundUnresolvedValue;
  555. else if (N > 1 || HasFunctionTemplate)
  556. ResultKind = LookupResult::FoundOverloaded;
  557. else
  558. ResultKind = LookupResult::Found;
  559. }
  560. void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
  561. CXXBasePaths::const_paths_iterator I, E;
  562. for (I = P.begin(), E = P.end(); I != E; ++I)
  563. for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;
  564. ++DI)
  565. addDecl(*DI);
  566. }
  567. void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
  568. Paths = new CXXBasePaths;
  569. Paths->swap(P);
  570. addDeclsFromBasePaths(*Paths);
  571. resolveKind();
  572. setAmbiguous(AmbiguousBaseSubobjects);
  573. }
  574. void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
  575. Paths = new CXXBasePaths;
  576. Paths->swap(P);
  577. addDeclsFromBasePaths(*Paths);
  578. resolveKind();
  579. setAmbiguous(AmbiguousBaseSubobjectTypes);
  580. }
  581. void LookupResult::print(raw_ostream &Out) {
  582. Out << Decls.size() << " result(s)";
  583. if (isAmbiguous()) Out << ", ambiguous";
  584. if (Paths) Out << ", base paths present";
  585. for (iterator I = begin(), E = end(); I != E; ++I) {
  586. Out << "\n";
  587. (*I)->print(Out, 2);
  588. }
  589. }
  590. LLVM_DUMP_METHOD void LookupResult::dump() {
  591. llvm::errs() << "lookup results for " << getLookupName().getAsString()
  592. << ":\n";
  593. for (NamedDecl *D : *this)
  594. D->dump();
  595. }
  596. /// Diagnose a missing builtin type.
  597. static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,
  598. llvm::StringRef Name) {
  599. S.Diag(SourceLocation(), diag::err_opencl_type_not_found)
  600. << TypeClass << Name;
  601. return S.Context.VoidTy;
  602. }
  603. /// Lookup an OpenCL enum type.
  604. static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
  605. LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
  606. Sema::LookupTagName);
  607. S.LookupName(Result, S.TUScope);
  608. if (Result.empty())
  609. return diagOpenCLBuiltinTypeError(S, "enum", Name);
  610. EnumDecl *Decl = Result.getAsSingle<EnumDecl>();
  611. if (!Decl)
  612. return diagOpenCLBuiltinTypeError(S, "enum", Name);
  613. return S.Context.getEnumType(Decl);
  614. }
  615. /// Lookup an OpenCL typedef type.
  616. static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
  617. LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
  618. Sema::LookupOrdinaryName);
  619. S.LookupName(Result, S.TUScope);
  620. if (Result.empty())
  621. return diagOpenCLBuiltinTypeError(S, "typedef", Name);
  622. TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();
  623. if (!Decl)
  624. return diagOpenCLBuiltinTypeError(S, "typedef", Name);
  625. return S.Context.getTypedefType(Decl);
  626. }
  627. /// Get the QualType instances of the return type and arguments for an OpenCL
  628. /// builtin function signature.
  629. /// \param S (in) The Sema instance.
  630. /// \param OpenCLBuiltin (in) The signature currently handled.
  631. /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
  632. /// type used as return type or as argument.
  633. /// Only meaningful for generic types, otherwise equals 1.
  634. /// \param RetTypes (out) List of the possible return types.
  635. /// \param ArgTypes (out) List of the possible argument types. For each
  636. /// argument, ArgTypes contains QualTypes for the Cartesian product
  637. /// of (vector sizes) x (types) .
  638. static void GetQualTypesForOpenCLBuiltin(
  639. Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,
  640. SmallVector<QualType, 1> &RetTypes,
  641. SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
  642. // Get the QualType instances of the return types.
  643. unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];
  644. OCL2Qual(S, TypeTable[Sig], RetTypes);
  645. GenTypeMaxCnt = RetTypes.size();
  646. // Get the QualType instances of the arguments.
  647. // First type is the return type, skip it.
  648. for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) {
  649. SmallVector<QualType, 1> Ty;
  650. OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
  651. Ty);
  652. GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
  653. ArgTypes.push_back(std::move(Ty));
  654. }
  655. }
  656. /// Create a list of the candidate function overloads for an OpenCL builtin
  657. /// function.
  658. /// \param Context (in) The ASTContext instance.
  659. /// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic
  660. /// type used as return type or as argument.
  661. /// Only meaningful for generic types, otherwise equals 1.
  662. /// \param FunctionList (out) List of FunctionTypes.
  663. /// \param RetTypes (in) List of the possible return types.
  664. /// \param ArgTypes (in) List of the possible types for the arguments.
  665. static void GetOpenCLBuiltinFctOverloads(
  666. ASTContext &Context, unsigned GenTypeMaxCnt,
  667. std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,
  668. SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
  669. FunctionProtoType::ExtProtoInfo PI(
  670. Context.getDefaultCallingConvention(false, false, true));
  671. PI.Variadic = false;
  672. // Do not attempt to create any FunctionTypes if there are no return types,
  673. // which happens when a type belongs to a disabled extension.
  674. if (RetTypes.size() == 0)
  675. return;
  676. // Create FunctionTypes for each (gen)type.
  677. for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
  678. SmallVector<QualType, 5> ArgList;
  679. for (unsigned A = 0; A < ArgTypes.size(); A++) {
  680. // Bail out if there is an argument that has no available types.
  681. if (ArgTypes[A].size() == 0)
  682. return;
  683. // Builtins such as "max" have an "sgentype" argument that represents
  684. // the corresponding scalar type of a gentype. The number of gentypes
  685. // must be a multiple of the number of sgentypes.
  686. assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 &&
  687. "argument type count not compatible with gentype type count");
  688. unsigned Idx = IGenType % ArgTypes[A].size();
  689. ArgList.push_back(ArgTypes[A][Idx]);
  690. }
  691. FunctionList.push_back(Context.getFunctionType(
  692. RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI));
  693. }
  694. }
  695. /// When trying to resolve a function name, if isOpenCLBuiltin() returns a
  696. /// non-null <Index, Len> pair, then the name is referencing an OpenCL
  697. /// builtin function. Add all candidate signatures to the LookUpResult.
  698. ///
  699. /// \param S (in) The Sema instance.
  700. /// \param LR (inout) The LookupResult instance.
  701. /// \param II (in) The identifier being resolved.
  702. /// \param FctIndex (in) Starting index in the BuiltinTable.
  703. /// \param Len (in) The signature list has Len elements.
  704. static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR,
  705. IdentifierInfo *II,
  706. const unsigned FctIndex,
  707. const unsigned Len) {
  708. // The builtin function declaration uses generic types (gentype).
  709. bool HasGenType = false;
  710. // Maximum number of types contained in a generic type used as return type or
  711. // as argument. Only meaningful for generic types, otherwise equals 1.
  712. unsigned GenTypeMaxCnt;
  713. ASTContext &Context = S.Context;
  714. for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {
  715. const OpenCLBuiltinStruct &OpenCLBuiltin =
  716. BuiltinTable[FctIndex + SignatureIndex];
  717. // Ignore this builtin function if it is not available in the currently
  718. // selected language version.
  719. if (!isOpenCLVersionContainedInMask(Context.getLangOpts(),
  720. OpenCLBuiltin.Versions))
  721. continue;
  722. // Ignore this builtin function if it carries an extension macro that is
  723. // not defined. This indicates that the extension is not supported by the
  724. // target, so the builtin function should not be available.
  725. StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];
  726. if (!Extensions.empty()) {
  727. SmallVector<StringRef, 2> ExtVec;
  728. Extensions.split(ExtVec, " ");
  729. bool AllExtensionsDefined = true;
  730. for (StringRef Ext : ExtVec) {
  731. if (!S.getPreprocessor().isMacroDefined(Ext)) {
  732. AllExtensionsDefined = false;
  733. break;
  734. }
  735. }
  736. if (!AllExtensionsDefined)
  737. continue;
  738. }
  739. SmallVector<QualType, 1> RetTypes;
  740. SmallVector<SmallVector<QualType, 1>, 5> ArgTypes;
  741. // Obtain QualType lists for the function signature.
  742. GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,
  743. ArgTypes);
  744. if (GenTypeMaxCnt > 1) {
  745. HasGenType = true;
  746. }
  747. // Create function overload for each type combination.
  748. std::vector<QualType> FunctionList;
  749. GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,
  750. ArgTypes);
  751. SourceLocation Loc = LR.getNameLoc();
  752. DeclContext *Parent = Context.getTranslationUnitDecl();
  753. FunctionDecl *NewOpenCLBuiltin;
  754. for (const auto &FTy : FunctionList) {
  755. NewOpenCLBuiltin = FunctionDecl::Create(
  756. Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,
  757. S.getCurFPFeatures().isFPConstrained(), false,
  758. FTy->isFunctionProtoType());
  759. NewOpenCLBuiltin->setImplicit();
  760. // Create Decl objects for each parameter, adding them to the
  761. // FunctionDecl.
  762. const auto *FP = cast<FunctionProtoType>(FTy);
  763. SmallVector<ParmVarDecl *, 4> ParmList;
  764. for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
  765. ParmVarDecl *Parm = ParmVarDecl::Create(
  766. Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(),
  767. nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr);
  768. Parm->setScopeInfo(0, IParm);
  769. ParmList.push_back(Parm);
  770. }
  771. NewOpenCLBuiltin->setParams(ParmList);
  772. // Add function attributes.
  773. if (OpenCLBuiltin.IsPure)
  774. NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context));
  775. if (OpenCLBuiltin.IsConst)
  776. NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context));
  777. if (OpenCLBuiltin.IsConv)
  778. NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context));
  779. if (!S.getLangOpts().OpenCLCPlusPlus)
  780. NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context));
  781. LR.addDecl(NewOpenCLBuiltin);
  782. }
  783. }
  784. // If we added overloads, need to resolve the lookup result.
  785. if (Len > 1 || HasGenType)
  786. LR.resolveKind();
  787. }
  788. /// Lookup a builtin function, when name lookup would otherwise
  789. /// fail.
  790. bool Sema::LookupBuiltin(LookupResult &R) {
  791. Sema::LookupNameKind NameKind = R.getLookupKind();
  792. // If we didn't find a use of this identifier, and if the identifier
  793. // corresponds to a compiler builtin, create the decl object for the builtin
  794. // now, injecting it into translation unit scope, and return it.
  795. if (NameKind == Sema::LookupOrdinaryName ||
  796. NameKind == Sema::LookupRedeclarationWithLinkage) {
  797. IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
  798. if (II) {
  799. if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
  800. if (II == getASTContext().getMakeIntegerSeqName()) {
  801. R.addDecl(getASTContext().getMakeIntegerSeqDecl());
  802. return true;
  803. } else if (II == getASTContext().getTypePackElementName()) {
  804. R.addDecl(getASTContext().getTypePackElementDecl());
  805. return true;
  806. }
  807. }
  808. // Check if this is an OpenCL Builtin, and if so, insert its overloads.
  809. if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {
  810. auto Index = isOpenCLBuiltin(II->getName());
  811. if (Index.first) {
  812. InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1,
  813. Index.second);
  814. return true;
  815. }
  816. }
  817. if (DeclareRISCVVBuiltins) {
  818. if (!RVIntrinsicManager)
  819. RVIntrinsicManager = CreateRISCVIntrinsicManager(*this);
  820. if (RVIntrinsicManager->CreateIntrinsicIfFound(R, II, PP))
  821. return true;
  822. }
  823. // If this is a builtin on this (or all) targets, create the decl.
  824. if (unsigned BuiltinID = II->getBuiltinID()) {
  825. // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
  826. // library functions like 'malloc'. Instead, we'll just error.
  827. if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL) &&
  828. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  829. return false;
  830. if (NamedDecl *D =
  831. LazilyCreateBuiltin(II, BuiltinID, TUScope,
  832. R.isForRedeclaration(), R.getNameLoc())) {
  833. R.addDecl(D);
  834. return true;
  835. }
  836. }
  837. }
  838. }
  839. return false;
  840. }
  841. /// Looks up the declaration of "struct objc_super" and
  842. /// saves it for later use in building builtin declaration of
  843. /// objc_msgSendSuper and objc_msgSendSuper_stret.
  844. static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) {
  845. ASTContext &Context = Sema.Context;
  846. LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),
  847. Sema::LookupTagName);
  848. Sema.LookupName(Result, S);
  849. if (Result.getResultKind() == LookupResult::Found)
  850. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  851. Context.setObjCSuperType(Context.getTagDeclType(TD));
  852. }
  853. void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) {
  854. if (ID == Builtin::BIobjc_msgSendSuper)
  855. LookupPredefedObjCSuperType(*this, S);
  856. }
  857. /// Determine whether we can declare a special member function within
  858. /// the class at this point.
  859. static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
  860. // We need to have a definition for the class.
  861. if (!Class->getDefinition() || Class->isDependentContext())
  862. return false;
  863. // We can't be in the middle of defining the class.
  864. return !Class->isBeingDefined();
  865. }
  866. void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
  867. if (!CanDeclareSpecialMemberFunction(Class))
  868. return;
  869. // If the default constructor has not yet been declared, do so now.
  870. if (Class->needsImplicitDefaultConstructor())
  871. DeclareImplicitDefaultConstructor(Class);
  872. // If the copy constructor has not yet been declared, do so now.
  873. if (Class->needsImplicitCopyConstructor())
  874. DeclareImplicitCopyConstructor(Class);
  875. // If the copy assignment operator has not yet been declared, do so now.
  876. if (Class->needsImplicitCopyAssignment())
  877. DeclareImplicitCopyAssignment(Class);
  878. if (getLangOpts().CPlusPlus11) {
  879. // If the move constructor has not yet been declared, do so now.
  880. if (Class->needsImplicitMoveConstructor())
  881. DeclareImplicitMoveConstructor(Class);
  882. // If the move assignment operator has not yet been declared, do so now.
  883. if (Class->needsImplicitMoveAssignment())
  884. DeclareImplicitMoveAssignment(Class);
  885. }
  886. // If the destructor has not yet been declared, do so now.
  887. if (Class->needsImplicitDestructor())
  888. DeclareImplicitDestructor(Class);
  889. }
  890. /// Determine whether this is the name of an implicitly-declared
  891. /// special member function.
  892. static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
  893. switch (Name.getNameKind()) {
  894. case DeclarationName::CXXConstructorName:
  895. case DeclarationName::CXXDestructorName:
  896. return true;
  897. case DeclarationName::CXXOperatorName:
  898. return Name.getCXXOverloadedOperator() == OO_Equal;
  899. default:
  900. break;
  901. }
  902. return false;
  903. }
  904. /// If there are any implicit member functions with the given name
  905. /// that need to be declared in the given declaration context, do so.
  906. static void DeclareImplicitMemberFunctionsWithName(Sema &S,
  907. DeclarationName Name,
  908. SourceLocation Loc,
  909. const DeclContext *DC) {
  910. if (!DC)
  911. return;
  912. switch (Name.getNameKind()) {
  913. case DeclarationName::CXXConstructorName:
  914. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  915. if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
  916. CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
  917. if (Record->needsImplicitDefaultConstructor())
  918. S.DeclareImplicitDefaultConstructor(Class);
  919. if (Record->needsImplicitCopyConstructor())
  920. S.DeclareImplicitCopyConstructor(Class);
  921. if (S.getLangOpts().CPlusPlus11 &&
  922. Record->needsImplicitMoveConstructor())
  923. S.DeclareImplicitMoveConstructor(Class);
  924. }
  925. break;
  926. case DeclarationName::CXXDestructorName:
  927. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  928. if (Record->getDefinition() && Record->needsImplicitDestructor() &&
  929. CanDeclareSpecialMemberFunction(Record))
  930. S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
  931. break;
  932. case DeclarationName::CXXOperatorName:
  933. if (Name.getCXXOverloadedOperator() != OO_Equal)
  934. break;
  935. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
  936. if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
  937. CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
  938. if (Record->needsImplicitCopyAssignment())
  939. S.DeclareImplicitCopyAssignment(Class);
  940. if (S.getLangOpts().CPlusPlus11 &&
  941. Record->needsImplicitMoveAssignment())
  942. S.DeclareImplicitMoveAssignment(Class);
  943. }
  944. }
  945. break;
  946. case DeclarationName::CXXDeductionGuideName:
  947. S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
  948. break;
  949. default:
  950. break;
  951. }
  952. }
  953. // Adds all qualifying matches for a name within a decl context to the
  954. // given lookup result. Returns true if any matches were found.
  955. static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
  956. bool Found = false;
  957. // Lazily declare C++ special member functions.
  958. if (S.getLangOpts().CPlusPlus)
  959. DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
  960. DC);
  961. // Perform lookup into this declaration context.
  962. DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
  963. for (NamedDecl *D : DR) {
  964. if ((D = R.getAcceptableDecl(D))) {
  965. R.addDecl(D);
  966. Found = true;
  967. }
  968. }
  969. if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))
  970. return true;
  971. if (R.getLookupName().getNameKind()
  972. != DeclarationName::CXXConversionFunctionName ||
  973. R.getLookupName().getCXXNameType()->isDependentType() ||
  974. !isa<CXXRecordDecl>(DC))
  975. return Found;
  976. // C++ [temp.mem]p6:
  977. // A specialization of a conversion function template is not found by
  978. // name lookup. Instead, any conversion function templates visible in the
  979. // context of the use are considered. [...]
  980. const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  981. if (!Record->isCompleteDefinition())
  982. return Found;
  983. // For conversion operators, 'operator auto' should only match
  984. // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
  985. // as a candidate for template substitution.
  986. auto *ContainedDeducedType =
  987. R.getLookupName().getCXXNameType()->getContainedDeducedType();
  988. if (R.getLookupName().getNameKind() ==
  989. DeclarationName::CXXConversionFunctionName &&
  990. ContainedDeducedType && ContainedDeducedType->isUndeducedType())
  991. return Found;
  992. for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
  993. UEnd = Record->conversion_end(); U != UEnd; ++U) {
  994. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
  995. if (!ConvTemplate)
  996. continue;
  997. // When we're performing lookup for the purposes of redeclaration, just
  998. // add the conversion function template. When we deduce template
  999. // arguments for specializations, we'll end up unifying the return
  1000. // type of the new declaration with the type of the function template.
  1001. if (R.isForRedeclaration()) {
  1002. R.addDecl(ConvTemplate);
  1003. Found = true;
  1004. continue;
  1005. }
  1006. // C++ [temp.mem]p6:
  1007. // [...] For each such operator, if argument deduction succeeds
  1008. // (14.9.2.3), the resulting specialization is used as if found by
  1009. // name lookup.
  1010. //
  1011. // When referencing a conversion function for any purpose other than
  1012. // a redeclaration (such that we'll be building an expression with the
  1013. // result), perform template argument deduction and place the
  1014. // specialization into the result set. We do this to avoid forcing all
  1015. // callers to perform special deduction for conversion functions.
  1016. TemplateDeductionInfo Info(R.getNameLoc());
  1017. FunctionDecl *Specialization = nullptr;
  1018. const FunctionProtoType *ConvProto
  1019. = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
  1020. assert(ConvProto && "Nonsensical conversion function template type");
  1021. // Compute the type of the function that we would expect the conversion
  1022. // function to have, if it were to match the name given.
  1023. // FIXME: Calling convention!
  1024. FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
  1025. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
  1026. EPI.ExceptionSpec = EST_None;
  1027. QualType ExpectedType = R.getSema().Context.getFunctionType(
  1028. R.getLookupName().getCXXNameType(), std::nullopt, EPI);
  1029. // Perform template argument deduction against the type that we would
  1030. // expect the function to have.
  1031. if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
  1032. Specialization, Info)
  1033. == Sema::TDK_Success) {
  1034. R.addDecl(Specialization);
  1035. Found = true;
  1036. }
  1037. }
  1038. return Found;
  1039. }
  1040. // Performs C++ unqualified lookup into the given file context.
  1041. static bool
  1042. CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
  1043. DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
  1044. assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
  1045. // Perform direct name lookup into the LookupCtx.
  1046. bool Found = LookupDirect(S, R, NS);
  1047. // Perform direct name lookup into the namespaces nominated by the
  1048. // using directives whose common ancestor is this namespace.
  1049. for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
  1050. if (LookupDirect(S, R, UUE.getNominatedNamespace()))
  1051. Found = true;
  1052. R.resolveKind();
  1053. return Found;
  1054. }
  1055. static bool isNamespaceOrTranslationUnitScope(Scope *S) {
  1056. if (DeclContext *Ctx = S->getEntity())
  1057. return Ctx->isFileContext();
  1058. return false;
  1059. }
  1060. /// Find the outer declaration context from this scope. This indicates the
  1061. /// context that we should search up to (exclusive) before considering the
  1062. /// parent of the specified scope.
  1063. static DeclContext *findOuterContext(Scope *S) {
  1064. for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())
  1065. if (DeclContext *DC = OuterS->getLookupEntity())
  1066. return DC;
  1067. return nullptr;
  1068. }
  1069. namespace {
  1070. /// An RAII object to specify that we want to find block scope extern
  1071. /// declarations.
  1072. struct FindLocalExternScope {
  1073. FindLocalExternScope(LookupResult &R)
  1074. : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
  1075. Decl::IDNS_LocalExtern) {
  1076. R.setFindLocalExtern(R.getIdentifierNamespace() &
  1077. (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
  1078. }
  1079. void restore() {
  1080. R.setFindLocalExtern(OldFindLocalExtern);
  1081. }
  1082. ~FindLocalExternScope() {
  1083. restore();
  1084. }
  1085. LookupResult &R;
  1086. bool OldFindLocalExtern;
  1087. };
  1088. } // end anonymous namespace
  1089. bool Sema::CppLookupName(LookupResult &R, Scope *S) {
  1090. assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
  1091. DeclarationName Name = R.getLookupName();
  1092. Sema::LookupNameKind NameKind = R.getLookupKind();
  1093. // If this is the name of an implicitly-declared special member function,
  1094. // go through the scope stack to implicitly declare
  1095. if (isImplicitlyDeclaredMemberFunctionName(Name)) {
  1096. for (Scope *PreS = S; PreS; PreS = PreS->getParent())
  1097. if (DeclContext *DC = PreS->getEntity())
  1098. DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
  1099. }
  1100. // Implicitly declare member functions with the name we're looking for, if in
  1101. // fact we are in a scope where it matters.
  1102. Scope *Initial = S;
  1103. IdentifierResolver::iterator
  1104. I = IdResolver.begin(Name),
  1105. IEnd = IdResolver.end();
  1106. // First we lookup local scope.
  1107. // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
  1108. // ...During unqualified name lookup (3.4.1), the names appear as if
  1109. // they were declared in the nearest enclosing namespace which contains
  1110. // both the using-directive and the nominated namespace.
  1111. // [Note: in this context, "contains" means "contains directly or
  1112. // indirectly".
  1113. //
  1114. // For example:
  1115. // namespace A { int i; }
  1116. // void foo() {
  1117. // int i;
  1118. // {
  1119. // using namespace A;
  1120. // ++i; // finds local 'i', A::i appears at global scope
  1121. // }
  1122. // }
  1123. //
  1124. UnqualUsingDirectiveSet UDirs(*this);
  1125. bool VisitedUsingDirectives = false;
  1126. bool LeftStartingScope = false;
  1127. // When performing a scope lookup, we want to find local extern decls.
  1128. FindLocalExternScope FindLocals(R);
  1129. for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
  1130. bool SearchNamespaceScope = true;
  1131. // Check whether the IdResolver has anything in this scope.
  1132. for (; I != IEnd && S->isDeclScope(*I); ++I) {
  1133. if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
  1134. if (NameKind == LookupRedeclarationWithLinkage &&
  1135. !(*I)->isTemplateParameter()) {
  1136. // If it's a template parameter, we still find it, so we can diagnose
  1137. // the invalid redeclaration.
  1138. // Determine whether this (or a previous) declaration is
  1139. // out-of-scope.
  1140. if (!LeftStartingScope && !Initial->isDeclScope(*I))
  1141. LeftStartingScope = true;
  1142. // If we found something outside of our starting scope that
  1143. // does not have linkage, skip it.
  1144. if (LeftStartingScope && !((*I)->hasLinkage())) {
  1145. R.setShadowed();
  1146. continue;
  1147. }
  1148. } else {
  1149. // We found something in this scope, we should not look at the
  1150. // namespace scope
  1151. SearchNamespaceScope = false;
  1152. }
  1153. R.addDecl(ND);
  1154. }
  1155. }
  1156. if (!SearchNamespaceScope) {
  1157. R.resolveKind();
  1158. if (S->isClassScope())
  1159. if (CXXRecordDecl *Record =
  1160. dyn_cast_or_null<CXXRecordDecl>(S->getEntity()))
  1161. R.setNamingClass(Record);
  1162. return true;
  1163. }
  1164. if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
  1165. // C++11 [class.friend]p11:
  1166. // If a friend declaration appears in a local class and the name
  1167. // specified is an unqualified name, a prior declaration is
  1168. // looked up without considering scopes that are outside the
  1169. // innermost enclosing non-class scope.
  1170. return false;
  1171. }
  1172. if (DeclContext *Ctx = S->getLookupEntity()) {
  1173. DeclContext *OuterCtx = findOuterContext(S);
  1174. for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
  1175. // We do not directly look into transparent contexts, since
  1176. // those entities will be found in the nearest enclosing
  1177. // non-transparent context.
  1178. if (Ctx->isTransparentContext())
  1179. continue;
  1180. // We do not look directly into function or method contexts,
  1181. // since all of the local variables and parameters of the
  1182. // function/method are present within the Scope.
  1183. if (Ctx->isFunctionOrMethod()) {
  1184. // If we have an Objective-C instance method, look for ivars
  1185. // in the corresponding interface.
  1186. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
  1187. if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
  1188. if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
  1189. ObjCInterfaceDecl *ClassDeclared;
  1190. if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
  1191. Name.getAsIdentifierInfo(),
  1192. ClassDeclared)) {
  1193. if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
  1194. R.addDecl(ND);
  1195. R.resolveKind();
  1196. return true;
  1197. }
  1198. }
  1199. }
  1200. }
  1201. continue;
  1202. }
  1203. // If this is a file context, we need to perform unqualified name
  1204. // lookup considering using directives.
  1205. if (Ctx->isFileContext()) {
  1206. // If we haven't handled using directives yet, do so now.
  1207. if (!VisitedUsingDirectives) {
  1208. // Add using directives from this context up to the top level.
  1209. for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
  1210. if (UCtx->isTransparentContext())
  1211. continue;
  1212. UDirs.visit(UCtx, UCtx);
  1213. }
  1214. // Find the innermost file scope, so we can add using directives
  1215. // from local scopes.
  1216. Scope *InnermostFileScope = S;
  1217. while (InnermostFileScope &&
  1218. !isNamespaceOrTranslationUnitScope(InnermostFileScope))
  1219. InnermostFileScope = InnermostFileScope->getParent();
  1220. UDirs.visitScopeChain(Initial, InnermostFileScope);
  1221. UDirs.done();
  1222. VisitedUsingDirectives = true;
  1223. }
  1224. if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
  1225. R.resolveKind();
  1226. return true;
  1227. }
  1228. continue;
  1229. }
  1230. // Perform qualified name lookup into this context.
  1231. // FIXME: In some cases, we know that every name that could be found by
  1232. // this qualified name lookup will also be on the identifier chain. For
  1233. // example, inside a class without any base classes, we never need to
  1234. // perform qualified lookup because all of the members are on top of the
  1235. // identifier chain.
  1236. if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
  1237. return true;
  1238. }
  1239. }
  1240. }
  1241. // Stop if we ran out of scopes.
  1242. // FIXME: This really, really shouldn't be happening.
  1243. if (!S) return false;
  1244. // If we are looking for members, no need to look into global/namespace scope.
  1245. if (NameKind == LookupMemberName)
  1246. return false;
  1247. // Collect UsingDirectiveDecls in all scopes, and recursively all
  1248. // nominated namespaces by those using-directives.
  1249. //
  1250. // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
  1251. // don't build it for each lookup!
  1252. if (!VisitedUsingDirectives) {
  1253. UDirs.visitScopeChain(Initial, S);
  1254. UDirs.done();
  1255. }
  1256. // If we're not performing redeclaration lookup, do not look for local
  1257. // extern declarations outside of a function scope.
  1258. if (!R.isForRedeclaration())
  1259. FindLocals.restore();
  1260. // Lookup namespace scope, and global scope.
  1261. // Unqualified name lookup in C++ requires looking into scopes
  1262. // that aren't strictly lexical, and therefore we walk through the
  1263. // context as well as walking through the scopes.
  1264. for (; S; S = S->getParent()) {
  1265. // Check whether the IdResolver has anything in this scope.
  1266. bool Found = false;
  1267. for (; I != IEnd && S->isDeclScope(*I); ++I) {
  1268. if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
  1269. // We found something. Look for anything else in our scope
  1270. // with this same name and in an acceptable identifier
  1271. // namespace, so that we can construct an overload set if we
  1272. // need to.
  1273. Found = true;
  1274. R.addDecl(ND);
  1275. }
  1276. }
  1277. if (Found && S->isTemplateParamScope()) {
  1278. R.resolveKind();
  1279. return true;
  1280. }
  1281. DeclContext *Ctx = S->getLookupEntity();
  1282. if (Ctx) {
  1283. DeclContext *OuterCtx = findOuterContext(S);
  1284. for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
  1285. // We do not directly look into transparent contexts, since
  1286. // those entities will be found in the nearest enclosing
  1287. // non-transparent context.
  1288. if (Ctx->isTransparentContext())
  1289. continue;
  1290. // If we have a context, and it's not a context stashed in the
  1291. // template parameter scope for an out-of-line definition, also
  1292. // look into that context.
  1293. if (!(Found && S->isTemplateParamScope())) {
  1294. assert(Ctx->isFileContext() &&
  1295. "We should have been looking only at file context here already.");
  1296. // Look into context considering using-directives.
  1297. if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
  1298. Found = true;
  1299. }
  1300. if (Found) {
  1301. R.resolveKind();
  1302. return true;
  1303. }
  1304. if (R.isForRedeclaration() && !Ctx->isTransparentContext())
  1305. return false;
  1306. }
  1307. }
  1308. if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
  1309. return false;
  1310. }
  1311. return !R.empty();
  1312. }
  1313. void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
  1314. if (auto *M = getCurrentModule())
  1315. Context.mergeDefinitionIntoModule(ND, M);
  1316. else
  1317. // We're not building a module; just make the definition visible.
  1318. ND->setVisibleDespiteOwningModule();
  1319. // If ND is a template declaration, make the template parameters
  1320. // visible too. They're not (necessarily) within a mergeable DeclContext.
  1321. if (auto *TD = dyn_cast<TemplateDecl>(ND))
  1322. for (auto *Param : *TD->getTemplateParameters())
  1323. makeMergedDefinitionVisible(Param);
  1324. }
  1325. /// Find the module in which the given declaration was defined.
  1326. static Module *getDefiningModule(Sema &S, Decl *Entity) {
  1327. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
  1328. // If this function was instantiated from a template, the defining module is
  1329. // the module containing the pattern.
  1330. if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
  1331. Entity = Pattern;
  1332. } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
  1333. if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
  1334. Entity = Pattern;
  1335. } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
  1336. if (auto *Pattern = ED->getTemplateInstantiationPattern())
  1337. Entity = Pattern;
  1338. } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
  1339. if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
  1340. Entity = Pattern;
  1341. }
  1342. // Walk up to the containing context. That might also have been instantiated
  1343. // from a template.
  1344. DeclContext *Context = Entity->getLexicalDeclContext();
  1345. if (Context->isFileContext())
  1346. return S.getOwningModule(Entity);
  1347. return getDefiningModule(S, cast<Decl>(Context));
  1348. }
  1349. llvm::DenseSet<Module*> &Sema::getLookupModules() {
  1350. unsigned N = CodeSynthesisContexts.size();
  1351. for (unsigned I = CodeSynthesisContextLookupModules.size();
  1352. I != N; ++I) {
  1353. Module *M = CodeSynthesisContexts[I].Entity ?
  1354. getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
  1355. nullptr;
  1356. if (M && !LookupModulesCache.insert(M).second)
  1357. M = nullptr;
  1358. CodeSynthesisContextLookupModules.push_back(M);
  1359. }
  1360. return LookupModulesCache;
  1361. }
  1362. /// Determine if we could use all the declarations in the module.
  1363. bool Sema::isUsableModule(const Module *M) {
  1364. assert(M && "We shouldn't check nullness for module here");
  1365. // Return quickly if we cached the result.
  1366. if (UsableModuleUnitsCache.count(M))
  1367. return true;
  1368. // If M is the global module fragment of the current translation unit. So it
  1369. // should be usable.
  1370. // [module.global.frag]p1:
  1371. // The global module fragment can be used to provide declarations that are
  1372. // attached to the global module and usable within the module unit.
  1373. if (M == GlobalModuleFragment ||
  1374. // If M is the module we're parsing, it should be usable. This covers the
  1375. // private module fragment. The private module fragment is usable only if
  1376. // it is within the current module unit. And it must be the current
  1377. // parsing module unit if it is within the current module unit according
  1378. // to the grammar of the private module fragment. NOTE: This is covered by
  1379. // the following condition. The intention of the check is to avoid string
  1380. // comparison as much as possible.
  1381. M == getCurrentModule() ||
  1382. // The module unit which is in the same module with the current module
  1383. // unit is usable.
  1384. //
  1385. // FIXME: Here we judge if they are in the same module by comparing the
  1386. // string. Is there any better solution?
  1387. M->getPrimaryModuleInterfaceName() ==
  1388. llvm::StringRef(getLangOpts().CurrentModule).split(':').first) {
  1389. UsableModuleUnitsCache.insert(M);
  1390. return true;
  1391. }
  1392. return false;
  1393. }
  1394. bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
  1395. for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
  1396. if (isModuleVisible(Merged))
  1397. return true;
  1398. return false;
  1399. }
  1400. bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
  1401. for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
  1402. if (isUsableModule(Merged))
  1403. return true;
  1404. return false;
  1405. }
  1406. template <typename ParmDecl>
  1407. static bool
  1408. hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D,
  1409. llvm::SmallVectorImpl<Module *> *Modules,
  1410. Sema::AcceptableKind Kind) {
  1411. if (!D->hasDefaultArgument())
  1412. return false;
  1413. llvm::SmallPtrSet<const ParmDecl *, 4> Visited;
  1414. while (D && Visited.insert(D).second) {
  1415. auto &DefaultArg = D->getDefaultArgStorage();
  1416. if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))
  1417. return true;
  1418. if (!DefaultArg.isInherited() && Modules) {
  1419. auto *NonConstD = const_cast<ParmDecl*>(D);
  1420. Modules->push_back(S.getOwningModule(NonConstD));
  1421. }
  1422. // If there was a previous default argument, maybe its parameter is
  1423. // acceptable.
  1424. D = DefaultArg.getInheritedFrom();
  1425. }
  1426. return false;
  1427. }
  1428. bool Sema::hasAcceptableDefaultArgument(
  1429. const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,
  1430. Sema::AcceptableKind Kind) {
  1431. if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
  1432. return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
  1433. if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
  1434. return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
  1435. return ::hasAcceptableDefaultArgument(
  1436. *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);
  1437. }
  1438. bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
  1439. llvm::SmallVectorImpl<Module *> *Modules) {
  1440. return hasAcceptableDefaultArgument(D, Modules,
  1441. Sema::AcceptableKind::Visible);
  1442. }
  1443. bool Sema::hasReachableDefaultArgument(
  1444. const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
  1445. return hasAcceptableDefaultArgument(D, Modules,
  1446. Sema::AcceptableKind::Reachable);
  1447. }
  1448. template <typename Filter>
  1449. static bool
  1450. hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D,
  1451. llvm::SmallVectorImpl<Module *> *Modules, Filter F,
  1452. Sema::AcceptableKind Kind) {
  1453. bool HasFilteredRedecls = false;
  1454. for (auto *Redecl : D->redecls()) {
  1455. auto *R = cast<NamedDecl>(Redecl);
  1456. if (!F(R))
  1457. continue;
  1458. if (S.isAcceptable(R, Kind))
  1459. return true;
  1460. HasFilteredRedecls = true;
  1461. if (Modules)
  1462. Modules->push_back(R->getOwningModule());
  1463. }
  1464. // Only return false if there is at least one redecl that is not filtered out.
  1465. if (HasFilteredRedecls)
  1466. return false;
  1467. return true;
  1468. }
  1469. static bool
  1470. hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D,
  1471. llvm::SmallVectorImpl<Module *> *Modules,
  1472. Sema::AcceptableKind Kind) {
  1473. return hasAcceptableDeclarationImpl(
  1474. S, D, Modules,
  1475. [](const NamedDecl *D) {
  1476. if (auto *RD = dyn_cast<CXXRecordDecl>(D))
  1477. return RD->getTemplateSpecializationKind() ==
  1478. TSK_ExplicitSpecialization;
  1479. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1480. return FD->getTemplateSpecializationKind() ==
  1481. TSK_ExplicitSpecialization;
  1482. if (auto *VD = dyn_cast<VarDecl>(D))
  1483. return VD->getTemplateSpecializationKind() ==
  1484. TSK_ExplicitSpecialization;
  1485. llvm_unreachable("unknown explicit specialization kind");
  1486. },
  1487. Kind);
  1488. }
  1489. bool Sema::hasVisibleExplicitSpecialization(
  1490. const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
  1491. return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
  1492. Sema::AcceptableKind::Visible);
  1493. }
  1494. bool Sema::hasReachableExplicitSpecialization(
  1495. const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
  1496. return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
  1497. Sema::AcceptableKind::Reachable);
  1498. }
  1499. static bool
  1500. hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D,
  1501. llvm::SmallVectorImpl<Module *> *Modules,
  1502. Sema::AcceptableKind Kind) {
  1503. assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
  1504. "not a member specialization");
  1505. return hasAcceptableDeclarationImpl(
  1506. S, D, Modules,
  1507. [](const NamedDecl *D) {
  1508. // If the specialization is declared at namespace scope, then it's a
  1509. // member specialization declaration. If it's lexically inside the class
  1510. // definition then it was instantiated.
  1511. //
  1512. // FIXME: This is a hack. There should be a better way to determine
  1513. // this.
  1514. // FIXME: What about MS-style explicit specializations declared within a
  1515. // class definition?
  1516. return D->getLexicalDeclContext()->isFileContext();
  1517. },
  1518. Kind);
  1519. }
  1520. bool Sema::hasVisibleMemberSpecialization(
  1521. const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
  1522. return hasAcceptableMemberSpecialization(*this, D, Modules,
  1523. Sema::AcceptableKind::Visible);
  1524. }
  1525. bool Sema::hasReachableMemberSpecialization(
  1526. const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
  1527. return hasAcceptableMemberSpecialization(*this, D, Modules,
  1528. Sema::AcceptableKind::Reachable);
  1529. }
  1530. /// Determine whether a declaration is acceptable to name lookup.
  1531. ///
  1532. /// This routine determines whether the declaration D is acceptable in the
  1533. /// current lookup context, taking into account the current template
  1534. /// instantiation stack. During template instantiation, a declaration is
  1535. /// acceptable if it is acceptable from a module containing any entity on the
  1536. /// template instantiation path (by instantiating a template, you allow it to
  1537. /// see the declarations that your module can see, including those later on in
  1538. /// your module).
  1539. bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
  1540. Sema::AcceptableKind Kind) {
  1541. assert(!D->isUnconditionallyVisible() &&
  1542. "should not call this: not in slow case");
  1543. Module *DeclModule = SemaRef.getOwningModule(D);
  1544. assert(DeclModule && "hidden decl has no owning module");
  1545. // If the owning module is visible, the decl is acceptable.
  1546. if (SemaRef.isModuleVisible(DeclModule,
  1547. D->isInvisibleOutsideTheOwningModule()))
  1548. return true;
  1549. // Determine whether a decl context is a file context for the purpose of
  1550. // visibility/reachability. This looks through some (export and linkage spec)
  1551. // transparent contexts, but not others (enums).
  1552. auto IsEffectivelyFileContext = [](const DeclContext *DC) {
  1553. return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
  1554. isa<ExportDecl>(DC);
  1555. };
  1556. // If this declaration is not at namespace scope
  1557. // then it is acceptable if its lexical parent has a acceptable definition.
  1558. DeclContext *DC = D->getLexicalDeclContext();
  1559. if (DC && !IsEffectivelyFileContext(DC)) {
  1560. // For a parameter, check whether our current template declaration's
  1561. // lexical context is acceptable, not whether there's some other acceptable
  1562. // definition of it, because parameters aren't "within" the definition.
  1563. //
  1564. // In C++ we need to check for a acceptable definition due to ODR merging,
  1565. // and in C we must not because each declaration of a function gets its own
  1566. // set of declarations for tags in prototype scope.
  1567. bool AcceptableWithinParent;
  1568. if (D->isTemplateParameter()) {
  1569. bool SearchDefinitions = true;
  1570. if (const auto *DCD = dyn_cast<Decl>(DC)) {
  1571. if (const auto *TD = DCD->getDescribedTemplate()) {
  1572. TemplateParameterList *TPL = TD->getTemplateParameters();
  1573. auto Index = getDepthAndIndex(D).second;
  1574. SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
  1575. }
  1576. }
  1577. if (SearchDefinitions)
  1578. AcceptableWithinParent =
  1579. SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
  1580. else
  1581. AcceptableWithinParent =
  1582. isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
  1583. } else if (isa<ParmVarDecl>(D) ||
  1584. (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
  1585. AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
  1586. else if (D->isModulePrivate()) {
  1587. // A module-private declaration is only acceptable if an enclosing lexical
  1588. // parent was merged with another definition in the current module.
  1589. AcceptableWithinParent = false;
  1590. do {
  1591. if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
  1592. AcceptableWithinParent = true;
  1593. break;
  1594. }
  1595. DC = DC->getLexicalParent();
  1596. } while (!IsEffectivelyFileContext(DC));
  1597. } else {
  1598. AcceptableWithinParent =
  1599. SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
  1600. }
  1601. if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
  1602. Kind == Sema::AcceptableKind::Visible &&
  1603. // FIXME: Do something better in this case.
  1604. !SemaRef.getLangOpts().ModulesLocalVisibility) {
  1605. // Cache the fact that this declaration is implicitly visible because
  1606. // its parent has a visible definition.
  1607. D->setVisibleDespiteOwningModule();
  1608. }
  1609. return AcceptableWithinParent;
  1610. }
  1611. if (Kind == Sema::AcceptableKind::Visible)
  1612. return false;
  1613. assert(Kind == Sema::AcceptableKind::Reachable &&
  1614. "Additional Sema::AcceptableKind?");
  1615. return isReachableSlow(SemaRef, D);
  1616. }
  1617. bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
  1618. // [module.global.frag]p2:
  1619. // A global-module-fragment specifies the contents of the global module
  1620. // fragment for a module unit. The global module fragment can be used to
  1621. // provide declarations that are attached to the global module and usable
  1622. // within the module unit.
  1623. //
  1624. // Global module fragment is special. Global Module fragment is only usable
  1625. // within the module unit it got defined [module.global.frag]p2. So here we
  1626. // check if the Module is the global module fragment in current translation
  1627. // unit.
  1628. if (M->isGlobalModule() && M != this->GlobalModuleFragment)
  1629. return false;
  1630. // The module might be ordinarily visible. For a module-private query, that
  1631. // means it is part of the current module.
  1632. if (ModulePrivate && isUsableModule(M))
  1633. return true;
  1634. // For a query which is not module-private, that means it is in our visible
  1635. // module set.
  1636. if (!ModulePrivate && VisibleModules.isVisible(M))
  1637. return true;
  1638. // Otherwise, it might be visible by virtue of the query being within a
  1639. // template instantiation or similar that is permitted to look inside M.
  1640. // Find the extra places where we need to look.
  1641. const auto &LookupModules = getLookupModules();
  1642. if (LookupModules.empty())
  1643. return false;
  1644. // If our lookup set contains the module, it's visible.
  1645. if (LookupModules.count(M))
  1646. return true;
  1647. // For a module-private query, that's everywhere we get to look.
  1648. if (ModulePrivate)
  1649. return false;
  1650. // Check whether M is transitively exported to an import of the lookup set.
  1651. return llvm::any_of(LookupModules, [&](const Module *LookupM) {
  1652. return LookupM->isModuleVisible(M);
  1653. });
  1654. }
  1655. // FIXME: Return false directly if we don't have an interface dependency on the
  1656. // translation unit containing D.
  1657. bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
  1658. assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
  1659. Module *DeclModule = SemaRef.getOwningModule(D);
  1660. assert(DeclModule && "hidden decl has no owning module");
  1661. // Entities in module map modules are reachable only if they're visible.
  1662. if (DeclModule->isModuleMapModule())
  1663. return false;
  1664. // If D comes from a module and SemaRef doesn't own a module, it implies D
  1665. // comes from another TU. In case SemaRef owns a module, we could judge if D
  1666. // comes from another TU by comparing the module unit.
  1667. if (SemaRef.isModuleUnitOfCurrentTU(DeclModule))
  1668. return true;
  1669. // [module.reach]/p3:
  1670. // A declaration D is reachable from a point P if:
  1671. // ...
  1672. // - D is not discarded ([module.global.frag]), appears in a translation unit
  1673. // that is reachable from P, and does not appear within a private module
  1674. // fragment.
  1675. //
  1676. // A declaration that's discarded in the GMF should be module-private.
  1677. if (D->isModulePrivate())
  1678. return false;
  1679. // [module.reach]/p1
  1680. // A translation unit U is necessarily reachable from a point P if U is a
  1681. // module interface unit on which the translation unit containing P has an
  1682. // interface dependency, or the translation unit containing P imports U, in
  1683. // either case prior to P ([module.import]).
  1684. //
  1685. // [module.import]/p10
  1686. // A translation unit has an interface dependency on a translation unit U if
  1687. // it contains a declaration (possibly a module-declaration) that imports U
  1688. // or if it has an interface dependency on a translation unit that has an
  1689. // interface dependency on U.
  1690. //
  1691. // So we could conclude the module unit U is necessarily reachable if:
  1692. // (1) The module unit U is module interface unit.
  1693. // (2) The current unit has an interface dependency on the module unit U.
  1694. //
  1695. // Here we only check for the first condition. Since we couldn't see
  1696. // DeclModule if it isn't (transitively) imported.
  1697. if (DeclModule->getTopLevelModule()->isModuleInterfaceUnit())
  1698. return true;
  1699. // [module.reach]/p2
  1700. // Additional translation units on
  1701. // which the point within the program has an interface dependency may be
  1702. // considered reachable, but it is unspecified which are and under what
  1703. // circumstances.
  1704. //
  1705. // The decision here is to treat all additional tranditional units as
  1706. // unreachable.
  1707. return false;
  1708. }
  1709. bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {
  1710. return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);
  1711. }
  1712. bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
  1713. // FIXME: If there are both visible and hidden declarations, we need to take
  1714. // into account whether redeclaration is possible. Example:
  1715. //
  1716. // Non-imported module:
  1717. // int f(T); // #1
  1718. // Some TU:
  1719. // static int f(U); // #2, not a redeclaration of #1
  1720. // int f(T); // #3, finds both, should link with #1 if T != U, but
  1721. // // with #2 if T == U; neither should be ambiguous.
  1722. for (auto *D : R) {
  1723. if (isVisible(D))
  1724. return true;
  1725. assert(D->isExternallyDeclarable() &&
  1726. "should not have hidden, non-externally-declarable result here");
  1727. }
  1728. // This function is called once "New" is essentially complete, but before a
  1729. // previous declaration is attached. We can't query the linkage of "New" in
  1730. // general, because attaching the previous declaration can change the
  1731. // linkage of New to match the previous declaration.
  1732. //
  1733. // However, because we've just determined that there is no *visible* prior
  1734. // declaration, we can compute the linkage here. There are two possibilities:
  1735. //
  1736. // * This is not a redeclaration; it's safe to compute the linkage now.
  1737. //
  1738. // * This is a redeclaration of a prior declaration that is externally
  1739. // redeclarable. In that case, the linkage of the declaration is not
  1740. // changed by attaching the prior declaration, because both are externally
  1741. // declarable (and thus ExternalLinkage or VisibleNoLinkage).
  1742. //
  1743. // FIXME: This is subtle and fragile.
  1744. return New->isExternallyDeclarable();
  1745. }
  1746. /// Retrieve the visible declaration corresponding to D, if any.
  1747. ///
  1748. /// This routine determines whether the declaration D is visible in the current
  1749. /// module, with the current imports. If not, it checks whether any
  1750. /// redeclaration of D is visible, and if so, returns that declaration.
  1751. ///
  1752. /// \returns D, or a visible previous declaration of D, whichever is more recent
  1753. /// and visible. If no declaration of D is visible, returns null.
  1754. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
  1755. unsigned IDNS) {
  1756. assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");
  1757. for (auto *RD : D->redecls()) {
  1758. // Don't bother with extra checks if we already know this one isn't visible.
  1759. if (RD == D)
  1760. continue;
  1761. auto ND = cast<NamedDecl>(RD);
  1762. // FIXME: This is wrong in the case where the previous declaration is not
  1763. // visible in the same scope as D. This needs to be done much more
  1764. // carefully.
  1765. if (ND->isInIdentifierNamespace(IDNS) &&
  1766. LookupResult::isAvailableForLookup(SemaRef, ND))
  1767. return ND;
  1768. }
  1769. return nullptr;
  1770. }
  1771. bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
  1772. llvm::SmallVectorImpl<Module *> *Modules) {
  1773. assert(!isVisible(D) && "not in slow case");
  1774. return hasAcceptableDeclarationImpl(
  1775. *this, D, Modules, [](const NamedDecl *) { return true; },
  1776. Sema::AcceptableKind::Visible);
  1777. }
  1778. bool Sema::hasReachableDeclarationSlow(
  1779. const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
  1780. assert(!isReachable(D) && "not in slow case");
  1781. return hasAcceptableDeclarationImpl(
  1782. *this, D, Modules, [](const NamedDecl *) { return true; },
  1783. Sema::AcceptableKind::Reachable);
  1784. }
  1785. NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
  1786. if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
  1787. // Namespaces are a bit of a special case: we expect there to be a lot of
  1788. // redeclarations of some namespaces, all declarations of a namespace are
  1789. // essentially interchangeable, all declarations are found by name lookup
  1790. // if any is, and namespaces are never looked up during template
  1791. // instantiation. So we benefit from caching the check in this case, and
  1792. // it is correct to do so.
  1793. auto *Key = ND->getCanonicalDecl();
  1794. if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
  1795. return Acceptable;
  1796. auto *Acceptable = isVisible(getSema(), Key)
  1797. ? Key
  1798. : findAcceptableDecl(getSema(), Key, IDNS);
  1799. if (Acceptable)
  1800. getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
  1801. return Acceptable;
  1802. }
  1803. return findAcceptableDecl(getSema(), D, IDNS);
  1804. }
  1805. bool LookupResult::isVisible(Sema &SemaRef, NamedDecl *D) {
  1806. // If this declaration is already visible, return it directly.
  1807. if (D->isUnconditionallyVisible())
  1808. return true;
  1809. // During template instantiation, we can refer to hidden declarations, if
  1810. // they were visible in any module along the path of instantiation.
  1811. return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);
  1812. }
  1813. bool LookupResult::isReachable(Sema &SemaRef, NamedDecl *D) {
  1814. if (D->isUnconditionallyVisible())
  1815. return true;
  1816. return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);
  1817. }
  1818. bool LookupResult::isAvailableForLookup(Sema &SemaRef, NamedDecl *ND) {
  1819. // We should check the visibility at the callsite already.
  1820. if (isVisible(SemaRef, ND))
  1821. return true;
  1822. // Deduction guide lives in namespace scope generally, but it is just a
  1823. // hint to the compilers. What we actually lookup for is the generated member
  1824. // of the corresponding template. So it is sufficient to check the
  1825. // reachability of the template decl.
  1826. if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())
  1827. return SemaRef.hasReachableDefinition(DeductionGuide);
  1828. // FIXME: The lookup for allocation function is a standalone process.
  1829. // (We can find the logics in Sema::FindAllocationFunctions)
  1830. //
  1831. // Such structure makes it a problem when we instantiate a template
  1832. // declaration using placement allocation function if the placement
  1833. // allocation function is invisible.
  1834. // (See https://github.com/llvm/llvm-project/issues/59601)
  1835. //
  1836. // Here we workaround it by making the placement allocation functions
  1837. // always acceptable. The downside is that we can't diagnose the direct
  1838. // use of the invisible placement allocation functions. (Although such uses
  1839. // should be rare).
  1840. if (auto *FD = dyn_cast<FunctionDecl>(ND);
  1841. FD && FD->isReservedGlobalPlacementOperator())
  1842. return true;
  1843. auto *DC = ND->getDeclContext();
  1844. // If ND is not visible and it is at namespace scope, it shouldn't be found
  1845. // by name lookup.
  1846. if (DC->isFileContext())
  1847. return false;
  1848. // [module.interface]p7
  1849. // Class and enumeration member names can be found by name lookup in any
  1850. // context in which a definition of the type is reachable.
  1851. //
  1852. // FIXME: The current implementation didn't consider about scope. For example,
  1853. // ```
  1854. // // m.cppm
  1855. // export module m;
  1856. // enum E1 { e1 };
  1857. // // Use.cpp
  1858. // import m;
  1859. // void test() {
  1860. // auto a = E1::e1; // Error as expected.
  1861. // auto b = e1; // Should be error. namespace-scope name e1 is not visible
  1862. // }
  1863. // ```
  1864. // For the above example, the current implementation would emit error for `a`
  1865. // correctly. However, the implementation wouldn't diagnose about `b` now.
  1866. // Since we only check the reachability for the parent only.
  1867. // See clang/test/CXX/module/module.interface/p7.cpp for example.
  1868. if (auto *TD = dyn_cast<TagDecl>(DC))
  1869. return SemaRef.hasReachableDefinition(TD);
  1870. return false;
  1871. }
  1872. /// Perform unqualified name lookup starting from a given
  1873. /// scope.
  1874. ///
  1875. /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
  1876. /// used to find names within the current scope. For example, 'x' in
  1877. /// @code
  1878. /// int x;
  1879. /// int f() {
  1880. /// return x; // unqualified name look finds 'x' in the global scope
  1881. /// }
  1882. /// @endcode
  1883. ///
  1884. /// Different lookup criteria can find different names. For example, a
  1885. /// particular scope can have both a struct and a function of the same
  1886. /// name, and each can be found by certain lookup criteria. For more
  1887. /// information about lookup criteria, see the documentation for the
  1888. /// class LookupCriteria.
  1889. ///
  1890. /// @param S The scope from which unqualified name lookup will
  1891. /// begin. If the lookup criteria permits, name lookup may also search
  1892. /// in the parent scopes.
  1893. ///
  1894. /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
  1895. /// look up and the lookup kind), and is updated with the results of lookup
  1896. /// including zero or more declarations and possibly additional information
  1897. /// used to diagnose ambiguities.
  1898. ///
  1899. /// @returns \c true if lookup succeeded and false otherwise.
  1900. bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
  1901. bool ForceNoCPlusPlus) {
  1902. DeclarationName Name = R.getLookupName();
  1903. if (!Name) return false;
  1904. LookupNameKind NameKind = R.getLookupKind();
  1905. if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
  1906. // Unqualified name lookup in C/Objective-C is purely lexical, so
  1907. // search in the declarations attached to the name.
  1908. if (NameKind == Sema::LookupRedeclarationWithLinkage) {
  1909. // Find the nearest non-transparent declaration scope.
  1910. while (!(S->getFlags() & Scope::DeclScope) ||
  1911. (S->getEntity() && S->getEntity()->isTransparentContext()))
  1912. S = S->getParent();
  1913. }
  1914. // When performing a scope lookup, we want to find local extern decls.
  1915. FindLocalExternScope FindLocals(R);
  1916. // Scan up the scope chain looking for a decl that matches this
  1917. // identifier that is in the appropriate namespace. This search
  1918. // should not take long, as shadowing of names is uncommon, and
  1919. // deep shadowing is extremely uncommon.
  1920. bool LeftStartingScope = false;
  1921. for (IdentifierResolver::iterator I = IdResolver.begin(Name),
  1922. IEnd = IdResolver.end();
  1923. I != IEnd; ++I)
  1924. if (NamedDecl *D = R.getAcceptableDecl(*I)) {
  1925. if (NameKind == LookupRedeclarationWithLinkage) {
  1926. // Determine whether this (or a previous) declaration is
  1927. // out-of-scope.
  1928. if (!LeftStartingScope && !S->isDeclScope(*I))
  1929. LeftStartingScope = true;
  1930. // If we found something outside of our starting scope that
  1931. // does not have linkage, skip it.
  1932. if (LeftStartingScope && !((*I)->hasLinkage())) {
  1933. R.setShadowed();
  1934. continue;
  1935. }
  1936. }
  1937. else if (NameKind == LookupObjCImplicitSelfParam &&
  1938. !isa<ImplicitParamDecl>(*I))
  1939. continue;
  1940. R.addDecl(D);
  1941. // Check whether there are any other declarations with the same name
  1942. // and in the same scope.
  1943. if (I != IEnd) {
  1944. // Find the scope in which this declaration was declared (if it
  1945. // actually exists in a Scope).
  1946. while (S && !S->isDeclScope(D))
  1947. S = S->getParent();
  1948. // If the scope containing the declaration is the translation unit,
  1949. // then we'll need to perform our checks based on the matching
  1950. // DeclContexts rather than matching scopes.
  1951. if (S && isNamespaceOrTranslationUnitScope(S))
  1952. S = nullptr;
  1953. // Compute the DeclContext, if we need it.
  1954. DeclContext *DC = nullptr;
  1955. if (!S)
  1956. DC = (*I)->getDeclContext()->getRedeclContext();
  1957. IdentifierResolver::iterator LastI = I;
  1958. for (++LastI; LastI != IEnd; ++LastI) {
  1959. if (S) {
  1960. // Match based on scope.
  1961. if (!S->isDeclScope(*LastI))
  1962. break;
  1963. } else {
  1964. // Match based on DeclContext.
  1965. DeclContext *LastDC
  1966. = (*LastI)->getDeclContext()->getRedeclContext();
  1967. if (!LastDC->Equals(DC))
  1968. break;
  1969. }
  1970. // If the declaration is in the right namespace and visible, add it.
  1971. if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
  1972. R.addDecl(LastD);
  1973. }
  1974. R.resolveKind();
  1975. }
  1976. return true;
  1977. }
  1978. } else {
  1979. // Perform C++ unqualified name lookup.
  1980. if (CppLookupName(R, S))
  1981. return true;
  1982. }
  1983. // If we didn't find a use of this identifier, and if the identifier
  1984. // corresponds to a compiler builtin, create the decl object for the builtin
  1985. // now, injecting it into translation unit scope, and return it.
  1986. if (AllowBuiltinCreation && LookupBuiltin(R))
  1987. return true;
  1988. // If we didn't find a use of this identifier, the ExternalSource
  1989. // may be able to handle the situation.
  1990. // Note: some lookup failures are expected!
  1991. // See e.g. R.isForRedeclaration().
  1992. return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
  1993. }
  1994. /// Perform qualified name lookup in the namespaces nominated by
  1995. /// using directives by the given context.
  1996. ///
  1997. /// C++98 [namespace.qual]p2:
  1998. /// Given X::m (where X is a user-declared namespace), or given \::m
  1999. /// (where X is the global namespace), let S be the set of all
  2000. /// declarations of m in X and in the transitive closure of all
  2001. /// namespaces nominated by using-directives in X and its used
  2002. /// namespaces, except that using-directives are ignored in any
  2003. /// namespace, including X, directly containing one or more
  2004. /// declarations of m. No namespace is searched more than once in
  2005. /// the lookup of a name. If S is the empty set, the program is
  2006. /// ill-formed. Otherwise, if S has exactly one member, or if the
  2007. /// context of the reference is a using-declaration
  2008. /// (namespace.udecl), S is the required set of declarations of
  2009. /// m. Otherwise if the use of m is not one that allows a unique
  2010. /// declaration to be chosen from S, the program is ill-formed.
  2011. ///
  2012. /// C++98 [namespace.qual]p5:
  2013. /// During the lookup of a qualified namespace member name, if the
  2014. /// lookup finds more than one declaration of the member, and if one
  2015. /// declaration introduces a class name or enumeration name and the
  2016. /// other declarations either introduce the same object, the same
  2017. /// enumerator or a set of functions, the non-type name hides the
  2018. /// class or enumeration name if and only if the declarations are
  2019. /// from the same namespace; otherwise (the declarations are from
  2020. /// different namespaces), the program is ill-formed.
  2021. static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
  2022. DeclContext *StartDC) {
  2023. assert(StartDC->isFileContext() && "start context is not a file context");
  2024. // We have not yet looked into these namespaces, much less added
  2025. // their "using-children" to the queue.
  2026. SmallVector<NamespaceDecl*, 8> Queue;
  2027. // We have at least added all these contexts to the queue.
  2028. llvm::SmallPtrSet<DeclContext*, 8> Visited;
  2029. Visited.insert(StartDC);
  2030. // We have already looked into the initial namespace; seed the queue
  2031. // with its using-children.
  2032. for (auto *I : StartDC->using_directives()) {
  2033. NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
  2034. if (S.isVisible(I) && Visited.insert(ND).second)
  2035. Queue.push_back(ND);
  2036. }
  2037. // The easiest way to implement the restriction in [namespace.qual]p5
  2038. // is to check whether any of the individual results found a tag
  2039. // and, if so, to declare an ambiguity if the final result is not
  2040. // a tag.
  2041. bool FoundTag = false;
  2042. bool FoundNonTag = false;
  2043. LookupResult LocalR(LookupResult::Temporary, R);
  2044. bool Found = false;
  2045. while (!Queue.empty()) {
  2046. NamespaceDecl *ND = Queue.pop_back_val();
  2047. // We go through some convolutions here to avoid copying results
  2048. // between LookupResults.
  2049. bool UseLocal = !R.empty();
  2050. LookupResult &DirectR = UseLocal ? LocalR : R;
  2051. bool FoundDirect = LookupDirect(S, DirectR, ND);
  2052. if (FoundDirect) {
  2053. // First do any local hiding.
  2054. DirectR.resolveKind();
  2055. // If the local result is a tag, remember that.
  2056. if (DirectR.isSingleTagDecl())
  2057. FoundTag = true;
  2058. else
  2059. FoundNonTag = true;
  2060. // Append the local results to the total results if necessary.
  2061. if (UseLocal) {
  2062. R.addAllDecls(LocalR);
  2063. LocalR.clear();
  2064. }
  2065. }
  2066. // If we find names in this namespace, ignore its using directives.
  2067. if (FoundDirect) {
  2068. Found = true;
  2069. continue;
  2070. }
  2071. for (auto *I : ND->using_directives()) {
  2072. NamespaceDecl *Nom = I->getNominatedNamespace();
  2073. if (S.isVisible(I) && Visited.insert(Nom).second)
  2074. Queue.push_back(Nom);
  2075. }
  2076. }
  2077. if (Found) {
  2078. if (FoundTag && FoundNonTag)
  2079. R.setAmbiguousQualifiedTagHiding();
  2080. else
  2081. R.resolveKind();
  2082. }
  2083. return Found;
  2084. }
  2085. /// Perform qualified name lookup into a given context.
  2086. ///
  2087. /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
  2088. /// names when the context of those names is explicit specified, e.g.,
  2089. /// "std::vector" or "x->member", or as part of unqualified name lookup.
  2090. ///
  2091. /// Different lookup criteria can find different names. For example, a
  2092. /// particular scope can have both a struct and a function of the same
  2093. /// name, and each can be found by certain lookup criteria. For more
  2094. /// information about lookup criteria, see the documentation for the
  2095. /// class LookupCriteria.
  2096. ///
  2097. /// \param R captures both the lookup criteria and any lookup results found.
  2098. ///
  2099. /// \param LookupCtx The context in which qualified name lookup will
  2100. /// search. If the lookup criteria permits, name lookup may also search
  2101. /// in the parent contexts or (for C++ classes) base classes.
  2102. ///
  2103. /// \param InUnqualifiedLookup true if this is qualified name lookup that
  2104. /// occurs as part of unqualified name lookup.
  2105. ///
  2106. /// \returns true if lookup succeeded, false if it failed.
  2107. bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
  2108. bool InUnqualifiedLookup) {
  2109. assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
  2110. if (!R.getLookupName())
  2111. return false;
  2112. // Make sure that the declaration context is complete.
  2113. assert((!isa<TagDecl>(LookupCtx) ||
  2114. LookupCtx->isDependentContext() ||
  2115. cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
  2116. cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
  2117. "Declaration context must already be complete!");
  2118. struct QualifiedLookupInScope {
  2119. bool oldVal;
  2120. DeclContext *Context;
  2121. // Set flag in DeclContext informing debugger that we're looking for qualified name
  2122. QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
  2123. oldVal = ctx->setUseQualifiedLookup();
  2124. }
  2125. ~QualifiedLookupInScope() {
  2126. Context->setUseQualifiedLookup(oldVal);
  2127. }
  2128. } QL(LookupCtx);
  2129. if (LookupDirect(*this, R, LookupCtx)) {
  2130. R.resolveKind();
  2131. if (isa<CXXRecordDecl>(LookupCtx))
  2132. R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
  2133. return true;
  2134. }
  2135. // Don't descend into implied contexts for redeclarations.
  2136. // C++98 [namespace.qual]p6:
  2137. // In a declaration for a namespace member in which the
  2138. // declarator-id is a qualified-id, given that the qualified-id
  2139. // for the namespace member has the form
  2140. // nested-name-specifier unqualified-id
  2141. // the unqualified-id shall name a member of the namespace
  2142. // designated by the nested-name-specifier.
  2143. // See also [class.mfct]p5 and [class.static.data]p2.
  2144. if (R.isForRedeclaration())
  2145. return false;
  2146. // If this is a namespace, look it up in the implied namespaces.
  2147. if (LookupCtx->isFileContext())
  2148. return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
  2149. // If this isn't a C++ class, we aren't allowed to look into base
  2150. // classes, we're done.
  2151. CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
  2152. if (!LookupRec || !LookupRec->getDefinition())
  2153. return false;
  2154. // We're done for lookups that can never succeed for C++ classes.
  2155. if (R.getLookupKind() == LookupOperatorName ||
  2156. R.getLookupKind() == LookupNamespaceName ||
  2157. R.getLookupKind() == LookupObjCProtocolName ||
  2158. R.getLookupKind() == LookupLabel)
  2159. return false;
  2160. // If we're performing qualified name lookup into a dependent class,
  2161. // then we are actually looking into a current instantiation. If we have any
  2162. // dependent base classes, then we either have to delay lookup until
  2163. // template instantiation time (at which point all bases will be available)
  2164. // or we have to fail.
  2165. if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
  2166. LookupRec->hasAnyDependentBases()) {
  2167. R.setNotFoundInCurrentInstantiation();
  2168. return false;
  2169. }
  2170. // Perform lookup into our base classes.
  2171. DeclarationName Name = R.getLookupName();
  2172. unsigned IDNS = R.getIdentifierNamespace();
  2173. // Look for this member in our base classes.
  2174. auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
  2175. CXXBasePath &Path) -> bool {
  2176. CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
  2177. // Drop leading non-matching lookup results from the declaration list so
  2178. // we don't need to consider them again below.
  2179. for (Path.Decls = BaseRecord->lookup(Name).begin();
  2180. Path.Decls != Path.Decls.end(); ++Path.Decls) {
  2181. if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
  2182. return true;
  2183. }
  2184. return false;
  2185. };
  2186. CXXBasePaths Paths;
  2187. Paths.setOrigin(LookupRec);
  2188. if (!LookupRec->lookupInBases(BaseCallback, Paths))
  2189. return false;
  2190. R.setNamingClass(LookupRec);
  2191. // C++ [class.member.lookup]p2:
  2192. // [...] If the resulting set of declarations are not all from
  2193. // sub-objects of the same type, or the set has a nonstatic member
  2194. // and includes members from distinct sub-objects, there is an
  2195. // ambiguity and the program is ill-formed. Otherwise that set is
  2196. // the result of the lookup.
  2197. QualType SubobjectType;
  2198. int SubobjectNumber = 0;
  2199. AccessSpecifier SubobjectAccess = AS_none;
  2200. // Check whether the given lookup result contains only static members.
  2201. auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
  2202. for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
  2203. if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
  2204. return false;
  2205. return true;
  2206. };
  2207. bool TemplateNameLookup = R.isTemplateNameLookup();
  2208. // Determine whether two sets of members contain the same members, as
  2209. // required by C++ [class.member.lookup]p6.
  2210. auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
  2211. DeclContext::lookup_iterator B) {
  2212. using Iterator = DeclContextLookupResult::iterator;
  2213. using Result = const void *;
  2214. auto Next = [&](Iterator &It, Iterator End) -> Result {
  2215. while (It != End) {
  2216. NamedDecl *ND = *It++;
  2217. if (!ND->isInIdentifierNamespace(IDNS))
  2218. continue;
  2219. // C++ [temp.local]p3:
  2220. // A lookup that finds an injected-class-name (10.2) can result in
  2221. // an ambiguity in certain cases (for example, if it is found in
  2222. // more than one base class). If all of the injected-class-names
  2223. // that are found refer to specializations of the same class
  2224. // template, and if the name is used as a template-name, the
  2225. // reference refers to the class template itself and not a
  2226. // specialization thereof, and is not ambiguous.
  2227. if (TemplateNameLookup)
  2228. if (auto *TD = getAsTemplateNameDecl(ND))
  2229. ND = TD;
  2230. // C++ [class.member.lookup]p3:
  2231. // type declarations (including injected-class-names) are replaced by
  2232. // the types they designate
  2233. if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {
  2234. QualType T = Context.getTypeDeclType(TD);
  2235. return T.getCanonicalType().getAsOpaquePtr();
  2236. }
  2237. return ND->getUnderlyingDecl()->getCanonicalDecl();
  2238. }
  2239. return nullptr;
  2240. };
  2241. // We'll often find the declarations are in the same order. Handle this
  2242. // case (and the special case of only one declaration) efficiently.
  2243. Iterator AIt = A, BIt = B, AEnd, BEnd;
  2244. while (true) {
  2245. Result AResult = Next(AIt, AEnd);
  2246. Result BResult = Next(BIt, BEnd);
  2247. if (!AResult && !BResult)
  2248. return true;
  2249. if (!AResult || !BResult)
  2250. return false;
  2251. if (AResult != BResult) {
  2252. // Found a mismatch; carefully check both lists, accounting for the
  2253. // possibility of declarations appearing more than once.
  2254. llvm::SmallDenseMap<Result, bool, 32> AResults;
  2255. for (; AResult; AResult = Next(AIt, AEnd))
  2256. AResults.insert({AResult, /*FoundInB*/false});
  2257. unsigned Found = 0;
  2258. for (; BResult; BResult = Next(BIt, BEnd)) {
  2259. auto It = AResults.find(BResult);
  2260. if (It == AResults.end())
  2261. return false;
  2262. if (!It->second) {
  2263. It->second = true;
  2264. ++Found;
  2265. }
  2266. }
  2267. return AResults.size() == Found;
  2268. }
  2269. }
  2270. };
  2271. for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
  2272. Path != PathEnd; ++Path) {
  2273. const CXXBasePathElement &PathElement = Path->back();
  2274. // Pick the best (i.e. most permissive i.e. numerically lowest) access
  2275. // across all paths.
  2276. SubobjectAccess = std::min(SubobjectAccess, Path->Access);
  2277. // Determine whether we're looking at a distinct sub-object or not.
  2278. if (SubobjectType.isNull()) {
  2279. // This is the first subobject we've looked at. Record its type.
  2280. SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
  2281. SubobjectNumber = PathElement.SubobjectNumber;
  2282. continue;
  2283. }
  2284. if (SubobjectType !=
  2285. Context.getCanonicalType(PathElement.Base->getType())) {
  2286. // We found members of the given name in two subobjects of
  2287. // different types. If the declaration sets aren't the same, this
  2288. // lookup is ambiguous.
  2289. //
  2290. // FIXME: The language rule says that this applies irrespective of
  2291. // whether the sets contain only static members.
  2292. if (HasOnlyStaticMembers(Path->Decls) &&
  2293. HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
  2294. continue;
  2295. R.setAmbiguousBaseSubobjectTypes(Paths);
  2296. return true;
  2297. }
  2298. // FIXME: This language rule no longer exists. Checking for ambiguous base
  2299. // subobjects should be done as part of formation of a class member access
  2300. // expression (when converting the object parameter to the member's type).
  2301. if (SubobjectNumber != PathElement.SubobjectNumber) {
  2302. // We have a different subobject of the same type.
  2303. // C++ [class.member.lookup]p5:
  2304. // A static member, a nested type or an enumerator defined in
  2305. // a base class T can unambiguously be found even if an object
  2306. // has more than one base class subobject of type T.
  2307. if (HasOnlyStaticMembers(Path->Decls))
  2308. continue;
  2309. // We have found a nonstatic member name in multiple, distinct
  2310. // subobjects. Name lookup is ambiguous.
  2311. R.setAmbiguousBaseSubobjects(Paths);
  2312. return true;
  2313. }
  2314. }
  2315. // Lookup in a base class succeeded; return these results.
  2316. for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
  2317. I != E; ++I) {
  2318. AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
  2319. (*I)->getAccess());
  2320. if (NamedDecl *ND = R.getAcceptableDecl(*I))
  2321. R.addDecl(ND, AS);
  2322. }
  2323. R.resolveKind();
  2324. return true;
  2325. }
  2326. /// Performs qualified name lookup or special type of lookup for
  2327. /// "__super::" scope specifier.
  2328. ///
  2329. /// This routine is a convenience overload meant to be called from contexts
  2330. /// that need to perform a qualified name lookup with an optional C++ scope
  2331. /// specifier that might require special kind of lookup.
  2332. ///
  2333. /// \param R captures both the lookup criteria and any lookup results found.
  2334. ///
  2335. /// \param LookupCtx The context in which qualified name lookup will
  2336. /// search.
  2337. ///
  2338. /// \param SS An optional C++ scope-specifier.
  2339. ///
  2340. /// \returns true if lookup succeeded, false if it failed.
  2341. bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
  2342. CXXScopeSpec &SS) {
  2343. auto *NNS = SS.getScopeRep();
  2344. if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
  2345. return LookupInSuper(R, NNS->getAsRecordDecl());
  2346. else
  2347. return LookupQualifiedName(R, LookupCtx);
  2348. }
  2349. /// Performs name lookup for a name that was parsed in the
  2350. /// source code, and may contain a C++ scope specifier.
  2351. ///
  2352. /// This routine is a convenience routine meant to be called from
  2353. /// contexts that receive a name and an optional C++ scope specifier
  2354. /// (e.g., "N::M::x"). It will then perform either qualified or
  2355. /// unqualified name lookup (with LookupQualifiedName or LookupName,
  2356. /// respectively) on the given name and return those results. It will
  2357. /// perform a special type of lookup for "__super::" scope specifier.
  2358. ///
  2359. /// @param S The scope from which unqualified name lookup will
  2360. /// begin.
  2361. ///
  2362. /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
  2363. ///
  2364. /// @param EnteringContext Indicates whether we are going to enter the
  2365. /// context of the scope-specifier SS (if present).
  2366. ///
  2367. /// @returns True if any decls were found (but possibly ambiguous)
  2368. bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
  2369. bool AllowBuiltinCreation, bool EnteringContext) {
  2370. if (SS && SS->isInvalid()) {
  2371. // When the scope specifier is invalid, don't even look for
  2372. // anything.
  2373. return false;
  2374. }
  2375. if (SS && SS->isSet()) {
  2376. NestedNameSpecifier *NNS = SS->getScopeRep();
  2377. if (NNS->getKind() == NestedNameSpecifier::Super)
  2378. return LookupInSuper(R, NNS->getAsRecordDecl());
  2379. if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
  2380. // We have resolved the scope specifier to a particular declaration
  2381. // contex, and will perform name lookup in that context.
  2382. if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
  2383. return false;
  2384. R.setContextRange(SS->getRange());
  2385. return LookupQualifiedName(R, DC);
  2386. }
  2387. // We could not resolve the scope specified to a specific declaration
  2388. // context, which means that SS refers to an unknown specialization.
  2389. // Name lookup can't find anything in this case.
  2390. R.setNotFoundInCurrentInstantiation();
  2391. R.setContextRange(SS->getRange());
  2392. return false;
  2393. }
  2394. // Perform unqualified name lookup starting in the given scope.
  2395. return LookupName(R, S, AllowBuiltinCreation);
  2396. }
  2397. /// Perform qualified name lookup into all base classes of the given
  2398. /// class.
  2399. ///
  2400. /// \param R captures both the lookup criteria and any lookup results found.
  2401. ///
  2402. /// \param Class The context in which qualified name lookup will
  2403. /// search. Name lookup will search in all base classes merging the results.
  2404. ///
  2405. /// @returns True if any decls were found (but possibly ambiguous)
  2406. bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
  2407. // The access-control rules we use here are essentially the rules for
  2408. // doing a lookup in Class that just magically skipped the direct
  2409. // members of Class itself. That is, the naming class is Class, and the
  2410. // access includes the access of the base.
  2411. for (const auto &BaseSpec : Class->bases()) {
  2412. CXXRecordDecl *RD = cast<CXXRecordDecl>(
  2413. BaseSpec.getType()->castAs<RecordType>()->getDecl());
  2414. LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
  2415. Result.setBaseObjectType(Context.getRecordType(Class));
  2416. LookupQualifiedName(Result, RD);
  2417. // Copy the lookup results into the target, merging the base's access into
  2418. // the path access.
  2419. for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
  2420. R.addDecl(I.getDecl(),
  2421. CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
  2422. I.getAccess()));
  2423. }
  2424. Result.suppressDiagnostics();
  2425. }
  2426. R.resolveKind();
  2427. R.setNamingClass(Class);
  2428. return !R.empty();
  2429. }
  2430. /// Produce a diagnostic describing the ambiguity that resulted
  2431. /// from name lookup.
  2432. ///
  2433. /// \param Result The result of the ambiguous lookup to be diagnosed.
  2434. void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
  2435. assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
  2436. DeclarationName Name = Result.getLookupName();
  2437. SourceLocation NameLoc = Result.getNameLoc();
  2438. SourceRange LookupRange = Result.getContextRange();
  2439. switch (Result.getAmbiguityKind()) {
  2440. case LookupResult::AmbiguousBaseSubobjects: {
  2441. CXXBasePaths *Paths = Result.getBasePaths();
  2442. QualType SubobjectType = Paths->front().back().Base->getType();
  2443. Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
  2444. << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
  2445. << LookupRange;
  2446. DeclContext::lookup_iterator Found = Paths->front().Decls;
  2447. while (isa<CXXMethodDecl>(*Found) &&
  2448. cast<CXXMethodDecl>(*Found)->isStatic())
  2449. ++Found;
  2450. Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
  2451. break;
  2452. }
  2453. case LookupResult::AmbiguousBaseSubobjectTypes: {
  2454. Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
  2455. << Name << LookupRange;
  2456. CXXBasePaths *Paths = Result.getBasePaths();
  2457. std::set<const NamedDecl *> DeclsPrinted;
  2458. for (CXXBasePaths::paths_iterator Path = Paths->begin(),
  2459. PathEnd = Paths->end();
  2460. Path != PathEnd; ++Path) {
  2461. const NamedDecl *D = *Path->Decls;
  2462. if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
  2463. continue;
  2464. if (DeclsPrinted.insert(D).second) {
  2465. if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
  2466. Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
  2467. << TD->getUnderlyingType();
  2468. else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
  2469. Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
  2470. << Context.getTypeDeclType(TD);
  2471. else
  2472. Diag(D->getLocation(), diag::note_ambiguous_member_found);
  2473. }
  2474. }
  2475. break;
  2476. }
  2477. case LookupResult::AmbiguousTagHiding: {
  2478. Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
  2479. llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
  2480. for (auto *D : Result)
  2481. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  2482. TagDecls.insert(TD);
  2483. Diag(TD->getLocation(), diag::note_hidden_tag);
  2484. }
  2485. for (auto *D : Result)
  2486. if (!isa<TagDecl>(D))
  2487. Diag(D->getLocation(), diag::note_hiding_object);
  2488. // For recovery purposes, go ahead and implement the hiding.
  2489. LookupResult::Filter F = Result.makeFilter();
  2490. while (F.hasNext()) {
  2491. if (TagDecls.count(F.next()))
  2492. F.erase();
  2493. }
  2494. F.done();
  2495. break;
  2496. }
  2497. case LookupResult::AmbiguousReference: {
  2498. Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
  2499. for (auto *D : Result)
  2500. Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
  2501. break;
  2502. }
  2503. }
  2504. }
  2505. namespace {
  2506. struct AssociatedLookup {
  2507. AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
  2508. Sema::AssociatedNamespaceSet &Namespaces,
  2509. Sema::AssociatedClassSet &Classes)
  2510. : S(S), Namespaces(Namespaces), Classes(Classes),
  2511. InstantiationLoc(InstantiationLoc) {
  2512. }
  2513. bool addClassTransitive(CXXRecordDecl *RD) {
  2514. Classes.insert(RD);
  2515. return ClassesTransitive.insert(RD);
  2516. }
  2517. Sema &S;
  2518. Sema::AssociatedNamespaceSet &Namespaces;
  2519. Sema::AssociatedClassSet &Classes;
  2520. SourceLocation InstantiationLoc;
  2521. private:
  2522. Sema::AssociatedClassSet ClassesTransitive;
  2523. };
  2524. } // end anonymous namespace
  2525. static void
  2526. addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
  2527. // Given the declaration context \param Ctx of a class, class template or
  2528. // enumeration, add the associated namespaces to \param Namespaces as described
  2529. // in [basic.lookup.argdep]p2.
  2530. static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
  2531. DeclContext *Ctx) {
  2532. // The exact wording has been changed in C++14 as a result of
  2533. // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
  2534. // to all language versions since it is possible to return a local type
  2535. // from a lambda in C++11.
  2536. //
  2537. // C++14 [basic.lookup.argdep]p2:
  2538. // If T is a class type [...]. Its associated namespaces are the innermost
  2539. // enclosing namespaces of its associated classes. [...]
  2540. //
  2541. // If T is an enumeration type, its associated namespace is the innermost
  2542. // enclosing namespace of its declaration. [...]
  2543. // We additionally skip inline namespaces. The innermost non-inline namespace
  2544. // contains all names of all its nested inline namespaces anyway, so we can
  2545. // replace the entire inline namespace tree with its root.
  2546. while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
  2547. Ctx = Ctx->getParent();
  2548. Namespaces.insert(Ctx->getPrimaryContext());
  2549. }
  2550. // Add the associated classes and namespaces for argument-dependent
  2551. // lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
  2552. static void
  2553. addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
  2554. const TemplateArgument &Arg) {
  2555. // C++ [basic.lookup.argdep]p2, last bullet:
  2556. // -- [...] ;
  2557. switch (Arg.getKind()) {
  2558. case TemplateArgument::Null:
  2559. break;
  2560. case TemplateArgument::Type:
  2561. // [...] the namespaces and classes associated with the types of the
  2562. // template arguments provided for template type parameters (excluding
  2563. // template template parameters)
  2564. addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
  2565. break;
  2566. case TemplateArgument::Template:
  2567. case TemplateArgument::TemplateExpansion: {
  2568. // [...] the namespaces in which any template template arguments are
  2569. // defined; and the classes in which any member templates used as
  2570. // template template arguments are defined.
  2571. TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
  2572. if (ClassTemplateDecl *ClassTemplate
  2573. = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
  2574. DeclContext *Ctx = ClassTemplate->getDeclContext();
  2575. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  2576. Result.Classes.insert(EnclosingClass);
  2577. // Add the associated namespace for this class.
  2578. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  2579. }
  2580. break;
  2581. }
  2582. case TemplateArgument::Declaration:
  2583. case TemplateArgument::Integral:
  2584. case TemplateArgument::Expression:
  2585. case TemplateArgument::NullPtr:
  2586. // [Note: non-type template arguments do not contribute to the set of
  2587. // associated namespaces. ]
  2588. break;
  2589. case TemplateArgument::Pack:
  2590. for (const auto &P : Arg.pack_elements())
  2591. addAssociatedClassesAndNamespaces(Result, P);
  2592. break;
  2593. }
  2594. }
  2595. // Add the associated classes and namespaces for argument-dependent lookup
  2596. // with an argument of class type (C++ [basic.lookup.argdep]p2).
  2597. static void
  2598. addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
  2599. CXXRecordDecl *Class) {
  2600. // Just silently ignore anything whose name is __va_list_tag.
  2601. if (Class->getDeclName() == Result.S.VAListTagName)
  2602. return;
  2603. // C++ [basic.lookup.argdep]p2:
  2604. // [...]
  2605. // -- If T is a class type (including unions), its associated
  2606. // classes are: the class itself; the class of which it is a
  2607. // member, if any; and its direct and indirect base classes.
  2608. // Its associated namespaces are the innermost enclosing
  2609. // namespaces of its associated classes.
  2610. // Add the class of which it is a member, if any.
  2611. DeclContext *Ctx = Class->getDeclContext();
  2612. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  2613. Result.Classes.insert(EnclosingClass);
  2614. // Add the associated namespace for this class.
  2615. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  2616. // -- If T is a template-id, its associated namespaces and classes are
  2617. // the namespace in which the template is defined; for member
  2618. // templates, the member template's class; the namespaces and classes
  2619. // associated with the types of the template arguments provided for
  2620. // template type parameters (excluding template template parameters); the
  2621. // namespaces in which any template template arguments are defined; and
  2622. // the classes in which any member templates used as template template
  2623. // arguments are defined. [Note: non-type template arguments do not
  2624. // contribute to the set of associated namespaces. ]
  2625. if (ClassTemplateSpecializationDecl *Spec
  2626. = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
  2627. DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
  2628. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  2629. Result.Classes.insert(EnclosingClass);
  2630. // Add the associated namespace for this class.
  2631. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  2632. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  2633. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  2634. addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
  2635. }
  2636. // Add the class itself. If we've already transitively visited this class,
  2637. // we don't need to visit base classes.
  2638. if (!Result.addClassTransitive(Class))
  2639. return;
  2640. // Only recurse into base classes for complete types.
  2641. if (!Result.S.isCompleteType(Result.InstantiationLoc,
  2642. Result.S.Context.getRecordType(Class)))
  2643. return;
  2644. // Add direct and indirect base classes along with their associated
  2645. // namespaces.
  2646. SmallVector<CXXRecordDecl *, 32> Bases;
  2647. Bases.push_back(Class);
  2648. while (!Bases.empty()) {
  2649. // Pop this class off the stack.
  2650. Class = Bases.pop_back_val();
  2651. // Visit the base classes.
  2652. for (const auto &Base : Class->bases()) {
  2653. const RecordType *BaseType = Base.getType()->getAs<RecordType>();
  2654. // In dependent contexts, we do ADL twice, and the first time around,
  2655. // the base type might be a dependent TemplateSpecializationType, or a
  2656. // TemplateTypeParmType. If that happens, simply ignore it.
  2657. // FIXME: If we want to support export, we probably need to add the
  2658. // namespace of the template in a TemplateSpecializationType, or even
  2659. // the classes and namespaces of known non-dependent arguments.
  2660. if (!BaseType)
  2661. continue;
  2662. CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  2663. if (Result.addClassTransitive(BaseDecl)) {
  2664. // Find the associated namespace for this base class.
  2665. DeclContext *BaseCtx = BaseDecl->getDeclContext();
  2666. CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
  2667. // Make sure we visit the bases of this base class.
  2668. if (BaseDecl->bases_begin() != BaseDecl->bases_end())
  2669. Bases.push_back(BaseDecl);
  2670. }
  2671. }
  2672. }
  2673. }
  2674. // Add the associated classes and namespaces for
  2675. // argument-dependent lookup with an argument of type T
  2676. // (C++ [basic.lookup.koenig]p2).
  2677. static void
  2678. addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
  2679. // C++ [basic.lookup.koenig]p2:
  2680. //
  2681. // For each argument type T in the function call, there is a set
  2682. // of zero or more associated namespaces and a set of zero or more
  2683. // associated classes to be considered. The sets of namespaces and
  2684. // classes is determined entirely by the types of the function
  2685. // arguments (and the namespace of any template template
  2686. // argument). Typedef names and using-declarations used to specify
  2687. // the types do not contribute to this set. The sets of namespaces
  2688. // and classes are determined in the following way:
  2689. SmallVector<const Type *, 16> Queue;
  2690. const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
  2691. while (true) {
  2692. switch (T->getTypeClass()) {
  2693. #define TYPE(Class, Base)
  2694. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  2695. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2696. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  2697. #define ABSTRACT_TYPE(Class, Base)
  2698. #include "clang/AST/TypeNodes.inc"
  2699. // T is canonical. We can also ignore dependent types because
  2700. // we don't need to do ADL at the definition point, but if we
  2701. // wanted to implement template export (or if we find some other
  2702. // use for associated classes and namespaces...) this would be
  2703. // wrong.
  2704. break;
  2705. // -- If T is a pointer to U or an array of U, its associated
  2706. // namespaces and classes are those associated with U.
  2707. case Type::Pointer:
  2708. T = cast<PointerType>(T)->getPointeeType().getTypePtr();
  2709. continue;
  2710. case Type::ConstantArray:
  2711. case Type::IncompleteArray:
  2712. case Type::VariableArray:
  2713. T = cast<ArrayType>(T)->getElementType().getTypePtr();
  2714. continue;
  2715. // -- If T is a fundamental type, its associated sets of
  2716. // namespaces and classes are both empty.
  2717. case Type::Builtin:
  2718. break;
  2719. // -- If T is a class type (including unions), its associated
  2720. // classes are: the class itself; the class of which it is
  2721. // a member, if any; and its direct and indirect base classes.
  2722. // Its associated namespaces are the innermost enclosing
  2723. // namespaces of its associated classes.
  2724. case Type::Record: {
  2725. CXXRecordDecl *Class =
  2726. cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
  2727. addAssociatedClassesAndNamespaces(Result, Class);
  2728. break;
  2729. }
  2730. // -- If T is an enumeration type, its associated namespace
  2731. // is the innermost enclosing namespace of its declaration.
  2732. // If it is a class member, its associated class is the
  2733. // member’s class; else it has no associated class.
  2734. case Type::Enum: {
  2735. EnumDecl *Enum = cast<EnumType>(T)->getDecl();
  2736. DeclContext *Ctx = Enum->getDeclContext();
  2737. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  2738. Result.Classes.insert(EnclosingClass);
  2739. // Add the associated namespace for this enumeration.
  2740. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  2741. break;
  2742. }
  2743. // -- If T is a function type, its associated namespaces and
  2744. // classes are those associated with the function parameter
  2745. // types and those associated with the return type.
  2746. case Type::FunctionProto: {
  2747. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  2748. for (const auto &Arg : Proto->param_types())
  2749. Queue.push_back(Arg.getTypePtr());
  2750. // fallthrough
  2751. [[fallthrough]];
  2752. }
  2753. case Type::FunctionNoProto: {
  2754. const FunctionType *FnType = cast<FunctionType>(T);
  2755. T = FnType->getReturnType().getTypePtr();
  2756. continue;
  2757. }
  2758. // -- If T is a pointer to a member function of a class X, its
  2759. // associated namespaces and classes are those associated
  2760. // with the function parameter types and return type,
  2761. // together with those associated with X.
  2762. //
  2763. // -- If T is a pointer to a data member of class X, its
  2764. // associated namespaces and classes are those associated
  2765. // with the member type together with those associated with
  2766. // X.
  2767. case Type::MemberPointer: {
  2768. const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
  2769. // Queue up the class type into which this points.
  2770. Queue.push_back(MemberPtr->getClass());
  2771. // And directly continue with the pointee type.
  2772. T = MemberPtr->getPointeeType().getTypePtr();
  2773. continue;
  2774. }
  2775. // As an extension, treat this like a normal pointer.
  2776. case Type::BlockPointer:
  2777. T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
  2778. continue;
  2779. // References aren't covered by the standard, but that's such an
  2780. // obvious defect that we cover them anyway.
  2781. case Type::LValueReference:
  2782. case Type::RValueReference:
  2783. T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
  2784. continue;
  2785. // These are fundamental types.
  2786. case Type::Vector:
  2787. case Type::ExtVector:
  2788. case Type::ConstantMatrix:
  2789. case Type::Complex:
  2790. case Type::BitInt:
  2791. break;
  2792. // Non-deduced auto types only get here for error cases.
  2793. case Type::Auto:
  2794. case Type::DeducedTemplateSpecialization:
  2795. break;
  2796. // If T is an Objective-C object or interface type, or a pointer to an
  2797. // object or interface type, the associated namespace is the global
  2798. // namespace.
  2799. case Type::ObjCObject:
  2800. case Type::ObjCInterface:
  2801. case Type::ObjCObjectPointer:
  2802. Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
  2803. break;
  2804. // Atomic types are just wrappers; use the associations of the
  2805. // contained type.
  2806. case Type::Atomic:
  2807. T = cast<AtomicType>(T)->getValueType().getTypePtr();
  2808. continue;
  2809. case Type::Pipe:
  2810. T = cast<PipeType>(T)->getElementType().getTypePtr();
  2811. continue;
  2812. }
  2813. if (Queue.empty())
  2814. break;
  2815. T = Queue.pop_back_val();
  2816. }
  2817. }
  2818. /// Find the associated classes and namespaces for
  2819. /// argument-dependent lookup for a call with the given set of
  2820. /// arguments.
  2821. ///
  2822. /// This routine computes the sets of associated classes and associated
  2823. /// namespaces searched by argument-dependent lookup
  2824. /// (C++ [basic.lookup.argdep]) for a given set of arguments.
  2825. void Sema::FindAssociatedClassesAndNamespaces(
  2826. SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
  2827. AssociatedNamespaceSet &AssociatedNamespaces,
  2828. AssociatedClassSet &AssociatedClasses) {
  2829. AssociatedNamespaces.clear();
  2830. AssociatedClasses.clear();
  2831. AssociatedLookup Result(*this, InstantiationLoc,
  2832. AssociatedNamespaces, AssociatedClasses);
  2833. // C++ [basic.lookup.koenig]p2:
  2834. // For each argument type T in the function call, there is a set
  2835. // of zero or more associated namespaces and a set of zero or more
  2836. // associated classes to be considered. The sets of namespaces and
  2837. // classes is determined entirely by the types of the function
  2838. // arguments (and the namespace of any template template
  2839. // argument).
  2840. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  2841. Expr *Arg = Args[ArgIdx];
  2842. if (Arg->getType() != Context.OverloadTy) {
  2843. addAssociatedClassesAndNamespaces(Result, Arg->getType());
  2844. continue;
  2845. }
  2846. // [...] In addition, if the argument is the name or address of a
  2847. // set of overloaded functions and/or function templates, its
  2848. // associated classes and namespaces are the union of those
  2849. // associated with each of the members of the set: the namespace
  2850. // in which the function or function template is defined and the
  2851. // classes and namespaces associated with its (non-dependent)
  2852. // parameter types and return type.
  2853. OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
  2854. for (const NamedDecl *D : OE->decls()) {
  2855. // Look through any using declarations to find the underlying function.
  2856. const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
  2857. // Add the classes and namespaces associated with the parameter
  2858. // types and return type of this function.
  2859. addAssociatedClassesAndNamespaces(Result, FDecl->getType());
  2860. }
  2861. }
  2862. }
  2863. NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
  2864. SourceLocation Loc,
  2865. LookupNameKind NameKind,
  2866. RedeclarationKind Redecl) {
  2867. LookupResult R(*this, Name, Loc, NameKind, Redecl);
  2868. LookupName(R, S);
  2869. return R.getAsSingle<NamedDecl>();
  2870. }
  2871. /// Find the protocol with the given name, if any.
  2872. ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
  2873. SourceLocation IdLoc,
  2874. RedeclarationKind Redecl) {
  2875. Decl *D = LookupSingleName(TUScope, II, IdLoc,
  2876. LookupObjCProtocolName, Redecl);
  2877. return cast_or_null<ObjCProtocolDecl>(D);
  2878. }
  2879. void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
  2880. UnresolvedSetImpl &Functions) {
  2881. // C++ [over.match.oper]p3:
  2882. // -- The set of non-member candidates is the result of the
  2883. // unqualified lookup of operator@ in the context of the
  2884. // expression according to the usual rules for name lookup in
  2885. // unqualified function calls (3.4.2) except that all member
  2886. // functions are ignored.
  2887. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  2888. LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
  2889. LookupName(Operators, S);
  2890. assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
  2891. Functions.append(Operators.begin(), Operators.end());
  2892. }
  2893. Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
  2894. CXXSpecialMember SM,
  2895. bool ConstArg,
  2896. bool VolatileArg,
  2897. bool RValueThis,
  2898. bool ConstThis,
  2899. bool VolatileThis) {
  2900. assert(CanDeclareSpecialMemberFunction(RD) &&
  2901. "doing special member lookup into record that isn't fully complete");
  2902. RD = RD->getDefinition();
  2903. if (RValueThis || ConstThis || VolatileThis)
  2904. assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
  2905. "constructors and destructors always have unqualified lvalue this");
  2906. if (ConstArg || VolatileArg)
  2907. assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
  2908. "parameter-less special members can't have qualified arguments");
  2909. // FIXME: Get the caller to pass in a location for the lookup.
  2910. SourceLocation LookupLoc = RD->getLocation();
  2911. llvm::FoldingSetNodeID ID;
  2912. ID.AddPointer(RD);
  2913. ID.AddInteger(SM);
  2914. ID.AddInteger(ConstArg);
  2915. ID.AddInteger(VolatileArg);
  2916. ID.AddInteger(RValueThis);
  2917. ID.AddInteger(ConstThis);
  2918. ID.AddInteger(VolatileThis);
  2919. void *InsertPoint;
  2920. SpecialMemberOverloadResultEntry *Result =
  2921. SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
  2922. // This was already cached
  2923. if (Result)
  2924. return *Result;
  2925. Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
  2926. Result = new (Result) SpecialMemberOverloadResultEntry(ID);
  2927. SpecialMemberCache.InsertNode(Result, InsertPoint);
  2928. if (SM == CXXDestructor) {
  2929. if (RD->needsImplicitDestructor()) {
  2930. runWithSufficientStackSpace(RD->getLocation(), [&] {
  2931. DeclareImplicitDestructor(RD);
  2932. });
  2933. }
  2934. CXXDestructorDecl *DD = RD->getDestructor();
  2935. Result->setMethod(DD);
  2936. Result->setKind(DD && !DD->isDeleted()
  2937. ? SpecialMemberOverloadResult::Success
  2938. : SpecialMemberOverloadResult::NoMemberOrDeleted);
  2939. return *Result;
  2940. }
  2941. // Prepare for overload resolution. Here we construct a synthetic argument
  2942. // if necessary and make sure that implicit functions are declared.
  2943. CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
  2944. DeclarationName Name;
  2945. Expr *Arg = nullptr;
  2946. unsigned NumArgs;
  2947. QualType ArgType = CanTy;
  2948. ExprValueKind VK = VK_LValue;
  2949. if (SM == CXXDefaultConstructor) {
  2950. Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
  2951. NumArgs = 0;
  2952. if (RD->needsImplicitDefaultConstructor()) {
  2953. runWithSufficientStackSpace(RD->getLocation(), [&] {
  2954. DeclareImplicitDefaultConstructor(RD);
  2955. });
  2956. }
  2957. } else {
  2958. if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
  2959. Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
  2960. if (RD->needsImplicitCopyConstructor()) {
  2961. runWithSufficientStackSpace(RD->getLocation(), [&] {
  2962. DeclareImplicitCopyConstructor(RD);
  2963. });
  2964. }
  2965. if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {
  2966. runWithSufficientStackSpace(RD->getLocation(), [&] {
  2967. DeclareImplicitMoveConstructor(RD);
  2968. });
  2969. }
  2970. } else {
  2971. Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  2972. if (RD->needsImplicitCopyAssignment()) {
  2973. runWithSufficientStackSpace(RD->getLocation(), [&] {
  2974. DeclareImplicitCopyAssignment(RD);
  2975. });
  2976. }
  2977. if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {
  2978. runWithSufficientStackSpace(RD->getLocation(), [&] {
  2979. DeclareImplicitMoveAssignment(RD);
  2980. });
  2981. }
  2982. }
  2983. if (ConstArg)
  2984. ArgType.addConst();
  2985. if (VolatileArg)
  2986. ArgType.addVolatile();
  2987. // This isn't /really/ specified by the standard, but it's implied
  2988. // we should be working from a PRValue in the case of move to ensure
  2989. // that we prefer to bind to rvalue references, and an LValue in the
  2990. // case of copy to ensure we don't bind to rvalue references.
  2991. // Possibly an XValue is actually correct in the case of move, but
  2992. // there is no semantic difference for class types in this restricted
  2993. // case.
  2994. if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
  2995. VK = VK_LValue;
  2996. else
  2997. VK = VK_PRValue;
  2998. }
  2999. OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
  3000. if (SM != CXXDefaultConstructor) {
  3001. NumArgs = 1;
  3002. Arg = &FakeArg;
  3003. }
  3004. // Create the object argument
  3005. QualType ThisTy = CanTy;
  3006. if (ConstThis)
  3007. ThisTy.addConst();
  3008. if (VolatileThis)
  3009. ThisTy.addVolatile();
  3010. Expr::Classification Classification =
  3011. OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
  3012. .Classify(Context);
  3013. // Now we perform lookup on the name we computed earlier and do overload
  3014. // resolution. Lookup is only performed directly into the class since there
  3015. // will always be a (possibly implicit) declaration to shadow any others.
  3016. OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
  3017. DeclContext::lookup_result R = RD->lookup(Name);
  3018. if (R.empty()) {
  3019. // We might have no default constructor because we have a lambda's closure
  3020. // type, rather than because there's some other declared constructor.
  3021. // Every class has a copy/move constructor, copy/move assignment, and
  3022. // destructor.
  3023. assert(SM == CXXDefaultConstructor &&
  3024. "lookup for a constructor or assignment operator was empty");
  3025. Result->setMethod(nullptr);
  3026. Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
  3027. return *Result;
  3028. }
  3029. // Copy the candidates as our processing of them may load new declarations
  3030. // from an external source and invalidate lookup_result.
  3031. SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
  3032. for (NamedDecl *CandDecl : Candidates) {
  3033. if (CandDecl->isInvalidDecl())
  3034. continue;
  3035. DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
  3036. auto CtorInfo = getConstructorInfo(Cand);
  3037. if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
  3038. if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
  3039. AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
  3040. llvm::ArrayRef(&Arg, NumArgs), OCS, true);
  3041. else if (CtorInfo)
  3042. AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
  3043. llvm::ArrayRef(&Arg, NumArgs), OCS,
  3044. /*SuppressUserConversions*/ true);
  3045. else
  3046. AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS,
  3047. /*SuppressUserConversions*/ true);
  3048. } else if (FunctionTemplateDecl *Tmpl =
  3049. dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
  3050. if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
  3051. AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy,
  3052. Classification,
  3053. llvm::ArrayRef(&Arg, NumArgs), OCS, true);
  3054. else if (CtorInfo)
  3055. AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl,
  3056. CtorInfo.FoundDecl, nullptr,
  3057. llvm::ArrayRef(&Arg, NumArgs), OCS, true);
  3058. else
  3059. AddTemplateOverloadCandidate(Tmpl, Cand, nullptr,
  3060. llvm::ArrayRef(&Arg, NumArgs), OCS, true);
  3061. } else {
  3062. assert(isa<UsingDecl>(Cand.getDecl()) &&
  3063. "illegal Kind of operator = Decl");
  3064. }
  3065. }
  3066. OverloadCandidateSet::iterator Best;
  3067. switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
  3068. case OR_Success:
  3069. Result->setMethod(cast<CXXMethodDecl>(Best->Function));
  3070. Result->setKind(SpecialMemberOverloadResult::Success);
  3071. break;
  3072. case OR_Deleted:
  3073. Result->setMethod(cast<CXXMethodDecl>(Best->Function));
  3074. Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
  3075. break;
  3076. case OR_Ambiguous:
  3077. Result->setMethod(nullptr);
  3078. Result->setKind(SpecialMemberOverloadResult::Ambiguous);
  3079. break;
  3080. case OR_No_Viable_Function:
  3081. Result->setMethod(nullptr);
  3082. Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
  3083. break;
  3084. }
  3085. return *Result;
  3086. }
  3087. /// Look up the default constructor for the given class.
  3088. CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
  3089. SpecialMemberOverloadResult Result =
  3090. LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
  3091. false, false);
  3092. return cast_or_null<CXXConstructorDecl>(Result.getMethod());
  3093. }
  3094. /// Look up the copying constructor for the given class.
  3095. CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
  3096. unsigned Quals) {
  3097. assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  3098. "non-const, non-volatile qualifiers for copy ctor arg");
  3099. SpecialMemberOverloadResult Result =
  3100. LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
  3101. Quals & Qualifiers::Volatile, false, false, false);
  3102. return cast_or_null<CXXConstructorDecl>(Result.getMethod());
  3103. }
  3104. /// Look up the moving constructor for the given class.
  3105. CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
  3106. unsigned Quals) {
  3107. SpecialMemberOverloadResult Result =
  3108. LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
  3109. Quals & Qualifiers::Volatile, false, false, false);
  3110. return cast_or_null<CXXConstructorDecl>(Result.getMethod());
  3111. }
  3112. /// Look up the constructors for the given class.
  3113. DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
  3114. // If the implicit constructors have not yet been declared, do so now.
  3115. if (CanDeclareSpecialMemberFunction(Class)) {
  3116. runWithSufficientStackSpace(Class->getLocation(), [&] {
  3117. if (Class->needsImplicitDefaultConstructor())
  3118. DeclareImplicitDefaultConstructor(Class);
  3119. if (Class->needsImplicitCopyConstructor())
  3120. DeclareImplicitCopyConstructor(Class);
  3121. if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
  3122. DeclareImplicitMoveConstructor(Class);
  3123. });
  3124. }
  3125. CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
  3126. DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
  3127. return Class->lookup(Name);
  3128. }
  3129. /// Look up the copying assignment operator for the given class.
  3130. CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
  3131. unsigned Quals, bool RValueThis,
  3132. unsigned ThisQuals) {
  3133. assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  3134. "non-const, non-volatile qualifiers for copy assignment arg");
  3135. assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  3136. "non-const, non-volatile qualifiers for copy assignment this");
  3137. SpecialMemberOverloadResult Result =
  3138. LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
  3139. Quals & Qualifiers::Volatile, RValueThis,
  3140. ThisQuals & Qualifiers::Const,
  3141. ThisQuals & Qualifiers::Volatile);
  3142. return Result.getMethod();
  3143. }
  3144. /// Look up the moving assignment operator for the given class.
  3145. CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
  3146. unsigned Quals,
  3147. bool RValueThis,
  3148. unsigned ThisQuals) {
  3149. assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  3150. "non-const, non-volatile qualifiers for copy assignment this");
  3151. SpecialMemberOverloadResult Result =
  3152. LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
  3153. Quals & Qualifiers::Volatile, RValueThis,
  3154. ThisQuals & Qualifiers::Const,
  3155. ThisQuals & Qualifiers::Volatile);
  3156. return Result.getMethod();
  3157. }
  3158. /// Look for the destructor of the given class.
  3159. ///
  3160. /// During semantic analysis, this routine should be used in lieu of
  3161. /// CXXRecordDecl::getDestructor().
  3162. ///
  3163. /// \returns The destructor for this class.
  3164. CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
  3165. return cast_or_null<CXXDestructorDecl>(
  3166. LookupSpecialMember(Class, CXXDestructor, false, false, false, false,
  3167. false)
  3168. .getMethod());
  3169. }
  3170. /// LookupLiteralOperator - Determine which literal operator should be used for
  3171. /// a user-defined literal, per C++11 [lex.ext].
  3172. ///
  3173. /// Normal overload resolution is not used to select which literal operator to
  3174. /// call for a user-defined literal. Look up the provided literal operator name,
  3175. /// and filter the results to the appropriate set for the given argument types.
  3176. Sema::LiteralOperatorLookupResult
  3177. Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
  3178. ArrayRef<QualType> ArgTys, bool AllowRaw,
  3179. bool AllowTemplate, bool AllowStringTemplatePack,
  3180. bool DiagnoseMissing, StringLiteral *StringLit) {
  3181. LookupName(R, S);
  3182. assert(R.getResultKind() != LookupResult::Ambiguous &&
  3183. "literal operator lookup can't be ambiguous");
  3184. // Filter the lookup results appropriately.
  3185. LookupResult::Filter F = R.makeFilter();
  3186. bool AllowCooked = true;
  3187. bool FoundRaw = false;
  3188. bool FoundTemplate = false;
  3189. bool FoundStringTemplatePack = false;
  3190. bool FoundCooked = false;
  3191. while (F.hasNext()) {
  3192. Decl *D = F.next();
  3193. if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
  3194. D = USD->getTargetDecl();
  3195. // If the declaration we found is invalid, skip it.
  3196. if (D->isInvalidDecl()) {
  3197. F.erase();
  3198. continue;
  3199. }
  3200. bool IsRaw = false;
  3201. bool IsTemplate = false;
  3202. bool IsStringTemplatePack = false;
  3203. bool IsCooked = false;
  3204. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  3205. if (FD->getNumParams() == 1 &&
  3206. FD->getParamDecl(0)->getType()->getAs<PointerType>())
  3207. IsRaw = true;
  3208. else if (FD->getNumParams() == ArgTys.size()) {
  3209. IsCooked = true;
  3210. for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
  3211. QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
  3212. if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
  3213. IsCooked = false;
  3214. break;
  3215. }
  3216. }
  3217. }
  3218. }
  3219. if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
  3220. TemplateParameterList *Params = FD->getTemplateParameters();
  3221. if (Params->size() == 1) {
  3222. IsTemplate = true;
  3223. if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
  3224. // Implied but not stated: user-defined integer and floating literals
  3225. // only ever use numeric literal operator templates, not templates
  3226. // taking a parameter of class type.
  3227. F.erase();
  3228. continue;
  3229. }
  3230. // A string literal template is only considered if the string literal
  3231. // is a well-formed template argument for the template parameter.
  3232. if (StringLit) {
  3233. SFINAETrap Trap(*this);
  3234. SmallVector<TemplateArgument, 1> SugaredChecked, CanonicalChecked;
  3235. TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);
  3236. if (CheckTemplateArgument(
  3237. Params->getParam(0), Arg, FD, R.getNameLoc(), R.getNameLoc(),
  3238. 0, SugaredChecked, CanonicalChecked, CTAK_Specified) ||
  3239. Trap.hasErrorOccurred())
  3240. IsTemplate = false;
  3241. }
  3242. } else {
  3243. IsStringTemplatePack = true;
  3244. }
  3245. }
  3246. if (AllowTemplate && StringLit && IsTemplate) {
  3247. FoundTemplate = true;
  3248. AllowRaw = false;
  3249. AllowCooked = false;
  3250. AllowStringTemplatePack = false;
  3251. if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
  3252. F.restart();
  3253. FoundRaw = FoundCooked = FoundStringTemplatePack = false;
  3254. }
  3255. } else if (AllowCooked && IsCooked) {
  3256. FoundCooked = true;
  3257. AllowRaw = false;
  3258. AllowTemplate = StringLit;
  3259. AllowStringTemplatePack = false;
  3260. if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
  3261. // Go through again and remove the raw and template decls we've
  3262. // already found.
  3263. F.restart();
  3264. FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
  3265. }
  3266. } else if (AllowRaw && IsRaw) {
  3267. FoundRaw = true;
  3268. } else if (AllowTemplate && IsTemplate) {
  3269. FoundTemplate = true;
  3270. } else if (AllowStringTemplatePack && IsStringTemplatePack) {
  3271. FoundStringTemplatePack = true;
  3272. } else {
  3273. F.erase();
  3274. }
  3275. }
  3276. F.done();
  3277. // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
  3278. // form for string literal operator templates.
  3279. if (StringLit && FoundTemplate)
  3280. return LOLR_Template;
  3281. // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
  3282. // parameter type, that is used in preference to a raw literal operator
  3283. // or literal operator template.
  3284. if (FoundCooked)
  3285. return LOLR_Cooked;
  3286. // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
  3287. // operator template, but not both.
  3288. if (FoundRaw && FoundTemplate) {
  3289. Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
  3290. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  3291. NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
  3292. return LOLR_Error;
  3293. }
  3294. if (FoundRaw)
  3295. return LOLR_Raw;
  3296. if (FoundTemplate)
  3297. return LOLR_Template;
  3298. if (FoundStringTemplatePack)
  3299. return LOLR_StringTemplatePack;
  3300. // Didn't find anything we could use.
  3301. if (DiagnoseMissing) {
  3302. Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
  3303. << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
  3304. << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
  3305. << (AllowTemplate || AllowStringTemplatePack);
  3306. return LOLR_Error;
  3307. }
  3308. return LOLR_ErrorNoDiagnostic;
  3309. }
  3310. void ADLResult::insert(NamedDecl *New) {
  3311. NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
  3312. // If we haven't yet seen a decl for this key, or the last decl
  3313. // was exactly this one, we're done.
  3314. if (Old == nullptr || Old == New) {
  3315. Old = New;
  3316. return;
  3317. }
  3318. // Otherwise, decide which is a more recent redeclaration.
  3319. FunctionDecl *OldFD = Old->getAsFunction();
  3320. FunctionDecl *NewFD = New->getAsFunction();
  3321. FunctionDecl *Cursor = NewFD;
  3322. while (true) {
  3323. Cursor = Cursor->getPreviousDecl();
  3324. // If we got to the end without finding OldFD, OldFD is the newer
  3325. // declaration; leave things as they are.
  3326. if (!Cursor) return;
  3327. // If we do find OldFD, then NewFD is newer.
  3328. if (Cursor == OldFD) break;
  3329. // Otherwise, keep looking.
  3330. }
  3331. Old = New;
  3332. }
  3333. void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
  3334. ArrayRef<Expr *> Args, ADLResult &Result) {
  3335. // Find all of the associated namespaces and classes based on the
  3336. // arguments we have.
  3337. AssociatedNamespaceSet AssociatedNamespaces;
  3338. AssociatedClassSet AssociatedClasses;
  3339. FindAssociatedClassesAndNamespaces(Loc, Args,
  3340. AssociatedNamespaces,
  3341. AssociatedClasses);
  3342. // C++ [basic.lookup.argdep]p3:
  3343. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  3344. // and let Y be the lookup set produced by argument dependent
  3345. // lookup (defined as follows). If X contains [...] then Y is
  3346. // empty. Otherwise Y is the set of declarations found in the
  3347. // namespaces associated with the argument types as described
  3348. // below. The set of declarations found by the lookup of the name
  3349. // is the union of X and Y.
  3350. //
  3351. // Here, we compute Y and add its members to the overloaded
  3352. // candidate set.
  3353. for (auto *NS : AssociatedNamespaces) {
  3354. // When considering an associated namespace, the lookup is the
  3355. // same as the lookup performed when the associated namespace is
  3356. // used as a qualifier (3.4.3.2) except that:
  3357. //
  3358. // -- Any using-directives in the associated namespace are
  3359. // ignored.
  3360. //
  3361. // -- Any namespace-scope friend functions declared in
  3362. // associated classes are visible within their respective
  3363. // namespaces even if they are not visible during an ordinary
  3364. // lookup (11.4).
  3365. //
  3366. // C++20 [basic.lookup.argdep] p4.3
  3367. // -- are exported, are attached to a named module M, do not appear
  3368. // in the translation unit containing the point of the lookup, and
  3369. // have the same innermost enclosing non-inline namespace scope as
  3370. // a declaration of an associated entity attached to M.
  3371. DeclContext::lookup_result R = NS->lookup(Name);
  3372. for (auto *D : R) {
  3373. auto *Underlying = D;
  3374. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  3375. Underlying = USD->getTargetDecl();
  3376. if (!isa<FunctionDecl>(Underlying) &&
  3377. !isa<FunctionTemplateDecl>(Underlying))
  3378. continue;
  3379. // The declaration is visible to argument-dependent lookup if either
  3380. // it's ordinarily visible or declared as a friend in an associated
  3381. // class.
  3382. bool Visible = false;
  3383. for (D = D->getMostRecentDecl(); D;
  3384. D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
  3385. if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
  3386. if (isVisible(D)) {
  3387. Visible = true;
  3388. break;
  3389. } else if (getLangOpts().CPlusPlusModules &&
  3390. D->isInExportDeclContext()) {
  3391. // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
  3392. Module *FM = D->getOwningModule();
  3393. // exports are only valid in module purview and outside of any
  3394. // PMF (although a PMF should not even be present in a module
  3395. // with an import).
  3396. assert(FM && FM->isModulePurview() && !FM->isPrivateModule() &&
  3397. "bad export context");
  3398. // .. are attached to a named module M, do not appear in the
  3399. // translation unit containing the point of the lookup..
  3400. if (!isModuleUnitOfCurrentTU(FM) &&
  3401. llvm::any_of(AssociatedClasses, [&](auto *E) {
  3402. // ... and have the same innermost enclosing non-inline
  3403. // namespace scope as a declaration of an associated entity
  3404. // attached to M
  3405. if (!E->hasOwningModule() ||
  3406. E->getOwningModule()->getTopLevelModuleName() !=
  3407. FM->getTopLevelModuleName())
  3408. return false;
  3409. // TODO: maybe this could be cached when generating the
  3410. // associated namespaces / entities.
  3411. DeclContext *Ctx = E->getDeclContext();
  3412. while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
  3413. Ctx = Ctx->getParent();
  3414. return Ctx == NS;
  3415. })) {
  3416. Visible = true;
  3417. break;
  3418. }
  3419. }
  3420. } else if (D->getFriendObjectKind()) {
  3421. auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
  3422. // [basic.lookup.argdep]p4:
  3423. // Argument-dependent lookup finds all declarations of functions and
  3424. // function templates that
  3425. // - ...
  3426. // - are declared as a friend ([class.friend]) of any class with a
  3427. // reachable definition in the set of associated entities,
  3428. //
  3429. // FIXME: If there's a merged definition of D that is reachable, then
  3430. // the friend declaration should be considered.
  3431. if (AssociatedClasses.count(RD) && isReachable(D)) {
  3432. Visible = true;
  3433. break;
  3434. }
  3435. }
  3436. }
  3437. // FIXME: Preserve D as the FoundDecl.
  3438. if (Visible)
  3439. Result.insert(Underlying);
  3440. }
  3441. }
  3442. }
  3443. //----------------------------------------------------------------------------
  3444. // Search for all visible declarations.
  3445. //----------------------------------------------------------------------------
  3446. VisibleDeclConsumer::~VisibleDeclConsumer() { }
  3447. bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
  3448. namespace {
  3449. class ShadowContextRAII;
  3450. class VisibleDeclsRecord {
  3451. public:
  3452. /// An entry in the shadow map, which is optimized to store a
  3453. /// single declaration (the common case) but can also store a list
  3454. /// of declarations.
  3455. typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
  3456. private:
  3457. /// A mapping from declaration names to the declarations that have
  3458. /// this name within a particular scope.
  3459. typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
  3460. /// A list of shadow maps, which is used to model name hiding.
  3461. std::list<ShadowMap> ShadowMaps;
  3462. /// The declaration contexts we have already visited.
  3463. llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
  3464. friend class ShadowContextRAII;
  3465. public:
  3466. /// Determine whether we have already visited this context
  3467. /// (and, if not, note that we are going to visit that context now).
  3468. bool visitedContext(DeclContext *Ctx) {
  3469. return !VisitedContexts.insert(Ctx).second;
  3470. }
  3471. bool alreadyVisitedContext(DeclContext *Ctx) {
  3472. return VisitedContexts.count(Ctx);
  3473. }
  3474. /// Determine whether the given declaration is hidden in the
  3475. /// current scope.
  3476. ///
  3477. /// \returns the declaration that hides the given declaration, or
  3478. /// NULL if no such declaration exists.
  3479. NamedDecl *checkHidden(NamedDecl *ND);
  3480. /// Add a declaration to the current shadow map.
  3481. void add(NamedDecl *ND) {
  3482. ShadowMaps.back()[ND->getDeclName()].push_back(ND);
  3483. }
  3484. };
  3485. /// RAII object that records when we've entered a shadow context.
  3486. class ShadowContextRAII {
  3487. VisibleDeclsRecord &Visible;
  3488. typedef VisibleDeclsRecord::ShadowMap ShadowMap;
  3489. public:
  3490. ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
  3491. Visible.ShadowMaps.emplace_back();
  3492. }
  3493. ~ShadowContextRAII() {
  3494. Visible.ShadowMaps.pop_back();
  3495. }
  3496. };
  3497. } // end anonymous namespace
  3498. NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
  3499. unsigned IDNS = ND->getIdentifierNamespace();
  3500. std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
  3501. for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
  3502. SM != SMEnd; ++SM) {
  3503. ShadowMap::iterator Pos = SM->find(ND->getDeclName());
  3504. if (Pos == SM->end())
  3505. continue;
  3506. for (auto *D : Pos->second) {
  3507. // A tag declaration does not hide a non-tag declaration.
  3508. if (D->hasTagIdentifierNamespace() &&
  3509. (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
  3510. Decl::IDNS_ObjCProtocol)))
  3511. continue;
  3512. // Protocols are in distinct namespaces from everything else.
  3513. if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
  3514. || (IDNS & Decl::IDNS_ObjCProtocol)) &&
  3515. D->getIdentifierNamespace() != IDNS)
  3516. continue;
  3517. // Functions and function templates in the same scope overload
  3518. // rather than hide. FIXME: Look for hiding based on function
  3519. // signatures!
  3520. if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
  3521. ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
  3522. SM == ShadowMaps.rbegin())
  3523. continue;
  3524. // A shadow declaration that's created by a resolved using declaration
  3525. // is not hidden by the same using declaration.
  3526. if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
  3527. cast<UsingShadowDecl>(ND)->getIntroducer() == D)
  3528. continue;
  3529. // We've found a declaration that hides this one.
  3530. return D;
  3531. }
  3532. }
  3533. return nullptr;
  3534. }
  3535. namespace {
  3536. class LookupVisibleHelper {
  3537. public:
  3538. LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
  3539. bool LoadExternal)
  3540. : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
  3541. LoadExternal(LoadExternal) {}
  3542. void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
  3543. bool IncludeGlobalScope) {
  3544. // Determine the set of using directives available during
  3545. // unqualified name lookup.
  3546. Scope *Initial = S;
  3547. UnqualUsingDirectiveSet UDirs(SemaRef);
  3548. if (SemaRef.getLangOpts().CPlusPlus) {
  3549. // Find the first namespace or translation-unit scope.
  3550. while (S && !isNamespaceOrTranslationUnitScope(S))
  3551. S = S->getParent();
  3552. UDirs.visitScopeChain(Initial, S);
  3553. }
  3554. UDirs.done();
  3555. // Look for visible declarations.
  3556. LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
  3557. Result.setAllowHidden(Consumer.includeHiddenDecls());
  3558. if (!IncludeGlobalScope)
  3559. Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
  3560. ShadowContextRAII Shadow(Visited);
  3561. lookupInScope(Initial, Result, UDirs);
  3562. }
  3563. void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
  3564. Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
  3565. LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
  3566. Result.setAllowHidden(Consumer.includeHiddenDecls());
  3567. if (!IncludeGlobalScope)
  3568. Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
  3569. ShadowContextRAII Shadow(Visited);
  3570. lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
  3571. /*InBaseClass=*/false);
  3572. }
  3573. private:
  3574. void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
  3575. bool QualifiedNameLookup, bool InBaseClass) {
  3576. if (!Ctx)
  3577. return;
  3578. // Make sure we don't visit the same context twice.
  3579. if (Visited.visitedContext(Ctx->getPrimaryContext()))
  3580. return;
  3581. Consumer.EnteredContext(Ctx);
  3582. // Outside C++, lookup results for the TU live on identifiers.
  3583. if (isa<TranslationUnitDecl>(Ctx) &&
  3584. !Result.getSema().getLangOpts().CPlusPlus) {
  3585. auto &S = Result.getSema();
  3586. auto &Idents = S.Context.Idents;
  3587. // Ensure all external identifiers are in the identifier table.
  3588. if (LoadExternal)
  3589. if (IdentifierInfoLookup *External =
  3590. Idents.getExternalIdentifierLookup()) {
  3591. std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
  3592. for (StringRef Name = Iter->Next(); !Name.empty();
  3593. Name = Iter->Next())
  3594. Idents.get(Name);
  3595. }
  3596. // Walk all lookup results in the TU for each identifier.
  3597. for (const auto &Ident : Idents) {
  3598. for (auto I = S.IdResolver.begin(Ident.getValue()),
  3599. E = S.IdResolver.end();
  3600. I != E; ++I) {
  3601. if (S.IdResolver.isDeclInScope(*I, Ctx)) {
  3602. if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
  3603. Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
  3604. Visited.add(ND);
  3605. }
  3606. }
  3607. }
  3608. }
  3609. return;
  3610. }
  3611. if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
  3612. Result.getSema().ForceDeclarationOfImplicitMembers(Class);
  3613. llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;
  3614. // We sometimes skip loading namespace-level results (they tend to be huge).
  3615. bool Load = LoadExternal ||
  3616. !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
  3617. // Enumerate all of the results in this context.
  3618. for (DeclContextLookupResult R :
  3619. Load ? Ctx->lookups()
  3620. : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
  3621. for (auto *D : R) {
  3622. if (auto *ND = Result.getAcceptableDecl(D)) {
  3623. // Rather than visit immediately, we put ND into a vector and visit
  3624. // all decls, in order, outside of this loop. The reason is that
  3625. // Consumer.FoundDecl() may invalidate the iterators used in the two
  3626. // loops above.
  3627. DeclsToVisit.push_back(ND);
  3628. }
  3629. }
  3630. }
  3631. for (auto *ND : DeclsToVisit) {
  3632. Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
  3633. Visited.add(ND);
  3634. }
  3635. DeclsToVisit.clear();
  3636. // Traverse using directives for qualified name lookup.
  3637. if (QualifiedNameLookup) {
  3638. ShadowContextRAII Shadow(Visited);
  3639. for (auto *I : Ctx->using_directives()) {
  3640. if (!Result.getSema().isVisible(I))
  3641. continue;
  3642. lookupInDeclContext(I->getNominatedNamespace(), Result,
  3643. QualifiedNameLookup, InBaseClass);
  3644. }
  3645. }
  3646. // Traverse the contexts of inherited C++ classes.
  3647. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
  3648. if (!Record->hasDefinition())
  3649. return;
  3650. for (const auto &B : Record->bases()) {
  3651. QualType BaseType = B.getType();
  3652. RecordDecl *RD;
  3653. if (BaseType->isDependentType()) {
  3654. if (!IncludeDependentBases) {
  3655. // Don't look into dependent bases, because name lookup can't look
  3656. // there anyway.
  3657. continue;
  3658. }
  3659. const auto *TST = BaseType->getAs<TemplateSpecializationType>();
  3660. if (!TST)
  3661. continue;
  3662. TemplateName TN = TST->getTemplateName();
  3663. const auto *TD =
  3664. dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
  3665. if (!TD)
  3666. continue;
  3667. RD = TD->getTemplatedDecl();
  3668. } else {
  3669. const auto *Record = BaseType->getAs<RecordType>();
  3670. if (!Record)
  3671. continue;
  3672. RD = Record->getDecl();
  3673. }
  3674. // FIXME: It would be nice to be able to determine whether referencing
  3675. // a particular member would be ambiguous. For example, given
  3676. //
  3677. // struct A { int member; };
  3678. // struct B { int member; };
  3679. // struct C : A, B { };
  3680. //
  3681. // void f(C *c) { c->### }
  3682. //
  3683. // accessing 'member' would result in an ambiguity. However, we
  3684. // could be smart enough to qualify the member with the base
  3685. // class, e.g.,
  3686. //
  3687. // c->B::member
  3688. //
  3689. // or
  3690. //
  3691. // c->A::member
  3692. // Find results in this base class (and its bases).
  3693. ShadowContextRAII Shadow(Visited);
  3694. lookupInDeclContext(RD, Result, QualifiedNameLookup,
  3695. /*InBaseClass=*/true);
  3696. }
  3697. }
  3698. // Traverse the contexts of Objective-C classes.
  3699. if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
  3700. // Traverse categories.
  3701. for (auto *Cat : IFace->visible_categories()) {
  3702. ShadowContextRAII Shadow(Visited);
  3703. lookupInDeclContext(Cat, Result, QualifiedNameLookup,
  3704. /*InBaseClass=*/false);
  3705. }
  3706. // Traverse protocols.
  3707. for (auto *I : IFace->all_referenced_protocols()) {
  3708. ShadowContextRAII Shadow(Visited);
  3709. lookupInDeclContext(I, Result, QualifiedNameLookup,
  3710. /*InBaseClass=*/false);
  3711. }
  3712. // Traverse the superclass.
  3713. if (IFace->getSuperClass()) {
  3714. ShadowContextRAII Shadow(Visited);
  3715. lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
  3716. /*InBaseClass=*/true);
  3717. }
  3718. // If there is an implementation, traverse it. We do this to find
  3719. // synthesized ivars.
  3720. if (IFace->getImplementation()) {
  3721. ShadowContextRAII Shadow(Visited);
  3722. lookupInDeclContext(IFace->getImplementation(), Result,
  3723. QualifiedNameLookup, InBaseClass);
  3724. }
  3725. } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
  3726. for (auto *I : Protocol->protocols()) {
  3727. ShadowContextRAII Shadow(Visited);
  3728. lookupInDeclContext(I, Result, QualifiedNameLookup,
  3729. /*InBaseClass=*/false);
  3730. }
  3731. } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
  3732. for (auto *I : Category->protocols()) {
  3733. ShadowContextRAII Shadow(Visited);
  3734. lookupInDeclContext(I, Result, QualifiedNameLookup,
  3735. /*InBaseClass=*/false);
  3736. }
  3737. // If there is an implementation, traverse it.
  3738. if (Category->getImplementation()) {
  3739. ShadowContextRAII Shadow(Visited);
  3740. lookupInDeclContext(Category->getImplementation(), Result,
  3741. QualifiedNameLookup, /*InBaseClass=*/true);
  3742. }
  3743. }
  3744. }
  3745. void lookupInScope(Scope *S, LookupResult &Result,
  3746. UnqualUsingDirectiveSet &UDirs) {
  3747. // No clients run in this mode and it's not supported. Please add tests and
  3748. // remove the assertion if you start relying on it.
  3749. assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
  3750. if (!S)
  3751. return;
  3752. if (!S->getEntity() ||
  3753. (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
  3754. (S->getEntity())->isFunctionOrMethod()) {
  3755. FindLocalExternScope FindLocals(Result);
  3756. // Walk through the declarations in this Scope. The consumer might add new
  3757. // decls to the scope as part of deserialization, so make a copy first.
  3758. SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
  3759. for (Decl *D : ScopeDecls) {
  3760. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  3761. if ((ND = Result.getAcceptableDecl(ND))) {
  3762. Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
  3763. Visited.add(ND);
  3764. }
  3765. }
  3766. }
  3767. DeclContext *Entity = S->getLookupEntity();
  3768. if (Entity) {
  3769. // Look into this scope's declaration context, along with any of its
  3770. // parent lookup contexts (e.g., enclosing classes), up to the point
  3771. // where we hit the context stored in the next outer scope.
  3772. DeclContext *OuterCtx = findOuterContext(S);
  3773. for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
  3774. Ctx = Ctx->getLookupParent()) {
  3775. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
  3776. if (Method->isInstanceMethod()) {
  3777. // For instance methods, look for ivars in the method's interface.
  3778. LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
  3779. Result.getNameLoc(),
  3780. Sema::LookupMemberName);
  3781. if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
  3782. lookupInDeclContext(IFace, IvarResult,
  3783. /*QualifiedNameLookup=*/false,
  3784. /*InBaseClass=*/false);
  3785. }
  3786. }
  3787. // We've already performed all of the name lookup that we need
  3788. // to for Objective-C methods; the next context will be the
  3789. // outer scope.
  3790. break;
  3791. }
  3792. if (Ctx->isFunctionOrMethod())
  3793. continue;
  3794. lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
  3795. /*InBaseClass=*/false);
  3796. }
  3797. } else if (!S->getParent()) {
  3798. // Look into the translation unit scope. We walk through the translation
  3799. // unit's declaration context, because the Scope itself won't have all of
  3800. // the declarations if we loaded a precompiled header.
  3801. // FIXME: We would like the translation unit's Scope object to point to
  3802. // the translation unit, so we don't need this special "if" branch.
  3803. // However, doing so would force the normal C++ name-lookup code to look
  3804. // into the translation unit decl when the IdentifierInfo chains would
  3805. // suffice. Once we fix that problem (which is part of a more general
  3806. // "don't look in DeclContexts unless we have to" optimization), we can
  3807. // eliminate this.
  3808. Entity = Result.getSema().Context.getTranslationUnitDecl();
  3809. lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
  3810. /*InBaseClass=*/false);
  3811. }
  3812. if (Entity) {
  3813. // Lookup visible declarations in any namespaces found by using
  3814. // directives.
  3815. for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
  3816. lookupInDeclContext(
  3817. const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
  3818. /*QualifiedNameLookup=*/false,
  3819. /*InBaseClass=*/false);
  3820. }
  3821. // Lookup names in the parent scope.
  3822. ShadowContextRAII Shadow(Visited);
  3823. lookupInScope(S->getParent(), Result, UDirs);
  3824. }
  3825. private:
  3826. VisibleDeclsRecord Visited;
  3827. VisibleDeclConsumer &Consumer;
  3828. bool IncludeDependentBases;
  3829. bool LoadExternal;
  3830. };
  3831. } // namespace
  3832. void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
  3833. VisibleDeclConsumer &Consumer,
  3834. bool IncludeGlobalScope, bool LoadExternal) {
  3835. LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
  3836. LoadExternal);
  3837. H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
  3838. }
  3839. void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
  3840. VisibleDeclConsumer &Consumer,
  3841. bool IncludeGlobalScope,
  3842. bool IncludeDependentBases, bool LoadExternal) {
  3843. LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
  3844. H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
  3845. }
  3846. /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
  3847. /// If GnuLabelLoc is a valid source location, then this is a definition
  3848. /// of an __label__ label name, otherwise it is a normal label definition
  3849. /// or use.
  3850. LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
  3851. SourceLocation GnuLabelLoc) {
  3852. // Do a lookup to see if we have a label with this name already.
  3853. NamedDecl *Res = nullptr;
  3854. if (GnuLabelLoc.isValid()) {
  3855. // Local label definitions always shadow existing labels.
  3856. Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
  3857. Scope *S = CurScope;
  3858. PushOnScopeChains(Res, S, true);
  3859. return cast<LabelDecl>(Res);
  3860. }
  3861. // Not a GNU local label.
  3862. Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
  3863. // If we found a label, check to see if it is in the same context as us.
  3864. // When in a Block, we don't want to reuse a label in an enclosing function.
  3865. if (Res && Res->getDeclContext() != CurContext)
  3866. Res = nullptr;
  3867. if (!Res) {
  3868. // If not forward referenced or defined already, create the backing decl.
  3869. Res = LabelDecl::Create(Context, CurContext, Loc, II);
  3870. Scope *S = CurScope->getFnParent();
  3871. assert(S && "Not in a function?");
  3872. PushOnScopeChains(Res, S, true);
  3873. }
  3874. return cast<LabelDecl>(Res);
  3875. }
  3876. //===----------------------------------------------------------------------===//
  3877. // Typo correction
  3878. //===----------------------------------------------------------------------===//
  3879. static bool isCandidateViable(CorrectionCandidateCallback &CCC,
  3880. TypoCorrection &Candidate) {
  3881. Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
  3882. return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
  3883. }
  3884. static void LookupPotentialTypoResult(Sema &SemaRef,
  3885. LookupResult &Res,
  3886. IdentifierInfo *Name,
  3887. Scope *S, CXXScopeSpec *SS,
  3888. DeclContext *MemberContext,
  3889. bool EnteringContext,
  3890. bool isObjCIvarLookup,
  3891. bool FindHidden);
  3892. /// Check whether the declarations found for a typo correction are
  3893. /// visible. Set the correction's RequiresImport flag to true if none of the
  3894. /// declarations are visible, false otherwise.
  3895. static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
  3896. TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
  3897. for (/**/; DI != DE; ++DI)
  3898. if (!LookupResult::isVisible(SemaRef, *DI))
  3899. break;
  3900. // No filtering needed if all decls are visible.
  3901. if (DI == DE) {
  3902. TC.setRequiresImport(false);
  3903. return;
  3904. }
  3905. llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
  3906. bool AnyVisibleDecls = !NewDecls.empty();
  3907. for (/**/; DI != DE; ++DI) {
  3908. if (LookupResult::isVisible(SemaRef, *DI)) {
  3909. if (!AnyVisibleDecls) {
  3910. // Found a visible decl, discard all hidden ones.
  3911. AnyVisibleDecls = true;
  3912. NewDecls.clear();
  3913. }
  3914. NewDecls.push_back(*DI);
  3915. } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
  3916. NewDecls.push_back(*DI);
  3917. }
  3918. if (NewDecls.empty())
  3919. TC = TypoCorrection();
  3920. else {
  3921. TC.setCorrectionDecls(NewDecls);
  3922. TC.setRequiresImport(!AnyVisibleDecls);
  3923. }
  3924. }
  3925. // Fill the supplied vector with the IdentifierInfo pointers for each piece of
  3926. // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
  3927. // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
  3928. static void getNestedNameSpecifierIdentifiers(
  3929. NestedNameSpecifier *NNS,
  3930. SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
  3931. if (NestedNameSpecifier *Prefix = NNS->getPrefix())
  3932. getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
  3933. else
  3934. Identifiers.clear();
  3935. const IdentifierInfo *II = nullptr;
  3936. switch (NNS->getKind()) {
  3937. case NestedNameSpecifier::Identifier:
  3938. II = NNS->getAsIdentifier();
  3939. break;
  3940. case NestedNameSpecifier::Namespace:
  3941. if (NNS->getAsNamespace()->isAnonymousNamespace())
  3942. return;
  3943. II = NNS->getAsNamespace()->getIdentifier();
  3944. break;
  3945. case NestedNameSpecifier::NamespaceAlias:
  3946. II = NNS->getAsNamespaceAlias()->getIdentifier();
  3947. break;
  3948. case NestedNameSpecifier::TypeSpecWithTemplate:
  3949. case NestedNameSpecifier::TypeSpec:
  3950. II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
  3951. break;
  3952. case NestedNameSpecifier::Global:
  3953. case NestedNameSpecifier::Super:
  3954. return;
  3955. }
  3956. if (II)
  3957. Identifiers.push_back(II);
  3958. }
  3959. void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
  3960. DeclContext *Ctx, bool InBaseClass) {
  3961. // Don't consider hidden names for typo correction.
  3962. if (Hiding)
  3963. return;
  3964. // Only consider entities with identifiers for names, ignoring
  3965. // special names (constructors, overloaded operators, selectors,
  3966. // etc.).
  3967. IdentifierInfo *Name = ND->getIdentifier();
  3968. if (!Name)
  3969. return;
  3970. // Only consider visible declarations and declarations from modules with
  3971. // names that exactly match.
  3972. if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
  3973. return;
  3974. FoundName(Name->getName());
  3975. }
  3976. void TypoCorrectionConsumer::FoundName(StringRef Name) {
  3977. // Compute the edit distance between the typo and the name of this
  3978. // entity, and add the identifier to the list of results.
  3979. addName(Name, nullptr);
  3980. }
  3981. void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
  3982. // Compute the edit distance between the typo and this keyword,
  3983. // and add the keyword to the list of results.
  3984. addName(Keyword, nullptr, nullptr, true);
  3985. }
  3986. void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
  3987. NestedNameSpecifier *NNS, bool isKeyword) {
  3988. // Use a simple length-based heuristic to determine the minimum possible
  3989. // edit distance. If the minimum isn't good enough, bail out early.
  3990. StringRef TypoStr = Typo->getName();
  3991. unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
  3992. if (MinED && TypoStr.size() / MinED < 3)
  3993. return;
  3994. // Compute an upper bound on the allowable edit distance, so that the
  3995. // edit-distance algorithm can short-circuit.
  3996. unsigned UpperBound = (TypoStr.size() + 2) / 3;
  3997. unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
  3998. if (ED > UpperBound) return;
  3999. TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
  4000. if (isKeyword) TC.makeKeyword();
  4001. TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
  4002. addCorrection(TC);
  4003. }
  4004. static const unsigned MaxTypoDistanceResultSets = 5;
  4005. void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
  4006. StringRef TypoStr = Typo->getName();
  4007. StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
  4008. // For very short typos, ignore potential corrections that have a different
  4009. // base identifier from the typo or which have a normalized edit distance
  4010. // longer than the typo itself.
  4011. if (TypoStr.size() < 3 &&
  4012. (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
  4013. return;
  4014. // If the correction is resolved but is not viable, ignore it.
  4015. if (Correction.isResolved()) {
  4016. checkCorrectionVisibility(SemaRef, Correction);
  4017. if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
  4018. return;
  4019. }
  4020. TypoResultList &CList =
  4021. CorrectionResults[Correction.getEditDistance(false)][Name];
  4022. if (!CList.empty() && !CList.back().isResolved())
  4023. CList.pop_back();
  4024. if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
  4025. auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
  4026. return TypoCorr.getCorrectionDecl() == NewND;
  4027. });
  4028. if (RI != CList.end()) {
  4029. // The Correction refers to a decl already in the list. No insertion is
  4030. // necessary and all further cases will return.
  4031. auto IsDeprecated = [](Decl *D) {
  4032. while (D) {
  4033. if (D->isDeprecated())
  4034. return true;
  4035. D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
  4036. }
  4037. return false;
  4038. };
  4039. // Prefer non deprecated Corrections over deprecated and only then
  4040. // sort using an alphabetical order.
  4041. std::pair<bool, std::string> NewKey = {
  4042. IsDeprecated(Correction.getFoundDecl()),
  4043. Correction.getAsString(SemaRef.getLangOpts())};
  4044. std::pair<bool, std::string> PrevKey = {
  4045. IsDeprecated(RI->getFoundDecl()),
  4046. RI->getAsString(SemaRef.getLangOpts())};
  4047. if (NewKey < PrevKey)
  4048. *RI = Correction;
  4049. return;
  4050. }
  4051. }
  4052. if (CList.empty() || Correction.isResolved())
  4053. CList.push_back(Correction);
  4054. while (CorrectionResults.size() > MaxTypoDistanceResultSets)
  4055. CorrectionResults.erase(std::prev(CorrectionResults.end()));
  4056. }
  4057. void TypoCorrectionConsumer::addNamespaces(
  4058. const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
  4059. SearchNamespaces = true;
  4060. for (auto KNPair : KnownNamespaces)
  4061. Namespaces.addNameSpecifier(KNPair.first);
  4062. bool SSIsTemplate = false;
  4063. if (NestedNameSpecifier *NNS =
  4064. (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
  4065. if (const Type *T = NNS->getAsType())
  4066. SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
  4067. }
  4068. // Do not transform this into an iterator-based loop. The loop body can
  4069. // trigger the creation of further types (through lazy deserialization) and
  4070. // invalid iterators into this list.
  4071. auto &Types = SemaRef.getASTContext().getTypes();
  4072. for (unsigned I = 0; I != Types.size(); ++I) {
  4073. const auto *TI = Types[I];
  4074. if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
  4075. CD = CD->getCanonicalDecl();
  4076. if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
  4077. !CD->isUnion() && CD->getIdentifier() &&
  4078. (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
  4079. (CD->isBeingDefined() || CD->isCompleteDefinition()))
  4080. Namespaces.addNameSpecifier(CD);
  4081. }
  4082. }
  4083. }
  4084. const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
  4085. if (++CurrentTCIndex < ValidatedCorrections.size())
  4086. return ValidatedCorrections[CurrentTCIndex];
  4087. CurrentTCIndex = ValidatedCorrections.size();
  4088. while (!CorrectionResults.empty()) {
  4089. auto DI = CorrectionResults.begin();
  4090. if (DI->second.empty()) {
  4091. CorrectionResults.erase(DI);
  4092. continue;
  4093. }
  4094. auto RI = DI->second.begin();
  4095. if (RI->second.empty()) {
  4096. DI->second.erase(RI);
  4097. performQualifiedLookups();
  4098. continue;
  4099. }
  4100. TypoCorrection TC = RI->second.pop_back_val();
  4101. if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
  4102. ValidatedCorrections.push_back(TC);
  4103. return ValidatedCorrections[CurrentTCIndex];
  4104. }
  4105. }
  4106. return ValidatedCorrections[0]; // The empty correction.
  4107. }
  4108. bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
  4109. IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
  4110. DeclContext *TempMemberContext = MemberContext;
  4111. CXXScopeSpec *TempSS = SS.get();
  4112. retry_lookup:
  4113. LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
  4114. EnteringContext,
  4115. CorrectionValidator->IsObjCIvarLookup,
  4116. Name == Typo && !Candidate.WillReplaceSpecifier());
  4117. switch (Result.getResultKind()) {
  4118. case LookupResult::NotFound:
  4119. case LookupResult::NotFoundInCurrentInstantiation:
  4120. case LookupResult::FoundUnresolvedValue:
  4121. if (TempSS) {
  4122. // Immediately retry the lookup without the given CXXScopeSpec
  4123. TempSS = nullptr;
  4124. Candidate.WillReplaceSpecifier(true);
  4125. goto retry_lookup;
  4126. }
  4127. if (TempMemberContext) {
  4128. if (SS && !TempSS)
  4129. TempSS = SS.get();
  4130. TempMemberContext = nullptr;
  4131. goto retry_lookup;
  4132. }
  4133. if (SearchNamespaces)
  4134. QualifiedResults.push_back(Candidate);
  4135. break;
  4136. case LookupResult::Ambiguous:
  4137. // We don't deal with ambiguities.
  4138. break;
  4139. case LookupResult::Found:
  4140. case LookupResult::FoundOverloaded:
  4141. // Store all of the Decls for overloaded symbols
  4142. for (auto *TRD : Result)
  4143. Candidate.addCorrectionDecl(TRD);
  4144. checkCorrectionVisibility(SemaRef, Candidate);
  4145. if (!isCandidateViable(*CorrectionValidator, Candidate)) {
  4146. if (SearchNamespaces)
  4147. QualifiedResults.push_back(Candidate);
  4148. break;
  4149. }
  4150. Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
  4151. return true;
  4152. }
  4153. return false;
  4154. }
  4155. void TypoCorrectionConsumer::performQualifiedLookups() {
  4156. unsigned TypoLen = Typo->getName().size();
  4157. for (const TypoCorrection &QR : QualifiedResults) {
  4158. for (const auto &NSI : Namespaces) {
  4159. DeclContext *Ctx = NSI.DeclCtx;
  4160. const Type *NSType = NSI.NameSpecifier->getAsType();
  4161. // If the current NestedNameSpecifier refers to a class and the
  4162. // current correction candidate is the name of that class, then skip
  4163. // it as it is unlikely a qualified version of the class' constructor
  4164. // is an appropriate correction.
  4165. if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
  4166. nullptr) {
  4167. if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
  4168. continue;
  4169. }
  4170. TypoCorrection TC(QR);
  4171. TC.ClearCorrectionDecls();
  4172. TC.setCorrectionSpecifier(NSI.NameSpecifier);
  4173. TC.setQualifierDistance(NSI.EditDistance);
  4174. TC.setCallbackDistance(0); // Reset the callback distance
  4175. // If the current correction candidate and namespace combination are
  4176. // too far away from the original typo based on the normalized edit
  4177. // distance, then skip performing a qualified name lookup.
  4178. unsigned TmpED = TC.getEditDistance(true);
  4179. if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
  4180. TypoLen / TmpED < 3)
  4181. continue;
  4182. Result.clear();
  4183. Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
  4184. if (!SemaRef.LookupQualifiedName(Result, Ctx))
  4185. continue;
  4186. // Any corrections added below will be validated in subsequent
  4187. // iterations of the main while() loop over the Consumer's contents.
  4188. switch (Result.getResultKind()) {
  4189. case LookupResult::Found:
  4190. case LookupResult::FoundOverloaded: {
  4191. if (SS && SS->isValid()) {
  4192. std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
  4193. std::string OldQualified;
  4194. llvm::raw_string_ostream OldOStream(OldQualified);
  4195. SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
  4196. OldOStream << Typo->getName();
  4197. // If correction candidate would be an identical written qualified
  4198. // identifier, then the existing CXXScopeSpec probably included a
  4199. // typedef that didn't get accounted for properly.
  4200. if (OldOStream.str() == NewQualified)
  4201. break;
  4202. }
  4203. for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
  4204. TRD != TRDEnd; ++TRD) {
  4205. if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
  4206. NSType ? NSType->getAsCXXRecordDecl()
  4207. : nullptr,
  4208. TRD.getPair()) == Sema::AR_accessible)
  4209. TC.addCorrectionDecl(*TRD);
  4210. }
  4211. if (TC.isResolved()) {
  4212. TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
  4213. addCorrection(TC);
  4214. }
  4215. break;
  4216. }
  4217. case LookupResult::NotFound:
  4218. case LookupResult::NotFoundInCurrentInstantiation:
  4219. case LookupResult::Ambiguous:
  4220. case LookupResult::FoundUnresolvedValue:
  4221. break;
  4222. }
  4223. }
  4224. }
  4225. QualifiedResults.clear();
  4226. }
  4227. TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
  4228. ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
  4229. : Context(Context), CurContextChain(buildContextChain(CurContext)) {
  4230. if (NestedNameSpecifier *NNS =
  4231. CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
  4232. llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
  4233. NNS->print(SpecifierOStream, Context.getPrintingPolicy());
  4234. getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
  4235. }
  4236. // Build the list of identifiers that would be used for an absolute
  4237. // (from the global context) NestedNameSpecifier referring to the current
  4238. // context.
  4239. for (DeclContext *C : llvm::reverse(CurContextChain)) {
  4240. if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
  4241. CurContextIdentifiers.push_back(ND->getIdentifier());
  4242. }
  4243. // Add the global context as a NestedNameSpecifier
  4244. SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
  4245. NestedNameSpecifier::GlobalSpecifier(Context), 1};
  4246. DistanceMap[1].push_back(SI);
  4247. }
  4248. auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
  4249. DeclContext *Start) -> DeclContextList {
  4250. assert(Start && "Building a context chain from a null context");
  4251. DeclContextList Chain;
  4252. for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
  4253. DC = DC->getLookupParent()) {
  4254. NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
  4255. if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
  4256. !(ND && ND->isAnonymousNamespace()))
  4257. Chain.push_back(DC->getPrimaryContext());
  4258. }
  4259. return Chain;
  4260. }
  4261. unsigned
  4262. TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
  4263. DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
  4264. unsigned NumSpecifiers = 0;
  4265. for (DeclContext *C : llvm::reverse(DeclChain)) {
  4266. if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
  4267. NNS = NestedNameSpecifier::Create(Context, NNS, ND);
  4268. ++NumSpecifiers;
  4269. } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
  4270. NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
  4271. RD->getTypeForDecl());
  4272. ++NumSpecifiers;
  4273. }
  4274. }
  4275. return NumSpecifiers;
  4276. }
  4277. void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
  4278. DeclContext *Ctx) {
  4279. NestedNameSpecifier *NNS = nullptr;
  4280. unsigned NumSpecifiers = 0;
  4281. DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
  4282. DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
  4283. // Eliminate common elements from the two DeclContext chains.
  4284. for (DeclContext *C : llvm::reverse(CurContextChain)) {
  4285. if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
  4286. break;
  4287. NamespaceDeclChain.pop_back();
  4288. }
  4289. // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
  4290. NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
  4291. // Add an explicit leading '::' specifier if needed.
  4292. if (NamespaceDeclChain.empty()) {
  4293. // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
  4294. NNS = NestedNameSpecifier::GlobalSpecifier(Context);
  4295. NumSpecifiers =
  4296. buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
  4297. } else if (NamedDecl *ND =
  4298. dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
  4299. IdentifierInfo *Name = ND->getIdentifier();
  4300. bool SameNameSpecifier = false;
  4301. if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
  4302. std::string NewNameSpecifier;
  4303. llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
  4304. SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
  4305. getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
  4306. NNS->print(SpecifierOStream, Context.getPrintingPolicy());
  4307. SpecifierOStream.flush();
  4308. SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
  4309. }
  4310. if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
  4311. // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
  4312. NNS = NestedNameSpecifier::GlobalSpecifier(Context);
  4313. NumSpecifiers =
  4314. buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
  4315. }
  4316. }
  4317. // If the built NestedNameSpecifier would be replacing an existing
  4318. // NestedNameSpecifier, use the number of component identifiers that
  4319. // would need to be changed as the edit distance instead of the number
  4320. // of components in the built NestedNameSpecifier.
  4321. if (NNS && !CurNameSpecifierIdentifiers.empty()) {
  4322. SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
  4323. getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
  4324. NumSpecifiers =
  4325. llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers),
  4326. llvm::ArrayRef(NewNameSpecifierIdentifiers));
  4327. }
  4328. SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
  4329. DistanceMap[NumSpecifiers].push_back(SI);
  4330. }
  4331. /// Perform name lookup for a possible result for typo correction.
  4332. static void LookupPotentialTypoResult(Sema &SemaRef,
  4333. LookupResult &Res,
  4334. IdentifierInfo *Name,
  4335. Scope *S, CXXScopeSpec *SS,
  4336. DeclContext *MemberContext,
  4337. bool EnteringContext,
  4338. bool isObjCIvarLookup,
  4339. bool FindHidden) {
  4340. Res.suppressDiagnostics();
  4341. Res.clear();
  4342. Res.setLookupName(Name);
  4343. Res.setAllowHidden(FindHidden);
  4344. if (MemberContext) {
  4345. if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
  4346. if (isObjCIvarLookup) {
  4347. if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
  4348. Res.addDecl(Ivar);
  4349. Res.resolveKind();
  4350. return;
  4351. }
  4352. }
  4353. if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
  4354. Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
  4355. Res.addDecl(Prop);
  4356. Res.resolveKind();
  4357. return;
  4358. }
  4359. }
  4360. SemaRef.LookupQualifiedName(Res, MemberContext);
  4361. return;
  4362. }
  4363. SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
  4364. EnteringContext);
  4365. // Fake ivar lookup; this should really be part of
  4366. // LookupParsedName.
  4367. if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
  4368. if (Method->isInstanceMethod() && Method->getClassInterface() &&
  4369. (Res.empty() ||
  4370. (Res.isSingleResult() &&
  4371. Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
  4372. if (ObjCIvarDecl *IV
  4373. = Method->getClassInterface()->lookupInstanceVariable(Name)) {
  4374. Res.addDecl(IV);
  4375. Res.resolveKind();
  4376. }
  4377. }
  4378. }
  4379. }
  4380. /// Add keywords to the consumer as possible typo corrections.
  4381. static void AddKeywordsToConsumer(Sema &SemaRef,
  4382. TypoCorrectionConsumer &Consumer,
  4383. Scope *S, CorrectionCandidateCallback &CCC,
  4384. bool AfterNestedNameSpecifier) {
  4385. if (AfterNestedNameSpecifier) {
  4386. // For 'X::', we know exactly which keywords can appear next.
  4387. Consumer.addKeywordResult("template");
  4388. if (CCC.WantExpressionKeywords)
  4389. Consumer.addKeywordResult("operator");
  4390. return;
  4391. }
  4392. if (CCC.WantObjCSuper)
  4393. Consumer.addKeywordResult("super");
  4394. if (CCC.WantTypeSpecifiers) {
  4395. // Add type-specifier keywords to the set of results.
  4396. static const char *const CTypeSpecs[] = {
  4397. "char", "const", "double", "enum", "float", "int", "long", "short",
  4398. "signed", "struct", "union", "unsigned", "void", "volatile",
  4399. "_Complex", "_Imaginary",
  4400. // storage-specifiers as well
  4401. "extern", "inline", "static", "typedef"
  4402. };
  4403. for (const auto *CTS : CTypeSpecs)
  4404. Consumer.addKeywordResult(CTS);
  4405. if (SemaRef.getLangOpts().C99)
  4406. Consumer.addKeywordResult("restrict");
  4407. if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
  4408. Consumer.addKeywordResult("bool");
  4409. else if (SemaRef.getLangOpts().C99)
  4410. Consumer.addKeywordResult("_Bool");
  4411. if (SemaRef.getLangOpts().CPlusPlus) {
  4412. Consumer.addKeywordResult("class");
  4413. Consumer.addKeywordResult("typename");
  4414. Consumer.addKeywordResult("wchar_t");
  4415. if (SemaRef.getLangOpts().CPlusPlus11) {
  4416. Consumer.addKeywordResult("char16_t");
  4417. Consumer.addKeywordResult("char32_t");
  4418. Consumer.addKeywordResult("constexpr");
  4419. Consumer.addKeywordResult("decltype");
  4420. Consumer.addKeywordResult("thread_local");
  4421. }
  4422. }
  4423. if (SemaRef.getLangOpts().GNUKeywords)
  4424. Consumer.addKeywordResult("typeof");
  4425. } else if (CCC.WantFunctionLikeCasts) {
  4426. static const char *const CastableTypeSpecs[] = {
  4427. "char", "double", "float", "int", "long", "short",
  4428. "signed", "unsigned", "void"
  4429. };
  4430. for (auto *kw : CastableTypeSpecs)
  4431. Consumer.addKeywordResult(kw);
  4432. }
  4433. if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
  4434. Consumer.addKeywordResult("const_cast");
  4435. Consumer.addKeywordResult("dynamic_cast");
  4436. Consumer.addKeywordResult("reinterpret_cast");
  4437. Consumer.addKeywordResult("static_cast");
  4438. }
  4439. if (CCC.WantExpressionKeywords) {
  4440. Consumer.addKeywordResult("sizeof");
  4441. if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
  4442. Consumer.addKeywordResult("false");
  4443. Consumer.addKeywordResult("true");
  4444. }
  4445. if (SemaRef.getLangOpts().CPlusPlus) {
  4446. static const char *const CXXExprs[] = {
  4447. "delete", "new", "operator", "throw", "typeid"
  4448. };
  4449. for (const auto *CE : CXXExprs)
  4450. Consumer.addKeywordResult(CE);
  4451. if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
  4452. cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
  4453. Consumer.addKeywordResult("this");
  4454. if (SemaRef.getLangOpts().CPlusPlus11) {
  4455. Consumer.addKeywordResult("alignof");
  4456. Consumer.addKeywordResult("nullptr");
  4457. }
  4458. }
  4459. if (SemaRef.getLangOpts().C11) {
  4460. // FIXME: We should not suggest _Alignof if the alignof macro
  4461. // is present.
  4462. Consumer.addKeywordResult("_Alignof");
  4463. }
  4464. }
  4465. if (CCC.WantRemainingKeywords) {
  4466. if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
  4467. // Statements.
  4468. static const char *const CStmts[] = {
  4469. "do", "else", "for", "goto", "if", "return", "switch", "while" };
  4470. for (const auto *CS : CStmts)
  4471. Consumer.addKeywordResult(CS);
  4472. if (SemaRef.getLangOpts().CPlusPlus) {
  4473. Consumer.addKeywordResult("catch");
  4474. Consumer.addKeywordResult("try");
  4475. }
  4476. if (S && S->getBreakParent())
  4477. Consumer.addKeywordResult("break");
  4478. if (S && S->getContinueParent())
  4479. Consumer.addKeywordResult("continue");
  4480. if (SemaRef.getCurFunction() &&
  4481. !SemaRef.getCurFunction()->SwitchStack.empty()) {
  4482. Consumer.addKeywordResult("case");
  4483. Consumer.addKeywordResult("default");
  4484. }
  4485. } else {
  4486. if (SemaRef.getLangOpts().CPlusPlus) {
  4487. Consumer.addKeywordResult("namespace");
  4488. Consumer.addKeywordResult("template");
  4489. }
  4490. if (S && S->isClassScope()) {
  4491. Consumer.addKeywordResult("explicit");
  4492. Consumer.addKeywordResult("friend");
  4493. Consumer.addKeywordResult("mutable");
  4494. Consumer.addKeywordResult("private");
  4495. Consumer.addKeywordResult("protected");
  4496. Consumer.addKeywordResult("public");
  4497. Consumer.addKeywordResult("virtual");
  4498. }
  4499. }
  4500. if (SemaRef.getLangOpts().CPlusPlus) {
  4501. Consumer.addKeywordResult("using");
  4502. if (SemaRef.getLangOpts().CPlusPlus11)
  4503. Consumer.addKeywordResult("static_assert");
  4504. }
  4505. }
  4506. }
  4507. std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
  4508. const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
  4509. Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
  4510. DeclContext *MemberContext, bool EnteringContext,
  4511. const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
  4512. if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
  4513. DisableTypoCorrection)
  4514. return nullptr;
  4515. // In Microsoft mode, don't perform typo correction in a template member
  4516. // function dependent context because it interferes with the "lookup into
  4517. // dependent bases of class templates" feature.
  4518. if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
  4519. isa<CXXMethodDecl>(CurContext))
  4520. return nullptr;
  4521. // We only attempt to correct typos for identifiers.
  4522. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
  4523. if (!Typo)
  4524. return nullptr;
  4525. // If the scope specifier itself was invalid, don't try to correct
  4526. // typos.
  4527. if (SS && SS->isInvalid())
  4528. return nullptr;
  4529. // Never try to correct typos during any kind of code synthesis.
  4530. if (!CodeSynthesisContexts.empty())
  4531. return nullptr;
  4532. // Don't try to correct 'super'.
  4533. if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
  4534. return nullptr;
  4535. // Abort if typo correction already failed for this specific typo.
  4536. IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
  4537. if (locs != TypoCorrectionFailures.end() &&
  4538. locs->second.count(TypoName.getLoc()))
  4539. return nullptr;
  4540. // Don't try to correct the identifier "vector" when in AltiVec mode.
  4541. // TODO: Figure out why typo correction misbehaves in this case, fix it, and
  4542. // remove this workaround.
  4543. if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
  4544. return nullptr;
  4545. // Provide a stop gap for files that are just seriously broken. Trying
  4546. // to correct all typos can turn into a HUGE performance penalty, causing
  4547. // some files to take minutes to get rejected by the parser.
  4548. unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
  4549. if (Limit && TyposCorrected >= Limit)
  4550. return nullptr;
  4551. ++TyposCorrected;
  4552. // If we're handling a missing symbol error, using modules, and the
  4553. // special search all modules option is used, look for a missing import.
  4554. if (ErrorRecovery && getLangOpts().Modules &&
  4555. getLangOpts().ModulesSearchAll) {
  4556. // The following has the side effect of loading the missing module.
  4557. getModuleLoader().lookupMissingImports(Typo->getName(),
  4558. TypoName.getBeginLoc());
  4559. }
  4560. // Extend the lifetime of the callback. We delayed this until here
  4561. // to avoid allocations in the hot path (which is where no typo correction
  4562. // occurs). Note that CorrectionCandidateCallback is polymorphic and
  4563. // initially stack-allocated.
  4564. std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
  4565. auto Consumer = std::make_unique<TypoCorrectionConsumer>(
  4566. *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
  4567. EnteringContext);
  4568. // Perform name lookup to find visible, similarly-named entities.
  4569. bool IsUnqualifiedLookup = false;
  4570. DeclContext *QualifiedDC = MemberContext;
  4571. if (MemberContext) {
  4572. LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
  4573. // Look in qualified interfaces.
  4574. if (OPT) {
  4575. for (auto *I : OPT->quals())
  4576. LookupVisibleDecls(I, LookupKind, *Consumer);
  4577. }
  4578. } else if (SS && SS->isSet()) {
  4579. QualifiedDC = computeDeclContext(*SS, EnteringContext);
  4580. if (!QualifiedDC)
  4581. return nullptr;
  4582. LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
  4583. } else {
  4584. IsUnqualifiedLookup = true;
  4585. }
  4586. // Determine whether we are going to search in the various namespaces for
  4587. // corrections.
  4588. bool SearchNamespaces
  4589. = getLangOpts().CPlusPlus &&
  4590. (IsUnqualifiedLookup || (SS && SS->isSet()));
  4591. if (IsUnqualifiedLookup || SearchNamespaces) {
  4592. // For unqualified lookup, look through all of the names that we have
  4593. // seen in this translation unit.
  4594. // FIXME: Re-add the ability to skip very unlikely potential corrections.
  4595. for (const auto &I : Context.Idents)
  4596. Consumer->FoundName(I.getKey());
  4597. // Walk through identifiers in external identifier sources.
  4598. // FIXME: Re-add the ability to skip very unlikely potential corrections.
  4599. if (IdentifierInfoLookup *External
  4600. = Context.Idents.getExternalIdentifierLookup()) {
  4601. std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
  4602. do {
  4603. StringRef Name = Iter->Next();
  4604. if (Name.empty())
  4605. break;
  4606. Consumer->FoundName(Name);
  4607. } while (true);
  4608. }
  4609. }
  4610. AddKeywordsToConsumer(*this, *Consumer, S,
  4611. *Consumer->getCorrectionValidator(),
  4612. SS && SS->isNotEmpty());
  4613. // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
  4614. // to search those namespaces.
  4615. if (SearchNamespaces) {
  4616. // Load any externally-known namespaces.
  4617. if (ExternalSource && !LoadedExternalKnownNamespaces) {
  4618. SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
  4619. LoadedExternalKnownNamespaces = true;
  4620. ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
  4621. for (auto *N : ExternalKnownNamespaces)
  4622. KnownNamespaces[N] = true;
  4623. }
  4624. Consumer->addNamespaces(KnownNamespaces);
  4625. }
  4626. return Consumer;
  4627. }
  4628. /// Try to "correct" a typo in the source code by finding
  4629. /// visible declarations whose names are similar to the name that was
  4630. /// present in the source code.
  4631. ///
  4632. /// \param TypoName the \c DeclarationNameInfo structure that contains
  4633. /// the name that was present in the source code along with its location.
  4634. ///
  4635. /// \param LookupKind the name-lookup criteria used to search for the name.
  4636. ///
  4637. /// \param S the scope in which name lookup occurs.
  4638. ///
  4639. /// \param SS the nested-name-specifier that precedes the name we're
  4640. /// looking for, if present.
  4641. ///
  4642. /// \param CCC A CorrectionCandidateCallback object that provides further
  4643. /// validation of typo correction candidates. It also provides flags for
  4644. /// determining the set of keywords permitted.
  4645. ///
  4646. /// \param MemberContext if non-NULL, the context in which to look for
  4647. /// a member access expression.
  4648. ///
  4649. /// \param EnteringContext whether we're entering the context described by
  4650. /// the nested-name-specifier SS.
  4651. ///
  4652. /// \param OPT when non-NULL, the search for visible declarations will
  4653. /// also walk the protocols in the qualified interfaces of \p OPT.
  4654. ///
  4655. /// \returns a \c TypoCorrection containing the corrected name if the typo
  4656. /// along with information such as the \c NamedDecl where the corrected name
  4657. /// was declared, and any additional \c NestedNameSpecifier needed to access
  4658. /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
  4659. TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
  4660. Sema::LookupNameKind LookupKind,
  4661. Scope *S, CXXScopeSpec *SS,
  4662. CorrectionCandidateCallback &CCC,
  4663. CorrectTypoKind Mode,
  4664. DeclContext *MemberContext,
  4665. bool EnteringContext,
  4666. const ObjCObjectPointerType *OPT,
  4667. bool RecordFailure) {
  4668. // Always let the ExternalSource have the first chance at correction, even
  4669. // if we would otherwise have given up.
  4670. if (ExternalSource) {
  4671. if (TypoCorrection Correction =
  4672. ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
  4673. MemberContext, EnteringContext, OPT))
  4674. return Correction;
  4675. }
  4676. // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
  4677. // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
  4678. // some instances of CTC_Unknown, while WantRemainingKeywords is true
  4679. // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
  4680. bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
  4681. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
  4682. auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
  4683. MemberContext, EnteringContext,
  4684. OPT, Mode == CTK_ErrorRecovery);
  4685. if (!Consumer)
  4686. return TypoCorrection();
  4687. // If we haven't found anything, we're done.
  4688. if (Consumer->empty())
  4689. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4690. // Make sure the best edit distance (prior to adding any namespace qualifiers)
  4691. // is not more that about a third of the length of the typo's identifier.
  4692. unsigned ED = Consumer->getBestEditDistance(true);
  4693. unsigned TypoLen = Typo->getName().size();
  4694. if (ED > 0 && TypoLen / ED < 3)
  4695. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4696. TypoCorrection BestTC = Consumer->getNextCorrection();
  4697. TypoCorrection SecondBestTC = Consumer->getNextCorrection();
  4698. if (!BestTC)
  4699. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4700. ED = BestTC.getEditDistance();
  4701. if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
  4702. // If this was an unqualified lookup and we believe the callback
  4703. // object wouldn't have filtered out possible corrections, note
  4704. // that no correction was found.
  4705. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4706. }
  4707. // If only a single name remains, return that result.
  4708. if (!SecondBestTC ||
  4709. SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
  4710. const TypoCorrection &Result = BestTC;
  4711. // Don't correct to a keyword that's the same as the typo; the keyword
  4712. // wasn't actually in scope.
  4713. if (ED == 0 && Result.isKeyword())
  4714. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4715. TypoCorrection TC = Result;
  4716. TC.setCorrectionRange(SS, TypoName);
  4717. checkCorrectionVisibility(*this, TC);
  4718. return TC;
  4719. } else if (SecondBestTC && ObjCMessageReceiver) {
  4720. // Prefer 'super' when we're completing in a message-receiver
  4721. // context.
  4722. if (BestTC.getCorrection().getAsString() != "super") {
  4723. if (SecondBestTC.getCorrection().getAsString() == "super")
  4724. BestTC = SecondBestTC;
  4725. else if ((*Consumer)["super"].front().isKeyword())
  4726. BestTC = (*Consumer)["super"].front();
  4727. }
  4728. // Don't correct to a keyword that's the same as the typo; the keyword
  4729. // wasn't actually in scope.
  4730. if (BestTC.getEditDistance() == 0 ||
  4731. BestTC.getCorrection().getAsString() != "super")
  4732. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  4733. BestTC.setCorrectionRange(SS, TypoName);
  4734. return BestTC;
  4735. }
  4736. // Record the failure's location if needed and return an empty correction. If
  4737. // this was an unqualified lookup and we believe the callback object did not
  4738. // filter out possible corrections, also cache the failure for the typo.
  4739. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
  4740. }
  4741. /// Try to "correct" a typo in the source code by finding
  4742. /// visible declarations whose names are similar to the name that was
  4743. /// present in the source code.
  4744. ///
  4745. /// \param TypoName the \c DeclarationNameInfo structure that contains
  4746. /// the name that was present in the source code along with its location.
  4747. ///
  4748. /// \param LookupKind the name-lookup criteria used to search for the name.
  4749. ///
  4750. /// \param S the scope in which name lookup occurs.
  4751. ///
  4752. /// \param SS the nested-name-specifier that precedes the name we're
  4753. /// looking for, if present.
  4754. ///
  4755. /// \param CCC A CorrectionCandidateCallback object that provides further
  4756. /// validation of typo correction candidates. It also provides flags for
  4757. /// determining the set of keywords permitted.
  4758. ///
  4759. /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
  4760. /// diagnostics when the actual typo correction is attempted.
  4761. ///
  4762. /// \param TRC A TypoRecoveryCallback functor that will be used to build an
  4763. /// Expr from a typo correction candidate.
  4764. ///
  4765. /// \param MemberContext if non-NULL, the context in which to look for
  4766. /// a member access expression.
  4767. ///
  4768. /// \param EnteringContext whether we're entering the context described by
  4769. /// the nested-name-specifier SS.
  4770. ///
  4771. /// \param OPT when non-NULL, the search for visible declarations will
  4772. /// also walk the protocols in the qualified interfaces of \p OPT.
  4773. ///
  4774. /// \returns a new \c TypoExpr that will later be replaced in the AST with an
  4775. /// Expr representing the result of performing typo correction, or nullptr if
  4776. /// typo correction is not possible. If nullptr is returned, no diagnostics will
  4777. /// be emitted and it is the responsibility of the caller to emit any that are
  4778. /// needed.
  4779. TypoExpr *Sema::CorrectTypoDelayed(
  4780. const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
  4781. Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
  4782. TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
  4783. DeclContext *MemberContext, bool EnteringContext,
  4784. const ObjCObjectPointerType *OPT) {
  4785. auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
  4786. MemberContext, EnteringContext,
  4787. OPT, Mode == CTK_ErrorRecovery);
  4788. // Give the external sema source a chance to correct the typo.
  4789. TypoCorrection ExternalTypo;
  4790. if (ExternalSource && Consumer) {
  4791. ExternalTypo = ExternalSource->CorrectTypo(
  4792. TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
  4793. MemberContext, EnteringContext, OPT);
  4794. if (ExternalTypo)
  4795. Consumer->addCorrection(ExternalTypo);
  4796. }
  4797. if (!Consumer || Consumer->empty())
  4798. return nullptr;
  4799. // Make sure the best edit distance (prior to adding any namespace qualifiers)
  4800. // is not more that about a third of the length of the typo's identifier.
  4801. unsigned ED = Consumer->getBestEditDistance(true);
  4802. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
  4803. if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
  4804. return nullptr;
  4805. ExprEvalContexts.back().NumTypos++;
  4806. return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),
  4807. TypoName.getLoc());
  4808. }
  4809. void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
  4810. if (!CDecl) return;
  4811. if (isKeyword())
  4812. CorrectionDecls.clear();
  4813. CorrectionDecls.push_back(CDecl);
  4814. if (!CorrectionName)
  4815. CorrectionName = CDecl->getDeclName();
  4816. }
  4817. std::string TypoCorrection::getAsString(const LangOptions &LO) const {
  4818. if (CorrectionNameSpec) {
  4819. std::string tmpBuffer;
  4820. llvm::raw_string_ostream PrefixOStream(tmpBuffer);
  4821. CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
  4822. PrefixOStream << CorrectionName;
  4823. return PrefixOStream.str();
  4824. }
  4825. return CorrectionName.getAsString();
  4826. }
  4827. bool CorrectionCandidateCallback::ValidateCandidate(
  4828. const TypoCorrection &candidate) {
  4829. if (!candidate.isResolved())
  4830. return true;
  4831. if (candidate.isKeyword())
  4832. return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
  4833. WantRemainingKeywords || WantObjCSuper;
  4834. bool HasNonType = false;
  4835. bool HasStaticMethod = false;
  4836. bool HasNonStaticMethod = false;
  4837. for (Decl *D : candidate) {
  4838. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
  4839. D = FTD->getTemplatedDecl();
  4840. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  4841. if (Method->isStatic())
  4842. HasStaticMethod = true;
  4843. else
  4844. HasNonStaticMethod = true;
  4845. }
  4846. if (!isa<TypeDecl>(D))
  4847. HasNonType = true;
  4848. }
  4849. if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
  4850. !candidate.getCorrectionSpecifier())
  4851. return false;
  4852. return WantTypeSpecifiers || HasNonType;
  4853. }
  4854. FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
  4855. bool HasExplicitTemplateArgs,
  4856. MemberExpr *ME)
  4857. : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
  4858. CurContext(SemaRef.CurContext), MemberFn(ME) {
  4859. WantTypeSpecifiers = false;
  4860. WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
  4861. !HasExplicitTemplateArgs && NumArgs == 1;
  4862. WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
  4863. WantRemainingKeywords = false;
  4864. }
  4865. bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
  4866. if (!candidate.getCorrectionDecl())
  4867. return candidate.isKeyword();
  4868. for (auto *C : candidate) {
  4869. FunctionDecl *FD = nullptr;
  4870. NamedDecl *ND = C->getUnderlyingDecl();
  4871. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  4872. FD = FTD->getTemplatedDecl();
  4873. if (!HasExplicitTemplateArgs && !FD) {
  4874. if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
  4875. // If the Decl is neither a function nor a template function,
  4876. // determine if it is a pointer or reference to a function. If so,
  4877. // check against the number of arguments expected for the pointee.
  4878. QualType ValType = cast<ValueDecl>(ND)->getType();
  4879. if (ValType.isNull())
  4880. continue;
  4881. if (ValType->isAnyPointerType() || ValType->isReferenceType())
  4882. ValType = ValType->getPointeeType();
  4883. if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
  4884. if (FPT->getNumParams() == NumArgs)
  4885. return true;
  4886. }
  4887. }
  4888. // A typo for a function-style cast can look like a function call in C++.
  4889. if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
  4890. : isa<TypeDecl>(ND)) &&
  4891. CurContext->getParentASTContext().getLangOpts().CPlusPlus)
  4892. // Only a class or class template can take two or more arguments.
  4893. return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
  4894. // Skip the current candidate if it is not a FunctionDecl or does not accept
  4895. // the current number of arguments.
  4896. if (!FD || !(FD->getNumParams() >= NumArgs &&
  4897. FD->getMinRequiredArguments() <= NumArgs))
  4898. continue;
  4899. // If the current candidate is a non-static C++ method, skip the candidate
  4900. // unless the method being corrected--or the current DeclContext, if the
  4901. // function being corrected is not a method--is a method in the same class
  4902. // or a descendent class of the candidate's parent class.
  4903. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  4904. if (MemberFn || !MD->isStatic()) {
  4905. CXXMethodDecl *CurMD =
  4906. MemberFn
  4907. ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
  4908. : dyn_cast_or_null<CXXMethodDecl>(CurContext);
  4909. CXXRecordDecl *CurRD =
  4910. CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
  4911. CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
  4912. if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
  4913. continue;
  4914. }
  4915. }
  4916. return true;
  4917. }
  4918. return false;
  4919. }
  4920. void Sema::diagnoseTypo(const TypoCorrection &Correction,
  4921. const PartialDiagnostic &TypoDiag,
  4922. bool ErrorRecovery) {
  4923. diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
  4924. ErrorRecovery);
  4925. }
  4926. /// Find which declaration we should import to provide the definition of
  4927. /// the given declaration.
  4928. static NamedDecl *getDefinitionToImport(NamedDecl *D) {
  4929. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  4930. return VD->getDefinition();
  4931. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  4932. return FD->getDefinition();
  4933. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  4934. return TD->getDefinition();
  4935. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
  4936. return ID->getDefinition();
  4937. if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
  4938. return PD->getDefinition();
  4939. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  4940. if (NamedDecl *TTD = TD->getTemplatedDecl())
  4941. return getDefinitionToImport(TTD);
  4942. return nullptr;
  4943. }
  4944. void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
  4945. MissingImportKind MIK, bool Recover) {
  4946. // Suggest importing a module providing the definition of this entity, if
  4947. // possible.
  4948. NamedDecl *Def = getDefinitionToImport(Decl);
  4949. if (!Def)
  4950. Def = Decl;
  4951. Module *Owner = getOwningModule(Def);
  4952. assert(Owner && "definition of hidden declaration is not in a module");
  4953. llvm::SmallVector<Module*, 8> OwningModules;
  4954. OwningModules.push_back(Owner);
  4955. auto Merged = Context.getModulesWithMergedDefinition(Def);
  4956. OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
  4957. diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
  4958. Recover);
  4959. }
  4960. /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
  4961. /// suggesting the addition of a #include of the specified file.
  4962. static std::string getHeaderNameForHeader(Preprocessor &PP, const FileEntry *E,
  4963. llvm::StringRef IncludingFile) {
  4964. bool IsSystem = false;
  4965. auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
  4966. E, IncludingFile, &IsSystem);
  4967. return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
  4968. }
  4969. void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
  4970. SourceLocation DeclLoc,
  4971. ArrayRef<Module *> Modules,
  4972. MissingImportKind MIK, bool Recover) {
  4973. assert(!Modules.empty());
  4974. auto NotePrevious = [&] {
  4975. // FIXME: Suppress the note backtrace even under
  4976. // -fdiagnostics-show-note-include-stack. We don't care how this
  4977. // declaration was previously reached.
  4978. Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
  4979. };
  4980. // Weed out duplicates from module list.
  4981. llvm::SmallVector<Module*, 8> UniqueModules;
  4982. llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
  4983. for (auto *M : Modules) {
  4984. if (M->isGlobalModule() || M->isPrivateModule())
  4985. continue;
  4986. if (UniqueModuleSet.insert(M).second)
  4987. UniqueModules.push_back(M);
  4988. }
  4989. // Try to find a suitable header-name to #include.
  4990. std::string HeaderName;
  4991. if (const FileEntry *Header =
  4992. PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
  4993. if (const FileEntry *FE =
  4994. SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
  4995. HeaderName = getHeaderNameForHeader(PP, Header, FE->tryGetRealPathName());
  4996. }
  4997. // If we have a #include we should suggest, or if all definition locations
  4998. // were in global module fragments, don't suggest an import.
  4999. if (!HeaderName.empty() || UniqueModules.empty()) {
  5000. // FIXME: Find a smart place to suggest inserting a #include, and add
  5001. // a FixItHint there.
  5002. Diag(UseLoc, diag::err_module_unimported_use_header)
  5003. << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
  5004. // Produce a note showing where the entity was declared.
  5005. NotePrevious();
  5006. if (Recover)
  5007. createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
  5008. return;
  5009. }
  5010. Modules = UniqueModules;
  5011. if (Modules.size() > 1) {
  5012. std::string ModuleList;
  5013. unsigned N = 0;
  5014. for (Module *M : Modules) {
  5015. ModuleList += "\n ";
  5016. if (++N == 5 && N != Modules.size()) {
  5017. ModuleList += "[...]";
  5018. break;
  5019. }
  5020. ModuleList += M->getFullModuleName();
  5021. }
  5022. Diag(UseLoc, diag::err_module_unimported_use_multiple)
  5023. << (int)MIK << Decl << ModuleList;
  5024. } else {
  5025. // FIXME: Add a FixItHint that imports the corresponding module.
  5026. Diag(UseLoc, diag::err_module_unimported_use)
  5027. << (int)MIK << Decl << Modules[0]->getFullModuleName();
  5028. }
  5029. NotePrevious();
  5030. // Try to recover by implicitly importing this module.
  5031. if (Recover)
  5032. createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
  5033. }
  5034. /// Diagnose a successfully-corrected typo. Separated from the correction
  5035. /// itself to allow external validation of the result, etc.
  5036. ///
  5037. /// \param Correction The result of performing typo correction.
  5038. /// \param TypoDiag The diagnostic to produce. This will have the corrected
  5039. /// string added to it (and usually also a fixit).
  5040. /// \param PrevNote A note to use when indicating the location of the entity to
  5041. /// which we are correcting. Will have the correction string added to it.
  5042. /// \param ErrorRecovery If \c true (the default), the caller is going to
  5043. /// recover from the typo as if the corrected string had been typed.
  5044. /// In this case, \c PDiag must be an error, and we will attach a fixit
  5045. /// to it.
  5046. void Sema::diagnoseTypo(const TypoCorrection &Correction,
  5047. const PartialDiagnostic &TypoDiag,
  5048. const PartialDiagnostic &PrevNote,
  5049. bool ErrorRecovery) {
  5050. std::string CorrectedStr = Correction.getAsString(getLangOpts());
  5051. std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
  5052. FixItHint FixTypo = FixItHint::CreateReplacement(
  5053. Correction.getCorrectionRange(), CorrectedStr);
  5054. // Maybe we're just missing a module import.
  5055. if (Correction.requiresImport()) {
  5056. NamedDecl *Decl = Correction.getFoundDecl();
  5057. assert(Decl && "import required but no declaration to import");
  5058. diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
  5059. MissingImportKind::Declaration, ErrorRecovery);
  5060. return;
  5061. }
  5062. Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
  5063. << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
  5064. NamedDecl *ChosenDecl =
  5065. Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
  5066. if (PrevNote.getDiagID() && ChosenDecl)
  5067. Diag(ChosenDecl->getLocation(), PrevNote)
  5068. << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
  5069. // Add any extra diagnostics.
  5070. for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
  5071. Diag(Correction.getCorrectionRange().getBegin(), PD);
  5072. }
  5073. TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
  5074. TypoDiagnosticGenerator TDG,
  5075. TypoRecoveryCallback TRC,
  5076. SourceLocation TypoLoc) {
  5077. assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
  5078. auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);
  5079. auto &State = DelayedTypos[TE];
  5080. State.Consumer = std::move(TCC);
  5081. State.DiagHandler = std::move(TDG);
  5082. State.RecoveryHandler = std::move(TRC);
  5083. if (TE)
  5084. TypoExprs.push_back(TE);
  5085. return TE;
  5086. }
  5087. const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
  5088. auto Entry = DelayedTypos.find(TE);
  5089. assert(Entry != DelayedTypos.end() &&
  5090. "Failed to get the state for a TypoExpr!");
  5091. return Entry->second;
  5092. }
  5093. void Sema::clearDelayedTypo(TypoExpr *TE) {
  5094. DelayedTypos.erase(TE);
  5095. }
  5096. void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
  5097. DeclarationNameInfo Name(II, IILoc);
  5098. LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
  5099. R.suppressDiagnostics();
  5100. R.setHideTags(false);
  5101. LookupName(R, S);
  5102. R.dump();
  5103. }