SemaLookup.cpp 190 KB

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