1 //===--- AST.cpp - Utility AST functions -----------------------*- C++ -*-===// 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 #include "AST.h" 10 11 #include "SourceCode.h" 12 #include "clang/AST/ASTContext.h" 13 #include "clang/AST/ASTTypeTraits.h" 14 #include "clang/AST/Decl.h" 15 #include "clang/AST/DeclBase.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/DeclTemplate.h" 18 #include "clang/AST/DeclarationName.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/NestedNameSpecifier.h" 21 #include "clang/AST/PrettyPrinter.h" 22 #include "clang/AST/RecursiveASTVisitor.h" 23 #include "clang/AST/Stmt.h" 24 #include "clang/AST/TemplateBase.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/Basic/Builtins.h" 27 #include "clang/Basic/SourceLocation.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/Basic/Specifiers.h" 30 #include "clang/Index/USRGeneration.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/None.h" 33 #include "llvm/ADT/Optional.h" 34 #include "llvm/ADT/STLExtras.h" 35 #include "llvm/ADT/SmallSet.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include <string> 40 #include <vector> 41 42 namespace clang { 43 namespace clangd { 44 45 namespace { 46 llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> 47 getTemplateSpecializationArgLocs(const NamedDecl &ND) { 48 if (auto *Func = llvm::dyn_cast<FunctionDecl>(&ND)) { 49 if (const ASTTemplateArgumentListInfo *Args = 50 Func->getTemplateSpecializationArgsAsWritten()) 51 return Args->arguments(); 52 } else if (auto *Cls = 53 llvm::dyn_cast<ClassTemplatePartialSpecializationDecl>(&ND)) { 54 if (auto *Args = Cls->getTemplateArgsAsWritten()) 55 return Args->arguments(); 56 } else if (auto *Var = 57 llvm::dyn_cast<VarTemplatePartialSpecializationDecl>(&ND)) { 58 if (auto *Args = Var->getTemplateArgsAsWritten()) 59 return Args->arguments(); 60 } else if (auto *Var = llvm::dyn_cast<VarTemplateSpecializationDecl>(&ND)) { 61 if (auto *Args = Var->getTemplateArgsInfo()) 62 return Args->arguments(); 63 } 64 // We return None for ClassTemplateSpecializationDecls because it does not 65 // contain TemplateArgumentLoc information. 66 return llvm::None; 67 } 68 69 template <class T> 70 bool isTemplateSpecializationKind(const NamedDecl *D, 71 TemplateSpecializationKind Kind) { 72 if (const auto *TD = dyn_cast<T>(D)) 73 return TD->getTemplateSpecializationKind() == Kind; 74 return false; 75 } 76 77 bool isTemplateSpecializationKind(const NamedDecl *D, 78 TemplateSpecializationKind Kind) { 79 return isTemplateSpecializationKind<FunctionDecl>(D, Kind) || 80 isTemplateSpecializationKind<CXXRecordDecl>(D, Kind) || 81 isTemplateSpecializationKind<VarDecl>(D, Kind); 82 } 83 84 // Store all UsingDirectiveDecls in parent contexts of DestContext, that were 85 // introduced before InsertionPoint. 86 llvm::DenseSet<const NamespaceDecl *> 87 getUsingNamespaceDirectives(const DeclContext *DestContext, 88 SourceLocation Until) { 89 const auto &SM = DestContext->getParentASTContext().getSourceManager(); 90 llvm::DenseSet<const NamespaceDecl *> VisibleNamespaceDecls; 91 for (const auto *DC = DestContext; DC; DC = DC->getLookupParent()) { 92 for (const auto *D : DC->decls()) { 93 if (!SM.isWrittenInSameFile(D->getLocation(), Until) || 94 !SM.isBeforeInTranslationUnit(D->getLocation(), Until)) 95 continue; 96 if (auto *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D)) 97 VisibleNamespaceDecls.insert( 98 UDD->getNominatedNamespace()->getCanonicalDecl()); 99 } 100 } 101 return VisibleNamespaceDecls; 102 } 103 104 // Goes over all parents of SourceContext until we find a common ancestor for 105 // DestContext and SourceContext. Any qualifier including and above common 106 // ancestor is redundant, therefore we stop at lowest common ancestor. 107 // In addition to that stops early whenever IsVisible returns true. This can be 108 // used to implement support for "using namespace" decls. 109 std::string 110 getQualification(ASTContext &Context, const DeclContext *DestContext, 111 const DeclContext *SourceContext, 112 llvm::function_ref<bool(NestedNameSpecifier *)> IsVisible) { 113 std::vector<const NestedNameSpecifier *> Parents; 114 bool ReachedNS = false; 115 for (const DeclContext *CurContext = SourceContext; CurContext; 116 CurContext = CurContext->getLookupParent()) { 117 // Stop once we reach a common ancestor. 118 if (CurContext->Encloses(DestContext)) 119 break; 120 121 NestedNameSpecifier *NNS = nullptr; 122 if (auto *TD = llvm::dyn_cast<TagDecl>(CurContext)) { 123 // There can't be any more tag parents after hitting a namespace. 124 assert(!ReachedNS); 125 (void)ReachedNS; 126 NNS = NestedNameSpecifier::Create(Context, nullptr, false, 127 TD->getTypeForDecl()); 128 } else if (auto *NSD = llvm::dyn_cast<NamespaceDecl>(CurContext)) { 129 ReachedNS = true; 130 NNS = NestedNameSpecifier::Create(Context, nullptr, NSD); 131 // Anonymous and inline namespace names are not spelled while qualifying 132 // a name, so skip those. 133 if (NSD->isAnonymousNamespace() || NSD->isInlineNamespace()) 134 continue; 135 } else { 136 // Other types of contexts cannot be spelled in code, just skip over 137 // them. 138 continue; 139 } 140 // Stop if this namespace is already visible at DestContext. 141 if (IsVisible(NNS)) 142 break; 143 144 Parents.push_back(NNS); 145 } 146 147 // Go over name-specifiers in reverse order to create necessary qualification, 148 // since we stored inner-most parent first. 149 std::string Result; 150 llvm::raw_string_ostream OS(Result); 151 for (const auto *Parent : llvm::reverse(Parents)) 152 Parent->print(OS, Context.getPrintingPolicy()); 153 return OS.str(); 154 } 155 156 } // namespace 157 158 bool isImplicitTemplateInstantiation(const NamedDecl *D) { 159 return isTemplateSpecializationKind(D, TSK_ImplicitInstantiation); 160 } 161 162 bool isExplicitTemplateSpecialization(const NamedDecl *D) { 163 return isTemplateSpecializationKind(D, TSK_ExplicitSpecialization); 164 } 165 166 bool isImplementationDetail(const Decl *D) { 167 return !isSpelledInSource(D->getLocation(), 168 D->getASTContext().getSourceManager()); 169 } 170 171 SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM) { 172 auto L = D.getLocation(); 173 if (isSpelledInSource(L, SM)) 174 return SM.getSpellingLoc(L); 175 return SM.getExpansionLoc(L); 176 } 177 178 std::string printQualifiedName(const NamedDecl &ND) { 179 std::string QName; 180 llvm::raw_string_ostream OS(QName); 181 PrintingPolicy Policy(ND.getASTContext().getLangOpts()); 182 // Note that inline namespaces are treated as transparent scopes. This 183 // reflects the way they're most commonly used for lookup. Ideally we'd 184 // include them, but at query time it's hard to find all the inline 185 // namespaces to query: the preamble doesn't have a dedicated list. 186 Policy.SuppressUnwrittenScope = true; 187 ND.printQualifiedName(OS, Policy); 188 OS.flush(); 189 assert(!StringRef(QName).startswith("::")); 190 return QName; 191 } 192 193 static bool isAnonymous(const DeclarationName &N) { 194 return N.isIdentifier() && !N.getAsIdentifierInfo(); 195 } 196 197 NestedNameSpecifierLoc getQualifierLoc(const NamedDecl &ND) { 198 if (auto *V = llvm::dyn_cast<DeclaratorDecl>(&ND)) 199 return V->getQualifierLoc(); 200 if (auto *T = llvm::dyn_cast<TagDecl>(&ND)) 201 return T->getQualifierLoc(); 202 return NestedNameSpecifierLoc(); 203 } 204 205 std::string printUsingNamespaceName(const ASTContext &Ctx, 206 const UsingDirectiveDecl &D) { 207 PrintingPolicy PP(Ctx.getLangOpts()); 208 std::string Name; 209 llvm::raw_string_ostream Out(Name); 210 211 if (auto *Qual = D.getQualifier()) 212 Qual->print(Out, PP); 213 D.getNominatedNamespaceAsWritten()->printName(Out); 214 return Out.str(); 215 } 216 217 std::string printName(const ASTContext &Ctx, const NamedDecl &ND) { 218 std::string Name; 219 llvm::raw_string_ostream Out(Name); 220 PrintingPolicy PP(Ctx.getLangOpts()); 221 // We don't consider a class template's args part of the constructor name. 222 PP.SuppressTemplateArgsInCXXConstructors = true; 223 224 // Handle 'using namespace'. They all have the same name - <using-directive>. 225 if (auto *UD = llvm::dyn_cast<UsingDirectiveDecl>(&ND)) { 226 Out << "using namespace "; 227 if (auto *Qual = UD->getQualifier()) 228 Qual->print(Out, PP); 229 UD->getNominatedNamespaceAsWritten()->printName(Out); 230 return Out.str(); 231 } 232 233 if (isAnonymous(ND.getDeclName())) { 234 // Come up with a presentation for an anonymous entity. 235 if (isa<NamespaceDecl>(ND)) 236 return "(anonymous namespace)"; 237 if (auto *Cls = llvm::dyn_cast<RecordDecl>(&ND)) { 238 if (Cls->isLambda()) 239 return "(lambda)"; 240 return ("(anonymous " + Cls->getKindName() + ")").str(); 241 } 242 if (isa<EnumDecl>(ND)) 243 return "(anonymous enum)"; 244 return "(anonymous)"; 245 } 246 247 // Print nested name qualifier if it was written in the source code. 248 if (auto *Qualifier = getQualifierLoc(ND).getNestedNameSpecifier()) 249 Qualifier->print(Out, PP); 250 // Print the name itself. 251 ND.getDeclName().print(Out, PP); 252 // Print template arguments. 253 Out << printTemplateSpecializationArgs(ND); 254 255 return Out.str(); 256 } 257 258 std::string printTemplateSpecializationArgs(const NamedDecl &ND) { 259 std::string TemplateArgs; 260 llvm::raw_string_ostream OS(TemplateArgs); 261 PrintingPolicy Policy(ND.getASTContext().getLangOpts()); 262 if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> Args = 263 getTemplateSpecializationArgLocs(ND)) { 264 printTemplateArgumentList(OS, *Args, Policy); 265 } else if (auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) { 266 if (const TypeSourceInfo *TSI = Cls->getTypeAsWritten()) { 267 // ClassTemplateSpecializationDecls do not contain 268 // TemplateArgumentTypeLocs, they only have TemplateArgumentTypes. So we 269 // create a new argument location list from TypeSourceInfo. 270 auto STL = TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>(); 271 llvm::SmallVector<TemplateArgumentLoc> ArgLocs; 272 ArgLocs.reserve(STL.getNumArgs()); 273 for (unsigned I = 0; I < STL.getNumArgs(); ++I) 274 ArgLocs.push_back(STL.getArgLoc(I)); 275 printTemplateArgumentList(OS, ArgLocs, Policy); 276 } else { 277 // FIXME: Fix cases when getTypeAsWritten returns null inside clang AST, 278 // e.g. friend decls. Currently we fallback to Template Arguments without 279 // location information. 280 printTemplateArgumentList(OS, Cls->getTemplateArgs().asArray(), Policy); 281 } 282 } 283 OS.flush(); 284 return TemplateArgs; 285 } 286 287 std::string printNamespaceScope(const DeclContext &DC) { 288 for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent()) 289 if (const auto *NS = dyn_cast<NamespaceDecl>(Ctx)) 290 if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace()) 291 return printQualifiedName(*NS) + "::"; 292 return ""; 293 } 294 295 static llvm::StringRef 296 getNameOrErrForObjCInterface(const ObjCInterfaceDecl *ID) { 297 return ID ? ID->getName() : "<<error-type>>"; 298 } 299 300 std::string printObjCMethod(const ObjCMethodDecl &Method) { 301 std::string Name; 302 llvm::raw_string_ostream OS(Name); 303 304 OS << (Method.isInstanceMethod() ? '-' : '+') << '['; 305 306 // Should always be true. 307 if (const ObjCContainerDecl *C = 308 dyn_cast<ObjCContainerDecl>(Method.getDeclContext())) 309 OS << printObjCContainer(*C); 310 311 Method.getSelector().print(OS << ' '); 312 if (Method.isVariadic()) 313 OS << ", ..."; 314 315 OS << ']'; 316 OS.flush(); 317 return Name; 318 } 319 320 std::string printObjCContainer(const ObjCContainerDecl &C) { 321 if (const ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(&C)) { 322 std::string Name; 323 llvm::raw_string_ostream OS(Name); 324 const ObjCInterfaceDecl *Class = Category->getClassInterface(); 325 OS << getNameOrErrForObjCInterface(Class) << '(' << Category->getName() 326 << ')'; 327 OS.flush(); 328 return Name; 329 } 330 if (const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(&C)) { 331 std::string Name; 332 llvm::raw_string_ostream OS(Name); 333 const ObjCInterfaceDecl *Class = CID->getClassInterface(); 334 OS << getNameOrErrForObjCInterface(Class) << '(' << CID->getName() << ')'; 335 OS.flush(); 336 return Name; 337 } 338 return C.getNameAsString(); 339 } 340 341 SymbolID getSymbolID(const Decl *D) { 342 llvm::SmallString<128> USR; 343 if (index::generateUSRForDecl(D, USR)) 344 return {}; 345 return SymbolID(USR); 346 } 347 348 SymbolID getSymbolID(const llvm::StringRef MacroName, const MacroInfo *MI, 349 const SourceManager &SM) { 350 if (MI == nullptr) 351 return {}; 352 llvm::SmallString<128> USR; 353 if (index::generateUSRForMacro(MacroName, MI->getDefinitionLoc(), SM, USR)) 354 return {}; 355 return SymbolID(USR); 356 } 357 358 std::string printType(const QualType QT, const DeclContext &CurContext, 359 const llvm::StringRef Placeholder) { 360 std::string Result; 361 llvm::raw_string_ostream OS(Result); 362 PrintingPolicy PP(CurContext.getParentASTContext().getPrintingPolicy()); 363 PP.SuppressTagKeyword = true; 364 PP.SuppressUnwrittenScope = true; 365 366 class PrintCB : public PrintingCallbacks { 367 public: 368 PrintCB(const DeclContext *CurContext) : CurContext(CurContext) {} 369 virtual ~PrintCB() {} 370 virtual bool isScopeVisible(const DeclContext *DC) const override { 371 return DC->Encloses(CurContext); 372 } 373 374 private: 375 const DeclContext *CurContext; 376 }; 377 PrintCB PCB(&CurContext); 378 PP.Callbacks = &PCB; 379 380 QT.print(OS, PP, Placeholder); 381 return OS.str(); 382 } 383 384 bool hasReservedName(const Decl &D) { 385 if (const auto *ND = llvm::dyn_cast<NamedDecl>(&D)) 386 if (const auto *II = ND->getIdentifier()) 387 return isReservedName(II->getName()); 388 return false; 389 } 390 391 bool hasReservedScope(const DeclContext &DC) { 392 for (const DeclContext *D = &DC; D; D = D->getParent()) { 393 if (D->isTransparentContext() || D->isInlineNamespace()) 394 continue; 395 if (const auto *ND = llvm::dyn_cast<NamedDecl>(D)) 396 if (hasReservedName(*ND)) 397 return true; 398 } 399 return false; 400 } 401 402 QualType declaredType(const TypeDecl *D) { 403 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) 404 if (const auto *TSI = CTSD->getTypeAsWritten()) 405 return TSI->getType(); 406 return D->getASTContext().getTypeDeclType(D); 407 } 408 409 namespace { 410 /// Computes the deduced type at a given location by visiting the relevant 411 /// nodes. We use this to display the actual type when hovering over an "auto" 412 /// keyword or "decltype()" expression. 413 /// FIXME: This could have been a lot simpler by visiting AutoTypeLocs but it 414 /// seems that the AutoTypeLocs that can be visited along with their AutoType do 415 /// not have the deduced type set. Instead, we have to go to the appropriate 416 /// DeclaratorDecl/FunctionDecl and work our back to the AutoType that does have 417 /// a deduced type set. The AST should be improved to simplify this scenario. 418 class DeducedTypeVisitor : public RecursiveASTVisitor<DeducedTypeVisitor> { 419 SourceLocation SearchedLocation; 420 421 public: 422 DeducedTypeVisitor(SourceLocation SearchedLocation) 423 : SearchedLocation(SearchedLocation) {} 424 425 // Handle auto initializers: 426 //- auto i = 1; 427 //- decltype(auto) i = 1; 428 //- auto& i = 1; 429 //- auto* i = &a; 430 bool VisitDeclaratorDecl(DeclaratorDecl *D) { 431 if (!D->getTypeSourceInfo() || 432 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc() != SearchedLocation) 433 return true; 434 435 if (auto *AT = D->getType()->getContainedAutoType()) { 436 DeducedType = AT->desugar(); 437 } 438 return true; 439 } 440 441 // Handle auto return types: 442 //- auto foo() {} 443 //- auto& foo() {} 444 //- auto foo() -> int {} 445 //- auto foo() -> decltype(1+1) {} 446 //- operator auto() const { return 10; } 447 bool VisitFunctionDecl(FunctionDecl *D) { 448 if (!D->getTypeSourceInfo()) 449 return true; 450 // Loc of auto in return type (c++14). 451 auto CurLoc = D->getReturnTypeSourceRange().getBegin(); 452 // Loc of "auto" in operator auto() 453 if (CurLoc.isInvalid() && isa<CXXConversionDecl>(D)) 454 CurLoc = D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 455 // Loc of "auto" in function with trailing return type (c++11). 456 if (CurLoc.isInvalid()) 457 CurLoc = D->getSourceRange().getBegin(); 458 if (CurLoc != SearchedLocation) 459 return true; 460 461 const AutoType *AT = D->getReturnType()->getContainedAutoType(); 462 if (AT && !AT->getDeducedType().isNull()) { 463 DeducedType = AT->getDeducedType(); 464 } else if (auto *DT = dyn_cast<DecltypeType>(D->getReturnType())) { 465 // auto in a trailing return type just points to a DecltypeType and 466 // getContainedAutoType does not unwrap it. 467 if (!DT->getUnderlyingType().isNull()) 468 DeducedType = DT->getUnderlyingType(); 469 } else if (!D->getReturnType().isNull()) { 470 DeducedType = D->getReturnType(); 471 } 472 return true; 473 } 474 475 // Handle non-auto decltype, e.g.: 476 // - auto foo() -> decltype(expr) {} 477 // - decltype(expr); 478 bool VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 479 if (TL.getBeginLoc() != SearchedLocation) 480 return true; 481 482 // A DecltypeType's underlying type can be another DecltypeType! E.g. 483 // int I = 0; 484 // decltype(I) J = I; 485 // decltype(J) K = J; 486 const DecltypeType *DT = dyn_cast<DecltypeType>(TL.getTypePtr()); 487 while (DT && !DT->getUnderlyingType().isNull()) { 488 DeducedType = DT->getUnderlyingType(); 489 DT = dyn_cast<DecltypeType>(DeducedType.getTypePtr()); 490 } 491 return true; 492 } 493 494 // Handle functions/lambdas with `auto` typed parameters. 495 // We deduce the type if there's exactly one instantiation visible. 496 bool VisitParmVarDecl(ParmVarDecl *PVD) { 497 if (!PVD->getType()->isDependentType()) 498 return true; 499 // 'auto' here does not name an AutoType, but an implicit template param. 500 TemplateTypeParmTypeLoc Auto = 501 getContainedAutoParamType(PVD->getTypeSourceInfo()->getTypeLoc()); 502 if (Auto.isNull() || Auto.getNameLoc() != SearchedLocation) 503 return true; 504 505 // We expect the TTP to be attached to this function template. 506 // Find the template and the param index. 507 auto *Templated = llvm::dyn_cast<FunctionDecl>(PVD->getDeclContext()); 508 if (!Templated) 509 return true; 510 auto *FTD = Templated->getDescribedFunctionTemplate(); 511 if (!FTD) 512 return true; 513 int ParamIndex = paramIndex(*FTD, *Auto.getDecl()); 514 if (ParamIndex < 0) { 515 assert(false && "auto TTP is not from enclosing function?"); 516 return true; 517 } 518 519 // Now find the instantiation and the deduced template type arg. 520 auto *Instantiation = 521 llvm::dyn_cast_or_null<FunctionDecl>(getOnlyInstantiation(Templated)); 522 if (!Instantiation) 523 return true; 524 const auto *Args = Instantiation->getTemplateSpecializationArgs(); 525 if (Args->size() != FTD->getTemplateParameters()->size()) 526 return true; // no weird variadic stuff 527 DeducedType = Args->get(ParamIndex).getAsType(); 528 return true; 529 } 530 531 static int paramIndex(const TemplateDecl &TD, NamedDecl &Param) { 532 unsigned I = 0; 533 for (auto *ND : *TD.getTemplateParameters()) { 534 if (&Param == ND) 535 return I; 536 ++I; 537 } 538 return -1; 539 } 540 541 QualType DeducedType; 542 }; 543 } // namespace 544 545 llvm::Optional<QualType> getDeducedType(ASTContext &ASTCtx, 546 SourceLocation Loc) { 547 if (!Loc.isValid()) 548 return {}; 549 DeducedTypeVisitor V(Loc); 550 V.TraverseAST(ASTCtx); 551 if (V.DeducedType.isNull()) 552 return llvm::None; 553 return V.DeducedType; 554 } 555 556 TemplateTypeParmTypeLoc getContainedAutoParamType(TypeLoc TL) { 557 if (auto QTL = TL.getAs<QualifiedTypeLoc>()) 558 return getContainedAutoParamType(QTL.getUnqualifiedLoc()); 559 if (llvm::isa<PointerType, ReferenceType, ParenType>(TL.getTypePtr())) 560 return getContainedAutoParamType(TL.getNextTypeLoc()); 561 if (auto FTL = TL.getAs<FunctionTypeLoc>()) 562 return getContainedAutoParamType(FTL.getReturnLoc()); 563 if (auto TTPTL = TL.getAs<TemplateTypeParmTypeLoc>()) { 564 if (TTPTL.getTypePtr()->getDecl()->isImplicit()) 565 return TTPTL; 566 } 567 return {}; 568 } 569 570 template <typename TemplateDeclTy> 571 static NamedDecl *getOnlyInstantiationImpl(TemplateDeclTy *TD) { 572 NamedDecl *Only = nullptr; 573 for (auto *Spec : TD->specializations()) { 574 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 575 continue; 576 if (Only != nullptr) 577 return nullptr; 578 Only = Spec; 579 } 580 return Only; 581 } 582 583 NamedDecl *getOnlyInstantiation(NamedDecl *TemplatedDecl) { 584 if (TemplateDecl *TD = TemplatedDecl->getDescribedTemplate()) { 585 if (auto *CTD = llvm::dyn_cast<ClassTemplateDecl>(TD)) 586 return getOnlyInstantiationImpl(CTD); 587 if (auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(TD)) 588 return getOnlyInstantiationImpl(FTD); 589 if (auto *VTD = llvm::dyn_cast<VarTemplateDecl>(TD)) 590 return getOnlyInstantiationImpl(VTD); 591 } 592 return nullptr; 593 } 594 595 std::vector<const Attr *> getAttributes(const DynTypedNode &N) { 596 std::vector<const Attr *> Result; 597 if (const auto *TL = N.get<TypeLoc>()) { 598 for (AttributedTypeLoc ATL = TL->getAs<AttributedTypeLoc>(); !ATL.isNull(); 599 ATL = ATL.getModifiedLoc().getAs<AttributedTypeLoc>()) { 600 if (const Attr *A = ATL.getAttr()) 601 Result.push_back(A); 602 assert(!ATL.getModifiedLoc().isNull()); 603 } 604 } 605 if (const auto *S = N.get<AttributedStmt>()) { 606 for (; S != nullptr; S = dyn_cast<AttributedStmt>(S->getSubStmt())) 607 for (const Attr *A : S->getAttrs()) 608 if (A) 609 Result.push_back(A); 610 } 611 if (const auto *D = N.get<Decl>()) { 612 for (const Attr *A : D->attrs()) 613 if (A) 614 Result.push_back(A); 615 } 616 return Result; 617 } 618 619 std::string getQualification(ASTContext &Context, 620 const DeclContext *DestContext, 621 SourceLocation InsertionPoint, 622 const NamedDecl *ND) { 623 auto VisibleNamespaceDecls = 624 getUsingNamespaceDirectives(DestContext, InsertionPoint); 625 return getQualification( 626 Context, DestContext, ND->getDeclContext(), 627 [&](NestedNameSpecifier *NNS) { 628 if (NNS->getKind() != NestedNameSpecifier::Namespace) 629 return false; 630 const auto *CanonNSD = NNS->getAsNamespace()->getCanonicalDecl(); 631 return llvm::any_of(VisibleNamespaceDecls, 632 [CanonNSD](const NamespaceDecl *NSD) { 633 return NSD->getCanonicalDecl() == CanonNSD; 634 }); 635 }); 636 } 637 638 std::string getQualification(ASTContext &Context, 639 const DeclContext *DestContext, 640 const NamedDecl *ND, 641 llvm::ArrayRef<std::string> VisibleNamespaces) { 642 for (llvm::StringRef NS : VisibleNamespaces) { 643 assert(NS.endswith("::")); 644 (void)NS; 645 } 646 return getQualification( 647 Context, DestContext, ND->getDeclContext(), 648 [&](NestedNameSpecifier *NNS) { 649 return llvm::any_of(VisibleNamespaces, [&](llvm::StringRef Namespace) { 650 std::string NS; 651 llvm::raw_string_ostream OS(NS); 652 NNS->print(OS, Context.getPrintingPolicy()); 653 return OS.str() == Namespace; 654 }); 655 }); 656 } 657 658 bool hasUnstableLinkage(const Decl *D) { 659 // Linkage of a ValueDecl depends on the type. 660 // If that's not deduced yet, deducing it may change the linkage. 661 auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D); 662 return VD && !VD->getType().isNull() && VD->getType()->isUndeducedType(); 663 } 664 665 bool isDeeplyNested(const Decl *D, unsigned MaxDepth) { 666 size_t ContextDepth = 0; 667 for (auto *Ctx = D->getDeclContext(); Ctx && !Ctx->isTranslationUnit(); 668 Ctx = Ctx->getParent()) { 669 if (++ContextDepth == MaxDepth) 670 return true; 671 } 672 return false; 673 } 674 675 namespace { 676 677 // returns true for `X` in `template <typename... X> void foo()` 678 bool isTemplateTypeParameterPack(NamedDecl *D) { 679 if (const auto *TTPD = dyn_cast<TemplateTypeParmDecl>(D)) { 680 return TTPD->isParameterPack(); 681 } 682 return false; 683 } 684 685 // Returns the template parameter pack type from an instantiated function 686 // template, if it exists, nullptr otherwise. 687 const TemplateTypeParmType *getFunctionPackType(const FunctionDecl *Callee) { 688 if (const auto *TemplateDecl = Callee->getPrimaryTemplate()) { 689 auto TemplateParams = TemplateDecl->getTemplateParameters()->asArray(); 690 // find the template parameter pack from the back 691 const auto It = std::find_if(TemplateParams.rbegin(), TemplateParams.rend(), 692 isTemplateTypeParameterPack); 693 if (It != TemplateParams.rend()) { 694 const auto *TTPD = dyn_cast<TemplateTypeParmDecl>(*It); 695 return TTPD->getTypeForDecl()->castAs<TemplateTypeParmType>(); 696 } 697 } 698 return nullptr; 699 } 700 701 // Returns the template parameter pack type that this parameter was expanded 702 // from (if in the Args... or Args&... or Args&&... form), if this is the case, 703 // nullptr otherwise. 704 const TemplateTypeParmType *getUnderylingPackType(const ParmVarDecl *Param) { 705 const auto *PlainType = Param->getType().getTypePtr(); 706 if (auto *RT = dyn_cast<ReferenceType>(PlainType)) 707 PlainType = RT->getPointeeTypeAsWritten().getTypePtr(); 708 if (const auto *SubstType = dyn_cast<SubstTemplateTypeParmType>(PlainType)) { 709 const auto *ReplacedParameter = SubstType->getReplacedParameter(); 710 if (ReplacedParameter->isParameterPack()) { 711 return dyn_cast<TemplateTypeParmType>( 712 ReplacedParameter->getCanonicalTypeUnqualified()->getTypePtr()); 713 } 714 } 715 return nullptr; 716 } 717 718 // This visitor walks over the body of an instantiated function template. 719 // The template accepts a parameter pack and the visitor records whether 720 // the pack parameters were forwarded to another call. For example, given: 721 // 722 // template <typename T, typename... Args> 723 // auto make_unique(Args... args) { 724 // return unique_ptr<T>(new T(args...)); 725 // } 726 // 727 // When called as `make_unique<std::string>(2, 'x')` this yields a function 728 // `make_unique<std::string, int, char>` with two parameters. 729 // The visitor records that those two parameters are forwarded to the 730 // `constructor std::string(int, char);`. 731 // 732 // This information is recorded in the `ForwardingInfo` split into fully 733 // resolved parameters (passed as argument to a parameter that is not an 734 // expanded template type parameter pack) and forwarding parameters (passed to a 735 // parameter that is an expanded template type parameter pack). 736 class ForwardingCallVisitor 737 : public RecursiveASTVisitor<ForwardingCallVisitor> { 738 public: 739 ForwardingCallVisitor(ArrayRef<const ParmVarDecl *> Parameters) 740 : Parameters{Parameters}, PackType{getUnderylingPackType( 741 Parameters.front())} {} 742 743 bool VisitCallExpr(CallExpr *E) { 744 auto *Callee = getCalleeDeclOrUniqueOverload(E); 745 if (Callee) { 746 handleCall(Callee, E->arguments()); 747 } 748 return !Info.hasValue(); 749 } 750 751 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 752 auto *Callee = E->getConstructor(); 753 if (Callee) { 754 handleCall(Callee, E->arguments()); 755 } 756 return !Info.hasValue(); 757 } 758 759 // The expanded parameter pack to be resolved 760 ArrayRef<const ParmVarDecl *> Parameters; 761 // The type of the parameter pack 762 const TemplateTypeParmType *PackType; 763 764 struct ForwardingInfo { 765 // If the parameters were resolved to another FunctionDecl, these are its 766 // first non-variadic parameters (i.e. the first entries of the parameter 767 // pack that are passed as arguments bound to a non-pack parameter.) 768 ArrayRef<const ParmVarDecl *> Head; 769 // If the parameters were resolved to another FunctionDecl, these are its 770 // variadic parameters (i.e. the entries of the parameter pack that are 771 // passed as arguments bound to a pack parameter.) 772 ArrayRef<const ParmVarDecl *> Pack; 773 // If the parameters were resolved to another FunctionDecl, these are its 774 // last non-variadic parameters (i.e. the last entries of the parameter pack 775 // that are passed as arguments bound to a non-pack parameter.) 776 ArrayRef<const ParmVarDecl *> Tail; 777 // If the parameters were resolved to another forwarding FunctionDecl, this 778 // is it. 779 Optional<FunctionDecl *> PackTarget; 780 }; 781 782 // The output of this visitor 783 Optional<ForwardingInfo> Info; 784 785 private: 786 // inspects the given callee with the given args to check whether it 787 // contains Parameters, and sets Info accordingly. 788 void handleCall(FunctionDecl *Callee, typename CallExpr::arg_range Args) { 789 if (std::any_of(Args.begin(), Args.end(), [](const Expr *E) { 790 return dyn_cast<PackExpansionExpr>(E) != nullptr; 791 })) { 792 return; 793 } 794 auto OptPackLocation = findPack(Args); 795 if (OptPackLocation) { 796 size_t PackLocation = OptPackLocation.getValue(); 797 ArrayRef<ParmVarDecl *> MatchingParams = 798 Callee->parameters().slice(PackLocation, Parameters.size()); 799 // Check whether the function has a parameter pack as the last template 800 // parameter 801 if (const auto *TTPT = getFunctionPackType(Callee)) { 802 // In this case: Separate the parameters into head, pack and tail 803 auto IsExpandedPack = [&](const ParmVarDecl *P) { 804 return getUnderylingPackType(P) == TTPT; 805 }; 806 ForwardingInfo FI; 807 FI.Head = MatchingParams.take_until(IsExpandedPack); 808 FI.Pack = MatchingParams.drop_front(FI.Head.size()) 809 .take_while(IsExpandedPack); 810 FI.Tail = MatchingParams.drop_front(FI.Head.size() + FI.Pack.size()); 811 FI.PackTarget = Callee; 812 Info = FI; 813 return; 814 } 815 // Default case: assume all parameters were fully resolved 816 ForwardingInfo FI; 817 FI.Head = MatchingParams; 818 Info = FI; 819 } 820 } 821 822 // Returns the beginning of the expanded pack represented by Parameters 823 // in the given arguments, if it is there. 824 llvm::Optional<size_t> findPack(typename CallExpr::arg_range Args) { 825 // find the argument directly referring to the first parameter 826 auto FirstMatch = std::find_if(Args.begin(), Args.end(), [&](Expr *Arg) { 827 const auto *RefArg = unwrapArgument(Arg); 828 if (RefArg) { 829 if (Parameters.front() == dyn_cast<ParmVarDecl>(RefArg->getDecl())) { 830 return true; 831 } 832 } 833 return false; 834 }); 835 if (FirstMatch == Args.end()) { 836 return llvm::None; 837 } 838 return std::distance(Args.begin(), FirstMatch); 839 } 840 841 static FunctionDecl *getCalleeDeclOrUniqueOverload(CallExpr *E) { 842 Decl *CalleeDecl = E->getCalleeDecl(); 843 auto *Callee = dyn_cast_or_null<FunctionDecl>(CalleeDecl); 844 if (!Callee) { 845 if (auto *Lookup = dyn_cast<UnresolvedLookupExpr>(E->getCallee())) { 846 Callee = resolveOverload(Lookup, E); 847 } 848 } 849 // Ignore the callee if the number of arguments is wrong (deal with va_args) 850 if (Callee->getNumParams() == E->getNumArgs()) 851 return Callee; 852 return nullptr; 853 } 854 855 static FunctionDecl *resolveOverload(UnresolvedLookupExpr *Lookup, 856 CallExpr *E) { 857 FunctionDecl *MatchingDecl = nullptr; 858 if (!Lookup->requiresADL()) { 859 // Check whether there is a single overload with this number of 860 // parameters 861 for (auto *Candidate : Lookup->decls()) { 862 if (auto *FuncCandidate = dyn_cast_or_null<FunctionDecl>(Candidate)) { 863 if (FuncCandidate->getNumParams() == E->getNumArgs()) { 864 if (MatchingDecl) { 865 // there are multiple candidates - abort 866 return nullptr; 867 } 868 MatchingDecl = FuncCandidate; 869 } 870 } 871 } 872 } 873 return MatchingDecl; 874 } 875 876 // Removes any implicit cast expressions around the given expression. 877 static const Expr *unwrapImplicitCast(const Expr *E) { 878 while (const auto *Cast = dyn_cast<ImplicitCastExpr>(E)) { 879 E = Cast->getSubExpr(); 880 } 881 return E; 882 } 883 884 // Maps std::forward(E) to E, nullptr otherwise 885 static const Expr *unwrapForward(const Expr *E) { 886 if (const auto *Call = dyn_cast<CallExpr>(E)) { 887 const auto Callee = Call->getBuiltinCallee(); 888 if (Callee == Builtin::BIforward) { 889 return Call->getArg(0); 890 } 891 } 892 return E; 893 } 894 895 // Maps std::forward(DeclRefExpr) to DeclRefExpr, removing any intermediate 896 // implicit casts, nullptr otherwise 897 static const DeclRefExpr *unwrapArgument(const Expr *E) { 898 E = unwrapImplicitCast(E); 899 E = unwrapForward(E); 900 E = unwrapImplicitCast(E); 901 return dyn_cast<DeclRefExpr>(E); 902 } 903 }; 904 905 } // namespace 906 907 SmallVector<const ParmVarDecl *> 908 resolveForwardingParameters(const FunctionDecl *D, unsigned MaxDepth) { 909 auto Parameters = D->parameters(); 910 // If the function has a template parameter pack 911 if (const auto *TTPT = getFunctionPackType(D)) { 912 // Split the parameters into head, pack and tail 913 auto IsExpandedPack = [TTPT](const ParmVarDecl *P) { 914 return getUnderylingPackType(P) == TTPT; 915 }; 916 ArrayRef<const ParmVarDecl *> Head = Parameters.take_until(IsExpandedPack); 917 ArrayRef<const ParmVarDecl *> Pack = 918 Parameters.drop_front(Head.size()).take_while(IsExpandedPack); 919 ArrayRef<const ParmVarDecl *> Tail = 920 Parameters.drop_front(Head.size() + Pack.size()); 921 SmallVector<const ParmVarDecl *> Result(Parameters.size()); 922 // Fill in non-pack parameters 923 auto HeadIt = std::copy(Head.begin(), Head.end(), Result.begin()); 924 auto TailIt = std::copy(Tail.rbegin(), Tail.rend(), Result.rbegin()); 925 // Recurse on pack parameters 926 size_t Depth = 0; 927 const FunctionDecl *CurrentFunction = D; 928 llvm::SmallSet<const FunctionTemplateDecl *, 4> SeenTemplates; 929 if (const auto *Template = D->getPrimaryTemplate()) { 930 SeenTemplates.insert(Template); 931 } 932 while (!Pack.empty() && CurrentFunction && Depth < MaxDepth) { 933 // Find call expressions involving the pack 934 ForwardingCallVisitor V{Pack}; 935 V.TraverseStmt(CurrentFunction->getBody()); 936 if (!V.Info) { 937 break; 938 } 939 // If we found something: Fill in non-pack parameters 940 auto Info = V.Info.getValue(); 941 HeadIt = std::copy(Info.Head.begin(), Info.Head.end(), HeadIt); 942 TailIt = std::copy(Info.Tail.rbegin(), Info.Tail.rend(), TailIt); 943 // Prepare next recursion level 944 Pack = Info.Pack; 945 CurrentFunction = Info.PackTarget.getValueOr(nullptr); 946 Depth++; 947 // If we are recursing into a previously encountered function: Abort 948 if (CurrentFunction) { 949 if (const auto *Template = CurrentFunction->getPrimaryTemplate()) { 950 bool NewFunction = SeenTemplates.insert(Template).second; 951 if (!NewFunction) { 952 return {Parameters.begin(), Parameters.end()}; 953 } 954 } 955 } 956 } 957 // Fill in the remaining unresolved pack parameters 958 HeadIt = std::copy(Pack.begin(), Pack.end(), HeadIt); 959 assert(TailIt.base() == HeadIt); 960 return Result; 961 } 962 return {Parameters.begin(), Parameters.end()}; 963 } 964 965 bool isExpandedFromParameterPack(const ParmVarDecl *D) { 966 return getUnderylingPackType(D) != nullptr; 967 } 968 969 } // namespace clangd 970 } // namespace clang 971