SemaLookup.cpp 205 KB

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