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