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