1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Decl subclasses. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/Decl.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/Attr.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/PrettyPrinter.h" 25 #include "clang/AST/Stmt.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/IdentifierTable.h" 29 #include "clang/Basic/Module.h" 30 #include "clang/Basic/Specifiers.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Frontend/FrontendDiagnostic.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include <algorithm> 35 36 using namespace clang; 37 38 Decl *clang::getPrimaryMergedDecl(Decl *D) { 39 return D->getASTContext().getPrimaryMergedDecl(D); 40 } 41 42 // Defined here so that it can be inlined into its direct callers. 43 bool Decl::isOutOfLine() const { 44 return !getLexicalDeclContext()->Equals(getDeclContext()); 45 } 46 47 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx) 48 : Decl(TranslationUnit, nullptr, SourceLocation()), 49 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) { 50 Hidden = Ctx.getLangOpts().ModulesLocalVisibility; 51 } 52 53 //===----------------------------------------------------------------------===// 54 // NamedDecl Implementation 55 //===----------------------------------------------------------------------===// 56 57 // Visibility rules aren't rigorously externally specified, but here 58 // are the basic principles behind what we implement: 59 // 60 // 1. An explicit visibility attribute is generally a direct expression 61 // of the user's intent and should be honored. Only the innermost 62 // visibility attribute applies. If no visibility attribute applies, 63 // global visibility settings are considered. 64 // 65 // 2. There is one caveat to the above: on or in a template pattern, 66 // an explicit visibility attribute is just a default rule, and 67 // visibility can be decreased by the visibility of template 68 // arguments. But this, too, has an exception: an attribute on an 69 // explicit specialization or instantiation causes all the visibility 70 // restrictions of the template arguments to be ignored. 71 // 72 // 3. A variable that does not otherwise have explicit visibility can 73 // be restricted by the visibility of its type. 74 // 75 // 4. A visibility restriction is explicit if it comes from an 76 // attribute (or something like it), not a global visibility setting. 77 // When emitting a reference to an external symbol, visibility 78 // restrictions are ignored unless they are explicit. 79 // 80 // 5. When computing the visibility of a non-type, including a 81 // non-type member of a class, only non-type visibility restrictions 82 // are considered: the 'visibility' attribute, global value-visibility 83 // settings, and a few special cases like __private_extern. 84 // 85 // 6. When computing the visibility of a type, including a type member 86 // of a class, only type visibility restrictions are considered: 87 // the 'type_visibility' attribute and global type-visibility settings. 88 // However, a 'visibility' attribute counts as a 'type_visibility' 89 // attribute on any declaration that only has the former. 90 // 91 // The visibility of a "secondary" entity, like a template argument, 92 // is computed using the kind of that entity, not the kind of the 93 // primary entity for which we are computing visibility. For example, 94 // the visibility of a specialization of either of these templates: 95 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X); 96 // template <class T, bool (&compare)(T, X)> class matcher; 97 // is restricted according to the type visibility of the argument 'T', 98 // the type visibility of 'bool(&)(T,X)', and the value visibility of 99 // the argument function 'compare'. That 'has_match' is a value 100 // and 'matcher' is a type only matters when looking for attributes 101 // and settings from the immediate context. 102 103 const unsigned IgnoreExplicitVisibilityBit = 2; 104 const unsigned IgnoreAllVisibilityBit = 4; 105 106 /// Kinds of LV computation. The linkage side of the computation is 107 /// always the same, but different things can change how visibility is 108 /// computed. 109 enum LVComputationKind { 110 /// Do an LV computation for, ultimately, a type. 111 /// Visibility may be restricted by type visibility settings and 112 /// the visibility of template arguments. 113 LVForType = NamedDecl::VisibilityForType, 114 115 /// Do an LV computation for, ultimately, a non-type declaration. 116 /// Visibility may be restricted by value visibility settings and 117 /// the visibility of template arguments. 118 LVForValue = NamedDecl::VisibilityForValue, 119 120 /// Do an LV computation for, ultimately, a type that already has 121 /// some sort of explicit visibility. Visibility may only be 122 /// restricted by the visibility of template arguments. 123 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit), 124 125 /// Do an LV computation for, ultimately, a non-type declaration 126 /// that already has some sort of explicit visibility. Visibility 127 /// may only be restricted by the visibility of template arguments. 128 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit), 129 130 /// Do an LV computation when we only care about the linkage. 131 LVForLinkageOnly = 132 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit 133 }; 134 135 /// Does this computation kind permit us to consider additional 136 /// visibility settings from attributes and the like? 137 static bool hasExplicitVisibilityAlready(LVComputationKind computation) { 138 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0); 139 } 140 141 /// Given an LVComputationKind, return one of the same type/value sort 142 /// that records that it already has explicit visibility. 143 static LVComputationKind 144 withExplicitVisibilityAlready(LVComputationKind oldKind) { 145 LVComputationKind newKind = 146 static_cast<LVComputationKind>(unsigned(oldKind) | 147 IgnoreExplicitVisibilityBit); 148 assert(oldKind != LVForType || newKind == LVForExplicitType); 149 assert(oldKind != LVForValue || newKind == LVForExplicitValue); 150 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType); 151 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue); 152 return newKind; 153 } 154 155 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D, 156 LVComputationKind kind) { 157 assert(!hasExplicitVisibilityAlready(kind) && 158 "asking for explicit visibility when we shouldn't be"); 159 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind); 160 } 161 162 /// Is the given declaration a "type" or a "value" for the purposes of 163 /// visibility computation? 164 static bool usesTypeVisibility(const NamedDecl *D) { 165 return isa<TypeDecl>(D) || 166 isa<ClassTemplateDecl>(D) || 167 isa<ObjCInterfaceDecl>(D); 168 } 169 170 /// Does the given declaration have member specialization information, 171 /// and if so, is it an explicit specialization? 172 template <class T> static typename 173 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type 174 isExplicitMemberSpecialization(const T *D) { 175 if (const MemberSpecializationInfo *member = 176 D->getMemberSpecializationInfo()) { 177 return member->isExplicitSpecialization(); 178 } 179 return false; 180 } 181 182 /// For templates, this question is easier: a member template can't be 183 /// explicitly instantiated, so there's a single bit indicating whether 184 /// or not this is an explicit member specialization. 185 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) { 186 return D->isMemberSpecialization(); 187 } 188 189 /// Given a visibility attribute, return the explicit visibility 190 /// associated with it. 191 template <class T> 192 static Visibility getVisibilityFromAttr(const T *attr) { 193 switch (attr->getVisibility()) { 194 case T::Default: 195 return DefaultVisibility; 196 case T::Hidden: 197 return HiddenVisibility; 198 case T::Protected: 199 return ProtectedVisibility; 200 } 201 llvm_unreachable("bad visibility kind"); 202 } 203 204 /// Return the explicit visibility of the given declaration. 205 static Optional<Visibility> getVisibilityOf(const NamedDecl *D, 206 NamedDecl::ExplicitVisibilityKind kind) { 207 // If we're ultimately computing the visibility of a type, look for 208 // a 'type_visibility' attribute before looking for 'visibility'. 209 if (kind == NamedDecl::VisibilityForType) { 210 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) { 211 return getVisibilityFromAttr(A); 212 } 213 } 214 215 // If this declaration has an explicit visibility attribute, use it. 216 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) { 217 return getVisibilityFromAttr(A); 218 } 219 220 // If we're on Mac OS X, an 'availability' for Mac OS X attribute 221 // implies visibility(default). 222 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) { 223 for (const auto *A : D->specific_attrs<AvailabilityAttr>()) 224 if (A->getPlatform()->getName().equals("macosx")) 225 return DefaultVisibility; 226 } 227 228 return None; 229 } 230 231 static LinkageInfo 232 getLVForType(const Type &T, LVComputationKind computation) { 233 if (computation == LVForLinkageOnly) 234 return LinkageInfo(T.getLinkage(), DefaultVisibility, true); 235 return T.getLinkageAndVisibility(); 236 } 237 238 /// \brief Get the most restrictive linkage for the types in the given 239 /// template parameter list. For visibility purposes, template 240 /// parameters are part of the signature of a template. 241 static LinkageInfo 242 getLVForTemplateParameterList(const TemplateParameterList *Params, 243 LVComputationKind computation) { 244 LinkageInfo LV; 245 for (const NamedDecl *P : *Params) { 246 // Template type parameters are the most common and never 247 // contribute to visibility, pack or not. 248 if (isa<TemplateTypeParmDecl>(P)) 249 continue; 250 251 // Non-type template parameters can be restricted by the value type, e.g. 252 // template <enum X> class A { ... }; 253 // We have to be careful here, though, because we can be dealing with 254 // dependent types. 255 if (const NonTypeTemplateParmDecl *NTTP = 256 dyn_cast<NonTypeTemplateParmDecl>(P)) { 257 // Handle the non-pack case first. 258 if (!NTTP->isExpandedParameterPack()) { 259 if (!NTTP->getType()->isDependentType()) { 260 LV.merge(getLVForType(*NTTP->getType(), computation)); 261 } 262 continue; 263 } 264 265 // Look at all the types in an expanded pack. 266 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) { 267 QualType type = NTTP->getExpansionType(i); 268 if (!type->isDependentType()) 269 LV.merge(type->getLinkageAndVisibility()); 270 } 271 continue; 272 } 273 274 // Template template parameters can be restricted by their 275 // template parameters, recursively. 276 const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P); 277 278 // Handle the non-pack case first. 279 if (!TTP->isExpandedParameterPack()) { 280 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(), 281 computation)); 282 continue; 283 } 284 285 // Look at all expansions in an expanded pack. 286 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters(); 287 i != n; ++i) { 288 LV.merge(getLVForTemplateParameterList( 289 TTP->getExpansionTemplateParameters(i), computation)); 290 } 291 } 292 293 return LV; 294 } 295 296 /// getLVForDecl - Get the linkage and visibility for the given declaration. 297 static LinkageInfo getLVForDecl(const NamedDecl *D, 298 LVComputationKind computation); 299 300 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) { 301 const Decl *Ret = nullptr; 302 const DeclContext *DC = D->getDeclContext(); 303 while (DC->getDeclKind() != Decl::TranslationUnit) { 304 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC)) 305 Ret = cast<Decl>(DC); 306 DC = DC->getParent(); 307 } 308 return Ret; 309 } 310 311 /// \brief Get the most restrictive linkage for the types and 312 /// declarations in the given template argument list. 313 /// 314 /// Note that we don't take an LVComputationKind because we always 315 /// want to honor the visibility of template arguments in the same way. 316 static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args, 317 LVComputationKind computation) { 318 LinkageInfo LV; 319 320 for (const TemplateArgument &Arg : Args) { 321 switch (Arg.getKind()) { 322 case TemplateArgument::Null: 323 case TemplateArgument::Integral: 324 case TemplateArgument::Expression: 325 continue; 326 327 case TemplateArgument::Type: 328 LV.merge(getLVForType(*Arg.getAsType(), computation)); 329 continue; 330 331 case TemplateArgument::Declaration: 332 if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) { 333 assert(!usesTypeVisibility(ND)); 334 LV.merge(getLVForDecl(ND, computation)); 335 } 336 continue; 337 338 case TemplateArgument::NullPtr: 339 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility()); 340 continue; 341 342 case TemplateArgument::Template: 343 case TemplateArgument::TemplateExpansion: 344 if (TemplateDecl *Template = 345 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()) 346 LV.merge(getLVForDecl(Template, computation)); 347 continue; 348 349 case TemplateArgument::Pack: 350 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation)); 351 continue; 352 } 353 llvm_unreachable("bad template argument kind"); 354 } 355 356 return LV; 357 } 358 359 static LinkageInfo 360 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs, 361 LVComputationKind computation) { 362 return getLVForTemplateArgumentList(TArgs.asArray(), computation); 363 } 364 365 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn, 366 const FunctionTemplateSpecializationInfo *specInfo) { 367 // Include visibility from the template parameters and arguments 368 // only if this is not an explicit instantiation or specialization 369 // with direct explicit visibility. (Implicit instantiations won't 370 // have a direct attribute.) 371 if (!specInfo->isExplicitInstantiationOrSpecialization()) 372 return true; 373 374 return !fn->hasAttr<VisibilityAttr>(); 375 } 376 377 /// Merge in template-related linkage and visibility for the given 378 /// function template specialization. 379 /// 380 /// We don't need a computation kind here because we can assume 381 /// LVForValue. 382 /// 383 /// \param[out] LV the computation to use for the parent 384 static void 385 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn, 386 const FunctionTemplateSpecializationInfo *specInfo, 387 LVComputationKind computation) { 388 bool considerVisibility = 389 shouldConsiderTemplateVisibility(fn, specInfo); 390 391 // Merge information from the template parameters. 392 FunctionTemplateDecl *temp = specInfo->getTemplate(); 393 LinkageInfo tempLV = 394 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 395 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 396 397 // Merge information from the template arguments. 398 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments; 399 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 400 LV.mergeMaybeWithVisibility(argsLV, considerVisibility); 401 } 402 403 /// Does the given declaration have a direct visibility attribute 404 /// that would match the given rules? 405 static bool hasDirectVisibilityAttribute(const NamedDecl *D, 406 LVComputationKind computation) { 407 switch (computation) { 408 case LVForType: 409 case LVForExplicitType: 410 if (D->hasAttr<TypeVisibilityAttr>()) 411 return true; 412 // fallthrough 413 case LVForValue: 414 case LVForExplicitValue: 415 if (D->hasAttr<VisibilityAttr>()) 416 return true; 417 return false; 418 case LVForLinkageOnly: 419 return false; 420 } 421 llvm_unreachable("bad visibility computation kind"); 422 } 423 424 /// Should we consider visibility associated with the template 425 /// arguments and parameters of the given class template specialization? 426 static bool shouldConsiderTemplateVisibility( 427 const ClassTemplateSpecializationDecl *spec, 428 LVComputationKind computation) { 429 // Include visibility from the template parameters and arguments 430 // only if this is not an explicit instantiation or specialization 431 // with direct explicit visibility (and note that implicit 432 // instantiations won't have a direct attribute). 433 // 434 // Furthermore, we want to ignore template parameters and arguments 435 // for an explicit specialization when computing the visibility of a 436 // member thereof with explicit visibility. 437 // 438 // This is a bit complex; let's unpack it. 439 // 440 // An explicit class specialization is an independent, top-level 441 // declaration. As such, if it or any of its members has an 442 // explicit visibility attribute, that must directly express the 443 // user's intent, and we should honor it. The same logic applies to 444 // an explicit instantiation of a member of such a thing. 445 446 // Fast path: if this is not an explicit instantiation or 447 // specialization, we always want to consider template-related 448 // visibility restrictions. 449 if (!spec->isExplicitInstantiationOrSpecialization()) 450 return true; 451 452 // This is the 'member thereof' check. 453 if (spec->isExplicitSpecialization() && 454 hasExplicitVisibilityAlready(computation)) 455 return false; 456 457 return !hasDirectVisibilityAttribute(spec, computation); 458 } 459 460 /// Merge in template-related linkage and visibility for the given 461 /// class template specialization. 462 static void mergeTemplateLV(LinkageInfo &LV, 463 const ClassTemplateSpecializationDecl *spec, 464 LVComputationKind computation) { 465 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); 466 467 // Merge information from the template parameters, but ignore 468 // visibility if we're only considering template arguments. 469 470 ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 471 LinkageInfo tempLV = 472 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 473 LV.mergeMaybeWithVisibility(tempLV, 474 considerVisibility && !hasExplicitVisibilityAlready(computation)); 475 476 // Merge information from the template arguments. We ignore 477 // template-argument visibility if we've got an explicit 478 // instantiation with a visibility attribute. 479 const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); 480 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 481 if (considerVisibility) 482 LV.mergeVisibility(argsLV); 483 LV.mergeExternalVisibility(argsLV); 484 } 485 486 /// Should we consider visibility associated with the template 487 /// arguments and parameters of the given variable template 488 /// specialization? As usual, follow class template specialization 489 /// logic up to initialization. 490 static bool shouldConsiderTemplateVisibility( 491 const VarTemplateSpecializationDecl *spec, 492 LVComputationKind computation) { 493 // Include visibility from the template parameters and arguments 494 // only if this is not an explicit instantiation or specialization 495 // with direct explicit visibility (and note that implicit 496 // instantiations won't have a direct attribute). 497 if (!spec->isExplicitInstantiationOrSpecialization()) 498 return true; 499 500 // An explicit variable specialization is an independent, top-level 501 // declaration. As such, if it has an explicit visibility attribute, 502 // that must directly express the user's intent, and we should honor 503 // it. 504 if (spec->isExplicitSpecialization() && 505 hasExplicitVisibilityAlready(computation)) 506 return false; 507 508 return !hasDirectVisibilityAttribute(spec, computation); 509 } 510 511 /// Merge in template-related linkage and visibility for the given 512 /// variable template specialization. As usual, follow class template 513 /// specialization logic up to initialization. 514 static void mergeTemplateLV(LinkageInfo &LV, 515 const VarTemplateSpecializationDecl *spec, 516 LVComputationKind computation) { 517 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); 518 519 // Merge information from the template parameters, but ignore 520 // visibility if we're only considering template arguments. 521 522 VarTemplateDecl *temp = spec->getSpecializedTemplate(); 523 LinkageInfo tempLV = 524 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 525 LV.mergeMaybeWithVisibility(tempLV, 526 considerVisibility && !hasExplicitVisibilityAlready(computation)); 527 528 // Merge information from the template arguments. We ignore 529 // template-argument visibility if we've got an explicit 530 // instantiation with a visibility attribute. 531 const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); 532 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); 533 if (considerVisibility) 534 LV.mergeVisibility(argsLV); 535 LV.mergeExternalVisibility(argsLV); 536 } 537 538 static bool useInlineVisibilityHidden(const NamedDecl *D) { 539 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c. 540 const LangOptions &Opts = D->getASTContext().getLangOpts(); 541 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden) 542 return false; 543 544 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 545 if (!FD) 546 return false; 547 548 TemplateSpecializationKind TSK = TSK_Undeclared; 549 if (FunctionTemplateSpecializationInfo *spec 550 = FD->getTemplateSpecializationInfo()) { 551 TSK = spec->getTemplateSpecializationKind(); 552 } else if (MemberSpecializationInfo *MSI = 553 FD->getMemberSpecializationInfo()) { 554 TSK = MSI->getTemplateSpecializationKind(); 555 } 556 557 const FunctionDecl *Def = nullptr; 558 // InlineVisibilityHidden only applies to definitions, and 559 // isInlined() only gives meaningful answers on definitions 560 // anyway. 561 return TSK != TSK_ExplicitInstantiationDeclaration && 562 TSK != TSK_ExplicitInstantiationDefinition && 563 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>(); 564 } 565 566 template <typename T> static bool isFirstInExternCContext(T *D) { 567 const T *First = D->getFirstDecl(); 568 return First->isInExternCContext(); 569 } 570 571 static bool isSingleLineLanguageLinkage(const Decl &D) { 572 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext())) 573 if (!SD->hasBraces()) 574 return true; 575 return false; 576 } 577 578 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, 579 LVComputationKind computation) { 580 assert(D->getDeclContext()->getRedeclContext()->isFileContext() && 581 "Not a name having namespace scope"); 582 ASTContext &Context = D->getASTContext(); 583 584 // C++ [basic.link]p3: 585 // A name having namespace scope (3.3.6) has internal linkage if it 586 // is the name of 587 // - an object, reference, function or function template that is 588 // explicitly declared static; or, 589 // (This bullet corresponds to C99 6.2.2p3.) 590 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 591 // Explicitly declared static. 592 if (Var->getStorageClass() == SC_Static) 593 return LinkageInfo::internal(); 594 595 // - a non-volatile object or reference that is explicitly declared const 596 // or constexpr and neither explicitly declared extern nor previously 597 // declared to have external linkage; or (there is no equivalent in C99) 598 if (Context.getLangOpts().CPlusPlus && 599 Var->getType().isConstQualified() && 600 !Var->getType().isVolatileQualified()) { 601 const VarDecl *PrevVar = Var->getPreviousDecl(); 602 if (PrevVar) 603 return getLVForDecl(PrevVar, computation); 604 605 if (Var->getStorageClass() != SC_Extern && 606 Var->getStorageClass() != SC_PrivateExtern && 607 !isSingleLineLanguageLinkage(*Var)) 608 return LinkageInfo::internal(); 609 } 610 611 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar; 612 PrevVar = PrevVar->getPreviousDecl()) { 613 if (PrevVar->getStorageClass() == SC_PrivateExtern && 614 Var->getStorageClass() == SC_None) 615 return PrevVar->getLinkageAndVisibility(); 616 // Explicitly declared static. 617 if (PrevVar->getStorageClass() == SC_Static) 618 return LinkageInfo::internal(); 619 } 620 } else if (const FunctionDecl *Function = D->getAsFunction()) { 621 // C++ [temp]p4: 622 // A non-member function template can have internal linkage; any 623 // other template name shall have external linkage. 624 625 // Explicitly declared static. 626 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static) 627 return LinkageInfo(InternalLinkage, DefaultVisibility, false); 628 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) { 629 // - a data member of an anonymous union. 630 const VarDecl *VD = IFD->getVarDecl(); 631 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!"); 632 return getLVForNamespaceScopeDecl(VD, computation); 633 } 634 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!"); 635 636 if (D->isInAnonymousNamespace()) { 637 const VarDecl *Var = dyn_cast<VarDecl>(D); 638 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D); 639 if ((!Var || !isFirstInExternCContext(Var)) && 640 (!Func || !isFirstInExternCContext(Func))) 641 return LinkageInfo::uniqueExternal(); 642 } 643 644 // Set up the defaults. 645 646 // C99 6.2.2p5: 647 // If the declaration of an identifier for an object has file 648 // scope and no storage-class specifier, its linkage is 649 // external. 650 LinkageInfo LV; 651 652 if (!hasExplicitVisibilityAlready(computation)) { 653 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) { 654 LV.mergeVisibility(*Vis, true); 655 } else { 656 // If we're declared in a namespace with a visibility attribute, 657 // use that namespace's visibility, and it still counts as explicit. 658 for (const DeclContext *DC = D->getDeclContext(); 659 !isa<TranslationUnitDecl>(DC); 660 DC = DC->getParent()) { 661 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC); 662 if (!ND) continue; 663 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) { 664 LV.mergeVisibility(*Vis, true); 665 break; 666 } 667 } 668 } 669 670 // Add in global settings if the above didn't give us direct visibility. 671 if (!LV.isVisibilityExplicit()) { 672 // Use global type/value visibility as appropriate. 673 Visibility globalVisibility; 674 if (computation == LVForValue) { 675 globalVisibility = Context.getLangOpts().getValueVisibilityMode(); 676 } else { 677 assert(computation == LVForType); 678 globalVisibility = Context.getLangOpts().getTypeVisibilityMode(); 679 } 680 LV.mergeVisibility(globalVisibility, /*explicit*/ false); 681 682 // If we're paying attention to global visibility, apply 683 // -finline-visibility-hidden if this is an inline method. 684 if (useInlineVisibilityHidden(D)) 685 LV.mergeVisibility(HiddenVisibility, true); 686 } 687 } 688 689 // C++ [basic.link]p4: 690 691 // A name having namespace scope has external linkage if it is the 692 // name of 693 // 694 // - an object or reference, unless it has internal linkage; or 695 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 696 // GCC applies the following optimization to variables and static 697 // data members, but not to functions: 698 // 699 // Modify the variable's LV by the LV of its type unless this is 700 // C or extern "C". This follows from [basic.link]p9: 701 // A type without linkage shall not be used as the type of a 702 // variable or function with external linkage unless 703 // - the entity has C language linkage, or 704 // - the entity is declared within an unnamed namespace, or 705 // - the entity is not used or is defined in the same 706 // translation unit. 707 // and [basic.link]p10: 708 // ...the types specified by all declarations referring to a 709 // given variable or function shall be identical... 710 // C does not have an equivalent rule. 711 // 712 // Ignore this if we've got an explicit attribute; the user 713 // probably knows what they're doing. 714 // 715 // Note that we don't want to make the variable non-external 716 // because of this, but unique-external linkage suits us. 717 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) { 718 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation); 719 if (TypeLV.getLinkage() != ExternalLinkage) 720 return LinkageInfo::uniqueExternal(); 721 if (!LV.isVisibilityExplicit()) 722 LV.mergeVisibility(TypeLV); 723 } 724 725 if (Var->getStorageClass() == SC_PrivateExtern) 726 LV.mergeVisibility(HiddenVisibility, true); 727 728 // Note that Sema::MergeVarDecl already takes care of implementing 729 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have 730 // to do it here. 731 732 // As per function and class template specializations (below), 733 // consider LV for the template and template arguments. We're at file 734 // scope, so we do not need to worry about nested specializations. 735 if (const VarTemplateSpecializationDecl *spec 736 = dyn_cast<VarTemplateSpecializationDecl>(Var)) { 737 mergeTemplateLV(LV, spec, computation); 738 } 739 740 // - a function, unless it has internal linkage; or 741 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 742 // In theory, we can modify the function's LV by the LV of its 743 // type unless it has C linkage (see comment above about variables 744 // for justification). In practice, GCC doesn't do this, so it's 745 // just too painful to make work. 746 747 if (Function->getStorageClass() == SC_PrivateExtern) 748 LV.mergeVisibility(HiddenVisibility, true); 749 750 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 751 // merging storage classes and visibility attributes, so we don't have to 752 // look at previous decls in here. 753 754 // In C++, then if the type of the function uses a type with 755 // unique-external linkage, it's not legally usable from outside 756 // this translation unit. However, we should use the C linkage 757 // rules instead for extern "C" declarations. 758 if (Context.getLangOpts().CPlusPlus && 759 !Function->isInExternCContext()) { 760 // Only look at the type-as-written. If this function has an auto-deduced 761 // return type, we can't compute the linkage of that type because it could 762 // require looking at the linkage of this function, and we don't need this 763 // for correctness because the type is not part of the function's 764 // signature. 765 // FIXME: This is a hack. We should be able to solve this circularity and 766 // the one in getLVForClassMember for Functions some other way. 767 QualType TypeAsWritten = Function->getType(); 768 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo()) 769 TypeAsWritten = TSI->getType(); 770 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage) 771 return LinkageInfo::uniqueExternal(); 772 } 773 774 // Consider LV from the template and the template arguments. 775 // We're at file scope, so we do not need to worry about nested 776 // specializations. 777 if (FunctionTemplateSpecializationInfo *specInfo 778 = Function->getTemplateSpecializationInfo()) { 779 mergeTemplateLV(LV, Function, specInfo, computation); 780 } 781 782 // - a named class (Clause 9), or an unnamed class defined in a 783 // typedef declaration in which the class has the typedef name 784 // for linkage purposes (7.1.3); or 785 // - a named enumeration (7.2), or an unnamed enumeration 786 // defined in a typedef declaration in which the enumeration 787 // has the typedef name for linkage purposes (7.1.3); or 788 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) { 789 // Unnamed tags have no linkage. 790 if (!Tag->hasNameForLinkage()) 791 return LinkageInfo::none(); 792 793 // If this is a class template specialization, consider the 794 // linkage of the template and template arguments. We're at file 795 // scope, so we do not need to worry about nested specializations. 796 if (const ClassTemplateSpecializationDecl *spec 797 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 798 mergeTemplateLV(LV, spec, computation); 799 } 800 801 // - an enumerator belonging to an enumeration with external linkage; 802 } else if (isa<EnumConstantDecl>(D)) { 803 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), 804 computation); 805 if (!isExternalFormalLinkage(EnumLV.getLinkage())) 806 return LinkageInfo::none(); 807 LV.merge(EnumLV); 808 809 // - a template, unless it is a function template that has 810 // internal linkage (Clause 14); 811 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) { 812 bool considerVisibility = !hasExplicitVisibilityAlready(computation); 813 LinkageInfo tempLV = 814 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 815 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 816 817 // - a namespace (7.3), unless it is declared within an unnamed 818 // namespace. 819 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) { 820 return LV; 821 822 // By extension, we assign external linkage to Objective-C 823 // interfaces. 824 } else if (isa<ObjCInterfaceDecl>(D)) { 825 // fallout 826 827 // Everything not covered here has no linkage. 828 } else { 829 // FIXME: A typedef declaration has linkage if it gives a type a name for 830 // linkage purposes. 831 return LinkageInfo::none(); 832 } 833 834 // If we ended up with non-external linkage, visibility should 835 // always be default. 836 if (LV.getLinkage() != ExternalLinkage) 837 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false); 838 839 return LV; 840 } 841 842 static LinkageInfo getLVForClassMember(const NamedDecl *D, 843 LVComputationKind computation) { 844 // Only certain class members have linkage. Note that fields don't 845 // really have linkage, but it's convenient to say they do for the 846 // purposes of calculating linkage of pointer-to-data-member 847 // template arguments. 848 // 849 // Templates also don't officially have linkage, but since we ignore 850 // the C++ standard and look at template arguments when determining 851 // linkage and visibility of a template specialization, we might hit 852 // a template template argument that way. If we do, we need to 853 // consider its linkage. 854 if (!(isa<CXXMethodDecl>(D) || 855 isa<VarDecl>(D) || 856 isa<FieldDecl>(D) || 857 isa<IndirectFieldDecl>(D) || 858 isa<TagDecl>(D) || 859 isa<TemplateDecl>(D))) 860 return LinkageInfo::none(); 861 862 LinkageInfo LV; 863 864 // If we have an explicit visibility attribute, merge that in. 865 if (!hasExplicitVisibilityAlready(computation)) { 866 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) 867 LV.mergeVisibility(*Vis, true); 868 // If we're paying attention to global visibility, apply 869 // -finline-visibility-hidden if this is an inline method. 870 // 871 // Note that we do this before merging information about 872 // the class visibility. 873 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D)) 874 LV.mergeVisibility(HiddenVisibility, true); 875 } 876 877 // If this class member has an explicit visibility attribute, the only 878 // thing that can change its visibility is the template arguments, so 879 // only look for them when processing the class. 880 LVComputationKind classComputation = computation; 881 if (LV.isVisibilityExplicit()) 882 classComputation = withExplicitVisibilityAlready(computation); 883 884 LinkageInfo classLV = 885 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation); 886 // If the class already has unique-external linkage, we can't improve. 887 if (classLV.getLinkage() == UniqueExternalLinkage) 888 return LinkageInfo::uniqueExternal(); 889 890 if (!isExternallyVisible(classLV.getLinkage())) 891 return LinkageInfo::none(); 892 893 894 // Otherwise, don't merge in classLV yet, because in certain cases 895 // we need to completely ignore the visibility from it. 896 897 // Specifically, if this decl exists and has an explicit attribute. 898 const NamedDecl *explicitSpecSuppressor = nullptr; 899 900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 901 // If the type of the function uses a type with unique-external 902 // linkage, it's not legally usable from outside this translation unit. 903 // But only look at the type-as-written. If this function has an 904 // auto-deduced return type, we can't compute the linkage of that type 905 // because it could require looking at the linkage of this function, and we 906 // don't need this for correctness because the type is not part of the 907 // function's signature. 908 // FIXME: This is a hack. We should be able to solve this circularity and 909 // the one in getLVForNamespaceScopeDecl for Functions some other way. 910 { 911 QualType TypeAsWritten = MD->getType(); 912 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 913 TypeAsWritten = TSI->getType(); 914 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage) 915 return LinkageInfo::uniqueExternal(); 916 } 917 // If this is a method template specialization, use the linkage for 918 // the template parameters and arguments. 919 if (FunctionTemplateSpecializationInfo *spec 920 = MD->getTemplateSpecializationInfo()) { 921 mergeTemplateLV(LV, MD, spec, computation); 922 if (spec->isExplicitSpecialization()) { 923 explicitSpecSuppressor = MD; 924 } else if (isExplicitMemberSpecialization(spec->getTemplate())) { 925 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl(); 926 } 927 } else if (isExplicitMemberSpecialization(MD)) { 928 explicitSpecSuppressor = MD; 929 } 930 931 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 932 if (const ClassTemplateSpecializationDecl *spec 933 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 934 mergeTemplateLV(LV, spec, computation); 935 if (spec->isExplicitSpecialization()) { 936 explicitSpecSuppressor = spec; 937 } else { 938 const ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 939 if (isExplicitMemberSpecialization(temp)) { 940 explicitSpecSuppressor = temp->getTemplatedDecl(); 941 } 942 } 943 } else if (isExplicitMemberSpecialization(RD)) { 944 explicitSpecSuppressor = RD; 945 } 946 947 // Static data members. 948 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 949 if (const VarTemplateSpecializationDecl *spec 950 = dyn_cast<VarTemplateSpecializationDecl>(VD)) 951 mergeTemplateLV(LV, spec, computation); 952 953 // Modify the variable's linkage by its type, but ignore the 954 // type's visibility unless it's a definition. 955 LinkageInfo typeLV = getLVForType(*VD->getType(), computation); 956 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit()) 957 LV.mergeVisibility(typeLV); 958 LV.mergeExternalVisibility(typeLV); 959 960 if (isExplicitMemberSpecialization(VD)) { 961 explicitSpecSuppressor = VD; 962 } 963 964 // Template members. 965 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) { 966 bool considerVisibility = 967 (!LV.isVisibilityExplicit() && 968 !classLV.isVisibilityExplicit() && 969 !hasExplicitVisibilityAlready(computation)); 970 LinkageInfo tempLV = 971 getLVForTemplateParameterList(temp->getTemplateParameters(), computation); 972 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 973 974 if (const RedeclarableTemplateDecl *redeclTemp = 975 dyn_cast<RedeclarableTemplateDecl>(temp)) { 976 if (isExplicitMemberSpecialization(redeclTemp)) { 977 explicitSpecSuppressor = temp->getTemplatedDecl(); 978 } 979 } 980 } 981 982 // We should never be looking for an attribute directly on a template. 983 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor)); 984 985 // If this member is an explicit member specialization, and it has 986 // an explicit attribute, ignore visibility from the parent. 987 bool considerClassVisibility = true; 988 if (explicitSpecSuppressor && 989 // optimization: hasDVA() is true only with explicit visibility. 990 LV.isVisibilityExplicit() && 991 classLV.getVisibility() != DefaultVisibility && 992 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) { 993 considerClassVisibility = false; 994 } 995 996 // Finally, merge in information from the class. 997 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility); 998 return LV; 999 } 1000 1001 void NamedDecl::anchor() { } 1002 1003 static LinkageInfo computeLVForDecl(const NamedDecl *D, 1004 LVComputationKind computation); 1005 1006 bool NamedDecl::isLinkageValid() const { 1007 if (!hasCachedLinkage()) 1008 return true; 1009 1010 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() == 1011 getCachedLinkage(); 1012 } 1013 1014 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const { 1015 StringRef name = getName(); 1016 if (name.empty()) return SFF_None; 1017 1018 if (name.front() == 'C') 1019 if (name == "CFStringCreateWithFormat" || 1020 name == "CFStringCreateWithFormatAndArguments" || 1021 name == "CFStringAppendFormat" || 1022 name == "CFStringAppendFormatAndArguments") 1023 return SFF_CFString; 1024 return SFF_None; 1025 } 1026 1027 Linkage NamedDecl::getLinkageInternal() const { 1028 // We don't care about visibility here, so ask for the cheapest 1029 // possible visibility analysis. 1030 return getLVForDecl(this, LVForLinkageOnly).getLinkage(); 1031 } 1032 1033 LinkageInfo NamedDecl::getLinkageAndVisibility() const { 1034 LVComputationKind computation = 1035 (usesTypeVisibility(this) ? LVForType : LVForValue); 1036 return getLVForDecl(this, computation); 1037 } 1038 1039 static Optional<Visibility> 1040 getExplicitVisibilityAux(const NamedDecl *ND, 1041 NamedDecl::ExplicitVisibilityKind kind, 1042 bool IsMostRecent) { 1043 assert(!IsMostRecent || ND == ND->getMostRecentDecl()); 1044 1045 // Check the declaration itself first. 1046 if (Optional<Visibility> V = getVisibilityOf(ND, kind)) 1047 return V; 1048 1049 // If this is a member class of a specialization of a class template 1050 // and the corresponding decl has explicit visibility, use that. 1051 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) { 1052 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass(); 1053 if (InstantiatedFrom) 1054 return getVisibilityOf(InstantiatedFrom, kind); 1055 } 1056 1057 // If there wasn't explicit visibility there, and this is a 1058 // specialization of a class template, check for visibility 1059 // on the pattern. 1060 if (const ClassTemplateSpecializationDecl *spec 1061 = dyn_cast<ClassTemplateSpecializationDecl>(ND)) 1062 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(), 1063 kind); 1064 1065 // Use the most recent declaration. 1066 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) { 1067 const NamedDecl *MostRecent = ND->getMostRecentDecl(); 1068 if (MostRecent != ND) 1069 return getExplicitVisibilityAux(MostRecent, kind, true); 1070 } 1071 1072 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) { 1073 if (Var->isStaticDataMember()) { 1074 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember(); 1075 if (InstantiatedFrom) 1076 return getVisibilityOf(InstantiatedFrom, kind); 1077 } 1078 1079 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var)) 1080 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(), 1081 kind); 1082 1083 return None; 1084 } 1085 // Also handle function template specializations. 1086 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) { 1087 // If the function is a specialization of a template with an 1088 // explicit visibility attribute, use that. 1089 if (FunctionTemplateSpecializationInfo *templateInfo 1090 = fn->getTemplateSpecializationInfo()) 1091 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(), 1092 kind); 1093 1094 // If the function is a member of a specialization of a class template 1095 // and the corresponding decl has explicit visibility, use that. 1096 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction(); 1097 if (InstantiatedFrom) 1098 return getVisibilityOf(InstantiatedFrom, kind); 1099 1100 return None; 1101 } 1102 1103 // The visibility of a template is stored in the templated decl. 1104 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND)) 1105 return getVisibilityOf(TD->getTemplatedDecl(), kind); 1106 1107 return None; 1108 } 1109 1110 Optional<Visibility> 1111 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const { 1112 return getExplicitVisibilityAux(this, kind, false); 1113 } 1114 1115 static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl, 1116 LVComputationKind computation) { 1117 // This lambda has its linkage/visibility determined by its owner. 1118 if (ContextDecl) { 1119 if (isa<ParmVarDecl>(ContextDecl)) 1120 DC = ContextDecl->getDeclContext()->getRedeclContext(); 1121 else 1122 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation); 1123 } 1124 1125 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) 1126 return getLVForDecl(ND, computation); 1127 1128 return LinkageInfo::external(); 1129 } 1130 1131 static LinkageInfo getLVForLocalDecl(const NamedDecl *D, 1132 LVComputationKind computation) { 1133 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 1134 if (Function->isInAnonymousNamespace() && 1135 !Function->isInExternCContext()) 1136 return LinkageInfo::uniqueExternal(); 1137 1138 // This is a "void f();" which got merged with a file static. 1139 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static) 1140 return LinkageInfo::internal(); 1141 1142 LinkageInfo LV; 1143 if (!hasExplicitVisibilityAlready(computation)) { 1144 if (Optional<Visibility> Vis = 1145 getExplicitVisibility(Function, computation)) 1146 LV.mergeVisibility(*Vis, true); 1147 } 1148 1149 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 1150 // merging storage classes and visibility attributes, so we don't have to 1151 // look at previous decls in here. 1152 1153 return LV; 1154 } 1155 1156 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 1157 if (Var->hasExternalStorage()) { 1158 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext()) 1159 return LinkageInfo::uniqueExternal(); 1160 1161 LinkageInfo LV; 1162 if (Var->getStorageClass() == SC_PrivateExtern) 1163 LV.mergeVisibility(HiddenVisibility, true); 1164 else if (!hasExplicitVisibilityAlready(computation)) { 1165 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation)) 1166 LV.mergeVisibility(*Vis, true); 1167 } 1168 1169 if (const VarDecl *Prev = Var->getPreviousDecl()) { 1170 LinkageInfo PrevLV = getLVForDecl(Prev, computation); 1171 if (PrevLV.getLinkage()) 1172 LV.setLinkage(PrevLV.getLinkage()); 1173 LV.mergeVisibility(PrevLV); 1174 } 1175 1176 return LV; 1177 } 1178 1179 if (!Var->isStaticLocal()) 1180 return LinkageInfo::none(); 1181 } 1182 1183 ASTContext &Context = D->getASTContext(); 1184 if (!Context.getLangOpts().CPlusPlus) 1185 return LinkageInfo::none(); 1186 1187 const Decl *OuterD = getOutermostFuncOrBlockContext(D); 1188 if (!OuterD) 1189 return LinkageInfo::none(); 1190 1191 LinkageInfo LV; 1192 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) { 1193 if (!BD->getBlockManglingNumber()) 1194 return LinkageInfo::none(); 1195 1196 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(), 1197 BD->getBlockManglingContextDecl(), computation); 1198 } else { 1199 const FunctionDecl *FD = cast<FunctionDecl>(OuterD); 1200 if (!FD->isInlined() && 1201 !isTemplateInstantiation(FD->getTemplateSpecializationKind())) 1202 return LinkageInfo::none(); 1203 1204 LV = getLVForDecl(FD, computation); 1205 } 1206 if (!isExternallyVisible(LV.getLinkage())) 1207 return LinkageInfo::none(); 1208 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(), 1209 LV.isVisibilityExplicit()); 1210 } 1211 1212 static inline const CXXRecordDecl* 1213 getOutermostEnclosingLambda(const CXXRecordDecl *Record) { 1214 const CXXRecordDecl *Ret = Record; 1215 while (Record && Record->isLambda()) { 1216 Ret = Record; 1217 if (!Record->getParent()) break; 1218 // Get the Containing Class of this Lambda Class 1219 Record = dyn_cast_or_null<CXXRecordDecl>( 1220 Record->getParent()->getParent()); 1221 } 1222 return Ret; 1223 } 1224 1225 static LinkageInfo computeLVForDecl(const NamedDecl *D, 1226 LVComputationKind computation) { 1227 // Objective-C: treat all Objective-C declarations as having external 1228 // linkage. 1229 switch (D->getKind()) { 1230 default: 1231 break; 1232 case Decl::ParmVar: 1233 return LinkageInfo::none(); 1234 case Decl::TemplateTemplateParm: // count these as external 1235 case Decl::NonTypeTemplateParm: 1236 case Decl::ObjCAtDefsField: 1237 case Decl::ObjCCategory: 1238 case Decl::ObjCCategoryImpl: 1239 case Decl::ObjCCompatibleAlias: 1240 case Decl::ObjCImplementation: 1241 case Decl::ObjCMethod: 1242 case Decl::ObjCProperty: 1243 case Decl::ObjCPropertyImpl: 1244 case Decl::ObjCProtocol: 1245 return LinkageInfo::external(); 1246 1247 case Decl::CXXRecord: { 1248 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D); 1249 if (Record->isLambda()) { 1250 if (!Record->getLambdaManglingNumber()) { 1251 // This lambda has no mangling number, so it's internal. 1252 return LinkageInfo::internal(); 1253 } 1254 1255 // This lambda has its linkage/visibility determined: 1256 // - either by the outermost lambda if that lambda has no mangling 1257 // number. 1258 // - or by the parent of the outer most lambda 1259 // This prevents infinite recursion in settings such as nested lambdas 1260 // used in NSDMI's, for e.g. 1261 // struct L { 1262 // int t{}; 1263 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t); 1264 // }; 1265 const CXXRecordDecl *OuterMostLambda = 1266 getOutermostEnclosingLambda(Record); 1267 if (!OuterMostLambda->getLambdaManglingNumber()) 1268 return LinkageInfo::internal(); 1269 1270 return getLVForClosure( 1271 OuterMostLambda->getDeclContext()->getRedeclContext(), 1272 OuterMostLambda->getLambdaContextDecl(), computation); 1273 } 1274 1275 break; 1276 } 1277 } 1278 1279 // Handle linkage for namespace-scope names. 1280 if (D->getDeclContext()->getRedeclContext()->isFileContext()) 1281 return getLVForNamespaceScopeDecl(D, computation); 1282 1283 // C++ [basic.link]p5: 1284 // In addition, a member function, static data member, a named 1285 // class or enumeration of class scope, or an unnamed class or 1286 // enumeration defined in a class-scope typedef declaration such 1287 // that the class or enumeration has the typedef name for linkage 1288 // purposes (7.1.3), has external linkage if the name of the class 1289 // has external linkage. 1290 if (D->getDeclContext()->isRecord()) 1291 return getLVForClassMember(D, computation); 1292 1293 // C++ [basic.link]p6: 1294 // The name of a function declared in block scope and the name of 1295 // an object declared by a block scope extern declaration have 1296 // linkage. If there is a visible declaration of an entity with 1297 // linkage having the same name and type, ignoring entities 1298 // declared outside the innermost enclosing namespace scope, the 1299 // block scope declaration declares that same entity and receives 1300 // the linkage of the previous declaration. If there is more than 1301 // one such matching entity, the program is ill-formed. Otherwise, 1302 // if no matching entity is found, the block scope entity receives 1303 // external linkage. 1304 if (D->getDeclContext()->isFunctionOrMethod()) 1305 return getLVForLocalDecl(D, computation); 1306 1307 // C++ [basic.link]p6: 1308 // Names not covered by these rules have no linkage. 1309 return LinkageInfo::none(); 1310 } 1311 1312 namespace clang { 1313 class LinkageComputer { 1314 public: 1315 static LinkageInfo getLVForDecl(const NamedDecl *D, 1316 LVComputationKind computation) { 1317 if (computation == LVForLinkageOnly && D->hasCachedLinkage()) 1318 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false); 1319 1320 LinkageInfo LV = computeLVForDecl(D, computation); 1321 if (D->hasCachedLinkage()) 1322 assert(D->getCachedLinkage() == LV.getLinkage()); 1323 1324 D->setCachedLinkage(LV.getLinkage()); 1325 1326 #ifndef NDEBUG 1327 // In C (because of gnu inline) and in c++ with microsoft extensions an 1328 // static can follow an extern, so we can have two decls with different 1329 // linkages. 1330 const LangOptions &Opts = D->getASTContext().getLangOpts(); 1331 if (!Opts.CPlusPlus || Opts.MicrosoftExt) 1332 return LV; 1333 1334 // We have just computed the linkage for this decl. By induction we know 1335 // that all other computed linkages match, check that the one we just 1336 // computed also does. 1337 NamedDecl *Old = nullptr; 1338 for (auto I : D->redecls()) { 1339 NamedDecl *T = cast<NamedDecl>(I); 1340 if (T == D) 1341 continue; 1342 if (!T->isInvalidDecl() && T->hasCachedLinkage()) { 1343 Old = T; 1344 break; 1345 } 1346 } 1347 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage()); 1348 #endif 1349 1350 return LV; 1351 } 1352 }; 1353 } 1354 1355 static LinkageInfo getLVForDecl(const NamedDecl *D, 1356 LVComputationKind computation) { 1357 return clang::LinkageComputer::getLVForDecl(D, computation); 1358 } 1359 1360 std::string NamedDecl::getQualifiedNameAsString() const { 1361 std::string QualName; 1362 llvm::raw_string_ostream OS(QualName); 1363 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1364 return OS.str(); 1365 } 1366 1367 void NamedDecl::printQualifiedName(raw_ostream &OS) const { 1368 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1369 } 1370 1371 void NamedDecl::printQualifiedName(raw_ostream &OS, 1372 const PrintingPolicy &P) const { 1373 const DeclContext *Ctx = getDeclContext(); 1374 1375 if (Ctx->isFunctionOrMethod()) { 1376 printName(OS); 1377 return; 1378 } 1379 1380 typedef SmallVector<const DeclContext *, 8> ContextsTy; 1381 ContextsTy Contexts; 1382 1383 // Collect contexts. 1384 while (Ctx && isa<NamedDecl>(Ctx)) { 1385 Contexts.push_back(Ctx); 1386 Ctx = Ctx->getParent(); 1387 } 1388 1389 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend(); 1390 I != E; ++I) { 1391 if (const ClassTemplateSpecializationDecl *Spec 1392 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) { 1393 OS << Spec->getName(); 1394 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1395 TemplateSpecializationType::PrintTemplateArgumentList(OS, 1396 TemplateArgs.data(), 1397 TemplateArgs.size(), 1398 P); 1399 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) { 1400 if (P.SuppressUnwrittenScope && 1401 (ND->isAnonymousNamespace() || ND->isInline())) 1402 continue; 1403 if (ND->isAnonymousNamespace()) 1404 OS << "(anonymous namespace)"; 1405 else 1406 OS << *ND; 1407 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) { 1408 if (!RD->getIdentifier()) 1409 OS << "(anonymous " << RD->getKindName() << ')'; 1410 else 1411 OS << *RD; 1412 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 1413 const FunctionProtoType *FT = nullptr; 1414 if (FD->hasWrittenPrototype()) 1415 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>()); 1416 1417 OS << *FD << '('; 1418 if (FT) { 1419 unsigned NumParams = FD->getNumParams(); 1420 for (unsigned i = 0; i < NumParams; ++i) { 1421 if (i) 1422 OS << ", "; 1423 OS << FD->getParamDecl(i)->getType().stream(P); 1424 } 1425 1426 if (FT->isVariadic()) { 1427 if (NumParams > 0) 1428 OS << ", "; 1429 OS << "..."; 1430 } 1431 } 1432 OS << ')'; 1433 } else { 1434 OS << *cast<NamedDecl>(*I); 1435 } 1436 OS << "::"; 1437 } 1438 1439 if (getDeclName()) 1440 OS << *this; 1441 else 1442 OS << "(anonymous)"; 1443 } 1444 1445 void NamedDecl::getNameForDiagnostic(raw_ostream &OS, 1446 const PrintingPolicy &Policy, 1447 bool Qualified) const { 1448 if (Qualified) 1449 printQualifiedName(OS, Policy); 1450 else 1451 printName(OS); 1452 } 1453 1454 static bool isKindReplaceableBy(Decl::Kind OldK, Decl::Kind NewK) { 1455 // For method declarations, we never replace. 1456 if (ObjCMethodDecl::classofKind(NewK)) 1457 return false; 1458 1459 if (OldK == NewK) 1460 return true; 1461 1462 // A compatibility alias for a class can be replaced by an interface. 1463 if (ObjCCompatibleAliasDecl::classofKind(OldK) && 1464 ObjCInterfaceDecl::classofKind(NewK)) 1465 return true; 1466 1467 // A typedef-declaration, alias-declaration, or Objective-C class declaration 1468 // can replace another declaration of the same type. Semantic analysis checks 1469 // that we have matching types. 1470 if ((TypedefNameDecl::classofKind(OldK) || 1471 ObjCInterfaceDecl::classofKind(OldK)) && 1472 (TypedefNameDecl::classofKind(NewK) || 1473 ObjCInterfaceDecl::classofKind(NewK))) 1474 return true; 1475 1476 // Otherwise, a kind mismatch implies that the declaration is not replaced. 1477 return false; 1478 } 1479 1480 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) { 1481 return true; 1482 } 1483 static bool isRedeclarableImpl(...) { return false; } 1484 static bool isRedeclarable(Decl::Kind K) { 1485 switch (K) { 1486 #define DECL(Type, Base) \ 1487 case Decl::Type: \ 1488 return isRedeclarableImpl((Type##Decl *)nullptr); 1489 #define ABSTRACT_DECL(DECL) 1490 #include "clang/AST/DeclNodes.inc" 1491 } 1492 llvm_unreachable("unknown decl kind"); 1493 } 1494 1495 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const { 1496 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 1497 1498 // Never replace one imported declaration with another; we need both results 1499 // when re-exporting. 1500 if (OldD->isFromASTFile() && isFromASTFile()) 1501 return false; 1502 1503 if (!isKindReplaceableBy(OldD->getKind(), getKind())) 1504 return false; 1505 1506 // Inline namespaces can give us two declarations with the same 1507 // name and kind in the same scope but different contexts; we should 1508 // keep both declarations in this case. 1509 if (!this->getDeclContext()->getRedeclContext()->Equals( 1510 OldD->getDeclContext()->getRedeclContext())) 1511 return false; 1512 1513 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 1514 // For function declarations, we keep track of redeclarations. 1515 // FIXME: This returns false for functions that should in fact be replaced. 1516 // Instead, perform some kind of type check? 1517 if (FD->getPreviousDecl() != OldD) 1518 return false; 1519 1520 // For function templates, the underlying function declarations are linked. 1521 if (const FunctionTemplateDecl *FunctionTemplate = 1522 dyn_cast<FunctionTemplateDecl>(this)) 1523 return FunctionTemplate->getTemplatedDecl()->declarationReplaces( 1524 cast<FunctionTemplateDecl>(OldD)->getTemplatedDecl()); 1525 1526 // Using shadow declarations can be overloaded on their target declarations 1527 // if they introduce functions. 1528 // FIXME: If our target replaces the old target, can we replace the old 1529 // shadow declaration? 1530 if (auto *USD = dyn_cast<UsingShadowDecl>(this)) 1531 if (USD->getTargetDecl() != cast<UsingShadowDecl>(OldD)->getTargetDecl()) 1532 return false; 1533 1534 // Using declarations can be overloaded if they introduce functions. 1535 if (auto *UD = dyn_cast<UsingDecl>(this)) { 1536 ASTContext &Context = getASTContext(); 1537 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) == 1538 Context.getCanonicalNestedNameSpecifier( 1539 cast<UsingDecl>(OldD)->getQualifier()); 1540 } 1541 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) { 1542 ASTContext &Context = getASTContext(); 1543 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) == 1544 Context.getCanonicalNestedNameSpecifier( 1545 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier()); 1546 } 1547 1548 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name. 1549 // We want to keep it, unless it nominates same namespace. 1550 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this)) 1551 return UD->getNominatedNamespace()->getOriginalNamespace() == 1552 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace() 1553 ->getOriginalNamespace(); 1554 1555 if (!IsKnownNewer && isRedeclarable(getKind())) { 1556 // Check whether this is actually newer than OldD. We want to keep the 1557 // newer declaration. This loop will usually only iterate once, because 1558 // OldD is usually the previous declaration. 1559 for (auto D : redecls()) { 1560 if (D == OldD) 1561 break; 1562 1563 // If we reach the canonical declaration, then OldD is not actually older 1564 // than this one. 1565 // 1566 // FIXME: In this case, we should not add this decl to the lookup table. 1567 if (D->isCanonicalDecl()) 1568 return false; 1569 } 1570 } 1571 1572 // It's a newer declaration of the same kind of declaration in the same scope, 1573 // and not an overload: we want this decl instead of the existing one. 1574 return true; 1575 } 1576 1577 bool NamedDecl::hasLinkage() const { 1578 return getFormalLinkage() != NoLinkage; 1579 } 1580 1581 NamedDecl *NamedDecl::getUnderlyingDeclImpl() { 1582 NamedDecl *ND = this; 1583 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND)) 1584 ND = UD->getTargetDecl(); 1585 1586 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 1587 return AD->getClassInterface(); 1588 1589 return ND; 1590 } 1591 1592 bool NamedDecl::isCXXInstanceMember() const { 1593 if (!isCXXClassMember()) 1594 return false; 1595 1596 const NamedDecl *D = this; 1597 if (isa<UsingShadowDecl>(D)) 1598 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1599 1600 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D)) 1601 return true; 1602 if (const CXXMethodDecl *MD = 1603 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction())) 1604 return MD->isInstance(); 1605 return false; 1606 } 1607 1608 //===----------------------------------------------------------------------===// 1609 // DeclaratorDecl Implementation 1610 //===----------------------------------------------------------------------===// 1611 1612 template <typename DeclT> 1613 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 1614 if (decl->getNumTemplateParameterLists() > 0) 1615 return decl->getTemplateParameterList(0)->getTemplateLoc(); 1616 else 1617 return decl->getInnerLocStart(); 1618 } 1619 1620 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 1621 TypeSourceInfo *TSI = getTypeSourceInfo(); 1622 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 1623 return SourceLocation(); 1624 } 1625 1626 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 1627 if (QualifierLoc) { 1628 // Make sure the extended decl info is allocated. 1629 if (!hasExtInfo()) { 1630 // Save (non-extended) type source info pointer. 1631 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1632 // Allocate external info struct. 1633 DeclInfo = new (getASTContext()) ExtInfo; 1634 // Restore savedTInfo into (extended) decl info. 1635 getExtInfo()->TInfo = savedTInfo; 1636 } 1637 // Set qualifier info. 1638 getExtInfo()->QualifierLoc = QualifierLoc; 1639 } else { 1640 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 1641 if (hasExtInfo()) { 1642 if (getExtInfo()->NumTemplParamLists == 0) { 1643 // Save type source info pointer. 1644 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 1645 // Deallocate the extended decl info. 1646 getASTContext().Deallocate(getExtInfo()); 1647 // Restore savedTInfo into (non-extended) decl info. 1648 DeclInfo = savedTInfo; 1649 } 1650 else 1651 getExtInfo()->QualifierLoc = QualifierLoc; 1652 } 1653 } 1654 } 1655 1656 void DeclaratorDecl::setTemplateParameterListsInfo( 1657 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 1658 assert(!TPLists.empty()); 1659 // Make sure the extended decl info is allocated. 1660 if (!hasExtInfo()) { 1661 // Save (non-extended) type source info pointer. 1662 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1663 // Allocate external info struct. 1664 DeclInfo = new (getASTContext()) ExtInfo; 1665 // Restore savedTInfo into (extended) decl info. 1666 getExtInfo()->TInfo = savedTInfo; 1667 } 1668 // Set the template parameter lists info. 1669 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 1670 } 1671 1672 SourceLocation DeclaratorDecl::getOuterLocStart() const { 1673 return getTemplateOrInnerLocStart(this); 1674 } 1675 1676 namespace { 1677 1678 // Helper function: returns true if QT is or contains a type 1679 // having a postfix component. 1680 bool typeIsPostfix(clang::QualType QT) { 1681 while (true) { 1682 const Type* T = QT.getTypePtr(); 1683 switch (T->getTypeClass()) { 1684 default: 1685 return false; 1686 case Type::Pointer: 1687 QT = cast<PointerType>(T)->getPointeeType(); 1688 break; 1689 case Type::BlockPointer: 1690 QT = cast<BlockPointerType>(T)->getPointeeType(); 1691 break; 1692 case Type::MemberPointer: 1693 QT = cast<MemberPointerType>(T)->getPointeeType(); 1694 break; 1695 case Type::LValueReference: 1696 case Type::RValueReference: 1697 QT = cast<ReferenceType>(T)->getPointeeType(); 1698 break; 1699 case Type::PackExpansion: 1700 QT = cast<PackExpansionType>(T)->getPattern(); 1701 break; 1702 case Type::Paren: 1703 case Type::ConstantArray: 1704 case Type::DependentSizedArray: 1705 case Type::IncompleteArray: 1706 case Type::VariableArray: 1707 case Type::FunctionProto: 1708 case Type::FunctionNoProto: 1709 return true; 1710 } 1711 } 1712 } 1713 1714 } // namespace 1715 1716 SourceRange DeclaratorDecl::getSourceRange() const { 1717 SourceLocation RangeEnd = getLocation(); 1718 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 1719 // If the declaration has no name or the type extends past the name take the 1720 // end location of the type. 1721 if (!getDeclName() || typeIsPostfix(TInfo->getType())) 1722 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 1723 } 1724 return SourceRange(getOuterLocStart(), RangeEnd); 1725 } 1726 1727 void QualifierInfo::setTemplateParameterListsInfo( 1728 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 1729 // Free previous template parameters (if any). 1730 if (NumTemplParamLists > 0) { 1731 Context.Deallocate(TemplParamLists); 1732 TemplParamLists = nullptr; 1733 NumTemplParamLists = 0; 1734 } 1735 // Set info on matched template parameter lists (if any). 1736 if (!TPLists.empty()) { 1737 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()]; 1738 NumTemplParamLists = TPLists.size(); 1739 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists); 1740 } 1741 } 1742 1743 //===----------------------------------------------------------------------===// 1744 // VarDecl Implementation 1745 //===----------------------------------------------------------------------===// 1746 1747 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 1748 switch (SC) { 1749 case SC_None: break; 1750 case SC_Auto: return "auto"; 1751 case SC_Extern: return "extern"; 1752 case SC_PrivateExtern: return "__private_extern__"; 1753 case SC_Register: return "register"; 1754 case SC_Static: return "static"; 1755 } 1756 1757 llvm_unreachable("Invalid storage class"); 1758 } 1759 1760 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC, 1761 SourceLocation StartLoc, SourceLocation IdLoc, 1762 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 1763 StorageClass SC) 1764 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), 1765 redeclarable_base(C), Init() { 1766 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned), 1767 "VarDeclBitfields too large!"); 1768 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned), 1769 "ParmVarDeclBitfields too large!"); 1770 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned), 1771 "NonParmVarDeclBitfields too large!"); 1772 AllBits = 0; 1773 VarDeclBits.SClass = SC; 1774 // Everything else is implicitly initialized to false. 1775 } 1776 1777 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, 1778 SourceLocation StartL, SourceLocation IdL, 1779 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 1780 StorageClass S) { 1781 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S); 1782 } 1783 1784 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1785 return new (C, ID) 1786 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr, 1787 QualType(), nullptr, SC_None); 1788 } 1789 1790 void VarDecl::setStorageClass(StorageClass SC) { 1791 assert(isLegalForVariable(SC)); 1792 VarDeclBits.SClass = SC; 1793 } 1794 1795 VarDecl::TLSKind VarDecl::getTLSKind() const { 1796 switch (VarDeclBits.TSCSpec) { 1797 case TSCS_unspecified: 1798 if (!hasAttr<ThreadAttr>() && 1799 !(getASTContext().getLangOpts().OpenMPUseTLS && 1800 getASTContext().getTargetInfo().isTLSSupported() && 1801 hasAttr<OMPThreadPrivateDeclAttr>())) 1802 return TLS_None; 1803 return ((getASTContext().getLangOpts().isCompatibleWithMSVC( 1804 LangOptions::MSVC2015)) || 1805 hasAttr<OMPThreadPrivateDeclAttr>()) 1806 ? TLS_Dynamic 1807 : TLS_Static; 1808 case TSCS___thread: // Fall through. 1809 case TSCS__Thread_local: 1810 return TLS_Static; 1811 case TSCS_thread_local: 1812 return TLS_Dynamic; 1813 } 1814 llvm_unreachable("Unknown thread storage class specifier!"); 1815 } 1816 1817 SourceRange VarDecl::getSourceRange() const { 1818 if (const Expr *Init = getInit()) { 1819 SourceLocation InitEnd = Init->getLocEnd(); 1820 // If Init is implicit, ignore its source range and fallback on 1821 // DeclaratorDecl::getSourceRange() to handle postfix elements. 1822 if (InitEnd.isValid() && InitEnd != getLocation()) 1823 return SourceRange(getOuterLocStart(), InitEnd); 1824 } 1825 return DeclaratorDecl::getSourceRange(); 1826 } 1827 1828 template<typename T> 1829 static LanguageLinkage getDeclLanguageLinkage(const T &D) { 1830 // C++ [dcl.link]p1: All function types, function names with external linkage, 1831 // and variable names with external linkage have a language linkage. 1832 if (!D.hasExternalFormalLinkage()) 1833 return NoLanguageLinkage; 1834 1835 // Language linkage is a C++ concept, but saying that everything else in C has 1836 // C language linkage fits the implementation nicely. 1837 ASTContext &Context = D.getASTContext(); 1838 if (!Context.getLangOpts().CPlusPlus) 1839 return CLanguageLinkage; 1840 1841 // C++ [dcl.link]p4: A C language linkage is ignored in determining the 1842 // language linkage of the names of class members and the function type of 1843 // class member functions. 1844 const DeclContext *DC = D.getDeclContext(); 1845 if (DC->isRecord()) 1846 return CXXLanguageLinkage; 1847 1848 // If the first decl is in an extern "C" context, any other redeclaration 1849 // will have C language linkage. If the first one is not in an extern "C" 1850 // context, we would have reported an error for any other decl being in one. 1851 if (isFirstInExternCContext(&D)) 1852 return CLanguageLinkage; 1853 return CXXLanguageLinkage; 1854 } 1855 1856 template<typename T> 1857 static bool isDeclExternC(const T &D) { 1858 // Since the context is ignored for class members, they can only have C++ 1859 // language linkage or no language linkage. 1860 const DeclContext *DC = D.getDeclContext(); 1861 if (DC->isRecord()) { 1862 assert(D.getASTContext().getLangOpts().CPlusPlus); 1863 return false; 1864 } 1865 1866 return D.getLanguageLinkage() == CLanguageLinkage; 1867 } 1868 1869 LanguageLinkage VarDecl::getLanguageLinkage() const { 1870 return getDeclLanguageLinkage(*this); 1871 } 1872 1873 bool VarDecl::isExternC() const { 1874 return isDeclExternC(*this); 1875 } 1876 1877 bool VarDecl::isInExternCContext() const { 1878 return getLexicalDeclContext()->isExternCContext(); 1879 } 1880 1881 bool VarDecl::isInExternCXXContext() const { 1882 return getLexicalDeclContext()->isExternCXXContext(); 1883 } 1884 1885 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); } 1886 1887 VarDecl::DefinitionKind 1888 VarDecl::isThisDeclarationADefinition(ASTContext &C) const { 1889 // C++ [basic.def]p2: 1890 // A declaration is a definition unless [...] it contains the 'extern' 1891 // specifier or a linkage-specification and neither an initializer [...], 1892 // it declares a static data member in a class declaration [...]. 1893 // C++1y [temp.expl.spec]p15: 1894 // An explicit specialization of a static data member or an explicit 1895 // specialization of a static data member template is a definition if the 1896 // declaration includes an initializer; otherwise, it is a declaration. 1897 // 1898 // FIXME: How do you declare (but not define) a partial specialization of 1899 // a static data member template outside the containing class? 1900 if (isStaticDataMember()) { 1901 if (isOutOfLine() && 1902 (hasInit() || 1903 // If the first declaration is out-of-line, this may be an 1904 // instantiation of an out-of-line partial specialization of a variable 1905 // template for which we have not yet instantiated the initializer. 1906 (getFirstDecl()->isOutOfLine() 1907 ? getTemplateSpecializationKind() == TSK_Undeclared 1908 : getTemplateSpecializationKind() != 1909 TSK_ExplicitSpecialization) || 1910 isa<VarTemplatePartialSpecializationDecl>(this))) 1911 return Definition; 1912 else 1913 return DeclarationOnly; 1914 } 1915 // C99 6.7p5: 1916 // A definition of an identifier is a declaration for that identifier that 1917 // [...] causes storage to be reserved for that object. 1918 // Note: that applies for all non-file-scope objects. 1919 // C99 6.9.2p1: 1920 // If the declaration of an identifier for an object has file scope and an 1921 // initializer, the declaration is an external definition for the identifier 1922 if (hasInit()) 1923 return Definition; 1924 1925 if (hasAttr<AliasAttr>()) 1926 return Definition; 1927 1928 if (const auto *SAA = getAttr<SelectAnyAttr>()) 1929 if (!SAA->isInherited()) 1930 return Definition; 1931 1932 // A variable template specialization (other than a static data member 1933 // template or an explicit specialization) is a declaration until we 1934 // instantiate its initializer. 1935 if (isa<VarTemplateSpecializationDecl>(this) && 1936 getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 1937 return DeclarationOnly; 1938 1939 if (hasExternalStorage()) 1940 return DeclarationOnly; 1941 1942 // [dcl.link] p7: 1943 // A declaration directly contained in a linkage-specification is treated 1944 // as if it contains the extern specifier for the purpose of determining 1945 // the linkage of the declared name and whether it is a definition. 1946 if (isSingleLineLanguageLinkage(*this)) 1947 return DeclarationOnly; 1948 1949 // C99 6.9.2p2: 1950 // A declaration of an object that has file scope without an initializer, 1951 // and without a storage class specifier or the scs 'static', constitutes 1952 // a tentative definition. 1953 // No such thing in C++. 1954 if (!C.getLangOpts().CPlusPlus && isFileVarDecl()) 1955 return TentativeDefinition; 1956 1957 // What's left is (in C, block-scope) declarations without initializers or 1958 // external storage. These are definitions. 1959 return Definition; 1960 } 1961 1962 VarDecl *VarDecl::getActingDefinition() { 1963 DefinitionKind Kind = isThisDeclarationADefinition(); 1964 if (Kind != TentativeDefinition) 1965 return nullptr; 1966 1967 VarDecl *LastTentative = nullptr; 1968 VarDecl *First = getFirstDecl(); 1969 for (auto I : First->redecls()) { 1970 Kind = I->isThisDeclarationADefinition(); 1971 if (Kind == Definition) 1972 return nullptr; 1973 else if (Kind == TentativeDefinition) 1974 LastTentative = I; 1975 } 1976 return LastTentative; 1977 } 1978 1979 VarDecl *VarDecl::getDefinition(ASTContext &C) { 1980 VarDecl *First = getFirstDecl(); 1981 for (auto I : First->redecls()) { 1982 if (I->isThisDeclarationADefinition(C) == Definition) 1983 return I; 1984 } 1985 return nullptr; 1986 } 1987 1988 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { 1989 DefinitionKind Kind = DeclarationOnly; 1990 1991 const VarDecl *First = getFirstDecl(); 1992 for (auto I : First->redecls()) { 1993 Kind = std::max(Kind, I->isThisDeclarationADefinition(C)); 1994 if (Kind == Definition) 1995 break; 1996 } 1997 1998 return Kind; 1999 } 2000 2001 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 2002 for (auto I : redecls()) { 2003 if (auto Expr = I->getInit()) { 2004 D = I; 2005 return Expr; 2006 } 2007 } 2008 return nullptr; 2009 } 2010 2011 bool VarDecl::isOutOfLine() const { 2012 if (Decl::isOutOfLine()) 2013 return true; 2014 2015 if (!isStaticDataMember()) 2016 return false; 2017 2018 // If this static data member was instantiated from a static data member of 2019 // a class template, check whether that static data member was defined 2020 // out-of-line. 2021 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 2022 return VD->isOutOfLine(); 2023 2024 return false; 2025 } 2026 2027 VarDecl *VarDecl::getOutOfLineDefinition() { 2028 if (!isStaticDataMember()) 2029 return nullptr; 2030 2031 for (auto RD : redecls()) { 2032 if (RD->getLexicalDeclContext()->isFileContext()) 2033 return RD; 2034 } 2035 2036 return nullptr; 2037 } 2038 2039 void VarDecl::setInit(Expr *I) { 2040 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 2041 Eval->~EvaluatedStmt(); 2042 getASTContext().Deallocate(Eval); 2043 } 2044 2045 Init = I; 2046 } 2047 2048 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const { 2049 const LangOptions &Lang = C.getLangOpts(); 2050 2051 if (!Lang.CPlusPlus) 2052 return false; 2053 2054 // In C++11, any variable of reference type can be used in a constant 2055 // expression if it is initialized by a constant expression. 2056 if (Lang.CPlusPlus11 && getType()->isReferenceType()) 2057 return true; 2058 2059 // Only const objects can be used in constant expressions in C++. C++98 does 2060 // not require the variable to be non-volatile, but we consider this to be a 2061 // defect. 2062 if (!getType().isConstQualified() || getType().isVolatileQualified()) 2063 return false; 2064 2065 // In C++, const, non-volatile variables of integral or enumeration types 2066 // can be used in constant expressions. 2067 if (getType()->isIntegralOrEnumerationType()) 2068 return true; 2069 2070 // Additionally, in C++11, non-volatile constexpr variables can be used in 2071 // constant expressions. 2072 return Lang.CPlusPlus11 && isConstexpr(); 2073 } 2074 2075 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt 2076 /// form, which contains extra information on the evaluated value of the 2077 /// initializer. 2078 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const { 2079 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>(); 2080 if (!Eval) { 2081 Stmt *S = Init.get<Stmt *>(); 2082 // Note: EvaluatedStmt contains an APValue, which usually holds 2083 // resources not allocated from the ASTContext. We need to do some 2084 // work to avoid leaking those, but we do so in VarDecl::evaluateValue 2085 // where we can detect whether there's anything to clean up or not. 2086 Eval = new (getASTContext()) EvaluatedStmt; 2087 Eval->Value = S; 2088 Init = Eval; 2089 } 2090 return Eval; 2091 } 2092 2093 APValue *VarDecl::evaluateValue() const { 2094 SmallVector<PartialDiagnosticAt, 8> Notes; 2095 return evaluateValue(Notes); 2096 } 2097 2098 namespace { 2099 // Destroy an APValue that was allocated in an ASTContext. 2100 void DestroyAPValue(void* UntypedValue) { 2101 static_cast<APValue*>(UntypedValue)->~APValue(); 2102 } 2103 } // namespace 2104 2105 APValue *VarDecl::evaluateValue( 2106 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 2107 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2108 2109 // We only produce notes indicating why an initializer is non-constant the 2110 // first time it is evaluated. FIXME: The notes won't always be emitted the 2111 // first time we try evaluation, so might not be produced at all. 2112 if (Eval->WasEvaluated) 2113 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated; 2114 2115 const Expr *Init = cast<Expr>(Eval->Value); 2116 assert(!Init->isValueDependent()); 2117 2118 if (Eval->IsEvaluating) { 2119 // FIXME: Produce a diagnostic for self-initialization. 2120 Eval->CheckedICE = true; 2121 Eval->IsICE = false; 2122 return nullptr; 2123 } 2124 2125 Eval->IsEvaluating = true; 2126 2127 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(), 2128 this, Notes); 2129 2130 // Ensure the computed APValue is cleaned up later if evaluation succeeded, 2131 // or that it's empty (so that there's nothing to clean up) if evaluation 2132 // failed. 2133 if (!Result) 2134 Eval->Evaluated = APValue(); 2135 else if (Eval->Evaluated.needsCleanup()) 2136 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated); 2137 2138 Eval->IsEvaluating = false; 2139 Eval->WasEvaluated = true; 2140 2141 // In C++11, we have determined whether the initializer was a constant 2142 // expression as a side-effect. 2143 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) { 2144 Eval->CheckedICE = true; 2145 Eval->IsICE = Result && Notes.empty(); 2146 } 2147 2148 return Result ? &Eval->Evaluated : nullptr; 2149 } 2150 2151 bool VarDecl::checkInitIsICE() const { 2152 // Initializers of weak variables are never ICEs. 2153 if (isWeak()) 2154 return false; 2155 2156 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 2157 if (Eval->CheckedICE) 2158 // We have already checked whether this subexpression is an 2159 // integral constant expression. 2160 return Eval->IsICE; 2161 2162 const Expr *Init = cast<Expr>(Eval->Value); 2163 assert(!Init->isValueDependent()); 2164 2165 // In C++11, evaluate the initializer to check whether it's a constant 2166 // expression. 2167 if (getASTContext().getLangOpts().CPlusPlus11) { 2168 SmallVector<PartialDiagnosticAt, 8> Notes; 2169 evaluateValue(Notes); 2170 return Eval->IsICE; 2171 } 2172 2173 // It's an ICE whether or not the definition we found is 2174 // out-of-line. See DR 721 and the discussion in Clang PR 2175 // 6206 for details. 2176 2177 if (Eval->CheckingICE) 2178 return false; 2179 Eval->CheckingICE = true; 2180 2181 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext()); 2182 Eval->CheckingICE = false; 2183 Eval->CheckedICE = true; 2184 return Eval->IsICE; 2185 } 2186 2187 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 2188 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2189 return cast<VarDecl>(MSI->getInstantiatedFrom()); 2190 2191 return nullptr; 2192 } 2193 2194 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 2195 if (const VarTemplateSpecializationDecl *Spec = 2196 dyn_cast<VarTemplateSpecializationDecl>(this)) 2197 return Spec->getSpecializationKind(); 2198 2199 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2200 return MSI->getTemplateSpecializationKind(); 2201 2202 return TSK_Undeclared; 2203 } 2204 2205 SourceLocation VarDecl::getPointOfInstantiation() const { 2206 if (const VarTemplateSpecializationDecl *Spec = 2207 dyn_cast<VarTemplateSpecializationDecl>(this)) 2208 return Spec->getPointOfInstantiation(); 2209 2210 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 2211 return MSI->getPointOfInstantiation(); 2212 2213 return SourceLocation(); 2214 } 2215 2216 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const { 2217 return getASTContext().getTemplateOrSpecializationInfo(this) 2218 .dyn_cast<VarTemplateDecl *>(); 2219 } 2220 2221 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) { 2222 getASTContext().setTemplateOrSpecializationInfo(this, Template); 2223 } 2224 2225 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 2226 if (isStaticDataMember()) 2227 // FIXME: Remove ? 2228 // return getASTContext().getInstantiatedFromStaticDataMember(this); 2229 return getASTContext().getTemplateOrSpecializationInfo(this) 2230 .dyn_cast<MemberSpecializationInfo *>(); 2231 return nullptr; 2232 } 2233 2234 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2235 SourceLocation PointOfInstantiation) { 2236 assert((isa<VarTemplateSpecializationDecl>(this) || 2237 getMemberSpecializationInfo()) && 2238 "not a variable or static data member template specialization"); 2239 2240 if (VarTemplateSpecializationDecl *Spec = 2241 dyn_cast<VarTemplateSpecializationDecl>(this)) { 2242 Spec->setSpecializationKind(TSK); 2243 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2244 Spec->getPointOfInstantiation().isInvalid()) 2245 Spec->setPointOfInstantiation(PointOfInstantiation); 2246 } 2247 2248 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) { 2249 MSI->setTemplateSpecializationKind(TSK); 2250 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && 2251 MSI->getPointOfInstantiation().isInvalid()) 2252 MSI->setPointOfInstantiation(PointOfInstantiation); 2253 } 2254 } 2255 2256 void 2257 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD, 2258 TemplateSpecializationKind TSK) { 2259 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() && 2260 "Previous template or instantiation?"); 2261 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK); 2262 } 2263 2264 //===----------------------------------------------------------------------===// 2265 // ParmVarDecl Implementation 2266 //===----------------------------------------------------------------------===// 2267 2268 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 2269 SourceLocation StartLoc, 2270 SourceLocation IdLoc, IdentifierInfo *Id, 2271 QualType T, TypeSourceInfo *TInfo, 2272 StorageClass S, Expr *DefArg) { 2273 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, 2274 S, DefArg); 2275 } 2276 2277 QualType ParmVarDecl::getOriginalType() const { 2278 TypeSourceInfo *TSI = getTypeSourceInfo(); 2279 QualType T = TSI ? TSI->getType() : getType(); 2280 if (const DecayedType *DT = dyn_cast<DecayedType>(T)) 2281 return DT->getOriginalType(); 2282 return T; 2283 } 2284 2285 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2286 return new (C, ID) 2287 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(), 2288 nullptr, QualType(), nullptr, SC_None, nullptr); 2289 } 2290 2291 SourceRange ParmVarDecl::getSourceRange() const { 2292 if (!hasInheritedDefaultArg()) { 2293 SourceRange ArgRange = getDefaultArgRange(); 2294 if (ArgRange.isValid()) 2295 return SourceRange(getOuterLocStart(), ArgRange.getEnd()); 2296 } 2297 2298 // DeclaratorDecl considers the range of postfix types as overlapping with the 2299 // declaration name, but this is not the case with parameters in ObjC methods. 2300 if (isa<ObjCMethodDecl>(getDeclContext())) 2301 return SourceRange(DeclaratorDecl::getLocStart(), getLocation()); 2302 2303 return DeclaratorDecl::getSourceRange(); 2304 } 2305 2306 Expr *ParmVarDecl::getDefaultArg() { 2307 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 2308 assert(!hasUninstantiatedDefaultArg() && 2309 "Default argument is not yet instantiated!"); 2310 2311 Expr *Arg = getInit(); 2312 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg)) 2313 return E->getSubExpr(); 2314 2315 return Arg; 2316 } 2317 2318 SourceRange ParmVarDecl::getDefaultArgRange() const { 2319 if (const Expr *E = getInit()) 2320 return E->getSourceRange(); 2321 2322 if (hasUninstantiatedDefaultArg()) 2323 return getUninstantiatedDefaultArg()->getSourceRange(); 2324 2325 return SourceRange(); 2326 } 2327 2328 bool ParmVarDecl::isParameterPack() const { 2329 return isa<PackExpansionType>(getType()); 2330 } 2331 2332 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { 2333 getASTContext().setParameterIndex(this, parameterIndex); 2334 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; 2335 } 2336 2337 unsigned ParmVarDecl::getParameterIndexLarge() const { 2338 return getASTContext().getParameterIndex(this); 2339 } 2340 2341 //===----------------------------------------------------------------------===// 2342 // FunctionDecl Implementation 2343 //===----------------------------------------------------------------------===// 2344 2345 void FunctionDecl::getNameForDiagnostic( 2346 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { 2347 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); 2348 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 2349 if (TemplateArgs) 2350 TemplateSpecializationType::PrintTemplateArgumentList( 2351 OS, TemplateArgs->data(), TemplateArgs->size(), Policy); 2352 } 2353 2354 bool FunctionDecl::isVariadic() const { 2355 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>()) 2356 return FT->isVariadic(); 2357 return false; 2358 } 2359 2360 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 2361 for (auto I : redecls()) { 2362 if (I->Body || I->IsLateTemplateParsed) { 2363 Definition = I; 2364 return true; 2365 } 2366 } 2367 2368 return false; 2369 } 2370 2371 bool FunctionDecl::hasTrivialBody() const 2372 { 2373 Stmt *S = getBody(); 2374 if (!S) { 2375 // Since we don't have a body for this function, we don't know if it's 2376 // trivial or not. 2377 return false; 2378 } 2379 2380 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 2381 return true; 2382 return false; 2383 } 2384 2385 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const { 2386 for (auto I : redecls()) { 2387 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed || 2388 I->hasAttr<AliasAttr>()) { 2389 Definition = I->IsDeleted ? I->getCanonicalDecl() : I; 2390 return true; 2391 } 2392 } 2393 2394 return false; 2395 } 2396 2397 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 2398 if (!hasBody(Definition)) 2399 return nullptr; 2400 2401 if (Definition->Body) 2402 return Definition->Body.get(getASTContext().getExternalSource()); 2403 2404 return nullptr; 2405 } 2406 2407 void FunctionDecl::setBody(Stmt *B) { 2408 Body = B; 2409 if (B) 2410 EndRangeLoc = B->getLocEnd(); 2411 } 2412 2413 void FunctionDecl::setPure(bool P) { 2414 IsPure = P; 2415 if (P) 2416 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 2417 Parent->markedVirtualFunctionPure(); 2418 } 2419 2420 template<std::size_t Len> 2421 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) { 2422 IdentifierInfo *II = ND->getIdentifier(); 2423 return II && II->isStr(Str); 2424 } 2425 2426 bool FunctionDecl::isMain() const { 2427 const TranslationUnitDecl *tunit = 2428 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 2429 return tunit && 2430 !tunit->getASTContext().getLangOpts().Freestanding && 2431 isNamed(this, "main"); 2432 } 2433 2434 bool FunctionDecl::isMSVCRTEntryPoint() const { 2435 const TranslationUnitDecl *TUnit = 2436 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 2437 if (!TUnit) 2438 return false; 2439 2440 // Even though we aren't really targeting MSVCRT if we are freestanding, 2441 // semantic analysis for these functions remains the same. 2442 2443 // MSVCRT entry points only exist on MSVCRT targets. 2444 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT()) 2445 return false; 2446 2447 // Nameless functions like constructors cannot be entry points. 2448 if (!getIdentifier()) 2449 return false; 2450 2451 return llvm::StringSwitch<bool>(getName()) 2452 .Cases("main", // an ANSI console app 2453 "wmain", // a Unicode console App 2454 "WinMain", // an ANSI GUI app 2455 "wWinMain", // a Unicode GUI app 2456 "DllMain", // a DLL 2457 true) 2458 .Default(false); 2459 } 2460 2461 bool FunctionDecl::isReservedGlobalPlacementOperator() const { 2462 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName); 2463 assert(getDeclName().getCXXOverloadedOperator() == OO_New || 2464 getDeclName().getCXXOverloadedOperator() == OO_Delete || 2465 getDeclName().getCXXOverloadedOperator() == OO_Array_New || 2466 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete); 2467 2468 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 2469 return false; 2470 2471 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>(); 2472 if (proto->getNumParams() != 2 || proto->isVariadic()) 2473 return false; 2474 2475 ASTContext &Context = 2476 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) 2477 ->getASTContext(); 2478 2479 // The result type and first argument type are constant across all 2480 // these operators. The second argument must be exactly void*. 2481 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy); 2482 } 2483 2484 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const { 2485 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName) 2486 return false; 2487 if (getDeclName().getCXXOverloadedOperator() != OO_New && 2488 getDeclName().getCXXOverloadedOperator() != OO_Delete && 2489 getDeclName().getCXXOverloadedOperator() != OO_Array_New && 2490 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete) 2491 return false; 2492 2493 if (isa<CXXRecordDecl>(getDeclContext())) 2494 return false; 2495 2496 // This can only fail for an invalid 'operator new' declaration. 2497 if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) 2498 return false; 2499 2500 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>(); 2501 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic()) 2502 return false; 2503 2504 // If this is a single-parameter function, it must be a replaceable global 2505 // allocation or deallocation function. 2506 if (FPT->getNumParams() == 1) 2507 return true; 2508 2509 // Otherwise, we're looking for a second parameter whose type is 2510 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'. 2511 QualType Ty = FPT->getParamType(1); 2512 ASTContext &Ctx = getASTContext(); 2513 if (Ctx.getLangOpts().SizedDeallocation && 2514 Ctx.hasSameType(Ty, Ctx.getSizeType())) 2515 return true; 2516 if (!Ty->isReferenceType()) 2517 return false; 2518 Ty = Ty->getPointeeType(); 2519 if (Ty.getCVRQualifiers() != Qualifiers::Const) 2520 return false; 2521 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 2522 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace(); 2523 } 2524 2525 LanguageLinkage FunctionDecl::getLanguageLinkage() const { 2526 return getDeclLanguageLinkage(*this); 2527 } 2528 2529 bool FunctionDecl::isExternC() const { 2530 return isDeclExternC(*this); 2531 } 2532 2533 bool FunctionDecl::isInExternCContext() const { 2534 return getLexicalDeclContext()->isExternCContext(); 2535 } 2536 2537 bool FunctionDecl::isInExternCXXContext() const { 2538 return getLexicalDeclContext()->isExternCXXContext(); 2539 } 2540 2541 bool FunctionDecl::isGlobal() const { 2542 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this)) 2543 return Method->isStatic(); 2544 2545 if (getCanonicalDecl()->getStorageClass() == SC_Static) 2546 return false; 2547 2548 for (const DeclContext *DC = getDeclContext(); 2549 DC->isNamespace(); 2550 DC = DC->getParent()) { 2551 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) { 2552 if (!Namespace->getDeclName()) 2553 return false; 2554 break; 2555 } 2556 } 2557 2558 return true; 2559 } 2560 2561 bool FunctionDecl::isNoReturn() const { 2562 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() || 2563 hasAttr<C11NoReturnAttr>() || 2564 getType()->getAs<FunctionType>()->getNoReturnAttr(); 2565 } 2566 2567 void 2568 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 2569 redeclarable_base::setPreviousDecl(PrevDecl); 2570 2571 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 2572 FunctionTemplateDecl *PrevFunTmpl 2573 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr; 2574 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 2575 FunTmpl->setPreviousDecl(PrevFunTmpl); 2576 } 2577 2578 if (PrevDecl && PrevDecl->IsInline) 2579 IsInline = true; 2580 } 2581 2582 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); } 2583 2584 /// \brief Returns a value indicating whether this function 2585 /// corresponds to a builtin function. 2586 /// 2587 /// The function corresponds to a built-in function if it is 2588 /// declared at translation scope or within an extern "C" block and 2589 /// its name matches with the name of a builtin. The returned value 2590 /// will be 0 for functions that do not correspond to a builtin, a 2591 /// value of type \c Builtin::ID if in the target-independent range 2592 /// \c [1,Builtin::First), or a target-specific builtin value. 2593 unsigned FunctionDecl::getBuiltinID() const { 2594 if (!getIdentifier()) 2595 return 0; 2596 2597 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 2598 if (!BuiltinID) 2599 return 0; 2600 2601 ASTContext &Context = getASTContext(); 2602 if (Context.getLangOpts().CPlusPlus) { 2603 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>( 2604 getFirstDecl()->getDeclContext()); 2605 // In C++, the first declaration of a builtin is always inside an implicit 2606 // extern "C". 2607 // FIXME: A recognised library function may not be directly in an extern "C" 2608 // declaration, for instance "extern "C" { namespace std { decl } }". 2609 if (!LinkageDecl) { 2610 if (BuiltinID == Builtin::BI__GetExceptionInfo && 2611 Context.getTargetInfo().getCXXABI().isMicrosoft() && 2612 isInStdNamespace()) 2613 return Builtin::BI__GetExceptionInfo; 2614 return 0; 2615 } 2616 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c) 2617 return 0; 2618 } 2619 2620 // If the function is marked "overloadable", it has a different mangled name 2621 // and is not the C library function. 2622 if (hasAttr<OverloadableAttr>()) 2623 return 0; 2624 2625 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 2626 return BuiltinID; 2627 2628 // This function has the name of a known C library 2629 // function. Determine whether it actually refers to the C library 2630 // function or whether it just has the same name. 2631 2632 // If this is a static function, it's not a builtin. 2633 if (getStorageClass() == SC_Static) 2634 return 0; 2635 2636 return BuiltinID; 2637 } 2638 2639 2640 /// getNumParams - Return the number of parameters this function must have 2641 /// based on its FunctionType. This is the length of the ParamInfo array 2642 /// after it has been created. 2643 unsigned FunctionDecl::getNumParams() const { 2644 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>(); 2645 return FPT ? FPT->getNumParams() : 0; 2646 } 2647 2648 void FunctionDecl::setParams(ASTContext &C, 2649 ArrayRef<ParmVarDecl *> NewParamInfo) { 2650 assert(!ParamInfo && "Already has param info!"); 2651 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); 2652 2653 // Zero params -> null pointer. 2654 if (!NewParamInfo.empty()) { 2655 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; 2656 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 2657 } 2658 } 2659 2660 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) { 2661 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!"); 2662 2663 if (!NewDecls.empty()) { 2664 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()]; 2665 std::copy(NewDecls.begin(), NewDecls.end(), A); 2666 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size()); 2667 // Move declarations introduced in prototype to the function context. 2668 for (auto I : NewDecls) { 2669 DeclContext *DC = I->getDeclContext(); 2670 // Forward-declared reference to an enumeration is not added to 2671 // declaration scope, so skip declaration that is absent from its 2672 // declaration contexts. 2673 if (DC->containsDecl(I)) { 2674 DC->removeDecl(I); 2675 I->setDeclContext(this); 2676 addDecl(I); 2677 } 2678 } 2679 } 2680 } 2681 2682 /// getMinRequiredArguments - Returns the minimum number of arguments 2683 /// needed to call this function. This may be fewer than the number of 2684 /// function parameters, if some of the parameters have default 2685 /// arguments (in C++) or are parameter packs (C++11). 2686 unsigned FunctionDecl::getMinRequiredArguments() const { 2687 if (!getASTContext().getLangOpts().CPlusPlus) 2688 return getNumParams(); 2689 2690 unsigned NumRequiredArgs = 0; 2691 for (auto *Param : params()) 2692 if (!Param->isParameterPack() && !Param->hasDefaultArg()) 2693 ++NumRequiredArgs; 2694 return NumRequiredArgs; 2695 } 2696 2697 /// \brief The combination of the extern and inline keywords under MSVC forces 2698 /// the function to be required. 2699 /// 2700 /// Note: This function assumes that we will only get called when isInlined() 2701 /// would return true for this FunctionDecl. 2702 bool FunctionDecl::isMSExternInline() const { 2703 assert(isInlined() && "expected to get called on an inlined function!"); 2704 2705 const ASTContext &Context = getASTContext(); 2706 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 2707 !hasAttr<DLLExportAttr>()) 2708 return false; 2709 2710 for (const FunctionDecl *FD = getMostRecentDecl(); FD; 2711 FD = FD->getPreviousDecl()) 2712 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 2713 return true; 2714 2715 return false; 2716 } 2717 2718 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) { 2719 if (Redecl->getStorageClass() != SC_Extern) 2720 return false; 2721 2722 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD; 2723 FD = FD->getPreviousDecl()) 2724 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) 2725 return false; 2726 2727 return true; 2728 } 2729 2730 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { 2731 // Only consider file-scope declarations in this test. 2732 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 2733 return false; 2734 2735 // Only consider explicit declarations; the presence of a builtin for a 2736 // libcall shouldn't affect whether a definition is externally visible. 2737 if (Redecl->isImplicit()) 2738 return false; 2739 2740 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 2741 return true; // Not an inline definition 2742 2743 return false; 2744 } 2745 2746 /// \brief For a function declaration in C or C++, determine whether this 2747 /// declaration causes the definition to be externally visible. 2748 /// 2749 /// For instance, this determines if adding the current declaration to the set 2750 /// of redeclarations of the given functions causes 2751 /// isInlineDefinitionExternallyVisible to change from false to true. 2752 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { 2753 assert(!doesThisDeclarationHaveABody() && 2754 "Must have a declaration without a body."); 2755 2756 ASTContext &Context = getASTContext(); 2757 2758 if (Context.getLangOpts().MSVCCompat) { 2759 const FunctionDecl *Definition; 2760 if (hasBody(Definition) && Definition->isInlined() && 2761 redeclForcesDefMSVC(this)) 2762 return true; 2763 } 2764 2765 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 2766 // With GNU inlining, a declaration with 'inline' but not 'extern', forces 2767 // an externally visible definition. 2768 // 2769 // FIXME: What happens if gnu_inline gets added on after the first 2770 // declaration? 2771 if (!isInlineSpecified() || getStorageClass() == SC_Extern) 2772 return false; 2773 2774 const FunctionDecl *Prev = this; 2775 bool FoundBody = false; 2776 while ((Prev = Prev->getPreviousDecl())) { 2777 FoundBody |= Prev->Body.isValid(); 2778 2779 if (Prev->Body) { 2780 // If it's not the case that both 'inline' and 'extern' are 2781 // specified on the definition, then it is always externally visible. 2782 if (!Prev->isInlineSpecified() || 2783 Prev->getStorageClass() != SC_Extern) 2784 return false; 2785 } else if (Prev->isInlineSpecified() && 2786 Prev->getStorageClass() != SC_Extern) { 2787 return false; 2788 } 2789 } 2790 return FoundBody; 2791 } 2792 2793 if (Context.getLangOpts().CPlusPlus) 2794 return false; 2795 2796 // C99 6.7.4p6: 2797 // [...] If all of the file scope declarations for a function in a 2798 // translation unit include the inline function specifier without extern, 2799 // then the definition in that translation unit is an inline definition. 2800 if (isInlineSpecified() && getStorageClass() != SC_Extern) 2801 return false; 2802 const FunctionDecl *Prev = this; 2803 bool FoundBody = false; 2804 while ((Prev = Prev->getPreviousDecl())) { 2805 FoundBody |= Prev->Body.isValid(); 2806 if (RedeclForcesDefC99(Prev)) 2807 return false; 2808 } 2809 return FoundBody; 2810 } 2811 2812 SourceRange FunctionDecl::getReturnTypeSourceRange() const { 2813 const TypeSourceInfo *TSI = getTypeSourceInfo(); 2814 if (!TSI) 2815 return SourceRange(); 2816 FunctionTypeLoc FTL = 2817 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>(); 2818 if (!FTL) 2819 return SourceRange(); 2820 2821 // Skip self-referential return types. 2822 const SourceManager &SM = getASTContext().getSourceManager(); 2823 SourceRange RTRange = FTL.getReturnLoc().getSourceRange(); 2824 SourceLocation Boundary = getNameInfo().getLocStart(); 2825 if (RTRange.isInvalid() || Boundary.isInvalid() || 2826 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary)) 2827 return SourceRange(); 2828 2829 return RTRange; 2830 } 2831 2832 bool FunctionDecl::hasUnusedResultAttr() const { 2833 QualType RetType = getReturnType(); 2834 if (RetType->isRecordType()) { 2835 const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl(); 2836 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(this); 2837 if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() && 2838 !(MD && MD->getCorrespondingMethodInClass(Ret, true))) 2839 return true; 2840 } 2841 return hasAttr<WarnUnusedResultAttr>(); 2842 } 2843 2844 /// \brief For an inline function definition in C, or for a gnu_inline function 2845 /// in C++, determine whether the definition will be externally visible. 2846 /// 2847 /// Inline function definitions are always available for inlining optimizations. 2848 /// However, depending on the language dialect, declaration specifiers, and 2849 /// attributes, the definition of an inline function may or may not be 2850 /// "externally" visible to other translation units in the program. 2851 /// 2852 /// In C99, inline definitions are not externally visible by default. However, 2853 /// if even one of the global-scope declarations is marked "extern inline", the 2854 /// inline definition becomes externally visible (C99 6.7.4p6). 2855 /// 2856 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function 2857 /// definition, we use the GNU semantics for inline, which are nearly the 2858 /// opposite of C99 semantics. In particular, "inline" by itself will create 2859 /// an externally visible symbol, but "extern inline" will not create an 2860 /// externally visible symbol. 2861 bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 2862 assert(doesThisDeclarationHaveABody() && "Must have the function definition"); 2863 assert(isInlined() && "Function must be inline"); 2864 ASTContext &Context = getASTContext(); 2865 2866 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 2867 // Note: If you change the logic here, please change 2868 // doesDeclarationForceExternallyVisibleDefinition as well. 2869 // 2870 // If it's not the case that both 'inline' and 'extern' are 2871 // specified on the definition, then this inline definition is 2872 // externally visible. 2873 if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) 2874 return true; 2875 2876 // If any declaration is 'inline' but not 'extern', then this definition 2877 // is externally visible. 2878 for (auto Redecl : redecls()) { 2879 if (Redecl->isInlineSpecified() && 2880 Redecl->getStorageClass() != SC_Extern) 2881 return true; 2882 } 2883 2884 return false; 2885 } 2886 2887 // The rest of this function is C-only. 2888 assert(!Context.getLangOpts().CPlusPlus && 2889 "should not use C inline rules in C++"); 2890 2891 // C99 6.7.4p6: 2892 // [...] If all of the file scope declarations for a function in a 2893 // translation unit include the inline function specifier without extern, 2894 // then the definition in that translation unit is an inline definition. 2895 for (auto Redecl : redecls()) { 2896 if (RedeclForcesDefC99(Redecl)) 2897 return true; 2898 } 2899 2900 // C99 6.7.4p6: 2901 // An inline definition does not provide an external definition for the 2902 // function, and does not forbid an external definition in another 2903 // translation unit. 2904 return false; 2905 } 2906 2907 /// getOverloadedOperator - Which C++ overloaded operator this 2908 /// function represents, if any. 2909 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 2910 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 2911 return getDeclName().getCXXOverloadedOperator(); 2912 else 2913 return OO_None; 2914 } 2915 2916 /// getLiteralIdentifier - The literal suffix identifier this function 2917 /// represents, if any. 2918 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 2919 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 2920 return getDeclName().getCXXLiteralIdentifier(); 2921 else 2922 return nullptr; 2923 } 2924 2925 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 2926 if (TemplateOrSpecialization.isNull()) 2927 return TK_NonTemplate; 2928 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 2929 return TK_FunctionTemplate; 2930 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 2931 return TK_MemberSpecialization; 2932 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 2933 return TK_FunctionTemplateSpecialization; 2934 if (TemplateOrSpecialization.is 2935 <DependentFunctionTemplateSpecializationInfo*>()) 2936 return TK_DependentFunctionTemplateSpecialization; 2937 2938 llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); 2939 } 2940 2941 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 2942 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 2943 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 2944 2945 return nullptr; 2946 } 2947 2948 void 2949 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 2950 FunctionDecl *FD, 2951 TemplateSpecializationKind TSK) { 2952 assert(TemplateOrSpecialization.isNull() && 2953 "Member function is already a specialization"); 2954 MemberSpecializationInfo *Info 2955 = new (C) MemberSpecializationInfo(FD, TSK); 2956 TemplateOrSpecialization = Info; 2957 } 2958 2959 bool FunctionDecl::isImplicitlyInstantiable() const { 2960 // If the function is invalid, it can't be implicitly instantiated. 2961 if (isInvalidDecl()) 2962 return false; 2963 2964 switch (getTemplateSpecializationKind()) { 2965 case TSK_Undeclared: 2966 case TSK_ExplicitInstantiationDefinition: 2967 return false; 2968 2969 case TSK_ImplicitInstantiation: 2970 return true; 2971 2972 // It is possible to instantiate TSK_ExplicitSpecialization kind 2973 // if the FunctionDecl has a class scope specialization pattern. 2974 case TSK_ExplicitSpecialization: 2975 return getClassScopeSpecializationPattern() != nullptr; 2976 2977 case TSK_ExplicitInstantiationDeclaration: 2978 // Handled below. 2979 break; 2980 } 2981 2982 // Find the actual template from which we will instantiate. 2983 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 2984 bool HasPattern = false; 2985 if (PatternDecl) 2986 HasPattern = PatternDecl->hasBody(PatternDecl); 2987 2988 // C++0x [temp.explicit]p9: 2989 // Except for inline functions, other explicit instantiation declarations 2990 // have the effect of suppressing the implicit instantiation of the entity 2991 // to which they refer. 2992 if (!HasPattern || !PatternDecl) 2993 return true; 2994 2995 return PatternDecl->isInlined(); 2996 } 2997 2998 bool FunctionDecl::isTemplateInstantiation() const { 2999 switch (getTemplateSpecializationKind()) { 3000 case TSK_Undeclared: 3001 case TSK_ExplicitSpecialization: 3002 return false; 3003 case TSK_ImplicitInstantiation: 3004 case TSK_ExplicitInstantiationDeclaration: 3005 case TSK_ExplicitInstantiationDefinition: 3006 return true; 3007 } 3008 llvm_unreachable("All TSK values handled."); 3009 } 3010 3011 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 3012 // Handle class scope explicit specialization special case. 3013 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 3014 return getClassScopeSpecializationPattern(); 3015 3016 // If this is a generic lambda call operator specialization, its 3017 // instantiation pattern is always its primary template's pattern 3018 // even if its primary template was instantiated from another 3019 // member template (which happens with nested generic lambdas). 3020 // Since a lambda's call operator's body is transformed eagerly, 3021 // we don't have to go hunting for a prototype definition template 3022 // (i.e. instantiated-from-member-template) to use as an instantiation 3023 // pattern. 3024 3025 if (isGenericLambdaCallOperatorSpecialization( 3026 dyn_cast<CXXMethodDecl>(this))) { 3027 assert(getPrimaryTemplate() && "A generic lambda specialization must be " 3028 "generated from a primary call operator " 3029 "template"); 3030 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() && 3031 "A generic lambda call operator template must always have a body - " 3032 "even if instantiated from a prototype (i.e. as written) member " 3033 "template"); 3034 return getPrimaryTemplate()->getTemplatedDecl(); 3035 } 3036 3037 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 3038 while (Primary->getInstantiatedFromMemberTemplate()) { 3039 // If we have hit a point where the user provided a specialization of 3040 // this template, we're done looking. 3041 if (Primary->isMemberSpecialization()) 3042 break; 3043 Primary = Primary->getInstantiatedFromMemberTemplate(); 3044 } 3045 3046 return Primary->getTemplatedDecl(); 3047 } 3048 3049 return getInstantiatedFromMemberFunction(); 3050 } 3051 3052 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 3053 if (FunctionTemplateSpecializationInfo *Info 3054 = TemplateOrSpecialization 3055 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3056 return Info->Template.getPointer(); 3057 } 3058 return nullptr; 3059 } 3060 3061 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const { 3062 return getASTContext().getClassScopeSpecializationPattern(this); 3063 } 3064 3065 const TemplateArgumentList * 3066 FunctionDecl::getTemplateSpecializationArgs() const { 3067 if (FunctionTemplateSpecializationInfo *Info 3068 = TemplateOrSpecialization 3069 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3070 return Info->TemplateArguments; 3071 } 3072 return nullptr; 3073 } 3074 3075 const ASTTemplateArgumentListInfo * 3076 FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 3077 if (FunctionTemplateSpecializationInfo *Info 3078 = TemplateOrSpecialization 3079 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 3080 return Info->TemplateArgumentsAsWritten; 3081 } 3082 return nullptr; 3083 } 3084 3085 void 3086 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 3087 FunctionTemplateDecl *Template, 3088 const TemplateArgumentList *TemplateArgs, 3089 void *InsertPos, 3090 TemplateSpecializationKind TSK, 3091 const TemplateArgumentListInfo *TemplateArgsAsWritten, 3092 SourceLocation PointOfInstantiation) { 3093 assert(TSK != TSK_Undeclared && 3094 "Must specify the type of function template specialization"); 3095 FunctionTemplateSpecializationInfo *Info 3096 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 3097 if (!Info) 3098 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK, 3099 TemplateArgs, 3100 TemplateArgsAsWritten, 3101 PointOfInstantiation); 3102 TemplateOrSpecialization = Info; 3103 Template->addSpecialization(Info, InsertPos); 3104 } 3105 3106 void 3107 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 3108 const UnresolvedSetImpl &Templates, 3109 const TemplateArgumentListInfo &TemplateArgs) { 3110 assert(TemplateOrSpecialization.isNull()); 3111 DependentFunctionTemplateSpecializationInfo *Info = 3112 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates, 3113 TemplateArgs); 3114 TemplateOrSpecialization = Info; 3115 } 3116 3117 DependentFunctionTemplateSpecializationInfo * 3118 DependentFunctionTemplateSpecializationInfo::Create( 3119 ASTContext &Context, const UnresolvedSetImpl &Ts, 3120 const TemplateArgumentListInfo &TArgs) { 3121 void *Buffer = Context.Allocate( 3122 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>( 3123 TArgs.size(), Ts.size())); 3124 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs); 3125 } 3126 3127 DependentFunctionTemplateSpecializationInfo:: 3128 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 3129 const TemplateArgumentListInfo &TArgs) 3130 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 3131 3132 NumTemplates = Ts.size(); 3133 NumArgs = TArgs.size(); 3134 3135 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>(); 3136 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 3137 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 3138 3139 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>(); 3140 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 3141 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 3142 } 3143 3144 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 3145 // For a function template specialization, query the specialization 3146 // information object. 3147 FunctionTemplateSpecializationInfo *FTSInfo 3148 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 3149 if (FTSInfo) 3150 return FTSInfo->getTemplateSpecializationKind(); 3151 3152 MemberSpecializationInfo *MSInfo 3153 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 3154 if (MSInfo) 3155 return MSInfo->getTemplateSpecializationKind(); 3156 3157 return TSK_Undeclared; 3158 } 3159 3160 void 3161 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 3162 SourceLocation PointOfInstantiation) { 3163 if (FunctionTemplateSpecializationInfo *FTSInfo 3164 = TemplateOrSpecialization.dyn_cast< 3165 FunctionTemplateSpecializationInfo*>()) { 3166 FTSInfo->setTemplateSpecializationKind(TSK); 3167 if (TSK != TSK_ExplicitSpecialization && 3168 PointOfInstantiation.isValid() && 3169 FTSInfo->getPointOfInstantiation().isInvalid()) 3170 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 3171 } else if (MemberSpecializationInfo *MSInfo 3172 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 3173 MSInfo->setTemplateSpecializationKind(TSK); 3174 if (TSK != TSK_ExplicitSpecialization && 3175 PointOfInstantiation.isValid() && 3176 MSInfo->getPointOfInstantiation().isInvalid()) 3177 MSInfo->setPointOfInstantiation(PointOfInstantiation); 3178 } else 3179 llvm_unreachable("Function cannot have a template specialization kind"); 3180 } 3181 3182 SourceLocation FunctionDecl::getPointOfInstantiation() const { 3183 if (FunctionTemplateSpecializationInfo *FTSInfo 3184 = TemplateOrSpecialization.dyn_cast< 3185 FunctionTemplateSpecializationInfo*>()) 3186 return FTSInfo->getPointOfInstantiation(); 3187 else if (MemberSpecializationInfo *MSInfo 3188 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 3189 return MSInfo->getPointOfInstantiation(); 3190 3191 return SourceLocation(); 3192 } 3193 3194 bool FunctionDecl::isOutOfLine() const { 3195 if (Decl::isOutOfLine()) 3196 return true; 3197 3198 // If this function was instantiated from a member function of a 3199 // class template, check whether that member function was defined out-of-line. 3200 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 3201 const FunctionDecl *Definition; 3202 if (FD->hasBody(Definition)) 3203 return Definition->isOutOfLine(); 3204 } 3205 3206 // If this function was instantiated from a function template, 3207 // check whether that function template was defined out-of-line. 3208 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 3209 const FunctionDecl *Definition; 3210 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 3211 return Definition->isOutOfLine(); 3212 } 3213 3214 return false; 3215 } 3216 3217 SourceRange FunctionDecl::getSourceRange() const { 3218 return SourceRange(getOuterLocStart(), EndRangeLoc); 3219 } 3220 3221 unsigned FunctionDecl::getMemoryFunctionKind() const { 3222 IdentifierInfo *FnInfo = getIdentifier(); 3223 3224 if (!FnInfo) 3225 return 0; 3226 3227 // Builtin handling. 3228 switch (getBuiltinID()) { 3229 case Builtin::BI__builtin_memset: 3230 case Builtin::BI__builtin___memset_chk: 3231 case Builtin::BImemset: 3232 return Builtin::BImemset; 3233 3234 case Builtin::BI__builtin_memcpy: 3235 case Builtin::BI__builtin___memcpy_chk: 3236 case Builtin::BImemcpy: 3237 return Builtin::BImemcpy; 3238 3239 case Builtin::BI__builtin_memmove: 3240 case Builtin::BI__builtin___memmove_chk: 3241 case Builtin::BImemmove: 3242 return Builtin::BImemmove; 3243 3244 case Builtin::BIstrlcpy: 3245 case Builtin::BI__builtin___strlcpy_chk: 3246 return Builtin::BIstrlcpy; 3247 3248 case Builtin::BIstrlcat: 3249 case Builtin::BI__builtin___strlcat_chk: 3250 return Builtin::BIstrlcat; 3251 3252 case Builtin::BI__builtin_memcmp: 3253 case Builtin::BImemcmp: 3254 return Builtin::BImemcmp; 3255 3256 case Builtin::BI__builtin_strncpy: 3257 case Builtin::BI__builtin___strncpy_chk: 3258 case Builtin::BIstrncpy: 3259 return Builtin::BIstrncpy; 3260 3261 case Builtin::BI__builtin_strncmp: 3262 case Builtin::BIstrncmp: 3263 return Builtin::BIstrncmp; 3264 3265 case Builtin::BI__builtin_strncasecmp: 3266 case Builtin::BIstrncasecmp: 3267 return Builtin::BIstrncasecmp; 3268 3269 case Builtin::BI__builtin_strncat: 3270 case Builtin::BI__builtin___strncat_chk: 3271 case Builtin::BIstrncat: 3272 return Builtin::BIstrncat; 3273 3274 case Builtin::BI__builtin_strndup: 3275 case Builtin::BIstrndup: 3276 return Builtin::BIstrndup; 3277 3278 case Builtin::BI__builtin_strlen: 3279 case Builtin::BIstrlen: 3280 return Builtin::BIstrlen; 3281 3282 default: 3283 if (isExternC()) { 3284 if (FnInfo->isStr("memset")) 3285 return Builtin::BImemset; 3286 else if (FnInfo->isStr("memcpy")) 3287 return Builtin::BImemcpy; 3288 else if (FnInfo->isStr("memmove")) 3289 return Builtin::BImemmove; 3290 else if (FnInfo->isStr("memcmp")) 3291 return Builtin::BImemcmp; 3292 else if (FnInfo->isStr("strncpy")) 3293 return Builtin::BIstrncpy; 3294 else if (FnInfo->isStr("strncmp")) 3295 return Builtin::BIstrncmp; 3296 else if (FnInfo->isStr("strncasecmp")) 3297 return Builtin::BIstrncasecmp; 3298 else if (FnInfo->isStr("strncat")) 3299 return Builtin::BIstrncat; 3300 else if (FnInfo->isStr("strndup")) 3301 return Builtin::BIstrndup; 3302 else if (FnInfo->isStr("strlen")) 3303 return Builtin::BIstrlen; 3304 } 3305 break; 3306 } 3307 return 0; 3308 } 3309 3310 //===----------------------------------------------------------------------===// 3311 // FieldDecl Implementation 3312 //===----------------------------------------------------------------------===// 3313 3314 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 3315 SourceLocation StartLoc, SourceLocation IdLoc, 3316 IdentifierInfo *Id, QualType T, 3317 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 3318 InClassInitStyle InitStyle) { 3319 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 3320 BW, Mutable, InitStyle); 3321 } 3322 3323 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3324 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(), 3325 SourceLocation(), nullptr, QualType(), nullptr, 3326 nullptr, false, ICIS_NoInit); 3327 } 3328 3329 bool FieldDecl::isAnonymousStructOrUnion() const { 3330 if (!isImplicit() || getDeclName()) 3331 return false; 3332 3333 if (const RecordType *Record = getType()->getAs<RecordType>()) 3334 return Record->getDecl()->isAnonymousStructOrUnion(); 3335 3336 return false; 3337 } 3338 3339 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { 3340 assert(isBitField() && "not a bitfield"); 3341 Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer()); 3342 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue(); 3343 } 3344 3345 unsigned FieldDecl::getFieldIndex() const { 3346 const FieldDecl *Canonical = getCanonicalDecl(); 3347 if (Canonical != this) 3348 return Canonical->getFieldIndex(); 3349 3350 if (CachedFieldIndex) return CachedFieldIndex - 1; 3351 3352 unsigned Index = 0; 3353 const RecordDecl *RD = getParent(); 3354 3355 for (auto *Field : RD->fields()) { 3356 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1; 3357 ++Index; 3358 } 3359 3360 assert(CachedFieldIndex && "failed to find field in parent"); 3361 return CachedFieldIndex - 1; 3362 } 3363 3364 SourceRange FieldDecl::getSourceRange() const { 3365 switch (InitStorage.getInt()) { 3366 // All three of these cases store an optional Expr*. 3367 case ISK_BitWidthOrNothing: 3368 case ISK_InClassCopyInit: 3369 case ISK_InClassListInit: 3370 if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer())) 3371 return SourceRange(getInnerLocStart(), E->getLocEnd()); 3372 // FALLTHROUGH 3373 3374 case ISK_CapturedVLAType: 3375 return DeclaratorDecl::getSourceRange(); 3376 } 3377 llvm_unreachable("bad init storage kind"); 3378 } 3379 3380 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) { 3381 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) && 3382 "capturing type in non-lambda or captured record."); 3383 assert(InitStorage.getInt() == ISK_BitWidthOrNothing && 3384 InitStorage.getPointer() == nullptr && 3385 "bit width, initializer or captured type already set"); 3386 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType), 3387 ISK_CapturedVLAType); 3388 } 3389 3390 //===----------------------------------------------------------------------===// 3391 // TagDecl Implementation 3392 //===----------------------------------------------------------------------===// 3393 3394 SourceLocation TagDecl::getOuterLocStart() const { 3395 return getTemplateOrInnerLocStart(this); 3396 } 3397 3398 SourceRange TagDecl::getSourceRange() const { 3399 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 3400 return SourceRange(getOuterLocStart(), E); 3401 } 3402 3403 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); } 3404 3405 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 3406 TypedefNameDeclOrQualifier = TDD; 3407 if (const Type *T = getTypeForDecl()) { 3408 (void)T; 3409 assert(T->isLinkageValid()); 3410 } 3411 assert(isLinkageValid()); 3412 } 3413 3414 void TagDecl::startDefinition() { 3415 IsBeingDefined = true; 3416 3417 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) { 3418 struct CXXRecordDecl::DefinitionData *Data = 3419 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 3420 for (auto I : redecls()) 3421 cast<CXXRecordDecl>(I)->DefinitionData = Data; 3422 } 3423 } 3424 3425 void TagDecl::completeDefinition() { 3426 assert((!isa<CXXRecordDecl>(this) || 3427 cast<CXXRecordDecl>(this)->hasDefinition()) && 3428 "definition completed but not started"); 3429 3430 IsCompleteDefinition = true; 3431 IsBeingDefined = false; 3432 3433 if (ASTMutationListener *L = getASTMutationListener()) 3434 L->CompletedTagDefinition(this); 3435 } 3436 3437 TagDecl *TagDecl::getDefinition() const { 3438 if (isCompleteDefinition()) 3439 return const_cast<TagDecl *>(this); 3440 3441 // If it's possible for us to have an out-of-date definition, check now. 3442 if (MayHaveOutOfDateDef) { 3443 if (IdentifierInfo *II = getIdentifier()) { 3444 if (II->isOutOfDate()) { 3445 updateOutOfDate(*II); 3446 } 3447 } 3448 } 3449 3450 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this)) 3451 return CXXRD->getDefinition(); 3452 3453 for (auto R : redecls()) 3454 if (R->isCompleteDefinition()) 3455 return R; 3456 3457 return nullptr; 3458 } 3459 3460 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 3461 if (QualifierLoc) { 3462 // Make sure the extended qualifier info is allocated. 3463 if (!hasExtInfo()) 3464 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 3465 // Set qualifier info. 3466 getExtInfo()->QualifierLoc = QualifierLoc; 3467 } else { 3468 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 3469 if (hasExtInfo()) { 3470 if (getExtInfo()->NumTemplParamLists == 0) { 3471 getASTContext().Deallocate(getExtInfo()); 3472 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr; 3473 } 3474 else 3475 getExtInfo()->QualifierLoc = QualifierLoc; 3476 } 3477 } 3478 } 3479 3480 void TagDecl::setTemplateParameterListsInfo( 3481 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) { 3482 assert(!TPLists.empty()); 3483 // Make sure the extended decl info is allocated. 3484 if (!hasExtInfo()) 3485 // Allocate external info struct. 3486 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 3487 // Set the template parameter lists info. 3488 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists); 3489 } 3490 3491 //===----------------------------------------------------------------------===// 3492 // EnumDecl Implementation 3493 //===----------------------------------------------------------------------===// 3494 3495 void EnumDecl::anchor() { } 3496 3497 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, 3498 SourceLocation StartLoc, SourceLocation IdLoc, 3499 IdentifierInfo *Id, 3500 EnumDecl *PrevDecl, bool IsScoped, 3501 bool IsScopedUsingClassTag, bool IsFixed) { 3502 EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, 3503 IsScoped, IsScopedUsingClassTag, 3504 IsFixed); 3505 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3506 C.getTypeDeclType(Enum, PrevDecl); 3507 return Enum; 3508 } 3509 3510 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3511 EnumDecl *Enum = 3512 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(), 3513 nullptr, nullptr, false, false, false); 3514 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3515 return Enum; 3516 } 3517 3518 SourceRange EnumDecl::getIntegerTypeRange() const { 3519 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo()) 3520 return TI->getTypeLoc().getSourceRange(); 3521 return SourceRange(); 3522 } 3523 3524 void EnumDecl::completeDefinition(QualType NewType, 3525 QualType NewPromotionType, 3526 unsigned NumPositiveBits, 3527 unsigned NumNegativeBits) { 3528 assert(!isCompleteDefinition() && "Cannot redefine enums!"); 3529 if (!IntegerType) 3530 IntegerType = NewType.getTypePtr(); 3531 PromotionType = NewPromotionType; 3532 setNumPositiveBits(NumPositiveBits); 3533 setNumNegativeBits(NumNegativeBits); 3534 TagDecl::completeDefinition(); 3535 } 3536 3537 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { 3538 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 3539 return MSI->getTemplateSpecializationKind(); 3540 3541 return TSK_Undeclared; 3542 } 3543 3544 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 3545 SourceLocation PointOfInstantiation) { 3546 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 3547 assert(MSI && "Not an instantiated member enumeration?"); 3548 MSI->setTemplateSpecializationKind(TSK); 3549 if (TSK != TSK_ExplicitSpecialization && 3550 PointOfInstantiation.isValid() && 3551 MSI->getPointOfInstantiation().isInvalid()) 3552 MSI->setPointOfInstantiation(PointOfInstantiation); 3553 } 3554 3555 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { 3556 if (SpecializationInfo) 3557 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom()); 3558 3559 return nullptr; 3560 } 3561 3562 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 3563 TemplateSpecializationKind TSK) { 3564 assert(!SpecializationInfo && "Member enum is already a specialization"); 3565 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); 3566 } 3567 3568 //===----------------------------------------------------------------------===// 3569 // RecordDecl Implementation 3570 //===----------------------------------------------------------------------===// 3571 3572 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C, 3573 DeclContext *DC, SourceLocation StartLoc, 3574 SourceLocation IdLoc, IdentifierInfo *Id, 3575 RecordDecl *PrevDecl) 3576 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) { 3577 HasFlexibleArrayMember = false; 3578 AnonymousStructOrUnion = false; 3579 HasObjectMember = false; 3580 HasVolatileMember = false; 3581 LoadedFieldsFromExternalStorage = false; 3582 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 3583 } 3584 3585 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 3586 SourceLocation StartLoc, SourceLocation IdLoc, 3587 IdentifierInfo *Id, RecordDecl* PrevDecl) { 3588 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC, 3589 StartLoc, IdLoc, Id, PrevDecl); 3590 R->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3591 3592 C.getTypeDeclType(R, PrevDecl); 3593 return R; 3594 } 3595 3596 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 3597 RecordDecl *R = 3598 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(), 3599 SourceLocation(), nullptr, nullptr); 3600 R->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3601 return R; 3602 } 3603 3604 bool RecordDecl::isInjectedClassName() const { 3605 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 3606 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 3607 } 3608 3609 bool RecordDecl::isLambda() const { 3610 if (auto RD = dyn_cast<CXXRecordDecl>(this)) 3611 return RD->isLambda(); 3612 return false; 3613 } 3614 3615 bool RecordDecl::isCapturedRecord() const { 3616 return hasAttr<CapturedRecordAttr>(); 3617 } 3618 3619 void RecordDecl::setCapturedRecord() { 3620 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext())); 3621 } 3622 3623 RecordDecl::field_iterator RecordDecl::field_begin() const { 3624 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage) 3625 LoadFieldsFromExternalStorage(); 3626 3627 return field_iterator(decl_iterator(FirstDecl)); 3628 } 3629 3630 /// completeDefinition - Notes that the definition of this type is now 3631 /// complete. 3632 void RecordDecl::completeDefinition() { 3633 assert(!isCompleteDefinition() && "Cannot redefine record!"); 3634 TagDecl::completeDefinition(); 3635 } 3636 3637 /// isMsStruct - Get whether or not this record uses ms_struct layout. 3638 /// This which can be turned on with an attribute, pragma, or the 3639 /// -mms-bitfields command-line option. 3640 bool RecordDecl::isMsStruct(const ASTContext &C) const { 3641 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1; 3642 } 3643 3644 void RecordDecl::LoadFieldsFromExternalStorage() const { 3645 ExternalASTSource *Source = getASTContext().getExternalSource(); 3646 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 3647 3648 // Notify that we have a RecordDecl doing some initialization. 3649 ExternalASTSource::Deserializing TheFields(Source); 3650 3651 SmallVector<Decl*, 64> Decls; 3652 LoadedFieldsFromExternalStorage = true; 3653 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) { 3654 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); 3655 }, Decls); 3656 3657 #ifndef NDEBUG 3658 // Check that all decls we got were FieldDecls. 3659 for (unsigned i=0, e=Decls.size(); i != e; ++i) 3660 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); 3661 #endif 3662 3663 if (Decls.empty()) 3664 return; 3665 3666 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls, 3667 /*FieldsAlreadyLoaded=*/false); 3668 } 3669 3670 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const { 3671 ASTContext &Context = getASTContext(); 3672 if (!Context.getLangOpts().Sanitize.hasOneOf( 3673 SanitizerKind::Address | SanitizerKind::KernelAddress) || 3674 !Context.getLangOpts().SanitizeAddressFieldPadding) 3675 return false; 3676 const auto &Blacklist = Context.getSanitizerBlacklist(); 3677 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this); 3678 // We may be able to relax some of these requirements. 3679 int ReasonToReject = -1; 3680 if (!CXXRD || CXXRD->isExternCContext()) 3681 ReasonToReject = 0; // is not C++. 3682 else if (CXXRD->hasAttr<PackedAttr>()) 3683 ReasonToReject = 1; // is packed. 3684 else if (CXXRD->isUnion()) 3685 ReasonToReject = 2; // is a union. 3686 else if (CXXRD->isTriviallyCopyable()) 3687 ReasonToReject = 3; // is trivially copyable. 3688 else if (CXXRD->hasTrivialDestructor()) 3689 ReasonToReject = 4; // has trivial destructor. 3690 else if (CXXRD->isStandardLayout()) 3691 ReasonToReject = 5; // is standard layout. 3692 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding")) 3693 ReasonToReject = 6; // is in a blacklisted file. 3694 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(), 3695 "field-padding")) 3696 ReasonToReject = 7; // is blacklisted. 3697 3698 if (EmitRemark) { 3699 if (ReasonToReject >= 0) 3700 Context.getDiagnostics().Report( 3701 getLocation(), 3702 diag::remark_sanitize_address_insert_extra_padding_rejected) 3703 << getQualifiedNameAsString() << ReasonToReject; 3704 else 3705 Context.getDiagnostics().Report( 3706 getLocation(), 3707 diag::remark_sanitize_address_insert_extra_padding_accepted) 3708 << getQualifiedNameAsString(); 3709 } 3710 return ReasonToReject < 0; 3711 } 3712 3713 const FieldDecl *RecordDecl::findFirstNamedDataMember() const { 3714 for (const auto *I : fields()) { 3715 if (I->getIdentifier()) 3716 return I; 3717 3718 if (const RecordType *RT = I->getType()->getAs<RecordType>()) 3719 if (const FieldDecl *NamedDataMember = 3720 RT->getDecl()->findFirstNamedDataMember()) 3721 return NamedDataMember; 3722 } 3723 3724 // We didn't find a named data member. 3725 return nullptr; 3726 } 3727 3728 3729 //===----------------------------------------------------------------------===// 3730 // BlockDecl Implementation 3731 //===----------------------------------------------------------------------===// 3732 3733 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { 3734 assert(!ParamInfo && "Already has param info!"); 3735 3736 // Zero params -> null pointer. 3737 if (!NewParamInfo.empty()) { 3738 NumParams = NewParamInfo.size(); 3739 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; 3740 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 3741 } 3742 } 3743 3744 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, 3745 bool CapturesCXXThis) { 3746 this->CapturesCXXThis = CapturesCXXThis; 3747 this->NumCaptures = Captures.size(); 3748 3749 if (Captures.empty()) { 3750 this->Captures = nullptr; 3751 return; 3752 } 3753 3754 this->Captures = Captures.copy(Context).data(); 3755 } 3756 3757 bool BlockDecl::capturesVariable(const VarDecl *variable) const { 3758 for (const auto &I : captures()) 3759 // Only auto vars can be captured, so no redeclaration worries. 3760 if (I.getVariable() == variable) 3761 return true; 3762 3763 return false; 3764 } 3765 3766 SourceRange BlockDecl::getSourceRange() const { 3767 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation()); 3768 } 3769 3770 //===----------------------------------------------------------------------===// 3771 // Other Decl Allocation/Deallocation Method Implementations 3772 //===----------------------------------------------------------------------===// 3773 3774 void TranslationUnitDecl::anchor() { } 3775 3776 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 3777 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C); 3778 } 3779 3780 void ExternCContextDecl::anchor() { } 3781 3782 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C, 3783 TranslationUnitDecl *DC) { 3784 return new (C, DC) ExternCContextDecl(DC); 3785 } 3786 3787 void LabelDecl::anchor() { } 3788 3789 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 3790 SourceLocation IdentL, IdentifierInfo *II) { 3791 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL); 3792 } 3793 3794 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 3795 SourceLocation IdentL, IdentifierInfo *II, 3796 SourceLocation GnuLabelL) { 3797 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 3798 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL); 3799 } 3800 3801 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3802 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, 3803 SourceLocation()); 3804 } 3805 3806 void LabelDecl::setMSAsmLabel(StringRef Name) { 3807 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; 3808 memcpy(Buffer, Name.data(), Name.size()); 3809 Buffer[Name.size()] = '\0'; 3810 MSAsmName = Buffer; 3811 } 3812 3813 void ValueDecl::anchor() { } 3814 3815 bool ValueDecl::isWeak() const { 3816 for (const auto *I : attrs()) 3817 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I)) 3818 return true; 3819 3820 return isWeakImported(); 3821 } 3822 3823 void ImplicitParamDecl::anchor() { } 3824 3825 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 3826 SourceLocation IdLoc, 3827 IdentifierInfo *Id, 3828 QualType Type) { 3829 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type); 3830 } 3831 3832 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 3833 unsigned ID) { 3834 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr, 3835 QualType()); 3836 } 3837 3838 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 3839 SourceLocation StartLoc, 3840 const DeclarationNameInfo &NameInfo, 3841 QualType T, TypeSourceInfo *TInfo, 3842 StorageClass SC, 3843 bool isInlineSpecified, 3844 bool hasWrittenPrototype, 3845 bool isConstexprSpecified) { 3846 FunctionDecl *New = 3847 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo, 3848 SC, isInlineSpecified, isConstexprSpecified); 3849 New->HasWrittenPrototype = hasWrittenPrototype; 3850 return New; 3851 } 3852 3853 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3854 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(), 3855 DeclarationNameInfo(), QualType(), nullptr, 3856 SC_None, false, false); 3857 } 3858 3859 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 3860 return new (C, DC) BlockDecl(DC, L); 3861 } 3862 3863 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3864 return new (C, ID) BlockDecl(nullptr, SourceLocation()); 3865 } 3866 3867 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC, 3868 unsigned NumParams) { 3869 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 3870 CapturedDecl(DC, NumParams); 3871 } 3872 3873 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID, 3874 unsigned NumParams) { 3875 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams)) 3876 CapturedDecl(nullptr, NumParams); 3877 } 3878 3879 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 3880 SourceLocation L, 3881 IdentifierInfo *Id, QualType T, 3882 Expr *E, const llvm::APSInt &V) { 3883 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V); 3884 } 3885 3886 EnumConstantDecl * 3887 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3888 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr, 3889 QualType(), nullptr, llvm::APSInt()); 3890 } 3891 3892 void IndirectFieldDecl::anchor() { } 3893 3894 IndirectFieldDecl * 3895 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 3896 IdentifierInfo *Id, QualType T, NamedDecl **CH, 3897 unsigned CHS) { 3898 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS); 3899 } 3900 3901 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, 3902 unsigned ID) { 3903 return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(), 3904 DeclarationName(), QualType(), nullptr, 3905 0); 3906 } 3907 3908 SourceRange EnumConstantDecl::getSourceRange() const { 3909 SourceLocation End = getLocation(); 3910 if (Init) 3911 End = Init->getLocEnd(); 3912 return SourceRange(getLocation(), End); 3913 } 3914 3915 void TypeDecl::anchor() { } 3916 3917 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 3918 SourceLocation StartLoc, SourceLocation IdLoc, 3919 IdentifierInfo *Id, TypeSourceInfo *TInfo) { 3920 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 3921 } 3922 3923 void TypedefNameDecl::anchor() { } 3924 3925 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const { 3926 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) { 3927 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl(); 3928 auto *ThisTypedef = this; 3929 if (AnyRedecl && OwningTypedef) { 3930 OwningTypedef = OwningTypedef->getCanonicalDecl(); 3931 ThisTypedef = ThisTypedef->getCanonicalDecl(); 3932 } 3933 if (OwningTypedef == ThisTypedef) 3934 return TT->getDecl(); 3935 } 3936 3937 return nullptr; 3938 } 3939 3940 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3941 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(), 3942 nullptr, nullptr); 3943 } 3944 3945 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, 3946 SourceLocation StartLoc, 3947 SourceLocation IdLoc, IdentifierInfo *Id, 3948 TypeSourceInfo *TInfo) { 3949 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo); 3950 } 3951 3952 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3953 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(), 3954 SourceLocation(), nullptr, nullptr); 3955 } 3956 3957 SourceRange TypedefDecl::getSourceRange() const { 3958 SourceLocation RangeEnd = getLocation(); 3959 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 3960 if (typeIsPostfix(TInfo->getType())) 3961 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 3962 } 3963 return SourceRange(getLocStart(), RangeEnd); 3964 } 3965 3966 SourceRange TypeAliasDecl::getSourceRange() const { 3967 SourceLocation RangeEnd = getLocStart(); 3968 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) 3969 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 3970 return SourceRange(getLocStart(), RangeEnd); 3971 } 3972 3973 void FileScopeAsmDecl::anchor() { } 3974 3975 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 3976 StringLiteral *Str, 3977 SourceLocation AsmLoc, 3978 SourceLocation RParenLoc) { 3979 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 3980 } 3981 3982 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 3983 unsigned ID) { 3984 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), 3985 SourceLocation()); 3986 } 3987 3988 void EmptyDecl::anchor() {} 3989 3990 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 3991 return new (C, DC) EmptyDecl(DC, L); 3992 } 3993 3994 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3995 return new (C, ID) EmptyDecl(nullptr, SourceLocation()); 3996 } 3997 3998 //===----------------------------------------------------------------------===// 3999 // ImportDecl Implementation 4000 //===----------------------------------------------------------------------===// 4001 4002 /// \brief Retrieve the number of module identifiers needed to name the given 4003 /// module. 4004 static unsigned getNumModuleIdentifiers(Module *Mod) { 4005 unsigned Result = 1; 4006 while (Mod->Parent) { 4007 Mod = Mod->Parent; 4008 ++Result; 4009 } 4010 return Result; 4011 } 4012 4013 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 4014 Module *Imported, 4015 ArrayRef<SourceLocation> IdentifierLocs) 4016 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true), 4017 NextLocalImport() 4018 { 4019 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); 4020 SourceLocation *StoredLocs = getTrailingObjects<SourceLocation>(); 4021 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(), 4022 StoredLocs); 4023 } 4024 4025 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 4026 Module *Imported, SourceLocation EndLoc) 4027 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false), 4028 NextLocalImport() 4029 { 4030 *getTrailingObjects<SourceLocation>() = EndLoc; 4031 } 4032 4033 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 4034 SourceLocation StartLoc, Module *Imported, 4035 ArrayRef<SourceLocation> IdentifierLocs) { 4036 return new (C, DC, 4037 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size())) 4038 ImportDecl(DC, StartLoc, Imported, IdentifierLocs); 4039 } 4040 4041 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 4042 SourceLocation StartLoc, 4043 Module *Imported, 4044 SourceLocation EndLoc) { 4045 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1)) 4046 ImportDecl(DC, StartLoc, Imported, EndLoc); 4047 Import->setImplicit(); 4048 return Import; 4049 } 4050 4051 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID, 4052 unsigned NumLocations) { 4053 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations)) 4054 ImportDecl(EmptyShell()); 4055 } 4056 4057 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { 4058 if (!ImportedAndComplete.getInt()) 4059 return None; 4060 4061 const SourceLocation *StoredLocs = getTrailingObjects<SourceLocation>(); 4062 return llvm::makeArrayRef(StoredLocs, 4063 getNumModuleIdentifiers(getImportedModule())); 4064 } 4065 4066 SourceRange ImportDecl::getSourceRange() const { 4067 if (!ImportedAndComplete.getInt()) 4068 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>()); 4069 4070 return SourceRange(getLocation(), getIdentifierLocs().back()); 4071 } 4072