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