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