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