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