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