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