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