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