SemaLookup.cpp 205 KB

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