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