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, DE = DI.end(); DI != DE; 642 ++DI) 643 addDecl(*DI); 644 } 645 646 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) { 647 Paths = new CXXBasePaths; 648 Paths->swap(P); 649 addDeclsFromBasePaths(*Paths); 650 resolveKind(); 651 setAmbiguous(AmbiguousBaseSubobjects); 652 } 653 654 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) { 655 Paths = new CXXBasePaths; 656 Paths->swap(P); 657 addDeclsFromBasePaths(*Paths); 658 resolveKind(); 659 setAmbiguous(AmbiguousBaseSubobjectTypes); 660 } 661 662 void LookupResult::print(raw_ostream &Out) { 663 Out << Decls.size() << " result(s)"; 664 if (isAmbiguous()) Out << ", ambiguous"; 665 if (Paths) Out << ", base paths present"; 666 667 for (iterator I = begin(), E = end(); I != E; ++I) { 668 Out << "\n"; 669 (*I)->print(Out, 2); 670 } 671 } 672 673 LLVM_DUMP_METHOD void LookupResult::dump() { 674 llvm::errs() << "lookup results for " << getLookupName().getAsString() 675 << ":\n"; 676 for (NamedDecl *D : *this) 677 D->dump(); 678 } 679 680 /// Diagnose a missing builtin type. 681 static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass, 682 llvm::StringRef Name) { 683 S.Diag(SourceLocation(), diag::err_opencl_type_not_found) 684 << TypeClass << Name; 685 return S.Context.VoidTy; 686 } 687 688 /// Lookup an OpenCL enum type. 689 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) { 690 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(), 691 Sema::LookupTagName); 692 S.LookupName(Result, S.TUScope); 693 if (Result.empty()) 694 return diagOpenCLBuiltinTypeError(S, "enum", Name); 695 EnumDecl *Decl = Result.getAsSingle<EnumDecl>(); 696 if (!Decl) 697 return diagOpenCLBuiltinTypeError(S, "enum", Name); 698 return S.Context.getEnumType(Decl); 699 } 700 701 /// Lookup an OpenCL typedef type. 702 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) { 703 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(), 704 Sema::LookupOrdinaryName); 705 S.LookupName(Result, S.TUScope); 706 if (Result.empty()) 707 return diagOpenCLBuiltinTypeError(S, "typedef", Name); 708 TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>(); 709 if (!Decl) 710 return diagOpenCLBuiltinTypeError(S, "typedef", Name); 711 return S.Context.getTypedefType(Decl); 712 } 713 714 /// Get the QualType instances of the return type and arguments for an OpenCL 715 /// builtin function signature. 716 /// \param S (in) The Sema instance. 717 /// \param OpenCLBuiltin (in) The signature currently handled. 718 /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic 719 /// type used as return type or as argument. 720 /// Only meaningful for generic types, otherwise equals 1. 721 /// \param RetTypes (out) List of the possible return types. 722 /// \param ArgTypes (out) List of the possible argument types. For each 723 /// argument, ArgTypes contains QualTypes for the Cartesian product 724 /// of (vector sizes) x (types) . 725 static void GetQualTypesForOpenCLBuiltin( 726 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt, 727 SmallVector<QualType, 1> &RetTypes, 728 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) { 729 // Get the QualType instances of the return types. 730 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex]; 731 OCL2Qual(S, TypeTable[Sig], RetTypes); 732 GenTypeMaxCnt = RetTypes.size(); 733 734 // Get the QualType instances of the arguments. 735 // First type is the return type, skip it. 736 for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) { 737 SmallVector<QualType, 1> Ty; 738 OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]], 739 Ty); 740 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt; 741 ArgTypes.push_back(std::move(Ty)); 742 } 743 } 744 745 /// Create a list of the candidate function overloads for an OpenCL builtin 746 /// function. 747 /// \param Context (in) The ASTContext instance. 748 /// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic 749 /// type used as return type or as argument. 750 /// Only meaningful for generic types, otherwise equals 1. 751 /// \param FunctionList (out) List of FunctionTypes. 752 /// \param RetTypes (in) List of the possible return types. 753 /// \param ArgTypes (in) List of the possible types for the arguments. 754 static void GetOpenCLBuiltinFctOverloads( 755 ASTContext &Context, unsigned GenTypeMaxCnt, 756 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes, 757 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) { 758 FunctionProtoType::ExtProtoInfo PI( 759 Context.getDefaultCallingConvention(false, false, true)); 760 PI.Variadic = false; 761 762 // 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).begin(); 2234 Path.Decls != Path.Decls.end(); ++Path.Decls) { 2235 if ((*Path.Decls)->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 = [&](DeclContext::lookup_iterator Result) { 2260 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I) 2261 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->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 = [&](DeclContext::lookup_iterator A, 2271 DeclContext::lookup_iterator 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, BIt = B, AEnd, BEnd; 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 (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end(); 2392 I != E; ++I) { 2393 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess, 2394 (*I)->getAccess()); 2395 if (NamedDecl *ND = R.getAcceptableDecl(*I)) 2396 R.addDecl(ND, AS); 2397 } 2398 R.resolveKind(); 2399 return true; 2400 } 2401 2402 /// Performs qualified name lookup or special type of lookup for 2403 /// "__super::" scope specifier. 2404 /// 2405 /// This routine is a convenience overload meant to be called from contexts 2406 /// that need to perform a qualified name lookup with an optional C++ scope 2407 /// specifier that might require special kind of lookup. 2408 /// 2409 /// \param R captures both the lookup criteria and any lookup results found. 2410 /// 2411 /// \param LookupCtx The context in which qualified name lookup will 2412 /// search. 2413 /// 2414 /// \param SS An optional C++ scope-specifier. 2415 /// 2416 /// \returns true if lookup succeeded, false if it failed. 2417 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2418 CXXScopeSpec &SS) { 2419 auto *NNS = SS.getScopeRep(); 2420 if (NNS && NNS->getKind() == NestedNameSpecifier::Super) 2421 return LookupInSuper(R, NNS->getAsRecordDecl()); 2422 else 2423 2424 return LookupQualifiedName(R, LookupCtx); 2425 } 2426 2427 /// Performs name lookup for a name that was parsed in the 2428 /// source code, and may contain a C++ scope specifier. 2429 /// 2430 /// This routine is a convenience routine meant to be called from 2431 /// contexts that receive a name and an optional C++ scope specifier 2432 /// (e.g., "N::M::x"). It will then perform either qualified or 2433 /// unqualified name lookup (with LookupQualifiedName or LookupName, 2434 /// respectively) on the given name and return those results. It will 2435 /// perform a special type of lookup for "__super::" scope specifier. 2436 /// 2437 /// @param S The scope from which unqualified name lookup will 2438 /// begin. 2439 /// 2440 /// @param SS An optional C++ scope-specifier, e.g., "::N::M". 2441 /// 2442 /// @param EnteringContext Indicates whether we are going to enter the 2443 /// context of the scope-specifier SS (if present). 2444 /// 2445 /// @returns True if any decls were found (but possibly ambiguous) 2446 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 2447 bool AllowBuiltinCreation, bool EnteringContext) { 2448 if (SS && SS->isInvalid()) { 2449 // When the scope specifier is invalid, don't even look for 2450 // anything. 2451 return false; 2452 } 2453 2454 if (SS && SS->isSet()) { 2455 NestedNameSpecifier *NNS = SS->getScopeRep(); 2456 if (NNS->getKind() == NestedNameSpecifier::Super) 2457 return LookupInSuper(R, NNS->getAsRecordDecl()); 2458 2459 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { 2460 // We have resolved the scope specifier to a particular declaration 2461 // contex, and will perform name lookup in that context. 2462 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) 2463 return false; 2464 2465 R.setContextRange(SS->getRange()); 2466 return LookupQualifiedName(R, DC); 2467 } 2468 2469 // We could not resolve the scope specified to a specific declaration 2470 // context, which means that SS refers to an unknown specialization. 2471 // Name lookup can't find anything in this case. 2472 R.setNotFoundInCurrentInstantiation(); 2473 R.setContextRange(SS->getRange()); 2474 return false; 2475 } 2476 2477 // Perform unqualified name lookup starting in the given scope. 2478 return LookupName(R, S, AllowBuiltinCreation); 2479 } 2480 2481 /// Perform qualified name lookup into all base classes of the given 2482 /// class. 2483 /// 2484 /// \param R captures both the lookup criteria and any lookup results found. 2485 /// 2486 /// \param Class The context in which qualified name lookup will 2487 /// search. Name lookup will search in all base classes merging the results. 2488 /// 2489 /// @returns True if any decls were found (but possibly ambiguous) 2490 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) { 2491 // The access-control rules we use here are essentially the rules for 2492 // doing a lookup in Class that just magically skipped the direct 2493 // members of Class itself. That is, the naming class is Class, and the 2494 // access includes the access of the base. 2495 for (const auto &BaseSpec : Class->bases()) { 2496 CXXRecordDecl *RD = cast<CXXRecordDecl>( 2497 BaseSpec.getType()->castAs<RecordType>()->getDecl()); 2498 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind()); 2499 Result.setBaseObjectType(Context.getRecordType(Class)); 2500 LookupQualifiedName(Result, RD); 2501 2502 // Copy the lookup results into the target, merging the base's access into 2503 // the path access. 2504 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) { 2505 R.addDecl(I.getDecl(), 2506 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(), 2507 I.getAccess())); 2508 } 2509 2510 Result.suppressDiagnostics(); 2511 } 2512 2513 R.resolveKind(); 2514 R.setNamingClass(Class); 2515 2516 return !R.empty(); 2517 } 2518 2519 /// Produce a diagnostic describing the ambiguity that resulted 2520 /// from name lookup. 2521 /// 2522 /// \param Result The result of the ambiguous lookup to be diagnosed. 2523 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { 2524 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 2525 2526 DeclarationName Name = Result.getLookupName(); 2527 SourceLocation NameLoc = Result.getNameLoc(); 2528 SourceRange LookupRange = Result.getContextRange(); 2529 2530 switch (Result.getAmbiguityKind()) { 2531 case LookupResult::AmbiguousBaseSubobjects: { 2532 CXXBasePaths *Paths = Result.getBasePaths(); 2533 QualType SubobjectType = Paths->front().back().Base->getType(); 2534 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 2535 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 2536 << LookupRange; 2537 2538 DeclContext::lookup_iterator Found = Paths->front().Decls; 2539 while (isa<CXXMethodDecl>(*Found) && 2540 cast<CXXMethodDecl>(*Found)->isStatic()) 2541 ++Found; 2542 2543 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 2544 break; 2545 } 2546 2547 case LookupResult::AmbiguousBaseSubobjectTypes: { 2548 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 2549 << Name << LookupRange; 2550 2551 CXXBasePaths *Paths = Result.getBasePaths(); 2552 std::set<const NamedDecl *> DeclsPrinted; 2553 for (CXXBasePaths::paths_iterator Path = Paths->begin(), 2554 PathEnd = Paths->end(); 2555 Path != PathEnd; ++Path) { 2556 const NamedDecl *D = *Path->Decls; 2557 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace())) 2558 continue; 2559 if (DeclsPrinted.insert(D).second) { 2560 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl())) 2561 Diag(D->getLocation(), diag::note_ambiguous_member_type_found) 2562 << TD->getUnderlyingType(); 2563 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) 2564 Diag(D->getLocation(), diag::note_ambiguous_member_type_found) 2565 << Context.getTypeDeclType(TD); 2566 else 2567 Diag(D->getLocation(), diag::note_ambiguous_member_found); 2568 } 2569 } 2570 break; 2571 } 2572 2573 case LookupResult::AmbiguousTagHiding: { 2574 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; 2575 2576 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls; 2577 2578 for (auto *D : Result) 2579 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 2580 TagDecls.insert(TD); 2581 Diag(TD->getLocation(), diag::note_hidden_tag); 2582 } 2583 2584 for (auto *D : Result) 2585 if (!isa<TagDecl>(D)) 2586 Diag(D->getLocation(), diag::note_hiding_object); 2587 2588 // For recovery purposes, go ahead and implement the hiding. 2589 LookupResult::Filter F = Result.makeFilter(); 2590 while (F.hasNext()) { 2591 if (TagDecls.count(F.next())) 2592 F.erase(); 2593 } 2594 F.done(); 2595 break; 2596 } 2597 2598 case LookupResult::AmbiguousReference: { 2599 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 2600 2601 for (auto *D : Result) 2602 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D; 2603 break; 2604 } 2605 } 2606 } 2607 2608 namespace { 2609 struct AssociatedLookup { 2610 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc, 2611 Sema::AssociatedNamespaceSet &Namespaces, 2612 Sema::AssociatedClassSet &Classes) 2613 : S(S), Namespaces(Namespaces), Classes(Classes), 2614 InstantiationLoc(InstantiationLoc) { 2615 } 2616 2617 bool addClassTransitive(CXXRecordDecl *RD) { 2618 Classes.insert(RD); 2619 return ClassesTransitive.insert(RD); 2620 } 2621 2622 Sema &S; 2623 Sema::AssociatedNamespaceSet &Namespaces; 2624 Sema::AssociatedClassSet &Classes; 2625 SourceLocation InstantiationLoc; 2626 2627 private: 2628 Sema::AssociatedClassSet ClassesTransitive; 2629 }; 2630 } // end anonymous namespace 2631 2632 static void 2633 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); 2634 2635 // Given the declaration context \param Ctx of a class, class template or 2636 // enumeration, add the associated namespaces to \param Namespaces as described 2637 // in [basic.lookup.argdep]p2. 2638 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, 2639 DeclContext *Ctx) { 2640 // The exact wording has been changed in C++14 as a result of 2641 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally 2642 // to all language versions since it is possible to return a local type 2643 // from a lambda in C++11. 2644 // 2645 // C++14 [basic.lookup.argdep]p2: 2646 // If T is a class type [...]. Its associated namespaces are the innermost 2647 // enclosing namespaces of its associated classes. [...] 2648 // 2649 // If T is an enumeration type, its associated namespace is the innermost 2650 // enclosing namespace of its declaration. [...] 2651 2652 // We additionally skip inline namespaces. The innermost non-inline namespace 2653 // contains all names of all its nested inline namespaces anyway, so we can 2654 // replace the entire inline namespace tree with its root. 2655 while (!Ctx->isFileContext() || Ctx->isInlineNamespace()) 2656 Ctx = Ctx->getParent(); 2657 2658 Namespaces.insert(Ctx->getPrimaryContext()); 2659 } 2660 2661 // Add the associated classes and namespaces for argument-dependent 2662 // lookup that involves a template argument (C++ [basic.lookup.argdep]p2). 2663 static void 2664 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 2665 const TemplateArgument &Arg) { 2666 // C++ [basic.lookup.argdep]p2, last bullet: 2667 // -- [...] ; 2668 switch (Arg.getKind()) { 2669 case TemplateArgument::Null: 2670 break; 2671 2672 case TemplateArgument::Type: 2673 // [...] the namespaces and classes associated with the types of the 2674 // template arguments provided for template type parameters (excluding 2675 // template template parameters) 2676 addAssociatedClassesAndNamespaces(Result, Arg.getAsType()); 2677 break; 2678 2679 case TemplateArgument::Template: 2680 case TemplateArgument::TemplateExpansion: { 2681 // [...] the namespaces in which any template template arguments are 2682 // defined; and the classes in which any member templates used as 2683 // template template arguments are defined. 2684 TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); 2685 if (ClassTemplateDecl *ClassTemplate 2686 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) { 2687 DeclContext *Ctx = ClassTemplate->getDeclContext(); 2688 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2689 Result.Classes.insert(EnclosingClass); 2690 // Add the associated namespace for this class. 2691 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2692 } 2693 break; 2694 } 2695 2696 case TemplateArgument::Declaration: 2697 case TemplateArgument::Integral: 2698 case TemplateArgument::Expression: 2699 case TemplateArgument::NullPtr: 2700 // [Note: non-type template arguments do not contribute to the set of 2701 // associated namespaces. ] 2702 break; 2703 2704 case TemplateArgument::Pack: 2705 for (const auto &P : Arg.pack_elements()) 2706 addAssociatedClassesAndNamespaces(Result, P); 2707 break; 2708 } 2709 } 2710 2711 // Add the associated classes and namespaces for argument-dependent lookup 2712 // with an argument of class type (C++ [basic.lookup.argdep]p2). 2713 static void 2714 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 2715 CXXRecordDecl *Class) { 2716 2717 // Just silently ignore anything whose name is __va_list_tag. 2718 if (Class->getDeclName() == Result.S.VAListTagName) 2719 return; 2720 2721 // C++ [basic.lookup.argdep]p2: 2722 // [...] 2723 // -- If T is a class type (including unions), its associated 2724 // classes are: the class itself; the class of which it is a 2725 // member, if any; and its direct and indirect base classes. 2726 // Its associated namespaces are the innermost enclosing 2727 // namespaces of its associated classes. 2728 2729 // Add the class of which it is a member, if any. 2730 DeclContext *Ctx = Class->getDeclContext(); 2731 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2732 Result.Classes.insert(EnclosingClass); 2733 2734 // Add the associated namespace for this class. 2735 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2736 2737 // -- If T is a template-id, its associated namespaces and classes are 2738 // the namespace in which the template is defined; for member 2739 // templates, the member template's class; the namespaces and classes 2740 // associated with the types of the template arguments provided for 2741 // template type parameters (excluding template template parameters); the 2742 // namespaces in which any template template arguments are defined; and 2743 // the classes in which any member templates used as template template 2744 // arguments are defined. [Note: non-type template arguments do not 2745 // contribute to the set of associated namespaces. ] 2746 if (ClassTemplateSpecializationDecl *Spec 2747 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { 2748 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); 2749 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2750 Result.Classes.insert(EnclosingClass); 2751 // Add the associated namespace for this class. 2752 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2753 2754 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 2755 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 2756 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]); 2757 } 2758 2759 // Add the class itself. If we've already transitively visited this class, 2760 // we don't need to visit base classes. 2761 if (!Result.addClassTransitive(Class)) 2762 return; 2763 2764 // Only recurse into base classes for complete types. 2765 if (!Result.S.isCompleteType(Result.InstantiationLoc, 2766 Result.S.Context.getRecordType(Class))) 2767 return; 2768 2769 // Add direct and indirect base classes along with their associated 2770 // namespaces. 2771 SmallVector<CXXRecordDecl *, 32> Bases; 2772 Bases.push_back(Class); 2773 while (!Bases.empty()) { 2774 // Pop this class off the stack. 2775 Class = Bases.pop_back_val(); 2776 2777 // Visit the base classes. 2778 for (const auto &Base : Class->bases()) { 2779 const RecordType *BaseType = Base.getType()->getAs<RecordType>(); 2780 // In dependent contexts, we do ADL twice, and the first time around, 2781 // the base type might be a dependent TemplateSpecializationType, or a 2782 // TemplateTypeParmType. If that happens, simply ignore it. 2783 // FIXME: If we want to support export, we probably need to add the 2784 // namespace of the template in a TemplateSpecializationType, or even 2785 // the classes and namespaces of known non-dependent arguments. 2786 if (!BaseType) 2787 continue; 2788 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 2789 if (Result.addClassTransitive(BaseDecl)) { 2790 // Find the associated namespace for this base class. 2791 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 2792 CollectEnclosingNamespace(Result.Namespaces, BaseCtx); 2793 2794 // Make sure we visit the bases of this base class. 2795 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 2796 Bases.push_back(BaseDecl); 2797 } 2798 } 2799 } 2800 } 2801 2802 // Add the associated classes and namespaces for 2803 // argument-dependent lookup with an argument of type T 2804 // (C++ [basic.lookup.koenig]p2). 2805 static void 2806 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { 2807 // C++ [basic.lookup.koenig]p2: 2808 // 2809 // For each argument type T in the function call, there is a set 2810 // of zero or more associated namespaces and a set of zero or more 2811 // associated classes to be considered. The sets of namespaces and 2812 // classes is determined entirely by the types of the function 2813 // arguments (and the namespace of any template template 2814 // argument). Typedef names and using-declarations used to specify 2815 // the types do not contribute to this set. The sets of namespaces 2816 // and classes are determined in the following way: 2817 2818 SmallVector<const Type *, 16> Queue; 2819 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); 2820 2821 while (true) { 2822 switch (T->getTypeClass()) { 2823 2824 #define TYPE(Class, Base) 2825 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 2826 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2827 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 2828 #define ABSTRACT_TYPE(Class, Base) 2829 #include "clang/AST/TypeNodes.inc" 2830 // T is canonical. We can also ignore dependent types because 2831 // we don't need to do ADL at the definition point, but if we 2832 // wanted to implement template export (or if we find some other 2833 // use for associated classes and namespaces...) this would be 2834 // wrong. 2835 break; 2836 2837 // -- If T is a pointer to U or an array of U, its associated 2838 // namespaces and classes are those associated with U. 2839 case Type::Pointer: 2840 T = cast<PointerType>(T)->getPointeeType().getTypePtr(); 2841 continue; 2842 case Type::ConstantArray: 2843 case Type::IncompleteArray: 2844 case Type::VariableArray: 2845 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 2846 continue; 2847 2848 // -- If T is a fundamental type, its associated sets of 2849 // namespaces and classes are both empty. 2850 case Type::Builtin: 2851 break; 2852 2853 // -- If T is a class type (including unions), its associated 2854 // classes are: the class itself; the class of which it is 2855 // a member, if any; and its direct and indirect base classes. 2856 // Its associated namespaces are the innermost enclosing 2857 // namespaces of its associated classes. 2858 case Type::Record: { 2859 CXXRecordDecl *Class = 2860 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); 2861 addAssociatedClassesAndNamespaces(Result, Class); 2862 break; 2863 } 2864 2865 // -- If T is an enumeration type, its associated namespace 2866 // is the innermost enclosing namespace of its declaration. 2867 // If it is a class member, its associated class is the 2868 // member’s class; else it has no associated class. 2869 case Type::Enum: { 2870 EnumDecl *Enum = cast<EnumType>(T)->getDecl(); 2871 2872 DeclContext *Ctx = Enum->getDeclContext(); 2873 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 2874 Result.Classes.insert(EnclosingClass); 2875 2876 // Add the associated namespace for this enumeration. 2877 CollectEnclosingNamespace(Result.Namespaces, Ctx); 2878 2879 break; 2880 } 2881 2882 // -- If T is a function type, its associated namespaces and 2883 // classes are those associated with the function parameter 2884 // types and those associated with the return type. 2885 case Type::FunctionProto: { 2886 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 2887 for (const auto &Arg : Proto->param_types()) 2888 Queue.push_back(Arg.getTypePtr()); 2889 // fallthrough 2890 LLVM_FALLTHROUGH; 2891 } 2892 case Type::FunctionNoProto: { 2893 const FunctionType *FnType = cast<FunctionType>(T); 2894 T = FnType->getReturnType().getTypePtr(); 2895 continue; 2896 } 2897 2898 // -- If T is a pointer to a member function of a class X, its 2899 // associated namespaces and classes are those associated 2900 // with the function parameter types and return type, 2901 // together with those associated with X. 2902 // 2903 // -- If T is a pointer to a data member of class X, its 2904 // associated namespaces and classes are those associated 2905 // with the member type together with those associated with 2906 // X. 2907 case Type::MemberPointer: { 2908 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); 2909 2910 // Queue up the class type into which this points. 2911 Queue.push_back(MemberPtr->getClass()); 2912 2913 // And directly continue with the pointee type. 2914 T = MemberPtr->getPointeeType().getTypePtr(); 2915 continue; 2916 } 2917 2918 // As an extension, treat this like a normal pointer. 2919 case Type::BlockPointer: 2920 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); 2921 continue; 2922 2923 // References aren't covered by the standard, but that's such an 2924 // obvious defect that we cover them anyway. 2925 case Type::LValueReference: 2926 case Type::RValueReference: 2927 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); 2928 continue; 2929 2930 // These are fundamental types. 2931 case Type::Vector: 2932 case Type::ExtVector: 2933 case Type::ConstantMatrix: 2934 case Type::Complex: 2935 case Type::ExtInt: 2936 break; 2937 2938 // Non-deduced auto types only get here for error cases. 2939 case Type::Auto: 2940 case Type::DeducedTemplateSpecialization: 2941 break; 2942 2943 // If T is an Objective-C object or interface type, or a pointer to an 2944 // object or interface type, the associated namespace is the global 2945 // namespace. 2946 case Type::ObjCObject: 2947 case Type::ObjCInterface: 2948 case Type::ObjCObjectPointer: 2949 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl()); 2950 break; 2951 2952 // Atomic types are just wrappers; use the associations of the 2953 // contained type. 2954 case Type::Atomic: 2955 T = cast<AtomicType>(T)->getValueType().getTypePtr(); 2956 continue; 2957 case Type::Pipe: 2958 T = cast<PipeType>(T)->getElementType().getTypePtr(); 2959 continue; 2960 } 2961 2962 if (Queue.empty()) 2963 break; 2964 T = Queue.pop_back_val(); 2965 } 2966 } 2967 2968 /// Find the associated classes and namespaces for 2969 /// argument-dependent lookup for a call with the given set of 2970 /// arguments. 2971 /// 2972 /// This routine computes the sets of associated classes and associated 2973 /// namespaces searched by argument-dependent lookup 2974 /// (C++ [basic.lookup.argdep]) for a given set of arguments. 2975 void Sema::FindAssociatedClassesAndNamespaces( 2976 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, 2977 AssociatedNamespaceSet &AssociatedNamespaces, 2978 AssociatedClassSet &AssociatedClasses) { 2979 AssociatedNamespaces.clear(); 2980 AssociatedClasses.clear(); 2981 2982 AssociatedLookup Result(*this, InstantiationLoc, 2983 AssociatedNamespaces, AssociatedClasses); 2984 2985 // C++ [basic.lookup.koenig]p2: 2986 // For each argument type T in the function call, there is a set 2987 // of zero or more associated namespaces and a set of zero or more 2988 // associated classes to be considered. The sets of namespaces and 2989 // classes is determined entirely by the types of the function 2990 // arguments (and the namespace of any template template 2991 // argument). 2992 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 2993 Expr *Arg = Args[ArgIdx]; 2994 2995 if (Arg->getType() != Context.OverloadTy) { 2996 addAssociatedClassesAndNamespaces(Result, Arg->getType()); 2997 continue; 2998 } 2999 3000 // [...] In addition, if the argument is the name or address of a 3001 // set of overloaded functions and/or function templates, its 3002 // associated classes and namespaces are the union of those 3003 // associated with each of the members of the set: the namespace 3004 // in which the function or function template is defined and the 3005 // classes and namespaces associated with its (non-dependent) 3006 // parameter types and return type. 3007 OverloadExpr *OE = OverloadExpr::find(Arg).Expression; 3008 3009 for (const NamedDecl *D : OE->decls()) { 3010 // Look through any using declarations to find the underlying function. 3011 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction(); 3012 3013 // Add the classes and namespaces associated with the parameter 3014 // types and return type of this function. 3015 addAssociatedClassesAndNamespaces(Result, FDecl->getType()); 3016 } 3017 } 3018 } 3019 3020 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, 3021 SourceLocation Loc, 3022 LookupNameKind NameKind, 3023 RedeclarationKind Redecl) { 3024 LookupResult R(*this, Name, Loc, NameKind, Redecl); 3025 LookupName(R, S); 3026 return R.getAsSingle<NamedDecl>(); 3027 } 3028 3029 /// Find the protocol with the given name, if any. 3030 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, 3031 SourceLocation IdLoc, 3032 RedeclarationKind Redecl) { 3033 Decl *D = LookupSingleName(TUScope, II, IdLoc, 3034 LookupObjCProtocolName, Redecl); 3035 return cast_or_null<ObjCProtocolDecl>(D); 3036 } 3037 3038 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 3039 UnresolvedSetImpl &Functions) { 3040 // C++ [over.match.oper]p3: 3041 // -- The set of non-member candidates is the result of the 3042 // unqualified lookup of operator@ in the context of the 3043 // expression according to the usual rules for name lookup in 3044 // unqualified function calls (3.4.2) except that all member 3045 // functions are ignored. 3046 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 3047 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); 3048 LookupName(Operators, S); 3049 3050 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 3051 Functions.append(Operators.begin(), Operators.end()); 3052 } 3053 3054 Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD, 3055 CXXSpecialMember SM, 3056 bool ConstArg, 3057 bool VolatileArg, 3058 bool RValueThis, 3059 bool ConstThis, 3060 bool VolatileThis) { 3061 assert(CanDeclareSpecialMemberFunction(RD) && 3062 "doing special member lookup into record that isn't fully complete"); 3063 RD = RD->getDefinition(); 3064 if (RValueThis || ConstThis || VolatileThis) 3065 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) && 3066 "constructors and destructors always have unqualified lvalue this"); 3067 if (ConstArg || VolatileArg) 3068 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) && 3069 "parameter-less special members can't have qualified arguments"); 3070 3071 // FIXME: Get the caller to pass in a location for the lookup. 3072 SourceLocation LookupLoc = RD->getLocation(); 3073 3074 llvm::FoldingSetNodeID ID; 3075 ID.AddPointer(RD); 3076 ID.AddInteger(SM); 3077 ID.AddInteger(ConstArg); 3078 ID.AddInteger(VolatileArg); 3079 ID.AddInteger(RValueThis); 3080 ID.AddInteger(ConstThis); 3081 ID.AddInteger(VolatileThis); 3082 3083 void *InsertPoint; 3084 SpecialMemberOverloadResultEntry *Result = 3085 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint); 3086 3087 // This was already cached 3088 if (Result) 3089 return *Result; 3090 3091 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>(); 3092 Result = new (Result) SpecialMemberOverloadResultEntry(ID); 3093 SpecialMemberCache.InsertNode(Result, InsertPoint); 3094 3095 if (SM == CXXDestructor) { 3096 if (RD->needsImplicitDestructor()) { 3097 runWithSufficientStackSpace(RD->getLocation(), [&] { 3098 DeclareImplicitDestructor(RD); 3099 }); 3100 } 3101 CXXDestructorDecl *DD = RD->getDestructor(); 3102 Result->setMethod(DD); 3103 Result->setKind(DD && !DD->isDeleted() 3104 ? SpecialMemberOverloadResult::Success 3105 : SpecialMemberOverloadResult::NoMemberOrDeleted); 3106 return *Result; 3107 } 3108 3109 // Prepare for overload resolution. Here we construct a synthetic argument 3110 // if necessary and make sure that implicit functions are declared. 3111 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD)); 3112 DeclarationName Name; 3113 Expr *Arg = nullptr; 3114 unsigned NumArgs; 3115 3116 QualType ArgType = CanTy; 3117 ExprValueKind VK = VK_LValue; 3118 3119 if (SM == CXXDefaultConstructor) { 3120 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 3121 NumArgs = 0; 3122 if (RD->needsImplicitDefaultConstructor()) { 3123 runWithSufficientStackSpace(RD->getLocation(), [&] { 3124 DeclareImplicitDefaultConstructor(RD); 3125 }); 3126 } 3127 } else { 3128 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) { 3129 Name = Context.DeclarationNames.getCXXConstructorName(CanTy); 3130 if (RD->needsImplicitCopyConstructor()) { 3131 runWithSufficientStackSpace(RD->getLocation(), [&] { 3132 DeclareImplicitCopyConstructor(RD); 3133 }); 3134 } 3135 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) { 3136 runWithSufficientStackSpace(RD->getLocation(), [&] { 3137 DeclareImplicitMoveConstructor(RD); 3138 }); 3139 } 3140 } else { 3141 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 3142 if (RD->needsImplicitCopyAssignment()) { 3143 runWithSufficientStackSpace(RD->getLocation(), [&] { 3144 DeclareImplicitCopyAssignment(RD); 3145 }); 3146 } 3147 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) { 3148 runWithSufficientStackSpace(RD->getLocation(), [&] { 3149 DeclareImplicitMoveAssignment(RD); 3150 }); 3151 } 3152 } 3153 3154 if (ConstArg) 3155 ArgType.addConst(); 3156 if (VolatileArg) 3157 ArgType.addVolatile(); 3158 3159 // This isn't /really/ specified by the standard, but it's implied 3160 // we should be working from an RValue in the case of move to ensure 3161 // that we prefer to bind to rvalue references, and an LValue in the 3162 // case of copy to ensure we don't bind to rvalue references. 3163 // Possibly an XValue is actually correct in the case of move, but 3164 // there is no semantic difference for class types in this restricted 3165 // case. 3166 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment) 3167 VK = VK_LValue; 3168 else 3169 VK = VK_RValue; 3170 } 3171 3172 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK); 3173 3174 if (SM != CXXDefaultConstructor) { 3175 NumArgs = 1; 3176 Arg = &FakeArg; 3177 } 3178 3179 // Create the object argument 3180 QualType ThisTy = CanTy; 3181 if (ConstThis) 3182 ThisTy.addConst(); 3183 if (VolatileThis) 3184 ThisTy.addVolatile(); 3185 Expr::Classification Classification = 3186 OpaqueValueExpr(LookupLoc, ThisTy, 3187 RValueThis ? VK_RValue : VK_LValue).Classify(Context); 3188 3189 // Now we perform lookup on the name we computed earlier and do overload 3190 // resolution. Lookup is only performed directly into the class since there 3191 // will always be a (possibly implicit) declaration to shadow any others. 3192 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal); 3193 DeclContext::lookup_result R = RD->lookup(Name); 3194 3195 if (R.empty()) { 3196 // We might have no default constructor because we have a lambda's closure 3197 // type, rather than because there's some other declared constructor. 3198 // Every class has a copy/move constructor, copy/move assignment, and 3199 // destructor. 3200 assert(SM == CXXDefaultConstructor && 3201 "lookup for a constructor or assignment operator was empty"); 3202 Result->setMethod(nullptr); 3203 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 3204 return *Result; 3205 } 3206 3207 // Copy the candidates as our processing of them may load new declarations 3208 // from an external source and invalidate lookup_result. 3209 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end()); 3210 3211 for (NamedDecl *CandDecl : Candidates) { 3212 if (CandDecl->isInvalidDecl()) 3213 continue; 3214 3215 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public); 3216 auto CtorInfo = getConstructorInfo(Cand); 3217 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) { 3218 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 3219 AddMethodCandidate(M, Cand, RD, ThisTy, Classification, 3220 llvm::makeArrayRef(&Arg, NumArgs), OCS, true); 3221 else if (CtorInfo) 3222 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl, 3223 llvm::makeArrayRef(&Arg, NumArgs), OCS, 3224 /*SuppressUserConversions*/ true); 3225 else 3226 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS, 3227 /*SuppressUserConversions*/ true); 3228 } else if (FunctionTemplateDecl *Tmpl = 3229 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) { 3230 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) 3231 AddMethodTemplateCandidate( 3232 Tmpl, Cand, RD, nullptr, ThisTy, Classification, 3233 llvm::makeArrayRef(&Arg, NumArgs), OCS, true); 3234 else if (CtorInfo) 3235 AddTemplateOverloadCandidate( 3236 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr, 3237 llvm::makeArrayRef(&Arg, NumArgs), OCS, true); 3238 else 3239 AddTemplateOverloadCandidate( 3240 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true); 3241 } else { 3242 assert(isa<UsingDecl>(Cand.getDecl()) && 3243 "illegal Kind of operator = Decl"); 3244 } 3245 } 3246 3247 OverloadCandidateSet::iterator Best; 3248 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) { 3249 case OR_Success: 3250 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 3251 Result->setKind(SpecialMemberOverloadResult::Success); 3252 break; 3253 3254 case OR_Deleted: 3255 Result->setMethod(cast<CXXMethodDecl>(Best->Function)); 3256 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 3257 break; 3258 3259 case OR_Ambiguous: 3260 Result->setMethod(nullptr); 3261 Result->setKind(SpecialMemberOverloadResult::Ambiguous); 3262 break; 3263 3264 case OR_No_Viable_Function: 3265 Result->setMethod(nullptr); 3266 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); 3267 break; 3268 } 3269 3270 return *Result; 3271 } 3272 3273 /// Look up the default constructor for the given class. 3274 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) { 3275 SpecialMemberOverloadResult Result = 3276 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false, 3277 false, false); 3278 3279 return cast_or_null<CXXConstructorDecl>(Result.getMethod()); 3280 } 3281 3282 /// Look up the copying constructor for the given class. 3283 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class, 3284 unsigned Quals) { 3285 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 3286 "non-const, non-volatile qualifiers for copy ctor arg"); 3287 SpecialMemberOverloadResult Result = 3288 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const, 3289 Quals & Qualifiers::Volatile, false, false, false); 3290 3291 return cast_or_null<CXXConstructorDecl>(Result.getMethod()); 3292 } 3293 3294 /// Look up the moving constructor for the given class. 3295 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class, 3296 unsigned Quals) { 3297 SpecialMemberOverloadResult Result = 3298 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const, 3299 Quals & Qualifiers::Volatile, false, false, false); 3300 3301 return cast_or_null<CXXConstructorDecl>(Result.getMethod()); 3302 } 3303 3304 /// Look up the constructors for the given class. 3305 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { 3306 // If the implicit constructors have not yet been declared, do so now. 3307 if (CanDeclareSpecialMemberFunction(Class)) { 3308 runWithSufficientStackSpace(Class->getLocation(), [&] { 3309 if (Class->needsImplicitDefaultConstructor()) 3310 DeclareImplicitDefaultConstructor(Class); 3311 if (Class->needsImplicitCopyConstructor()) 3312 DeclareImplicitCopyConstructor(Class); 3313 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor()) 3314 DeclareImplicitMoveConstructor(Class); 3315 }); 3316 } 3317 3318 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class)); 3319 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T); 3320 return Class->lookup(Name); 3321 } 3322 3323 /// Look up the copying assignment operator for the given class. 3324 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class, 3325 unsigned Quals, bool RValueThis, 3326 unsigned ThisQuals) { 3327 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 3328 "non-const, non-volatile qualifiers for copy assignment arg"); 3329 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 3330 "non-const, non-volatile qualifiers for copy assignment this"); 3331 SpecialMemberOverloadResult Result = 3332 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const, 3333 Quals & Qualifiers::Volatile, RValueThis, 3334 ThisQuals & Qualifiers::Const, 3335 ThisQuals & Qualifiers::Volatile); 3336 3337 return Result.getMethod(); 3338 } 3339 3340 /// Look up the moving assignment operator for the given class. 3341 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class, 3342 unsigned Quals, 3343 bool RValueThis, 3344 unsigned ThisQuals) { 3345 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && 3346 "non-const, non-volatile qualifiers for copy assignment this"); 3347 SpecialMemberOverloadResult Result = 3348 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const, 3349 Quals & Qualifiers::Volatile, RValueThis, 3350 ThisQuals & Qualifiers::Const, 3351 ThisQuals & Qualifiers::Volatile); 3352 3353 return Result.getMethod(); 3354 } 3355 3356 /// Look for the destructor of the given class. 3357 /// 3358 /// During semantic analysis, this routine should be used in lieu of 3359 /// CXXRecordDecl::getDestructor(). 3360 /// 3361 /// \returns The destructor for this class. 3362 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { 3363 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor, 3364 false, false, false, 3365 false, false).getMethod()); 3366 } 3367 3368 /// LookupLiteralOperator - Determine which literal operator should be used for 3369 /// a user-defined literal, per C++11 [lex.ext]. 3370 /// 3371 /// Normal overload resolution is not used to select which literal operator to 3372 /// call for a user-defined literal. Look up the provided literal operator name, 3373 /// and filter the results to the appropriate set for the given argument types. 3374 Sema::LiteralOperatorLookupResult 3375 Sema::LookupLiteralOperator(Scope *S, LookupResult &R, 3376 ArrayRef<QualType> ArgTys, bool AllowRaw, 3377 bool AllowTemplate, bool AllowStringTemplatePack, 3378 bool DiagnoseMissing, StringLiteral *StringLit) { 3379 LookupName(R, S); 3380 assert(R.getResultKind() != LookupResult::Ambiguous && 3381 "literal operator lookup can't be ambiguous"); 3382 3383 // Filter the lookup results appropriately. 3384 LookupResult::Filter F = R.makeFilter(); 3385 3386 bool AllowCooked = true; 3387 bool FoundRaw = false; 3388 bool FoundTemplate = false; 3389 bool FoundStringTemplatePack = false; 3390 bool FoundCooked = false; 3391 3392 while (F.hasNext()) { 3393 Decl *D = F.next(); 3394 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) 3395 D = USD->getTargetDecl(); 3396 3397 // If the declaration we found is invalid, skip it. 3398 if (D->isInvalidDecl()) { 3399 F.erase(); 3400 continue; 3401 } 3402 3403 bool IsRaw = false; 3404 bool IsTemplate = false; 3405 bool IsStringTemplatePack = false; 3406 bool IsCooked = false; 3407 3408 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3409 if (FD->getNumParams() == 1 && 3410 FD->getParamDecl(0)->getType()->getAs<PointerType>()) 3411 IsRaw = true; 3412 else if (FD->getNumParams() == ArgTys.size()) { 3413 IsCooked = true; 3414 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) { 3415 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType(); 3416 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) { 3417 IsCooked = false; 3418 break; 3419 } 3420 } 3421 } 3422 } 3423 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) { 3424 TemplateParameterList *Params = FD->getTemplateParameters(); 3425 if (Params->size() == 1) { 3426 IsTemplate = true; 3427 if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) { 3428 // Implied but not stated: user-defined integer and floating literals 3429 // only ever use numeric literal operator templates, not templates 3430 // taking a parameter of class type. 3431 F.erase(); 3432 continue; 3433 } 3434 3435 // A string literal template is only considered if the string literal 3436 // is a well-formed template argument for the template parameter. 3437 if (StringLit) { 3438 SFINAETrap Trap(*this); 3439 SmallVector<TemplateArgument, 1> Checked; 3440 TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit); 3441 if (CheckTemplateArgument(Params->getParam(0), Arg, FD, 3442 R.getNameLoc(), R.getNameLoc(), 0, 3443 Checked) || 3444 Trap.hasErrorOccurred()) 3445 IsTemplate = false; 3446 } 3447 } else { 3448 IsStringTemplatePack = true; 3449 } 3450 } 3451 3452 if (AllowTemplate && StringLit && IsTemplate) { 3453 FoundTemplate = true; 3454 AllowRaw = false; 3455 AllowCooked = false; 3456 AllowStringTemplatePack = false; 3457 if (FoundRaw || FoundCooked || FoundStringTemplatePack) { 3458 F.restart(); 3459 FoundRaw = FoundCooked = FoundStringTemplatePack = false; 3460 } 3461 } else if (AllowCooked && IsCooked) { 3462 FoundCooked = true; 3463 AllowRaw = false; 3464 AllowTemplate = StringLit; 3465 AllowStringTemplatePack = false; 3466 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) { 3467 // Go through again and remove the raw and template decls we've 3468 // already found. 3469 F.restart(); 3470 FoundRaw = FoundTemplate = FoundStringTemplatePack = false; 3471 } 3472 } else if (AllowRaw && IsRaw) { 3473 FoundRaw = true; 3474 } else if (AllowTemplate && IsTemplate) { 3475 FoundTemplate = true; 3476 } else if (AllowStringTemplatePack && IsStringTemplatePack) { 3477 FoundStringTemplatePack = true; 3478 } else { 3479 F.erase(); 3480 } 3481 } 3482 3483 F.done(); 3484 3485 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template 3486 // form for string literal operator templates. 3487 if (StringLit && FoundTemplate) 3488 return LOLR_Template; 3489 3490 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching 3491 // parameter type, that is used in preference to a raw literal operator 3492 // or literal operator template. 3493 if (FoundCooked) 3494 return LOLR_Cooked; 3495 3496 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal 3497 // operator template, but not both. 3498 if (FoundRaw && FoundTemplate) { 3499 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 3500 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 3501 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction()); 3502 return LOLR_Error; 3503 } 3504 3505 if (FoundRaw) 3506 return LOLR_Raw; 3507 3508 if (FoundTemplate) 3509 return LOLR_Template; 3510 3511 if (FoundStringTemplatePack) 3512 return LOLR_StringTemplatePack; 3513 3514 // Didn't find anything we could use. 3515 if (DiagnoseMissing) { 3516 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator) 3517 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0] 3518 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw 3519 << (AllowTemplate || AllowStringTemplatePack); 3520 return LOLR_Error; 3521 } 3522 3523 return LOLR_ErrorNoDiagnostic; 3524 } 3525 3526 void ADLResult::insert(NamedDecl *New) { 3527 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; 3528 3529 // If we haven't yet seen a decl for this key, or the last decl 3530 // was exactly this one, we're done. 3531 if (Old == nullptr || Old == New) { 3532 Old = New; 3533 return; 3534 } 3535 3536 // Otherwise, decide which is a more recent redeclaration. 3537 FunctionDecl *OldFD = Old->getAsFunction(); 3538 FunctionDecl *NewFD = New->getAsFunction(); 3539 3540 FunctionDecl *Cursor = NewFD; 3541 while (true) { 3542 Cursor = Cursor->getPreviousDecl(); 3543 3544 // If we got to the end without finding OldFD, OldFD is the newer 3545 // declaration; leave things as they are. 3546 if (!Cursor) return; 3547 3548 // If we do find OldFD, then NewFD is newer. 3549 if (Cursor == OldFD) break; 3550 3551 // Otherwise, keep looking. 3552 } 3553 3554 Old = New; 3555 } 3556 3557 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 3558 ArrayRef<Expr *> Args, ADLResult &Result) { 3559 // Find all of the associated namespaces and classes based on the 3560 // arguments we have. 3561 AssociatedNamespaceSet AssociatedNamespaces; 3562 AssociatedClassSet AssociatedClasses; 3563 FindAssociatedClassesAndNamespaces(Loc, Args, 3564 AssociatedNamespaces, 3565 AssociatedClasses); 3566 3567 // C++ [basic.lookup.argdep]p3: 3568 // Let X be the lookup set produced by unqualified lookup (3.4.1) 3569 // and let Y be the lookup set produced by argument dependent 3570 // lookup (defined as follows). If X contains [...] then Y is 3571 // empty. Otherwise Y is the set of declarations found in the 3572 // namespaces associated with the argument types as described 3573 // below. The set of declarations found by the lookup of the name 3574 // is the union of X and Y. 3575 // 3576 // Here, we compute Y and add its members to the overloaded 3577 // candidate set. 3578 for (auto *NS : AssociatedNamespaces) { 3579 // When considering an associated namespace, the lookup is the 3580 // same as the lookup performed when the associated namespace is 3581 // used as a qualifier (3.4.3.2) except that: 3582 // 3583 // -- Any using-directives in the associated namespace are 3584 // ignored. 3585 // 3586 // -- Any namespace-scope friend functions declared in 3587 // associated classes are visible within their respective 3588 // namespaces even if they are not visible during an ordinary 3589 // lookup (11.4). 3590 DeclContext::lookup_result R = NS->lookup(Name); 3591 for (auto *D : R) { 3592 auto *Underlying = D; 3593 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 3594 Underlying = USD->getTargetDecl(); 3595 3596 if (!isa<FunctionDecl>(Underlying) && 3597 !isa<FunctionTemplateDecl>(Underlying)) 3598 continue; 3599 3600 // The declaration is visible to argument-dependent lookup if either 3601 // it's ordinarily visible or declared as a friend in an associated 3602 // class. 3603 bool Visible = false; 3604 for (D = D->getMostRecentDecl(); D; 3605 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) { 3606 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) { 3607 if (isVisible(D)) { 3608 Visible = true; 3609 break; 3610 } 3611 } else if (D->getFriendObjectKind()) { 3612 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext()); 3613 if (AssociatedClasses.count(RD) && isVisible(D)) { 3614 Visible = true; 3615 break; 3616 } 3617 } 3618 } 3619 3620 // FIXME: Preserve D as the FoundDecl. 3621 if (Visible) 3622 Result.insert(Underlying); 3623 } 3624 } 3625 } 3626 3627 //---------------------------------------------------------------------------- 3628 // Search for all visible declarations. 3629 //---------------------------------------------------------------------------- 3630 VisibleDeclConsumer::~VisibleDeclConsumer() { } 3631 3632 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; } 3633 3634 namespace { 3635 3636 class ShadowContextRAII; 3637 3638 class VisibleDeclsRecord { 3639 public: 3640 /// An entry in the shadow map, which is optimized to store a 3641 /// single declaration (the common case) but can also store a list 3642 /// of declarations. 3643 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry; 3644 3645 private: 3646 /// A mapping from declaration names to the declarations that have 3647 /// this name within a particular scope. 3648 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 3649 3650 /// A list of shadow maps, which is used to model name hiding. 3651 std::list<ShadowMap> ShadowMaps; 3652 3653 /// The declaration contexts we have already visited. 3654 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; 3655 3656 friend class ShadowContextRAII; 3657 3658 public: 3659 /// Determine whether we have already visited this context 3660 /// (and, if not, note that we are going to visit that context now). 3661 bool visitedContext(DeclContext *Ctx) { 3662 return !VisitedContexts.insert(Ctx).second; 3663 } 3664 3665 bool alreadyVisitedContext(DeclContext *Ctx) { 3666 return VisitedContexts.count(Ctx); 3667 } 3668 3669 /// Determine whether the given declaration is hidden in the 3670 /// current scope. 3671 /// 3672 /// \returns the declaration that hides the given declaration, or 3673 /// NULL if no such declaration exists. 3674 NamedDecl *checkHidden(NamedDecl *ND); 3675 3676 /// Add a declaration to the current shadow map. 3677 void add(NamedDecl *ND) { 3678 ShadowMaps.back()[ND->getDeclName()].push_back(ND); 3679 } 3680 }; 3681 3682 /// RAII object that records when we've entered a shadow context. 3683 class ShadowContextRAII { 3684 VisibleDeclsRecord &Visible; 3685 3686 typedef VisibleDeclsRecord::ShadowMap ShadowMap; 3687 3688 public: 3689 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { 3690 Visible.ShadowMaps.emplace_back(); 3691 } 3692 3693 ~ShadowContextRAII() { 3694 Visible.ShadowMaps.pop_back(); 3695 } 3696 }; 3697 3698 } // end anonymous namespace 3699 3700 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { 3701 unsigned IDNS = ND->getIdentifierNamespace(); 3702 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); 3703 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); 3704 SM != SMEnd; ++SM) { 3705 ShadowMap::iterator Pos = SM->find(ND->getDeclName()); 3706 if (Pos == SM->end()) 3707 continue; 3708 3709 for (auto *D : Pos->second) { 3710 // A tag declaration does not hide a non-tag declaration. 3711 if (D->hasTagIdentifierNamespace() && 3712 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 3713 Decl::IDNS_ObjCProtocol))) 3714 continue; 3715 3716 // Protocols are in distinct namespaces from everything else. 3717 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 3718 || (IDNS & Decl::IDNS_ObjCProtocol)) && 3719 D->getIdentifierNamespace() != IDNS) 3720 continue; 3721 3722 // Functions and function templates in the same scope overload 3723 // rather than hide. FIXME: Look for hiding based on function 3724 // signatures! 3725 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 3726 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && 3727 SM == ShadowMaps.rbegin()) 3728 continue; 3729 3730 // A shadow declaration that's created by a resolved using declaration 3731 // is not hidden by the same using declaration. 3732 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) && 3733 cast<UsingShadowDecl>(ND)->getUsingDecl() == D) 3734 continue; 3735 3736 // We've found a declaration that hides this one. 3737 return D; 3738 } 3739 } 3740 3741 return nullptr; 3742 } 3743 3744 namespace { 3745 class LookupVisibleHelper { 3746 public: 3747 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases, 3748 bool LoadExternal) 3749 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases), 3750 LoadExternal(LoadExternal) {} 3751 3752 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind, 3753 bool IncludeGlobalScope) { 3754 // Determine the set of using directives available during 3755 // unqualified name lookup. 3756 Scope *Initial = S; 3757 UnqualUsingDirectiveSet UDirs(SemaRef); 3758 if (SemaRef.getLangOpts().CPlusPlus) { 3759 // Find the first namespace or translation-unit scope. 3760 while (S && !isNamespaceOrTranslationUnitScope(S)) 3761 S = S->getParent(); 3762 3763 UDirs.visitScopeChain(Initial, S); 3764 } 3765 UDirs.done(); 3766 3767 // Look for visible declarations. 3768 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind); 3769 Result.setAllowHidden(Consumer.includeHiddenDecls()); 3770 if (!IncludeGlobalScope) 3771 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl()); 3772 ShadowContextRAII Shadow(Visited); 3773 lookupInScope(Initial, Result, UDirs); 3774 } 3775 3776 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx, 3777 Sema::LookupNameKind Kind, bool IncludeGlobalScope) { 3778 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind); 3779 Result.setAllowHidden(Consumer.includeHiddenDecls()); 3780 if (!IncludeGlobalScope) 3781 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl()); 3782 3783 ShadowContextRAII Shadow(Visited); 3784 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true, 3785 /*InBaseClass=*/false); 3786 } 3787 3788 private: 3789 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result, 3790 bool QualifiedNameLookup, bool InBaseClass) { 3791 if (!Ctx) 3792 return; 3793 3794 // Make sure we don't visit the same context twice. 3795 if (Visited.visitedContext(Ctx->getPrimaryContext())) 3796 return; 3797 3798 Consumer.EnteredContext(Ctx); 3799 3800 // Outside C++, lookup results for the TU live on identifiers. 3801 if (isa<TranslationUnitDecl>(Ctx) && 3802 !Result.getSema().getLangOpts().CPlusPlus) { 3803 auto &S = Result.getSema(); 3804 auto &Idents = S.Context.Idents; 3805 3806 // Ensure all external identifiers are in the identifier table. 3807 if (LoadExternal) 3808 if (IdentifierInfoLookup *External = 3809 Idents.getExternalIdentifierLookup()) { 3810 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); 3811 for (StringRef Name = Iter->Next(); !Name.empty(); 3812 Name = Iter->Next()) 3813 Idents.get(Name); 3814 } 3815 3816 // Walk all lookup results in the TU for each identifier. 3817 for (const auto &Ident : Idents) { 3818 for (auto I = S.IdResolver.begin(Ident.getValue()), 3819 E = S.IdResolver.end(); 3820 I != E; ++I) { 3821 if (S.IdResolver.isDeclInScope(*I, Ctx)) { 3822 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) { 3823 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); 3824 Visited.add(ND); 3825 } 3826 } 3827 } 3828 } 3829 3830 return; 3831 } 3832 3833 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) 3834 Result.getSema().ForceDeclarationOfImplicitMembers(Class); 3835 3836 // We sometimes skip loading namespace-level results (they tend to be huge). 3837 bool Load = LoadExternal || 3838 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx)); 3839 // Enumerate all of the results in this context. 3840 for (DeclContextLookupResult R : 3841 Load ? Ctx->lookups() 3842 : Ctx->noload_lookups(/*PreserveInternalState=*/false)) { 3843 for (auto *D : R) { 3844 if (auto *ND = Result.getAcceptableDecl(D)) { 3845 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); 3846 Visited.add(ND); 3847 } 3848 } 3849 } 3850 3851 // Traverse using directives for qualified name lookup. 3852 if (QualifiedNameLookup) { 3853 ShadowContextRAII Shadow(Visited); 3854 for (auto I : Ctx->using_directives()) { 3855 if (!Result.getSema().isVisible(I)) 3856 continue; 3857 lookupInDeclContext(I->getNominatedNamespace(), Result, 3858 QualifiedNameLookup, InBaseClass); 3859 } 3860 } 3861 3862 // Traverse the contexts of inherited C++ classes. 3863 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 3864 if (!Record->hasDefinition()) 3865 return; 3866 3867 for (const auto &B : Record->bases()) { 3868 QualType BaseType = B.getType(); 3869 3870 RecordDecl *RD; 3871 if (BaseType->isDependentType()) { 3872 if (!IncludeDependentBases) { 3873 // Don't look into dependent bases, because name lookup can't look 3874 // there anyway. 3875 continue; 3876 } 3877 const auto *TST = BaseType->getAs<TemplateSpecializationType>(); 3878 if (!TST) 3879 continue; 3880 TemplateName TN = TST->getTemplateName(); 3881 const auto *TD = 3882 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()); 3883 if (!TD) 3884 continue; 3885 RD = TD->getTemplatedDecl(); 3886 } else { 3887 const auto *Record = BaseType->getAs<RecordType>(); 3888 if (!Record) 3889 continue; 3890 RD = Record->getDecl(); 3891 } 3892 3893 // FIXME: It would be nice to be able to determine whether referencing 3894 // a particular member would be ambiguous. For example, given 3895 // 3896 // struct A { int member; }; 3897 // struct B { int member; }; 3898 // struct C : A, B { }; 3899 // 3900 // void f(C *c) { c->### } 3901 // 3902 // accessing 'member' would result in an ambiguity. However, we 3903 // could be smart enough to qualify the member with the base 3904 // class, e.g., 3905 // 3906 // c->B::member 3907 // 3908 // or 3909 // 3910 // c->A::member 3911 3912 // Find results in this base class (and its bases). 3913 ShadowContextRAII Shadow(Visited); 3914 lookupInDeclContext(RD, Result, QualifiedNameLookup, 3915 /*InBaseClass=*/true); 3916 } 3917 } 3918 3919 // Traverse the contexts of Objective-C classes. 3920 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) { 3921 // Traverse categories. 3922 for (auto *Cat : IFace->visible_categories()) { 3923 ShadowContextRAII Shadow(Visited); 3924 lookupInDeclContext(Cat, Result, QualifiedNameLookup, 3925 /*InBaseClass=*/false); 3926 } 3927 3928 // Traverse protocols. 3929 for (auto *I : IFace->all_referenced_protocols()) { 3930 ShadowContextRAII Shadow(Visited); 3931 lookupInDeclContext(I, Result, QualifiedNameLookup, 3932 /*InBaseClass=*/false); 3933 } 3934 3935 // Traverse the superclass. 3936 if (IFace->getSuperClass()) { 3937 ShadowContextRAII Shadow(Visited); 3938 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup, 3939 /*InBaseClass=*/true); 3940 } 3941 3942 // If there is an implementation, traverse it. We do this to find 3943 // synthesized ivars. 3944 if (IFace->getImplementation()) { 3945 ShadowContextRAII Shadow(Visited); 3946 lookupInDeclContext(IFace->getImplementation(), Result, 3947 QualifiedNameLookup, InBaseClass); 3948 } 3949 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) { 3950 for (auto *I : Protocol->protocols()) { 3951 ShadowContextRAII Shadow(Visited); 3952 lookupInDeclContext(I, Result, QualifiedNameLookup, 3953 /*InBaseClass=*/false); 3954 } 3955 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) { 3956 for (auto *I : Category->protocols()) { 3957 ShadowContextRAII Shadow(Visited); 3958 lookupInDeclContext(I, Result, QualifiedNameLookup, 3959 /*InBaseClass=*/false); 3960 } 3961 3962 // If there is an implementation, traverse it. 3963 if (Category->getImplementation()) { 3964 ShadowContextRAII Shadow(Visited); 3965 lookupInDeclContext(Category->getImplementation(), Result, 3966 QualifiedNameLookup, /*InBaseClass=*/true); 3967 } 3968 } 3969 } 3970 3971 void lookupInScope(Scope *S, LookupResult &Result, 3972 UnqualUsingDirectiveSet &UDirs) { 3973 // No clients run in this mode and it's not supported. Please add tests and 3974 // remove the assertion if you start relying on it. 3975 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope"); 3976 3977 if (!S) 3978 return; 3979 3980 if (!S->getEntity() || 3981 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) || 3982 (S->getEntity())->isFunctionOrMethod()) { 3983 FindLocalExternScope FindLocals(Result); 3984 // Walk through the declarations in this Scope. The consumer might add new 3985 // decls to the scope as part of deserialization, so make a copy first. 3986 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end()); 3987 for (Decl *D : ScopeDecls) { 3988 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 3989 if ((ND = Result.getAcceptableDecl(ND))) { 3990 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false); 3991 Visited.add(ND); 3992 } 3993 } 3994 } 3995 3996 DeclContext *Entity = S->getLookupEntity(); 3997 if (Entity) { 3998 // Look into this scope's declaration context, along with any of its 3999 // parent lookup contexts (e.g., enclosing classes), up to the point 4000 // where we hit the context stored in the next outer scope. 4001 DeclContext *OuterCtx = findOuterContext(S); 4002 4003 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx); 4004 Ctx = Ctx->getLookupParent()) { 4005 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 4006 if (Method->isInstanceMethod()) { 4007 // For instance methods, look for ivars in the method's interface. 4008 LookupResult IvarResult(Result.getSema(), Result.getLookupName(), 4009 Result.getNameLoc(), 4010 Sema::LookupMemberName); 4011 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) { 4012 lookupInDeclContext(IFace, IvarResult, 4013 /*QualifiedNameLookup=*/false, 4014 /*InBaseClass=*/false); 4015 } 4016 } 4017 4018 // We've already performed all of the name lookup that we need 4019 // to for Objective-C methods; the next context will be the 4020 // outer scope. 4021 break; 4022 } 4023 4024 if (Ctx->isFunctionOrMethod()) 4025 continue; 4026 4027 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false, 4028 /*InBaseClass=*/false); 4029 } 4030 } else if (!S->getParent()) { 4031 // Look into the translation unit scope. We walk through the translation 4032 // unit's declaration context, because the Scope itself won't have all of 4033 // the declarations if we loaded a precompiled header. 4034 // FIXME: We would like the translation unit's Scope object to point to 4035 // the translation unit, so we don't need this special "if" branch. 4036 // However, doing so would force the normal C++ name-lookup code to look 4037 // into the translation unit decl when the IdentifierInfo chains would 4038 // suffice. Once we fix that problem (which is part of a more general 4039 // "don't look in DeclContexts unless we have to" optimization), we can 4040 // eliminate this. 4041 Entity = Result.getSema().Context.getTranslationUnitDecl(); 4042 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false, 4043 /*InBaseClass=*/false); 4044 } 4045 4046 if (Entity) { 4047 // Lookup visible declarations in any namespaces found by using 4048 // directives. 4049 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity)) 4050 lookupInDeclContext( 4051 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result, 4052 /*QualifiedNameLookup=*/false, 4053 /*InBaseClass=*/false); 4054 } 4055 4056 // Lookup names in the parent scope. 4057 ShadowContextRAII Shadow(Visited); 4058 lookupInScope(S->getParent(), Result, UDirs); 4059 } 4060 4061 private: 4062 VisibleDeclsRecord Visited; 4063 VisibleDeclConsumer &Consumer; 4064 bool IncludeDependentBases; 4065 bool LoadExternal; 4066 }; 4067 } // namespace 4068 4069 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, 4070 VisibleDeclConsumer &Consumer, 4071 bool IncludeGlobalScope, bool LoadExternal) { 4072 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false, 4073 LoadExternal); 4074 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope); 4075 } 4076 4077 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 4078 VisibleDeclConsumer &Consumer, 4079 bool IncludeGlobalScope, 4080 bool IncludeDependentBases, bool LoadExternal) { 4081 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal); 4082 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope); 4083 } 4084 4085 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. 4086 /// If GnuLabelLoc is a valid source location, then this is a definition 4087 /// of an __label__ label name, otherwise it is a normal label definition 4088 /// or use. 4089 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc, 4090 SourceLocation GnuLabelLoc) { 4091 // Do a lookup to see if we have a label with this name already. 4092 NamedDecl *Res = nullptr; 4093 4094 if (GnuLabelLoc.isValid()) { 4095 // Local label definitions always shadow existing labels. 4096 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc); 4097 Scope *S = CurScope; 4098 PushOnScopeChains(Res, S, true); 4099 return cast<LabelDecl>(Res); 4100 } 4101 4102 // Not a GNU local label. 4103 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration); 4104 // If we found a label, check to see if it is in the same context as us. 4105 // When in a Block, we don't want to reuse a label in an enclosing function. 4106 if (Res && Res->getDeclContext() != CurContext) 4107 Res = nullptr; 4108 if (!Res) { 4109 // If not forward referenced or defined already, create the backing decl. 4110 Res = LabelDecl::Create(Context, CurContext, Loc, II); 4111 Scope *S = CurScope->getFnParent(); 4112 assert(S && "Not in a function?"); 4113 PushOnScopeChains(Res, S, true); 4114 } 4115 return cast<LabelDecl>(Res); 4116 } 4117 4118 //===----------------------------------------------------------------------===// 4119 // Typo correction 4120 //===----------------------------------------------------------------------===// 4121 4122 static bool isCandidateViable(CorrectionCandidateCallback &CCC, 4123 TypoCorrection &Candidate) { 4124 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate)); 4125 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance; 4126 } 4127 4128 static void LookupPotentialTypoResult(Sema &SemaRef, 4129 LookupResult &Res, 4130 IdentifierInfo *Name, 4131 Scope *S, CXXScopeSpec *SS, 4132 DeclContext *MemberContext, 4133 bool EnteringContext, 4134 bool isObjCIvarLookup, 4135 bool FindHidden); 4136 4137 /// Check whether the declarations found for a typo correction are 4138 /// visible. Set the correction's RequiresImport flag to true if none of the 4139 /// declarations are visible, false otherwise. 4140 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) { 4141 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end(); 4142 4143 for (/**/; DI != DE; ++DI) 4144 if (!LookupResult::isVisible(SemaRef, *DI)) 4145 break; 4146 // No filtering needed if all decls are visible. 4147 if (DI == DE) { 4148 TC.setRequiresImport(false); 4149 return; 4150 } 4151 4152 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI); 4153 bool AnyVisibleDecls = !NewDecls.empty(); 4154 4155 for (/**/; DI != DE; ++DI) { 4156 if (LookupResult::isVisible(SemaRef, *DI)) { 4157 if (!AnyVisibleDecls) { 4158 // Found a visible decl, discard all hidden ones. 4159 AnyVisibleDecls = true; 4160 NewDecls.clear(); 4161 } 4162 NewDecls.push_back(*DI); 4163 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate()) 4164 NewDecls.push_back(*DI); 4165 } 4166 4167 if (NewDecls.empty()) 4168 TC = TypoCorrection(); 4169 else { 4170 TC.setCorrectionDecls(NewDecls); 4171 TC.setRequiresImport(!AnyVisibleDecls); 4172 } 4173 } 4174 4175 // Fill the supplied vector with the IdentifierInfo pointers for each piece of 4176 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::", 4177 // fill the vector with the IdentifierInfo pointers for "foo" and "bar"). 4178 static void getNestedNameSpecifierIdentifiers( 4179 NestedNameSpecifier *NNS, 4180 SmallVectorImpl<const IdentifierInfo*> &Identifiers) { 4181 if (NestedNameSpecifier *Prefix = NNS->getPrefix()) 4182 getNestedNameSpecifierIdentifiers(Prefix, Identifiers); 4183 else 4184 Identifiers.clear(); 4185 4186 const IdentifierInfo *II = nullptr; 4187 4188 switch (NNS->getKind()) { 4189 case NestedNameSpecifier::Identifier: 4190 II = NNS->getAsIdentifier(); 4191 break; 4192 4193 case NestedNameSpecifier::Namespace: 4194 if (NNS->getAsNamespace()->isAnonymousNamespace()) 4195 return; 4196 II = NNS->getAsNamespace()->getIdentifier(); 4197 break; 4198 4199 case NestedNameSpecifier::NamespaceAlias: 4200 II = NNS->getAsNamespaceAlias()->getIdentifier(); 4201 break; 4202 4203 case NestedNameSpecifier::TypeSpecWithTemplate: 4204 case NestedNameSpecifier::TypeSpec: 4205 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier(); 4206 break; 4207 4208 case NestedNameSpecifier::Global: 4209 case NestedNameSpecifier::Super: 4210 return; 4211 } 4212 4213 if (II) 4214 Identifiers.push_back(II); 4215 } 4216 4217 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, 4218 DeclContext *Ctx, bool InBaseClass) { 4219 // Don't consider hidden names for typo correction. 4220 if (Hiding) 4221 return; 4222 4223 // Only consider entities with identifiers for names, ignoring 4224 // special names (constructors, overloaded operators, selectors, 4225 // etc.). 4226 IdentifierInfo *Name = ND->getIdentifier(); 4227 if (!Name) 4228 return; 4229 4230 // Only consider visible declarations and declarations from modules with 4231 // names that exactly match. 4232 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo) 4233 return; 4234 4235 FoundName(Name->getName()); 4236 } 4237 4238 void TypoCorrectionConsumer::FoundName(StringRef Name) { 4239 // Compute the edit distance between the typo and the name of this 4240 // entity, and add the identifier to the list of results. 4241 addName(Name, nullptr); 4242 } 4243 4244 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) { 4245 // Compute the edit distance between the typo and this keyword, 4246 // and add the keyword to the list of results. 4247 addName(Keyword, nullptr, nullptr, true); 4248 } 4249 4250 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND, 4251 NestedNameSpecifier *NNS, bool isKeyword) { 4252 // Use a simple length-based heuristic to determine the minimum possible 4253 // edit distance. If the minimum isn't good enough, bail out early. 4254 StringRef TypoStr = Typo->getName(); 4255 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size()); 4256 if (MinED && TypoStr.size() / MinED < 3) 4257 return; 4258 4259 // Compute an upper bound on the allowable edit distance, so that the 4260 // edit-distance algorithm can short-circuit. 4261 unsigned UpperBound = (TypoStr.size() + 2) / 3; 4262 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound); 4263 if (ED > UpperBound) return; 4264 4265 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED); 4266 if (isKeyword) TC.makeKeyword(); 4267 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo()); 4268 addCorrection(TC); 4269 } 4270 4271 static const unsigned MaxTypoDistanceResultSets = 5; 4272 4273 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) { 4274 StringRef TypoStr = Typo->getName(); 4275 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName(); 4276 4277 // For very short typos, ignore potential corrections that have a different 4278 // base identifier from the typo or which have a normalized edit distance 4279 // longer than the typo itself. 4280 if (TypoStr.size() < 3 && 4281 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size())) 4282 return; 4283 4284 // If the correction is resolved but is not viable, ignore it. 4285 if (Correction.isResolved()) { 4286 checkCorrectionVisibility(SemaRef, Correction); 4287 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction)) 4288 return; 4289 } 4290 4291 TypoResultList &CList = 4292 CorrectionResults[Correction.getEditDistance(false)][Name]; 4293 4294 if (!CList.empty() && !CList.back().isResolved()) 4295 CList.pop_back(); 4296 if (NamedDecl *NewND = Correction.getCorrectionDecl()) { 4297 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts()); 4298 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end(); 4299 RI != RIEnd; ++RI) { 4300 // If the Correction refers to a decl already in the result list, 4301 // replace the existing result if the string representation of Correction 4302 // comes before the current result alphabetically, then stop as there is 4303 // nothing more to be done to add Correction to the candidate set. 4304 if (RI->getCorrectionDecl() == NewND) { 4305 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts())) 4306 *RI = Correction; 4307 return; 4308 } 4309 } 4310 } 4311 if (CList.empty() || Correction.isResolved()) 4312 CList.push_back(Correction); 4313 4314 while (CorrectionResults.size() > MaxTypoDistanceResultSets) 4315 CorrectionResults.erase(std::prev(CorrectionResults.end())); 4316 } 4317 4318 void TypoCorrectionConsumer::addNamespaces( 4319 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) { 4320 SearchNamespaces = true; 4321 4322 for (auto KNPair : KnownNamespaces) 4323 Namespaces.addNameSpecifier(KNPair.first); 4324 4325 bool SSIsTemplate = false; 4326 if (NestedNameSpecifier *NNS = 4327 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) { 4328 if (const Type *T = NNS->getAsType()) 4329 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization; 4330 } 4331 // Do not transform this into an iterator-based loop. The loop body can 4332 // trigger the creation of further types (through lazy deserialization) and 4333 // invalid iterators into this list. 4334 auto &Types = SemaRef.getASTContext().getTypes(); 4335 for (unsigned I = 0; I != Types.size(); ++I) { 4336 const auto *TI = Types[I]; 4337 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) { 4338 CD = CD->getCanonicalDecl(); 4339 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() && 4340 !CD->isUnion() && CD->getIdentifier() && 4341 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) && 4342 (CD->isBeingDefined() || CD->isCompleteDefinition())) 4343 Namespaces.addNameSpecifier(CD); 4344 } 4345 } 4346 } 4347 4348 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() { 4349 if (++CurrentTCIndex < ValidatedCorrections.size()) 4350 return ValidatedCorrections[CurrentTCIndex]; 4351 4352 CurrentTCIndex = ValidatedCorrections.size(); 4353 while (!CorrectionResults.empty()) { 4354 auto DI = CorrectionResults.begin(); 4355 if (DI->second.empty()) { 4356 CorrectionResults.erase(DI); 4357 continue; 4358 } 4359 4360 auto RI = DI->second.begin(); 4361 if (RI->second.empty()) { 4362 DI->second.erase(RI); 4363 performQualifiedLookups(); 4364 continue; 4365 } 4366 4367 TypoCorrection TC = RI->second.pop_back_val(); 4368 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) { 4369 ValidatedCorrections.push_back(TC); 4370 return ValidatedCorrections[CurrentTCIndex]; 4371 } 4372 } 4373 return ValidatedCorrections[0]; // The empty correction. 4374 } 4375 4376 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) { 4377 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo(); 4378 DeclContext *TempMemberContext = MemberContext; 4379 CXXScopeSpec *TempSS = SS.get(); 4380 retry_lookup: 4381 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext, 4382 EnteringContext, 4383 CorrectionValidator->IsObjCIvarLookup, 4384 Name == Typo && !Candidate.WillReplaceSpecifier()); 4385 switch (Result.getResultKind()) { 4386 case LookupResult::NotFound: 4387 case LookupResult::NotFoundInCurrentInstantiation: 4388 case LookupResult::FoundUnresolvedValue: 4389 if (TempSS) { 4390 // Immediately retry the lookup without the given CXXScopeSpec 4391 TempSS = nullptr; 4392 Candidate.WillReplaceSpecifier(true); 4393 goto retry_lookup; 4394 } 4395 if (TempMemberContext) { 4396 if (SS && !TempSS) 4397 TempSS = SS.get(); 4398 TempMemberContext = nullptr; 4399 goto retry_lookup; 4400 } 4401 if (SearchNamespaces) 4402 QualifiedResults.push_back(Candidate); 4403 break; 4404 4405 case LookupResult::Ambiguous: 4406 // We don't deal with ambiguities. 4407 break; 4408 4409 case LookupResult::Found: 4410 case LookupResult::FoundOverloaded: 4411 // Store all of the Decls for overloaded symbols 4412 for (auto *TRD : Result) 4413 Candidate.addCorrectionDecl(TRD); 4414 checkCorrectionVisibility(SemaRef, Candidate); 4415 if (!isCandidateViable(*CorrectionValidator, Candidate)) { 4416 if (SearchNamespaces) 4417 QualifiedResults.push_back(Candidate); 4418 break; 4419 } 4420 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo()); 4421 return true; 4422 } 4423 return false; 4424 } 4425 4426 void TypoCorrectionConsumer::performQualifiedLookups() { 4427 unsigned TypoLen = Typo->getName().size(); 4428 for (const TypoCorrection &QR : QualifiedResults) { 4429 for (const auto &NSI : Namespaces) { 4430 DeclContext *Ctx = NSI.DeclCtx; 4431 const Type *NSType = NSI.NameSpecifier->getAsType(); 4432 4433 // If the current NestedNameSpecifier refers to a class and the 4434 // current correction candidate is the name of that class, then skip 4435 // it as it is unlikely a qualified version of the class' constructor 4436 // is an appropriate correction. 4437 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 4438 nullptr) { 4439 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo()) 4440 continue; 4441 } 4442 4443 TypoCorrection TC(QR); 4444 TC.ClearCorrectionDecls(); 4445 TC.setCorrectionSpecifier(NSI.NameSpecifier); 4446 TC.setQualifierDistance(NSI.EditDistance); 4447 TC.setCallbackDistance(0); // Reset the callback distance 4448 4449 // If the current correction candidate and namespace combination are 4450 // too far away from the original typo based on the normalized edit 4451 // distance, then skip performing a qualified name lookup. 4452 unsigned TmpED = TC.getEditDistance(true); 4453 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED && 4454 TypoLen / TmpED < 3) 4455 continue; 4456 4457 Result.clear(); 4458 Result.setLookupName(QR.getCorrectionAsIdentifierInfo()); 4459 if (!SemaRef.LookupQualifiedName(Result, Ctx)) 4460 continue; 4461 4462 // Any corrections added below will be validated in subsequent 4463 // iterations of the main while() loop over the Consumer's contents. 4464 switch (Result.getResultKind()) { 4465 case LookupResult::Found: 4466 case LookupResult::FoundOverloaded: { 4467 if (SS && SS->isValid()) { 4468 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts()); 4469 std::string OldQualified; 4470 llvm::raw_string_ostream OldOStream(OldQualified); 4471 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy()); 4472 OldOStream << Typo->getName(); 4473 // If correction candidate would be an identical written qualified 4474 // identifier, then the existing CXXScopeSpec probably included a 4475 // typedef that didn't get accounted for properly. 4476 if (OldOStream.str() == NewQualified) 4477 break; 4478 } 4479 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end(); 4480 TRD != TRDEnd; ++TRD) { 4481 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(), 4482 NSType ? NSType->getAsCXXRecordDecl() 4483 : nullptr, 4484 TRD.getPair()) == Sema::AR_accessible) 4485 TC.addCorrectionDecl(*TRD); 4486 } 4487 if (TC.isResolved()) { 4488 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo()); 4489 addCorrection(TC); 4490 } 4491 break; 4492 } 4493 case LookupResult::NotFound: 4494 case LookupResult::NotFoundInCurrentInstantiation: 4495 case LookupResult::Ambiguous: 4496 case LookupResult::FoundUnresolvedValue: 4497 break; 4498 } 4499 } 4500 } 4501 QualifiedResults.clear(); 4502 } 4503 4504 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet( 4505 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec) 4506 : Context(Context), CurContextChain(buildContextChain(CurContext)) { 4507 if (NestedNameSpecifier *NNS = 4508 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) { 4509 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier); 4510 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 4511 4512 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers); 4513 } 4514 // Build the list of identifiers that would be used for an absolute 4515 // (from the global context) NestedNameSpecifier referring to the current 4516 // context. 4517 for (DeclContext *C : llvm::reverse(CurContextChain)) { 4518 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) 4519 CurContextIdentifiers.push_back(ND->getIdentifier()); 4520 } 4521 4522 // Add the global context as a NestedNameSpecifier 4523 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()), 4524 NestedNameSpecifier::GlobalSpecifier(Context), 1}; 4525 DistanceMap[1].push_back(SI); 4526 } 4527 4528 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain( 4529 DeclContext *Start) -> DeclContextList { 4530 assert(Start && "Building a context chain from a null context"); 4531 DeclContextList Chain; 4532 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr; 4533 DC = DC->getLookupParent()) { 4534 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC); 4535 if (!DC->isInlineNamespace() && !DC->isTransparentContext() && 4536 !(ND && ND->isAnonymousNamespace())) 4537 Chain.push_back(DC->getPrimaryContext()); 4538 } 4539 return Chain; 4540 } 4541 4542 unsigned 4543 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier( 4544 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) { 4545 unsigned NumSpecifiers = 0; 4546 for (DeclContext *C : llvm::reverse(DeclChain)) { 4547 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) { 4548 NNS = NestedNameSpecifier::Create(Context, NNS, ND); 4549 ++NumSpecifiers; 4550 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) { 4551 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(), 4552 RD->getTypeForDecl()); 4553 ++NumSpecifiers; 4554 } 4555 } 4556 return NumSpecifiers; 4557 } 4558 4559 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier( 4560 DeclContext *Ctx) { 4561 NestedNameSpecifier *NNS = nullptr; 4562 unsigned NumSpecifiers = 0; 4563 DeclContextList NamespaceDeclChain(buildContextChain(Ctx)); 4564 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain); 4565 4566 // Eliminate common elements from the two DeclContext chains. 4567 for (DeclContext *C : llvm::reverse(CurContextChain)) { 4568 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C) 4569 break; 4570 NamespaceDeclChain.pop_back(); 4571 } 4572 4573 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain 4574 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS); 4575 4576 // Add an explicit leading '::' specifier if needed. 4577 if (NamespaceDeclChain.empty()) { 4578 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 4579 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 4580 NumSpecifiers = 4581 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); 4582 } else if (NamedDecl *ND = 4583 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) { 4584 IdentifierInfo *Name = ND->getIdentifier(); 4585 bool SameNameSpecifier = false; 4586 if (std::find(CurNameSpecifierIdentifiers.begin(), 4587 CurNameSpecifierIdentifiers.end(), 4588 Name) != CurNameSpecifierIdentifiers.end()) { 4589 std::string NewNameSpecifier; 4590 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier); 4591 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers; 4592 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 4593 NNS->print(SpecifierOStream, Context.getPrintingPolicy()); 4594 SpecifierOStream.flush(); 4595 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier; 4596 } 4597 if (SameNameSpecifier || llvm::find(CurContextIdentifiers, Name) != 4598 CurContextIdentifiers.end()) { 4599 // Rebuild the NestedNameSpecifier as a globally-qualified specifier. 4600 NNS = NestedNameSpecifier::GlobalSpecifier(Context); 4601 NumSpecifiers = 4602 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); 4603 } 4604 } 4605 4606 // If the built NestedNameSpecifier would be replacing an existing 4607 // NestedNameSpecifier, use the number of component identifiers that 4608 // would need to be changed as the edit distance instead of the number 4609 // of components in the built NestedNameSpecifier. 4610 if (NNS && !CurNameSpecifierIdentifiers.empty()) { 4611 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers; 4612 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); 4613 NumSpecifiers = llvm::ComputeEditDistance( 4614 llvm::makeArrayRef(CurNameSpecifierIdentifiers), 4615 llvm::makeArrayRef(NewNameSpecifierIdentifiers)); 4616 } 4617 4618 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers}; 4619 DistanceMap[NumSpecifiers].push_back(SI); 4620 } 4621 4622 /// Perform name lookup for a possible result for typo correction. 4623 static void LookupPotentialTypoResult(Sema &SemaRef, 4624 LookupResult &Res, 4625 IdentifierInfo *Name, 4626 Scope *S, CXXScopeSpec *SS, 4627 DeclContext *MemberContext, 4628 bool EnteringContext, 4629 bool isObjCIvarLookup, 4630 bool FindHidden) { 4631 Res.suppressDiagnostics(); 4632 Res.clear(); 4633 Res.setLookupName(Name); 4634 Res.setAllowHidden(FindHidden); 4635 if (MemberContext) { 4636 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) { 4637 if (isObjCIvarLookup) { 4638 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) { 4639 Res.addDecl(Ivar); 4640 Res.resolveKind(); 4641 return; 4642 } 4643 } 4644 4645 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration( 4646 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 4647 Res.addDecl(Prop); 4648 Res.resolveKind(); 4649 return; 4650 } 4651 } 4652 4653 SemaRef.LookupQualifiedName(Res, MemberContext); 4654 return; 4655 } 4656 4657 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, 4658 EnteringContext); 4659 4660 // Fake ivar lookup; this should really be part of 4661 // LookupParsedName. 4662 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 4663 if (Method->isInstanceMethod() && Method->getClassInterface() && 4664 (Res.empty() || 4665 (Res.isSingleResult() && 4666 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) { 4667 if (ObjCIvarDecl *IV 4668 = Method->getClassInterface()->lookupInstanceVariable(Name)) { 4669 Res.addDecl(IV); 4670 Res.resolveKind(); 4671 } 4672 } 4673 } 4674 } 4675 4676 /// Add keywords to the consumer as possible typo corrections. 4677 static void AddKeywordsToConsumer(Sema &SemaRef, 4678 TypoCorrectionConsumer &Consumer, 4679 Scope *S, CorrectionCandidateCallback &CCC, 4680 bool AfterNestedNameSpecifier) { 4681 if (AfterNestedNameSpecifier) { 4682 // For 'X::', we know exactly which keywords can appear next. 4683 Consumer.addKeywordResult("template"); 4684 if (CCC.WantExpressionKeywords) 4685 Consumer.addKeywordResult("operator"); 4686 return; 4687 } 4688 4689 if (CCC.WantObjCSuper) 4690 Consumer.addKeywordResult("super"); 4691 4692 if (CCC.WantTypeSpecifiers) { 4693 // Add type-specifier keywords to the set of results. 4694 static const char *const CTypeSpecs[] = { 4695 "char", "const", "double", "enum", "float", "int", "long", "short", 4696 "signed", "struct", "union", "unsigned", "void", "volatile", 4697 "_Complex", "_Imaginary", 4698 // storage-specifiers as well 4699 "extern", "inline", "static", "typedef" 4700 }; 4701 4702 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs); 4703 for (unsigned I = 0; I != NumCTypeSpecs; ++I) 4704 Consumer.addKeywordResult(CTypeSpecs[I]); 4705 4706 if (SemaRef.getLangOpts().C99) 4707 Consumer.addKeywordResult("restrict"); 4708 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) 4709 Consumer.addKeywordResult("bool"); 4710 else if (SemaRef.getLangOpts().C99) 4711 Consumer.addKeywordResult("_Bool"); 4712 4713 if (SemaRef.getLangOpts().CPlusPlus) { 4714 Consumer.addKeywordResult("class"); 4715 Consumer.addKeywordResult("typename"); 4716 Consumer.addKeywordResult("wchar_t"); 4717 4718 if (SemaRef.getLangOpts().CPlusPlus11) { 4719 Consumer.addKeywordResult("char16_t"); 4720 Consumer.addKeywordResult("char32_t"); 4721 Consumer.addKeywordResult("constexpr"); 4722 Consumer.addKeywordResult("decltype"); 4723 Consumer.addKeywordResult("thread_local"); 4724 } 4725 } 4726 4727 if (SemaRef.getLangOpts().GNUKeywords) 4728 Consumer.addKeywordResult("typeof"); 4729 } else if (CCC.WantFunctionLikeCasts) { 4730 static const char *const CastableTypeSpecs[] = { 4731 "char", "double", "float", "int", "long", "short", 4732 "signed", "unsigned", "void" 4733 }; 4734 for (auto *kw : CastableTypeSpecs) 4735 Consumer.addKeywordResult(kw); 4736 } 4737 4738 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) { 4739 Consumer.addKeywordResult("const_cast"); 4740 Consumer.addKeywordResult("dynamic_cast"); 4741 Consumer.addKeywordResult("reinterpret_cast"); 4742 Consumer.addKeywordResult("static_cast"); 4743 } 4744 4745 if (CCC.WantExpressionKeywords) { 4746 Consumer.addKeywordResult("sizeof"); 4747 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) { 4748 Consumer.addKeywordResult("false"); 4749 Consumer.addKeywordResult("true"); 4750 } 4751 4752 if (SemaRef.getLangOpts().CPlusPlus) { 4753 static const char *const CXXExprs[] = { 4754 "delete", "new", "operator", "throw", "typeid" 4755 }; 4756 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs); 4757 for (unsigned I = 0; I != NumCXXExprs; ++I) 4758 Consumer.addKeywordResult(CXXExprs[I]); 4759 4760 if (isa<CXXMethodDecl>(SemaRef.CurContext) && 4761 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance()) 4762 Consumer.addKeywordResult("this"); 4763 4764 if (SemaRef.getLangOpts().CPlusPlus11) { 4765 Consumer.addKeywordResult("alignof"); 4766 Consumer.addKeywordResult("nullptr"); 4767 } 4768 } 4769 4770 if (SemaRef.getLangOpts().C11) { 4771 // FIXME: We should not suggest _Alignof if the alignof macro 4772 // is present. 4773 Consumer.addKeywordResult("_Alignof"); 4774 } 4775 } 4776 4777 if (CCC.WantRemainingKeywords) { 4778 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) { 4779 // Statements. 4780 static const char *const CStmts[] = { 4781 "do", "else", "for", "goto", "if", "return", "switch", "while" }; 4782 const unsigned NumCStmts = llvm::array_lengthof(CStmts); 4783 for (unsigned I = 0; I != NumCStmts; ++I) 4784 Consumer.addKeywordResult(CStmts[I]); 4785 4786 if (SemaRef.getLangOpts().CPlusPlus) { 4787 Consumer.addKeywordResult("catch"); 4788 Consumer.addKeywordResult("try"); 4789 } 4790 4791 if (S && S->getBreakParent()) 4792 Consumer.addKeywordResult("break"); 4793 4794 if (S && S->getContinueParent()) 4795 Consumer.addKeywordResult("continue"); 4796 4797 if (SemaRef.getCurFunction() && 4798 !SemaRef.getCurFunction()->SwitchStack.empty()) { 4799 Consumer.addKeywordResult("case"); 4800 Consumer.addKeywordResult("default"); 4801 } 4802 } else { 4803 if (SemaRef.getLangOpts().CPlusPlus) { 4804 Consumer.addKeywordResult("namespace"); 4805 Consumer.addKeywordResult("template"); 4806 } 4807 4808 if (S && S->isClassScope()) { 4809 Consumer.addKeywordResult("explicit"); 4810 Consumer.addKeywordResult("friend"); 4811 Consumer.addKeywordResult("mutable"); 4812 Consumer.addKeywordResult("private"); 4813 Consumer.addKeywordResult("protected"); 4814 Consumer.addKeywordResult("public"); 4815 Consumer.addKeywordResult("virtual"); 4816 } 4817 } 4818 4819 if (SemaRef.getLangOpts().CPlusPlus) { 4820 Consumer.addKeywordResult("using"); 4821 4822 if (SemaRef.getLangOpts().CPlusPlus11) 4823 Consumer.addKeywordResult("static_assert"); 4824 } 4825 } 4826 } 4827 4828 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer( 4829 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, 4830 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, 4831 DeclContext *MemberContext, bool EnteringContext, 4832 const ObjCObjectPointerType *OPT, bool ErrorRecovery) { 4833 4834 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking || 4835 DisableTypoCorrection) 4836 return nullptr; 4837 4838 // In Microsoft mode, don't perform typo correction in a template member 4839 // function dependent context because it interferes with the "lookup into 4840 // dependent bases of class templates" feature. 4841 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 4842 isa<CXXMethodDecl>(CurContext)) 4843 return nullptr; 4844 4845 // We only attempt to correct typos for identifiers. 4846 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 4847 if (!Typo) 4848 return nullptr; 4849 4850 // If the scope specifier itself was invalid, don't try to correct 4851 // typos. 4852 if (SS && SS->isInvalid()) 4853 return nullptr; 4854 4855 // Never try to correct typos during any kind of code synthesis. 4856 if (!CodeSynthesisContexts.empty()) 4857 return nullptr; 4858 4859 // Don't try to correct 'super'. 4860 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier()) 4861 return nullptr; 4862 4863 // Abort if typo correction already failed for this specific typo. 4864 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo); 4865 if (locs != TypoCorrectionFailures.end() && 4866 locs->second.count(TypoName.getLoc())) 4867 return nullptr; 4868 4869 // Don't try to correct the identifier "vector" when in AltiVec mode. 4870 // TODO: Figure out why typo correction misbehaves in this case, fix it, and 4871 // remove this workaround. 4872 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector")) 4873 return nullptr; 4874 4875 // Provide a stop gap for files that are just seriously broken. Trying 4876 // to correct all typos can turn into a HUGE performance penalty, causing 4877 // some files to take minutes to get rejected by the parser. 4878 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit; 4879 if (Limit && TyposCorrected >= Limit) 4880 return nullptr; 4881 ++TyposCorrected; 4882 4883 // If we're handling a missing symbol error, using modules, and the 4884 // special search all modules option is used, look for a missing import. 4885 if (ErrorRecovery && getLangOpts().Modules && 4886 getLangOpts().ModulesSearchAll) { 4887 // The following has the side effect of loading the missing module. 4888 getModuleLoader().lookupMissingImports(Typo->getName(), 4889 TypoName.getBeginLoc()); 4890 } 4891 4892 // Extend the lifetime of the callback. We delayed this until here 4893 // to avoid allocations in the hot path (which is where no typo correction 4894 // occurs). Note that CorrectionCandidateCallback is polymorphic and 4895 // initially stack-allocated. 4896 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone(); 4897 auto Consumer = std::make_unique<TypoCorrectionConsumer>( 4898 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext, 4899 EnteringContext); 4900 4901 // Perform name lookup to find visible, similarly-named entities. 4902 bool IsUnqualifiedLookup = false; 4903 DeclContext *QualifiedDC = MemberContext; 4904 if (MemberContext) { 4905 LookupVisibleDecls(MemberContext, LookupKind, *Consumer); 4906 4907 // Look in qualified interfaces. 4908 if (OPT) { 4909 for (auto *I : OPT->quals()) 4910 LookupVisibleDecls(I, LookupKind, *Consumer); 4911 } 4912 } else if (SS && SS->isSet()) { 4913 QualifiedDC = computeDeclContext(*SS, EnteringContext); 4914 if (!QualifiedDC) 4915 return nullptr; 4916 4917 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer); 4918 } else { 4919 IsUnqualifiedLookup = true; 4920 } 4921 4922 // Determine whether we are going to search in the various namespaces for 4923 // corrections. 4924 bool SearchNamespaces 4925 = getLangOpts().CPlusPlus && 4926 (IsUnqualifiedLookup || (SS && SS->isSet())); 4927 4928 if (IsUnqualifiedLookup || SearchNamespaces) { 4929 // For unqualified lookup, look through all of the names that we have 4930 // seen in this translation unit. 4931 // FIXME: Re-add the ability to skip very unlikely potential corrections. 4932 for (const auto &I : Context.Idents) 4933 Consumer->FoundName(I.getKey()); 4934 4935 // Walk through identifiers in external identifier sources. 4936 // FIXME: Re-add the ability to skip very unlikely potential corrections. 4937 if (IdentifierInfoLookup *External 4938 = Context.Idents.getExternalIdentifierLookup()) { 4939 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); 4940 do { 4941 StringRef Name = Iter->Next(); 4942 if (Name.empty()) 4943 break; 4944 4945 Consumer->FoundName(Name); 4946 } while (true); 4947 } 4948 } 4949 4950 AddKeywordsToConsumer(*this, *Consumer, S, 4951 *Consumer->getCorrectionValidator(), 4952 SS && SS->isNotEmpty()); 4953 4954 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going 4955 // to search those namespaces. 4956 if (SearchNamespaces) { 4957 // Load any externally-known namespaces. 4958 if (ExternalSource && !LoadedExternalKnownNamespaces) { 4959 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces; 4960 LoadedExternalKnownNamespaces = true; 4961 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces); 4962 for (auto *N : ExternalKnownNamespaces) 4963 KnownNamespaces[N] = true; 4964 } 4965 4966 Consumer->addNamespaces(KnownNamespaces); 4967 } 4968 4969 return Consumer; 4970 } 4971 4972 /// Try to "correct" a typo in the source code by finding 4973 /// visible declarations whose names are similar to the name that was 4974 /// present in the source code. 4975 /// 4976 /// \param TypoName the \c DeclarationNameInfo structure that contains 4977 /// the name that was present in the source code along with its location. 4978 /// 4979 /// \param LookupKind the name-lookup criteria used to search for the name. 4980 /// 4981 /// \param S the scope in which name lookup occurs. 4982 /// 4983 /// \param SS the nested-name-specifier that precedes the name we're 4984 /// looking for, if present. 4985 /// 4986 /// \param CCC A CorrectionCandidateCallback object that provides further 4987 /// validation of typo correction candidates. It also provides flags for 4988 /// determining the set of keywords permitted. 4989 /// 4990 /// \param MemberContext if non-NULL, the context in which to look for 4991 /// a member access expression. 4992 /// 4993 /// \param EnteringContext whether we're entering the context described by 4994 /// the nested-name-specifier SS. 4995 /// 4996 /// \param OPT when non-NULL, the search for visible declarations will 4997 /// also walk the protocols in the qualified interfaces of \p OPT. 4998 /// 4999 /// \returns a \c TypoCorrection containing the corrected name if the typo 5000 /// along with information such as the \c NamedDecl where the corrected name 5001 /// was declared, and any additional \c NestedNameSpecifier needed to access 5002 /// it (C++ only). The \c TypoCorrection is empty if there is no correction. 5003 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName, 5004 Sema::LookupNameKind LookupKind, 5005 Scope *S, CXXScopeSpec *SS, 5006 CorrectionCandidateCallback &CCC, 5007 CorrectTypoKind Mode, 5008 DeclContext *MemberContext, 5009 bool EnteringContext, 5010 const ObjCObjectPointerType *OPT, 5011 bool RecordFailure) { 5012 // Always let the ExternalSource have the first chance at correction, even 5013 // if we would otherwise have given up. 5014 if (ExternalSource) { 5015 if (TypoCorrection Correction = 5016 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC, 5017 MemberContext, EnteringContext, OPT)) 5018 return Correction; 5019 } 5020 5021 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver; 5022 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for 5023 // some instances of CTC_Unknown, while WantRemainingKeywords is true 5024 // for CTC_Unknown but not for CTC_ObjCMessageReceiver. 5025 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords; 5026 5027 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 5028 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC, 5029 MemberContext, EnteringContext, 5030 OPT, Mode == CTK_ErrorRecovery); 5031 5032 if (!Consumer) 5033 return TypoCorrection(); 5034 5035 // If we haven't found anything, we're done. 5036 if (Consumer->empty()) 5037 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5038 5039 // Make sure the best edit distance (prior to adding any namespace qualifiers) 5040 // is not more that about a third of the length of the typo's identifier. 5041 unsigned ED = Consumer->getBestEditDistance(true); 5042 unsigned TypoLen = Typo->getName().size(); 5043 if (ED > 0 && TypoLen / ED < 3) 5044 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5045 5046 TypoCorrection BestTC = Consumer->getNextCorrection(); 5047 TypoCorrection SecondBestTC = Consumer->getNextCorrection(); 5048 if (!BestTC) 5049 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5050 5051 ED = BestTC.getEditDistance(); 5052 5053 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) { 5054 // If this was an unqualified lookup and we believe the callback 5055 // object wouldn't have filtered out possible corrections, note 5056 // that no correction was found. 5057 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5058 } 5059 5060 // If only a single name remains, return that result. 5061 if (!SecondBestTC || 5062 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) { 5063 const TypoCorrection &Result = BestTC; 5064 5065 // Don't correct to a keyword that's the same as the typo; the keyword 5066 // wasn't actually in scope. 5067 if (ED == 0 && Result.isKeyword()) 5068 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5069 5070 TypoCorrection TC = Result; 5071 TC.setCorrectionRange(SS, TypoName); 5072 checkCorrectionVisibility(*this, TC); 5073 return TC; 5074 } else if (SecondBestTC && ObjCMessageReceiver) { 5075 // Prefer 'super' when we're completing in a message-receiver 5076 // context. 5077 5078 if (BestTC.getCorrection().getAsString() != "super") { 5079 if (SecondBestTC.getCorrection().getAsString() == "super") 5080 BestTC = SecondBestTC; 5081 else if ((*Consumer)["super"].front().isKeyword()) 5082 BestTC = (*Consumer)["super"].front(); 5083 } 5084 // Don't correct to a keyword that's the same as the typo; the keyword 5085 // wasn't actually in scope. 5086 if (BestTC.getEditDistance() == 0 || 5087 BestTC.getCorrection().getAsString() != "super") 5088 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); 5089 5090 BestTC.setCorrectionRange(SS, TypoName); 5091 return BestTC; 5092 } 5093 5094 // Record the failure's location if needed and return an empty correction. If 5095 // this was an unqualified lookup and we believe the callback object did not 5096 // filter out possible corrections, also cache the failure for the typo. 5097 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC); 5098 } 5099 5100 /// Try to "correct" a typo in the source code by finding 5101 /// visible declarations whose names are similar to the name that was 5102 /// present in the source code. 5103 /// 5104 /// \param TypoName the \c DeclarationNameInfo structure that contains 5105 /// the name that was present in the source code along with its location. 5106 /// 5107 /// \param LookupKind the name-lookup criteria used to search for the name. 5108 /// 5109 /// \param S the scope in which name lookup occurs. 5110 /// 5111 /// \param SS the nested-name-specifier that precedes the name we're 5112 /// looking for, if present. 5113 /// 5114 /// \param CCC A CorrectionCandidateCallback object that provides further 5115 /// validation of typo correction candidates. It also provides flags for 5116 /// determining the set of keywords permitted. 5117 /// 5118 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print 5119 /// diagnostics when the actual typo correction is attempted. 5120 /// 5121 /// \param TRC A TypoRecoveryCallback functor that will be used to build an 5122 /// Expr from a typo correction candidate. 5123 /// 5124 /// \param MemberContext if non-NULL, the context in which to look for 5125 /// a member access expression. 5126 /// 5127 /// \param EnteringContext whether we're entering the context described by 5128 /// the nested-name-specifier SS. 5129 /// 5130 /// \param OPT when non-NULL, the search for visible declarations will 5131 /// also walk the protocols in the qualified interfaces of \p OPT. 5132 /// 5133 /// \returns a new \c TypoExpr that will later be replaced in the AST with an 5134 /// Expr representing the result of performing typo correction, or nullptr if 5135 /// typo correction is not possible. If nullptr is returned, no diagnostics will 5136 /// be emitted and it is the responsibility of the caller to emit any that are 5137 /// needed. 5138 TypoExpr *Sema::CorrectTypoDelayed( 5139 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, 5140 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, 5141 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, 5142 DeclContext *MemberContext, bool EnteringContext, 5143 const ObjCObjectPointerType *OPT) { 5144 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC, 5145 MemberContext, EnteringContext, 5146 OPT, Mode == CTK_ErrorRecovery); 5147 5148 // Give the external sema source a chance to correct the typo. 5149 TypoCorrection ExternalTypo; 5150 if (ExternalSource && Consumer) { 5151 ExternalTypo = ExternalSource->CorrectTypo( 5152 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(), 5153 MemberContext, EnteringContext, OPT); 5154 if (ExternalTypo) 5155 Consumer->addCorrection(ExternalTypo); 5156 } 5157 5158 if (!Consumer || Consumer->empty()) 5159 return nullptr; 5160 5161 // Make sure the best edit distance (prior to adding any namespace qualifiers) 5162 // is not more that about a third of the length of the typo's identifier. 5163 unsigned ED = Consumer->getBestEditDistance(true); 5164 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); 5165 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3) 5166 return nullptr; 5167 ExprEvalContexts.back().NumTypos++; 5168 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC), 5169 TypoName.getLoc()); 5170 } 5171 5172 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) { 5173 if (!CDecl) return; 5174 5175 if (isKeyword()) 5176 CorrectionDecls.clear(); 5177 5178 CorrectionDecls.push_back(CDecl); 5179 5180 if (!CorrectionName) 5181 CorrectionName = CDecl->getDeclName(); 5182 } 5183 5184 std::string TypoCorrection::getAsString(const LangOptions &LO) const { 5185 if (CorrectionNameSpec) { 5186 std::string tmpBuffer; 5187 llvm::raw_string_ostream PrefixOStream(tmpBuffer); 5188 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO)); 5189 PrefixOStream << CorrectionName; 5190 return PrefixOStream.str(); 5191 } 5192 5193 return CorrectionName.getAsString(); 5194 } 5195 5196 bool CorrectionCandidateCallback::ValidateCandidate( 5197 const TypoCorrection &candidate) { 5198 if (!candidate.isResolved()) 5199 return true; 5200 5201 if (candidate.isKeyword()) 5202 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts || 5203 WantRemainingKeywords || WantObjCSuper; 5204 5205 bool HasNonType = false; 5206 bool HasStaticMethod = false; 5207 bool HasNonStaticMethod = false; 5208 for (Decl *D : candidate) { 5209 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 5210 D = FTD->getTemplatedDecl(); 5211 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 5212 if (Method->isStatic()) 5213 HasStaticMethod = true; 5214 else 5215 HasNonStaticMethod = true; 5216 } 5217 if (!isa<TypeDecl>(D)) 5218 HasNonType = true; 5219 } 5220 5221 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod && 5222 !candidate.getCorrectionSpecifier()) 5223 return false; 5224 5225 return WantTypeSpecifiers || HasNonType; 5226 } 5227 5228 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, 5229 bool HasExplicitTemplateArgs, 5230 MemberExpr *ME) 5231 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs), 5232 CurContext(SemaRef.CurContext), MemberFn(ME) { 5233 WantTypeSpecifiers = false; 5234 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && 5235 !HasExplicitTemplateArgs && NumArgs == 1; 5236 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1; 5237 WantRemainingKeywords = false; 5238 } 5239 5240 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) { 5241 if (!candidate.getCorrectionDecl()) 5242 return candidate.isKeyword(); 5243 5244 for (auto *C : candidate) { 5245 FunctionDecl *FD = nullptr; 5246 NamedDecl *ND = C->getUnderlyingDecl(); 5247 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 5248 FD = FTD->getTemplatedDecl(); 5249 if (!HasExplicitTemplateArgs && !FD) { 5250 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 5251 // If the Decl is neither a function nor a template function, 5252 // determine if it is a pointer or reference to a function. If so, 5253 // check against the number of arguments expected for the pointee. 5254 QualType ValType = cast<ValueDecl>(ND)->getType(); 5255 if (ValType.isNull()) 5256 continue; 5257 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 5258 ValType = ValType->getPointeeType(); 5259 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 5260 if (FPT->getNumParams() == NumArgs) 5261 return true; 5262 } 5263 } 5264 5265 // A typo for a function-style cast can look like a function call in C++. 5266 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr 5267 : isa<TypeDecl>(ND)) && 5268 CurContext->getParentASTContext().getLangOpts().CPlusPlus) 5269 // Only a class or class template can take two or more arguments. 5270 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND); 5271 5272 // Skip the current candidate if it is not a FunctionDecl or does not accept 5273 // the current number of arguments. 5274 if (!FD || !(FD->getNumParams() >= NumArgs && 5275 FD->getMinRequiredArguments() <= NumArgs)) 5276 continue; 5277 5278 // If the current candidate is a non-static C++ method, skip the candidate 5279 // unless the method being corrected--or the current DeclContext, if the 5280 // function being corrected is not a method--is a method in the same class 5281 // or a descendent class of the candidate's parent class. 5282 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 5283 if (MemberFn || !MD->isStatic()) { 5284 CXXMethodDecl *CurMD = 5285 MemberFn 5286 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl()) 5287 : dyn_cast_or_null<CXXMethodDecl>(CurContext); 5288 CXXRecordDecl *CurRD = 5289 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr; 5290 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl(); 5291 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD))) 5292 continue; 5293 } 5294 } 5295 return true; 5296 } 5297 return false; 5298 } 5299 5300 void Sema::diagnoseTypo(const TypoCorrection &Correction, 5301 const PartialDiagnostic &TypoDiag, 5302 bool ErrorRecovery) { 5303 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl), 5304 ErrorRecovery); 5305 } 5306 5307 /// Find which declaration we should import to provide the definition of 5308 /// the given declaration. 5309 static NamedDecl *getDefinitionToImport(NamedDecl *D) { 5310 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 5311 return VD->getDefinition(); 5312 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 5313 return FD->getDefinition(); 5314 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 5315 return TD->getDefinition(); 5316 // The first definition for this ObjCInterfaceDecl might be in the TU 5317 // and not associated with any module. Use the one we know to be complete 5318 // and have just seen in a module. 5319 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) 5320 return ID; 5321 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) 5322 return PD->getDefinition(); 5323 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 5324 if (NamedDecl *TTD = TD->getTemplatedDecl()) 5325 return getDefinitionToImport(TTD); 5326 return nullptr; 5327 } 5328 5329 void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, 5330 MissingImportKind MIK, bool Recover) { 5331 // Suggest importing a module providing the definition of this entity, if 5332 // possible. 5333 NamedDecl *Def = getDefinitionToImport(Decl); 5334 if (!Def) 5335 Def = Decl; 5336 5337 Module *Owner = getOwningModule(Def); 5338 assert(Owner && "definition of hidden declaration is not in a module"); 5339 5340 llvm::SmallVector<Module*, 8> OwningModules; 5341 OwningModules.push_back(Owner); 5342 auto Merged = Context.getModulesWithMergedDefinition(Def); 5343 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end()); 5344 5345 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK, 5346 Recover); 5347 } 5348 5349 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic 5350 /// suggesting the addition of a #include of the specified file. 5351 static std::string getHeaderNameForHeader(Preprocessor &PP, const FileEntry *E, 5352 llvm::StringRef IncludingFile) { 5353 bool IsSystem = false; 5354 auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics( 5355 E, IncludingFile, &IsSystem); 5356 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"'); 5357 } 5358 5359 void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl, 5360 SourceLocation DeclLoc, 5361 ArrayRef<Module *> Modules, 5362 MissingImportKind MIK, bool Recover) { 5363 assert(!Modules.empty()); 5364 5365 auto NotePrevious = [&] { 5366 // FIXME: Suppress the note backtrace even under 5367 // -fdiagnostics-show-note-include-stack. We don't care how this 5368 // declaration was previously reached. 5369 Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK; 5370 }; 5371 5372 // Weed out duplicates from module list. 5373 llvm::SmallVector<Module*, 8> UniqueModules; 5374 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet; 5375 for (auto *M : Modules) { 5376 if (M->Kind == Module::GlobalModuleFragment) 5377 continue; 5378 if (UniqueModuleSet.insert(M).second) 5379 UniqueModules.push_back(M); 5380 } 5381 5382 // Try to find a suitable header-name to #include. 5383 std::string HeaderName; 5384 if (const FileEntry *Header = 5385 PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) { 5386 if (const FileEntry *FE = 5387 SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc))) 5388 HeaderName = getHeaderNameForHeader(PP, Header, FE->tryGetRealPathName()); 5389 } 5390 5391 // If we have a #include we should suggest, or if all definition locations 5392 // were in global module fragments, don't suggest an import. 5393 if (!HeaderName.empty() || UniqueModules.empty()) { 5394 // FIXME: Find a smart place to suggest inserting a #include, and add 5395 // a FixItHint there. 5396 Diag(UseLoc, diag::err_module_unimported_use_header) 5397 << (int)MIK << Decl << !HeaderName.empty() << HeaderName; 5398 // Produce a note showing where the entity was declared. 5399 NotePrevious(); 5400 if (Recover) 5401 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]); 5402 return; 5403 } 5404 5405 Modules = UniqueModules; 5406 5407 if (Modules.size() > 1) { 5408 std::string ModuleList; 5409 unsigned N = 0; 5410 for (Module *M : Modules) { 5411 ModuleList += "\n "; 5412 if (++N == 5 && N != Modules.size()) { 5413 ModuleList += "[...]"; 5414 break; 5415 } 5416 ModuleList += M->getFullModuleName(); 5417 } 5418 5419 Diag(UseLoc, diag::err_module_unimported_use_multiple) 5420 << (int)MIK << Decl << ModuleList; 5421 } else { 5422 // FIXME: Add a FixItHint that imports the corresponding module. 5423 Diag(UseLoc, diag::err_module_unimported_use) 5424 << (int)MIK << Decl << Modules[0]->getFullModuleName(); 5425 } 5426 5427 NotePrevious(); 5428 5429 // Try to recover by implicitly importing this module. 5430 if (Recover) 5431 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]); 5432 } 5433 5434 /// Diagnose a successfully-corrected typo. Separated from the correction 5435 /// itself to allow external validation of the result, etc. 5436 /// 5437 /// \param Correction The result of performing typo correction. 5438 /// \param TypoDiag The diagnostic to produce. This will have the corrected 5439 /// string added to it (and usually also a fixit). 5440 /// \param PrevNote A note to use when indicating the location of the entity to 5441 /// which we are correcting. Will have the correction string added to it. 5442 /// \param ErrorRecovery If \c true (the default), the caller is going to 5443 /// recover from the typo as if the corrected string had been typed. 5444 /// In this case, \c PDiag must be an error, and we will attach a fixit 5445 /// to it. 5446 void Sema::diagnoseTypo(const TypoCorrection &Correction, 5447 const PartialDiagnostic &TypoDiag, 5448 const PartialDiagnostic &PrevNote, 5449 bool ErrorRecovery) { 5450 std::string CorrectedStr = Correction.getAsString(getLangOpts()); 5451 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts()); 5452 FixItHint FixTypo = FixItHint::CreateReplacement( 5453 Correction.getCorrectionRange(), CorrectedStr); 5454 5455 // Maybe we're just missing a module import. 5456 if (Correction.requiresImport()) { 5457 NamedDecl *Decl = Correction.getFoundDecl(); 5458 assert(Decl && "import required but no declaration to import"); 5459 5460 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl, 5461 MissingImportKind::Declaration, ErrorRecovery); 5462 return; 5463 } 5464 5465 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag) 5466 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint()); 5467 5468 NamedDecl *ChosenDecl = 5469 Correction.isKeyword() ? nullptr : Correction.getFoundDecl(); 5470 if (PrevNote.getDiagID() && ChosenDecl) 5471 Diag(ChosenDecl->getLocation(), PrevNote) 5472 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo); 5473 5474 // Add any extra diagnostics. 5475 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics()) 5476 Diag(Correction.getCorrectionRange().getBegin(), PD); 5477 } 5478 5479 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 5480 TypoDiagnosticGenerator TDG, 5481 TypoRecoveryCallback TRC, 5482 SourceLocation TypoLoc) { 5483 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer"); 5484 auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc); 5485 auto &State = DelayedTypos[TE]; 5486 State.Consumer = std::move(TCC); 5487 State.DiagHandler = std::move(TDG); 5488 State.RecoveryHandler = std::move(TRC); 5489 if (TE) 5490 TypoExprs.push_back(TE); 5491 return TE; 5492 } 5493 5494 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const { 5495 auto Entry = DelayedTypos.find(TE); 5496 assert(Entry != DelayedTypos.end() && 5497 "Failed to get the state for a TypoExpr!"); 5498 return Entry->second; 5499 } 5500 5501 void Sema::clearDelayedTypo(TypoExpr *TE) { 5502 DelayedTypos.erase(TE); 5503 } 5504 5505 void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) { 5506 DeclarationNameInfo Name(II, IILoc); 5507 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration); 5508 R.suppressDiagnostics(); 5509 R.setHideTags(false); 5510 LookupName(R, S); 5511 R.dump(); 5512 } 5513