1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Decl subclasses.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/AST/Stmt.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/ASTMutationListener.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/IdentifierTable.h"
27 #include "clang/Basic/Module.h"
28 #include "clang/Basic/Specifiers.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/Support/ErrorHandling.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // NamedDecl Implementation
38 //===----------------------------------------------------------------------===//
40 static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
41 // If this declaration has an explicit visibility attribute, use it.
42 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
43 switch (A->getVisibility()) {
44 case VisibilityAttr::Default:
45 return DefaultVisibility;
46 case VisibilityAttr::Hidden:
47 return HiddenVisibility;
48 case VisibilityAttr::Protected:
49 return ProtectedVisibility;
53 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
54 // implies visibility(default).
55 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
56 for (specific_attr_iterator<AvailabilityAttr>
57 A = D->specific_attr_begin<AvailabilityAttr>(),
58 AEnd = D->specific_attr_end<AvailabilityAttr>();
60 if ((*A)->getPlatform()->getName().equals("macosx"))
61 return DefaultVisibility;
64 return llvm::Optional<Visibility>();
67 typedef NamedDecl::LinkageInfo LinkageInfo;
70 /// Flags controlling the computation of linkage and visibility.
72 const bool ConsiderGlobalVisibility;
73 const bool ConsiderVisibilityAttributes;
74 const bool ConsiderTemplateParameterTypes;
76 LVFlags() : ConsiderGlobalVisibility(true),
77 ConsiderVisibilityAttributes(true),
78 ConsiderTemplateParameterTypes(true) {
81 LVFlags(bool Global, bool Attributes, bool Parameters) :
82 ConsiderGlobalVisibility(Global),
83 ConsiderVisibilityAttributes(Attributes),
84 ConsiderTemplateParameterTypes(Parameters) {
87 /// \brief Returns a set of flags that is only useful for computing the
88 /// linkage, not the visibility, of a declaration.
89 static LVFlags CreateOnlyDeclLinkage() {
90 return LVFlags(false, false, false);
93 } // end anonymous namespace
95 static LinkageInfo getLVForType(QualType T) {
96 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
97 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
100 /// \brief Get the most restrictive linkage for the types in the given
101 /// template parameter list.
103 getLVForTemplateParameterList(const TemplateParameterList *Params) {
104 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
105 for (TemplateParameterList::const_iterator P = Params->begin(),
106 PEnd = Params->end();
108 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
109 if (NTTP->isExpandedParameterPack()) {
110 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
111 QualType T = NTTP->getExpansionType(I);
112 if (!T->isDependentType())
113 LV.merge(getLVForType(T));
118 if (!NTTP->getType()->isDependentType()) {
119 LV.merge(getLVForType(NTTP->getType()));
124 if (TemplateTemplateParmDecl *TTP
125 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
126 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
133 /// getLVForDecl - Get the linkage and visibility for the given declaration.
134 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
136 /// \brief Get the most restrictive linkage for the types and
137 /// declarations in the given template argument list.
138 static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args,
141 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
143 for (unsigned I = 0; I != NumArgs; ++I) {
144 switch (Args[I].getKind()) {
145 case TemplateArgument::Null:
146 case TemplateArgument::Integral:
147 case TemplateArgument::Expression:
150 case TemplateArgument::Type:
151 LV.merge(getLVForType(Args[I].getAsType()));
154 case TemplateArgument::Declaration:
155 // The decl can validly be null as the representation of nullptr
156 // arguments, valid only in C++0x.
157 if (Decl *D = Args[I].getAsDecl()) {
158 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
159 LV = merge(LV, getLVForDecl(ND, F));
163 case TemplateArgument::Template:
164 case TemplateArgument::TemplateExpansion:
165 if (TemplateDecl *Template
166 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
167 LV.merge(getLVForDecl(Template, F));
170 case TemplateArgument::Pack:
171 LV.mergeWithMin(getLVForTemplateArgumentList(Args[I].pack_begin(),
182 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
184 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
187 static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
188 const FunctionTemplateSpecializationInfo *spec) {
189 return !(spec->isExplicitSpecialization() &&
190 fn->hasAttr<VisibilityAttr>());
193 static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
194 return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
197 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
198 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
199 "Not a name having namespace scope");
200 ASTContext &Context = D->getASTContext();
202 // C++ [basic.link]p3:
203 // A name having namespace scope (3.3.6) has internal linkage if it
205 // - an object, reference, function or function template that is
206 // explicitly declared static; or,
207 // (This bullet corresponds to C99 6.2.2p3.)
208 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
209 // Explicitly declared static.
210 if (Var->getStorageClass() == SC_Static)
211 return LinkageInfo::internal();
213 // - an object or reference that is explicitly declared const
214 // and neither explicitly declared extern nor previously
215 // declared to have external linkage; or
216 // (there is no equivalent in C99)
217 if (Context.getLangOpts().CPlusPlus &&
218 Var->getType().isConstant(Context) &&
219 Var->getStorageClass() != SC_Extern &&
220 Var->getStorageClass() != SC_PrivateExtern) {
221 bool FoundExtern = false;
222 for (const VarDecl *PrevVar = Var->getPreviousDecl();
223 PrevVar && !FoundExtern;
224 PrevVar = PrevVar->getPreviousDecl())
225 if (isExternalLinkage(PrevVar->getLinkage()))
229 return LinkageInfo::internal();
231 if (Var->getStorageClass() == SC_None) {
232 const VarDecl *PrevVar = Var->getPreviousDecl();
233 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
234 if (PrevVar->getStorageClass() == SC_PrivateExtern)
237 return PrevVar->getLinkageAndVisibility();
239 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
241 // A non-member function template can have internal linkage; any
242 // other template name shall have external linkage.
243 const FunctionDecl *Function = 0;
244 if (const FunctionTemplateDecl *FunTmpl
245 = dyn_cast<FunctionTemplateDecl>(D))
246 Function = FunTmpl->getTemplatedDecl();
248 Function = cast<FunctionDecl>(D);
250 // Explicitly declared static.
251 if (Function->getStorageClass() == SC_Static)
252 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
253 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
254 // - a data member of an anonymous union.
255 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
256 return LinkageInfo::internal();
259 if (D->isInAnonymousNamespace()) {
260 const VarDecl *Var = dyn_cast<VarDecl>(D);
261 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
262 if ((!Var || !Var->getDeclContext()->isExternCContext()) &&
263 (!Func || !Func->getDeclContext()->isExternCContext()))
264 return LinkageInfo::uniqueExternal();
267 // Set up the defaults.
270 // If the declaration of an identifier for an object has file
271 // scope and no storage-class specifier, its linkage is
274 LV.mergeVisibility(Context.getLangOpts().getVisibilityMode());
276 if (F.ConsiderVisibilityAttributes) {
277 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
278 LV.setVisibility(*Vis, true);
280 // If we're declared in a namespace with a visibility attribute,
281 // use that namespace's visibility, but don't call it explicit.
282 for (const DeclContext *DC = D->getDeclContext();
283 !isa<TranslationUnitDecl>(DC);
284 DC = DC->getParent()) {
285 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
287 if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
288 LV.setVisibility(*Vis, true);
295 // C++ [basic.link]p4:
297 // A name having namespace scope has external linkage if it is the
300 // - an object or reference, unless it has internal linkage; or
301 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
302 // GCC applies the following optimization to variables and static
303 // data members, but not to functions:
305 // Modify the variable's LV by the LV of its type unless this is
306 // C or extern "C". This follows from [basic.link]p9:
307 // A type without linkage shall not be used as the type of a
308 // variable or function with external linkage unless
309 // - the entity has C language linkage, or
310 // - the entity is declared within an unnamed namespace, or
311 // - the entity is not used or is defined in the same
313 // and [basic.link]p10:
314 // ...the types specified by all declarations referring to a
315 // given variable or function shall be identical...
316 // C does not have an equivalent rule.
318 // Ignore this if we've got an explicit attribute; the user
319 // probably knows what they're doing.
321 // Note that we don't want to make the variable non-external
322 // because of this, but unique-external linkage suits us.
323 if (Context.getLangOpts().CPlusPlus &&
324 !Var->getDeclContext()->isExternCContext()) {
325 LinkageInfo TypeLV = getLVForType(Var->getType());
326 if (TypeLV.linkage() != ExternalLinkage)
327 return LinkageInfo::uniqueExternal();
328 LV.mergeVisibilityWithMin(TypeLV);
331 if (Var->getStorageClass() == SC_PrivateExtern)
332 LV.setVisibility(HiddenVisibility, true);
334 if (!Context.getLangOpts().CPlusPlus &&
335 (Var->getStorageClass() == SC_Extern ||
336 Var->getStorageClass() == SC_PrivateExtern)) {
339 // For an identifier declared with the storage-class specifier
340 // extern in a scope in which a prior declaration of that
341 // identifier is visible, if the prior declaration specifies
342 // internal or external linkage, the linkage of the identifier
343 // at the later declaration is the same as the linkage
344 // specified at the prior declaration. If no prior declaration
345 // is visible, or if the prior declaration specifies no
346 // linkage, then the identifier has external linkage.
347 if (const VarDecl *PrevVar = Var->getPreviousDecl()) {
348 LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
349 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
350 LV.mergeVisibility(PrevLV);
354 // - a function, unless it has internal linkage; or
355 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
356 // In theory, we can modify the function's LV by the LV of its
357 // type unless it has C linkage (see comment above about variables
358 // for justification). In practice, GCC doesn't do this, so it's
359 // just too painful to make work.
361 if (Function->getStorageClass() == SC_PrivateExtern)
362 LV.setVisibility(HiddenVisibility, true);
365 // If the declaration of an identifier for a function has no
366 // storage-class specifier, its linkage is determined exactly
367 // as if it were declared with the storage-class specifier
369 if (!Context.getLangOpts().CPlusPlus &&
370 (Function->getStorageClass() == SC_Extern ||
371 Function->getStorageClass() == SC_PrivateExtern ||
372 Function->getStorageClass() == SC_None)) {
374 // For an identifier declared with the storage-class specifier
375 // extern in a scope in which a prior declaration of that
376 // identifier is visible, if the prior declaration specifies
377 // internal or external linkage, the linkage of the identifier
378 // at the later declaration is the same as the linkage
379 // specified at the prior declaration. If no prior declaration
380 // is visible, or if the prior declaration specifies no
381 // linkage, then the identifier has external linkage.
382 if (const FunctionDecl *PrevFunc = Function->getPreviousDecl()) {
383 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
384 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
385 LV.mergeVisibility(PrevLV);
389 // In C++, then if the type of the function uses a type with
390 // unique-external linkage, it's not legally usable from outside
391 // this translation unit. However, we should use the C linkage
392 // rules instead for extern "C" declarations.
393 if (Context.getLangOpts().CPlusPlus &&
394 !Function->getDeclContext()->isExternCContext() &&
395 Function->getType()->getLinkage() == UniqueExternalLinkage)
396 return LinkageInfo::uniqueExternal();
398 // Consider LV from the template and the template arguments unless
399 // this is an explicit specialization with a visibility attribute.
400 if (FunctionTemplateSpecializationInfo *specInfo
401 = Function->getTemplateSpecializationInfo()) {
402 if (shouldConsiderTemplateLV(Function, specInfo)) {
403 LV.merge(getLVForDecl(specInfo->getTemplate(),
404 LVFlags::CreateOnlyDeclLinkage()));
405 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
406 LV.mergeWithMin(getLVForTemplateArgumentList(templateArgs, F));
410 // - a named class (Clause 9), or an unnamed class defined in a
411 // typedef declaration in which the class has the typedef name
412 // for linkage purposes (7.1.3); or
413 // - a named enumeration (7.2), or an unnamed enumeration
414 // defined in a typedef declaration in which the enumeration
415 // has the typedef name for linkage purposes (7.1.3); or
416 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
417 // Unnamed tags have no linkage.
418 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
419 return LinkageInfo::none();
421 // If this is a class template specialization, consider the
422 // linkage of the template and template arguments.
423 if (const ClassTemplateSpecializationDecl *spec
424 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
425 if (shouldConsiderTemplateLV(spec)) {
426 // From the template.
427 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
428 LVFlags::CreateOnlyDeclLinkage()));
430 // The arguments at which the template was instantiated.
431 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
432 LV.mergeWithMin(getLVForTemplateArgumentList(TemplateArgs, F));
436 // - an enumerator belonging to an enumeration with external linkage;
437 } else if (isa<EnumConstantDecl>(D)) {
438 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
439 if (!isExternalLinkage(EnumLV.linkage()))
440 return LinkageInfo::none();
443 // - a template, unless it is a function template that has
444 // internal linkage (Clause 14);
445 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
446 if (F.ConsiderTemplateParameterTypes)
447 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
449 // - a namespace (7.3), unless it is declared within an unnamed
451 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
454 // By extension, we assign external linkage to Objective-C
456 } else if (isa<ObjCInterfaceDecl>(D)) {
459 // Everything not covered here has no linkage.
461 return LinkageInfo::none();
464 // If we ended up with non-external linkage, visibility should
465 // always be default.
466 if (LV.linkage() != ExternalLinkage)
467 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
472 static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
473 // Only certain class members have linkage. Note that fields don't
474 // really have linkage, but it's convenient to say they do for the
475 // purposes of calculating linkage of pointer-to-data-member
476 // template arguments.
477 if (!(isa<CXXMethodDecl>(D) ||
481 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
482 return LinkageInfo::none();
485 LV.mergeVisibility(D->getASTContext().getLangOpts().getVisibilityMode());
487 bool DHasExplicitVisibility = false;
488 // If we have an explicit visibility attribute, merge that in.
489 if (F.ConsiderVisibilityAttributes) {
490 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
491 LV.mergeVisibility(*Vis, true);
493 DHasExplicitVisibility = true;
496 // Ignore both global visibility and attributes when computing our
497 // parent's visibility if we already have an explicit one.
498 LVFlags ClassF = DHasExplicitVisibility ?
499 LVFlags::CreateOnlyDeclLinkage() : F;
501 // If we're paying attention to global visibility, apply
502 // -finline-visibility-hidden if this is an inline method.
504 // Note that we do this before merging information about
505 // the class visibility.
506 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
507 TemplateSpecializationKind TSK = TSK_Undeclared;
508 if (FunctionTemplateSpecializationInfo *spec
509 = MD->getTemplateSpecializationInfo()) {
510 TSK = spec->getTemplateSpecializationKind();
511 } else if (MemberSpecializationInfo *MSI =
512 MD->getMemberSpecializationInfo()) {
513 TSK = MSI->getTemplateSpecializationKind();
516 const FunctionDecl *Def = 0;
517 // InlineVisibilityHidden only applies to definitions, and
518 // isInlined() only gives meaningful answers on definitions
520 if (TSK != TSK_ExplicitInstantiationDeclaration &&
521 TSK != TSK_ExplicitInstantiationDefinition &&
522 F.ConsiderGlobalVisibility &&
523 !LV.visibilityExplicit() &&
524 MD->getASTContext().getLangOpts().InlineVisibilityHidden &&
525 MD->hasBody(Def) && Def->isInlined())
526 LV.mergeVisibility(HiddenVisibility, true);
529 // Class members only have linkage if their class has external
531 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
532 if (!isExternalLinkage(LV.linkage()))
533 return LinkageInfo::none();
535 // If the class already has unique-external linkage, we can't improve.
536 if (LV.linkage() == UniqueExternalLinkage)
537 return LinkageInfo::uniqueExternal();
539 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
540 // If the type of the function uses a type with unique-external
541 // linkage, it's not legally usable from outside this translation unit.
542 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
543 return LinkageInfo::uniqueExternal();
545 // If this is a method template specialization, use the linkage for
546 // the template parameters and arguments.
547 if (FunctionTemplateSpecializationInfo *spec
548 = MD->getTemplateSpecializationInfo()) {
549 if (shouldConsiderTemplateLV(MD, spec)) {
550 LV.mergeWithMin(getLVForTemplateArgumentList(*spec->TemplateArguments,
552 if (F.ConsiderTemplateParameterTypes)
553 LV.merge(getLVForTemplateParameterList(
554 spec->getTemplate()->getTemplateParameters()));
558 // Note that in contrast to basically every other situation, we
559 // *do* apply -fvisibility to method declarations.
561 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
562 if (const ClassTemplateSpecializationDecl *spec
563 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
564 if (shouldConsiderTemplateLV(spec)) {
565 // Merge template argument/parameter information for member
566 // class template specializations.
567 LV.mergeWithMin(getLVForTemplateArgumentList(spec->getTemplateArgs(),
569 if (F.ConsiderTemplateParameterTypes)
570 LV.merge(getLVForTemplateParameterList(
571 spec->getSpecializedTemplate()->getTemplateParameters()));
575 // Static data members.
576 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
577 // Modify the variable's linkage by its type, but ignore the
578 // type's visibility unless it's a definition.
579 LinkageInfo TypeLV = getLVForType(VD->getType());
580 if (TypeLV.linkage() != ExternalLinkage)
581 LV.mergeLinkage(UniqueExternalLinkage);
582 if (!LV.visibilityExplicit())
583 LV.mergeVisibility(TypeLV);
589 static void clearLinkageForClass(const CXXRecordDecl *record) {
590 for (CXXRecordDecl::decl_iterator
591 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
593 if (isa<NamedDecl>(child))
594 cast<NamedDecl>(child)->ClearLinkageCache();
598 void NamedDecl::anchor() { }
600 void NamedDecl::ClearLinkageCache() {
601 // Note that we can't skip clearing the linkage of children just
602 // because the parent doesn't have cached linkage: we don't cache
603 // when computing linkage for parent contexts.
605 HasCachedLinkage = 0;
607 // If we're changing the linkage of a class, we need to reset the
608 // linkage of child declarations, too.
609 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
610 clearLinkageForClass(record);
612 if (ClassTemplateDecl *temp =
613 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
614 // Clear linkage for the template pattern.
615 CXXRecordDecl *record = temp->getTemplatedDecl();
616 record->HasCachedLinkage = 0;
617 clearLinkageForClass(record);
619 // We need to clear linkage for specializations, too.
620 for (ClassTemplateDecl::spec_iterator
621 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
622 i->ClearLinkageCache();
625 // Clear cached linkage for function template decls, too.
626 if (FunctionTemplateDecl *temp =
627 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
628 temp->getTemplatedDecl()->ClearLinkageCache();
629 for (FunctionTemplateDecl::spec_iterator
630 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
631 i->ClearLinkageCache();
636 Linkage NamedDecl::getLinkage() const {
637 if (HasCachedLinkage) {
638 assert(Linkage(CachedLinkage) ==
639 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
640 return Linkage(CachedLinkage);
643 CachedLinkage = getLVForDecl(this,
644 LVFlags::CreateOnlyDeclLinkage()).linkage();
645 HasCachedLinkage = 1;
646 return Linkage(CachedLinkage);
649 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
650 LinkageInfo LI = getLVForDecl(this, LVFlags());
651 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
652 HasCachedLinkage = 1;
653 CachedLinkage = LI.linkage();
657 llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
658 // Use the most recent declaration of a variable.
659 if (const VarDecl *var = dyn_cast<VarDecl>(this))
660 return getVisibilityOf(var->getMostRecentDecl());
662 // Use the most recent declaration of a function, and also handle
663 // function template specializations.
664 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
665 if (llvm::Optional<Visibility> V
666 = getVisibilityOf(fn->getMostRecentDecl()))
669 // If the function is a specialization of a template with an
670 // explicit visibility attribute, use that.
671 if (FunctionTemplateSpecializationInfo *templateInfo
672 = fn->getTemplateSpecializationInfo())
673 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
675 // If the function is a member of a specialization of a class template
676 // and the corresponding decl has explicit visibility, use that.
677 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
678 if (InstantiatedFrom)
679 return getVisibilityOf(InstantiatedFrom);
681 return llvm::Optional<Visibility>();
684 // Otherwise, just check the declaration itself first.
685 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
688 // If there wasn't explicit visibility there, and this is a
689 // specialization of a class template, check for visibility
691 if (const ClassTemplateSpecializationDecl *spec
692 = dyn_cast<ClassTemplateSpecializationDecl>(this))
693 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
695 // If this is a member class of a specialization of a class template
696 // and the corresponding decl has explicit visibility, use that.
697 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
698 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
699 if (InstantiatedFrom)
700 return getVisibilityOf(InstantiatedFrom);
703 return llvm::Optional<Visibility>();
706 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
707 // Objective-C: treat all Objective-C declarations as having external
709 switch (D->getKind()) {
713 return LinkageInfo::none();
714 case Decl::TemplateTemplateParm: // count these as external
715 case Decl::NonTypeTemplateParm:
716 case Decl::ObjCAtDefsField:
717 case Decl::ObjCCategory:
718 case Decl::ObjCCategoryImpl:
719 case Decl::ObjCCompatibleAlias:
720 case Decl::ObjCImplementation:
721 case Decl::ObjCMethod:
722 case Decl::ObjCProperty:
723 case Decl::ObjCPropertyImpl:
724 case Decl::ObjCProtocol:
725 return LinkageInfo::external();
727 case Decl::CXXRecord: {
728 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
729 if (Record->isLambda()) {
730 if (!Record->getLambdaManglingNumber()) {
731 // This lambda has no mangling number, so it's internal.
732 return LinkageInfo::internal();
735 // This lambda has its linkage/visibility determined by its owner.
736 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
737 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
738 if (isa<ParmVarDecl>(ContextDecl))
739 DC = ContextDecl->getDeclContext()->getRedeclContext();
741 return getLVForDecl(cast<NamedDecl>(ContextDecl), Flags);
744 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
745 return getLVForDecl(ND, Flags);
747 return LinkageInfo::external();
754 // Handle linkage for namespace-scope names.
755 if (D->getDeclContext()->getRedeclContext()->isFileContext())
756 return getLVForNamespaceScopeDecl(D, Flags);
758 // C++ [basic.link]p5:
759 // In addition, a member function, static data member, a named
760 // class or enumeration of class scope, or an unnamed class or
761 // enumeration defined in a class-scope typedef declaration such
762 // that the class or enumeration has the typedef name for linkage
763 // purposes (7.1.3), has external linkage if the name of the class
764 // has external linkage.
765 if (D->getDeclContext()->isRecord())
766 return getLVForClassMember(D, Flags);
768 // C++ [basic.link]p6:
769 // The name of a function declared in block scope and the name of
770 // an object declared by a block scope extern declaration have
771 // linkage. If there is a visible declaration of an entity with
772 // linkage having the same name and type, ignoring entities
773 // declared outside the innermost enclosing namespace scope, the
774 // block scope declaration declares that same entity and receives
775 // the linkage of the previous declaration. If there is more than
776 // one such matching entity, the program is ill-formed. Otherwise,
777 // if no matching entity is found, the block scope entity receives
779 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
780 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
781 if (Function->isInAnonymousNamespace() &&
782 !Function->getDeclContext()->isExternCContext())
783 return LinkageInfo::uniqueExternal();
786 if (Flags.ConsiderVisibilityAttributes) {
787 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
788 LV.setVisibility(*Vis, true);
791 if (const FunctionDecl *Prev = Function->getPreviousDecl()) {
792 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
793 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
794 LV.mergeVisibility(PrevLV);
800 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
801 if (Var->getStorageClass() == SC_Extern ||
802 Var->getStorageClass() == SC_PrivateExtern) {
803 if (Var->isInAnonymousNamespace() &&
804 !Var->getDeclContext()->isExternCContext())
805 return LinkageInfo::uniqueExternal();
808 if (Var->getStorageClass() == SC_PrivateExtern)
809 LV.setVisibility(HiddenVisibility, true);
810 else if (Flags.ConsiderVisibilityAttributes) {
811 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
812 LV.setVisibility(*Vis, true);
815 if (const VarDecl *Prev = Var->getPreviousDecl()) {
816 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
817 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
818 LV.mergeVisibility(PrevLV);
825 // C++ [basic.link]p6:
826 // Names not covered by these rules have no linkage.
827 return LinkageInfo::none();
830 std::string NamedDecl::getQualifiedNameAsString() const {
831 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
834 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
835 const DeclContext *Ctx = getDeclContext();
837 if (Ctx->isFunctionOrMethod())
838 return getNameAsString();
840 typedef SmallVector<const DeclContext *, 8> ContextsTy;
844 while (Ctx && isa<NamedDecl>(Ctx)) {
845 Contexts.push_back(Ctx);
846 Ctx = Ctx->getParent();
849 std::string QualName;
850 llvm::raw_string_ostream OS(QualName);
852 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
854 if (const ClassTemplateSpecializationDecl *Spec
855 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
856 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
857 std::string TemplateArgsStr
858 = TemplateSpecializationType::PrintTemplateArgumentList(
862 OS << Spec->getName() << TemplateArgsStr;
863 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
864 if (ND->isAnonymousNamespace())
865 OS << "<anonymous namespace>";
868 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
869 if (!RD->getIdentifier())
870 OS << "<anonymous " << RD->getKindName() << '>';
873 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
874 const FunctionProtoType *FT = 0;
875 if (FD->hasWrittenPrototype())
876 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
880 unsigned NumParams = FD->getNumParams();
881 for (unsigned i = 0; i < NumParams; ++i) {
885 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
889 if (FT->isVariadic()) {
897 OS << *cast<NamedDecl>(*I);
910 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
911 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
913 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
914 // We want to keep it, unless it nominates same namespace.
915 if (getKind() == Decl::UsingDirective) {
916 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
917 ->getOriginalNamespace() ==
918 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
919 ->getOriginalNamespace();
922 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
923 // For function declarations, we keep track of redeclarations.
924 return FD->getPreviousDecl() == OldD;
926 // For function templates, the underlying function declarations are linked.
927 if (const FunctionTemplateDecl *FunctionTemplate
928 = dyn_cast<FunctionTemplateDecl>(this))
929 if (const FunctionTemplateDecl *OldFunctionTemplate
930 = dyn_cast<FunctionTemplateDecl>(OldD))
931 return FunctionTemplate->getTemplatedDecl()
932 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
934 // For method declarations, we keep track of redeclarations.
935 if (isa<ObjCMethodDecl>(this))
938 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
941 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
942 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
943 cast<UsingShadowDecl>(OldD)->getTargetDecl();
945 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
946 ASTContext &Context = getASTContext();
947 return Context.getCanonicalNestedNameSpecifier(
948 cast<UsingDecl>(this)->getQualifier()) ==
949 Context.getCanonicalNestedNameSpecifier(
950 cast<UsingDecl>(OldD)->getQualifier());
953 // A typedef of an Objective-C class type can replace an Objective-C class
954 // declaration or definition, and vice versa.
955 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
956 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
959 // For non-function declarations, if the declarations are of the
960 // same kind then this must be a redeclaration, or semantic analysis
961 // would not have given us the new declaration.
962 return this->getKind() == OldD->getKind();
965 bool NamedDecl::hasLinkage() const {
966 return getLinkage() != NoLinkage;
969 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
970 NamedDecl *ND = this;
971 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
972 ND = UD->getTargetDecl();
974 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
975 return AD->getClassInterface();
980 bool NamedDecl::isCXXInstanceMember() const {
981 if (!isCXXClassMember())
984 const NamedDecl *D = this;
985 if (isa<UsingShadowDecl>(D))
986 D = cast<UsingShadowDecl>(D)->getTargetDecl();
988 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
990 if (isa<CXXMethodDecl>(D))
991 return cast<CXXMethodDecl>(D)->isInstance();
992 if (isa<FunctionTemplateDecl>(D))
993 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
994 ->getTemplatedDecl())->isInstance();
998 //===----------------------------------------------------------------------===//
999 // DeclaratorDecl Implementation
1000 //===----------------------------------------------------------------------===//
1002 template <typename DeclT>
1003 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1004 if (decl->getNumTemplateParameterLists() > 0)
1005 return decl->getTemplateParameterList(0)->getTemplateLoc();
1007 return decl->getInnerLocStart();
1010 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1011 TypeSourceInfo *TSI = getTypeSourceInfo();
1012 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1013 return SourceLocation();
1016 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1018 // Make sure the extended decl info is allocated.
1019 if (!hasExtInfo()) {
1020 // Save (non-extended) type source info pointer.
1021 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1022 // Allocate external info struct.
1023 DeclInfo = new (getASTContext()) ExtInfo;
1024 // Restore savedTInfo into (extended) decl info.
1025 getExtInfo()->TInfo = savedTInfo;
1027 // Set qualifier info.
1028 getExtInfo()->QualifierLoc = QualifierLoc;
1030 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1032 if (getExtInfo()->NumTemplParamLists == 0) {
1033 // Save type source info pointer.
1034 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1035 // Deallocate the extended decl info.
1036 getASTContext().Deallocate(getExtInfo());
1037 // Restore savedTInfo into (non-extended) decl info.
1038 DeclInfo = savedTInfo;
1041 getExtInfo()->QualifierLoc = QualifierLoc;
1047 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1048 unsigned NumTPLists,
1049 TemplateParameterList **TPLists) {
1050 assert(NumTPLists > 0);
1051 // Make sure the extended decl info is allocated.
1052 if (!hasExtInfo()) {
1053 // Save (non-extended) type source info pointer.
1054 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1055 // Allocate external info struct.
1056 DeclInfo = new (getASTContext()) ExtInfo;
1057 // Restore savedTInfo into (extended) decl info.
1058 getExtInfo()->TInfo = savedTInfo;
1060 // Set the template parameter lists info.
1061 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1064 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1065 return getTemplateOrInnerLocStart(this);
1070 // Helper function: returns true if QT is or contains a type
1071 // having a postfix component.
1072 bool typeIsPostfix(clang::QualType QT) {
1074 const Type* T = QT.getTypePtr();
1075 switch (T->getTypeClass()) {
1079 QT = cast<PointerType>(T)->getPointeeType();
1081 case Type::BlockPointer:
1082 QT = cast<BlockPointerType>(T)->getPointeeType();
1084 case Type::MemberPointer:
1085 QT = cast<MemberPointerType>(T)->getPointeeType();
1087 case Type::LValueReference:
1088 case Type::RValueReference:
1089 QT = cast<ReferenceType>(T)->getPointeeType();
1091 case Type::PackExpansion:
1092 QT = cast<PackExpansionType>(T)->getPattern();
1095 case Type::ConstantArray:
1096 case Type::DependentSizedArray:
1097 case Type::IncompleteArray:
1098 case Type::VariableArray:
1099 case Type::FunctionProto:
1100 case Type::FunctionNoProto:
1108 SourceRange DeclaratorDecl::getSourceRange() const {
1109 SourceLocation RangeEnd = getLocation();
1110 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1111 if (typeIsPostfix(TInfo->getType()))
1112 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1114 return SourceRange(getOuterLocStart(), RangeEnd);
1118 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1119 unsigned NumTPLists,
1120 TemplateParameterList **TPLists) {
1121 assert((NumTPLists == 0 || TPLists != 0) &&
1122 "Empty array of template parameters with positive size!");
1124 // Free previous template parameters (if any).
1125 if (NumTemplParamLists > 0) {
1126 Context.Deallocate(TemplParamLists);
1127 TemplParamLists = 0;
1128 NumTemplParamLists = 0;
1130 // Set info on matched template parameter lists (if any).
1131 if (NumTPLists > 0) {
1132 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1133 NumTemplParamLists = NumTPLists;
1134 for (unsigned i = NumTPLists; i-- > 0; )
1135 TemplParamLists[i] = TPLists[i];
1139 //===----------------------------------------------------------------------===//
1140 // VarDecl Implementation
1141 //===----------------------------------------------------------------------===//
1143 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1145 case SC_None: break;
1146 case SC_Auto: return "auto";
1147 case SC_Extern: return "extern";
1148 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1149 case SC_PrivateExtern: return "__private_extern__";
1150 case SC_Register: return "register";
1151 case SC_Static: return "static";
1154 llvm_unreachable("Invalid storage class");
1157 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1158 SourceLocation StartL, SourceLocation IdL,
1159 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1160 StorageClass S, StorageClass SCAsWritten) {
1161 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
1164 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1165 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1166 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1167 QualType(), 0, SC_None, SC_None);
1170 void VarDecl::setStorageClass(StorageClass SC) {
1171 assert(isLegalForVariable(SC));
1172 if (getStorageClass() != SC)
1173 ClearLinkageCache();
1175 VarDeclBits.SClass = SC;
1178 SourceRange VarDecl::getSourceRange() const {
1180 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
1181 return DeclaratorDecl::getSourceRange();
1184 bool VarDecl::isExternC() const {
1185 if (getLinkage() != ExternalLinkage)
1188 const DeclContext *DC = getDeclContext();
1192 ASTContext &Context = getASTContext();
1193 if (!Context.getLangOpts().CPlusPlus)
1195 return DC->isExternCContext();
1198 VarDecl *VarDecl::getCanonicalDecl() {
1199 return getFirstDeclaration();
1202 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1203 ASTContext &C) const
1205 // C++ [basic.def]p2:
1206 // A declaration is a definition unless [...] it contains the 'extern'
1207 // specifier or a linkage-specification and neither an initializer [...],
1208 // it declares a static data member in a class declaration [...].
1209 // C++ [temp.expl.spec]p15:
1210 // An explicit specialization of a static data member of a template is a
1211 // definition if the declaration includes an initializer; otherwise, it is
1213 if (isStaticDataMember()) {
1214 if (isOutOfLine() && (hasInit() ||
1215 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1218 return DeclarationOnly;
1221 // A definition of an identifier is a declaration for that identifier that
1222 // [...] causes storage to be reserved for that object.
1223 // Note: that applies for all non-file-scope objects.
1225 // If the declaration of an identifier for an object has file scope and an
1226 // initializer, the declaration is an external definition for the identifier
1229 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1230 if (hasExternalStorage())
1231 return DeclarationOnly;
1233 if (getStorageClassAsWritten() == SC_Extern ||
1234 getStorageClassAsWritten() == SC_PrivateExtern) {
1235 for (const VarDecl *PrevVar = getPreviousDecl();
1236 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
1237 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1238 return DeclarationOnly;
1242 // A declaration of an object that has file scope without an initializer,
1243 // and without a storage class specifier or the scs 'static', constitutes
1244 // a tentative definition.
1245 // No such thing in C++.
1246 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1247 return TentativeDefinition;
1249 // What's left is (in C, block-scope) declarations without initializers or
1250 // external storage. These are definitions.
1254 VarDecl *VarDecl::getActingDefinition() {
1255 DefinitionKind Kind = isThisDeclarationADefinition();
1256 if (Kind != TentativeDefinition)
1259 VarDecl *LastTentative = 0;
1260 VarDecl *First = getFirstDeclaration();
1261 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1263 Kind = (*I)->isThisDeclarationADefinition();
1264 if (Kind == Definition)
1266 else if (Kind == TentativeDefinition)
1269 return LastTentative;
1272 bool VarDecl::isTentativeDefinitionNow() const {
1273 DefinitionKind Kind = isThisDeclarationADefinition();
1274 if (Kind != TentativeDefinition)
1277 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1278 if ((*I)->isThisDeclarationADefinition() == Definition)
1284 VarDecl *VarDecl::getDefinition(ASTContext &C) {
1285 VarDecl *First = getFirstDeclaration();
1286 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1288 if ((*I)->isThisDeclarationADefinition(C) == Definition)
1294 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1295 DefinitionKind Kind = DeclarationOnly;
1297 const VarDecl *First = getFirstDeclaration();
1298 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1300 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
1301 if (Kind == Definition)
1308 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1309 redecl_iterator I = redecls_begin(), E = redecls_end();
1310 while (I != E && !I->getInit())
1315 return I->getInit();
1320 bool VarDecl::isOutOfLine() const {
1321 if (Decl::isOutOfLine())
1324 if (!isStaticDataMember())
1327 // If this static data member was instantiated from a static data member of
1328 // a class template, check whether that static data member was defined
1330 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1331 return VD->isOutOfLine();
1336 VarDecl *VarDecl::getOutOfLineDefinition() {
1337 if (!isStaticDataMember())
1340 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1341 RD != RDEnd; ++RD) {
1342 if (RD->getLexicalDeclContext()->isFileContext())
1349 void VarDecl::setInit(Expr *I) {
1350 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1351 Eval->~EvaluatedStmt();
1352 getASTContext().Deallocate(Eval);
1358 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1359 const LangOptions &Lang = C.getLangOpts();
1361 if (!Lang.CPlusPlus)
1364 // In C++11, any variable of reference type can be used in a constant
1365 // expression if it is initialized by a constant expression.
1366 if (Lang.CPlusPlus0x && getType()->isReferenceType())
1369 // Only const objects can be used in constant expressions in C++. C++98 does
1370 // not require the variable to be non-volatile, but we consider this to be a
1372 if (!getType().isConstQualified() || getType().isVolatileQualified())
1375 // In C++, const, non-volatile variables of integral or enumeration types
1376 // can be used in constant expressions.
1377 if (getType()->isIntegralOrEnumerationType())
1380 // Additionally, in C++11, non-volatile constexpr variables can be used in
1381 // constant expressions.
1382 return Lang.CPlusPlus0x && isConstexpr();
1385 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1386 /// form, which contains extra information on the evaluated value of the
1388 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1389 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1391 Stmt *S = Init.get<Stmt *>();
1392 Eval = new (getASTContext()) EvaluatedStmt;
1399 APValue *VarDecl::evaluateValue() const {
1400 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1401 return evaluateValue(Notes);
1404 APValue *VarDecl::evaluateValue(
1405 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1406 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1408 // We only produce notes indicating why an initializer is non-constant the
1409 // first time it is evaluated. FIXME: The notes won't always be emitted the
1410 // first time we try evaluation, so might not be produced at all.
1411 if (Eval->WasEvaluated)
1412 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
1414 const Expr *Init = cast<Expr>(Eval->Value);
1415 assert(!Init->isValueDependent());
1417 if (Eval->IsEvaluating) {
1418 // FIXME: Produce a diagnostic for self-initialization.
1419 Eval->CheckedICE = true;
1420 Eval->IsICE = false;
1424 Eval->IsEvaluating = true;
1426 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1429 // Ensure the result is an uninitialized APValue if evaluation fails.
1431 Eval->Evaluated = APValue();
1433 Eval->IsEvaluating = false;
1434 Eval->WasEvaluated = true;
1436 // In C++11, we have determined whether the initializer was a constant
1437 // expression as a side-effect.
1438 if (getASTContext().getLangOpts().CPlusPlus0x && !Eval->CheckedICE) {
1439 Eval->CheckedICE = true;
1440 Eval->IsICE = Result && Notes.empty();
1443 return Result ? &Eval->Evaluated : 0;
1446 bool VarDecl::checkInitIsICE() const {
1447 // Initializers of weak variables are never ICEs.
1451 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1452 if (Eval->CheckedICE)
1453 // We have already checked whether this subexpression is an
1454 // integral constant expression.
1457 const Expr *Init = cast<Expr>(Eval->Value);
1458 assert(!Init->isValueDependent());
1460 // In C++11, evaluate the initializer to check whether it's a constant
1462 if (getASTContext().getLangOpts().CPlusPlus0x) {
1463 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1464 evaluateValue(Notes);
1468 // It's an ICE whether or not the definition we found is
1469 // out-of-line. See DR 721 and the discussion in Clang PR
1470 // 6206 for details.
1472 if (Eval->CheckingICE)
1474 Eval->CheckingICE = true;
1476 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1477 Eval->CheckingICE = false;
1478 Eval->CheckedICE = true;
1482 bool VarDecl::extendsLifetimeOfTemporary() const {
1483 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
1485 const Expr *E = getInit();
1489 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1490 E = Cleanups->getSubExpr();
1492 return isa<MaterializeTemporaryExpr>(E);
1495 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
1496 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1497 return cast<VarDecl>(MSI->getInstantiatedFrom());
1502 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
1503 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1504 return MSI->getTemplateSpecializationKind();
1506 return TSK_Undeclared;
1509 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
1510 return getASTContext().getInstantiatedFromStaticDataMember(this);
1513 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1514 SourceLocation PointOfInstantiation) {
1515 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
1516 assert(MSI && "Not an instantiated static data member?");
1517 MSI->setTemplateSpecializationKind(TSK);
1518 if (TSK != TSK_ExplicitSpecialization &&
1519 PointOfInstantiation.isValid() &&
1520 MSI->getPointOfInstantiation().isInvalid())
1521 MSI->setPointOfInstantiation(PointOfInstantiation);
1524 //===----------------------------------------------------------------------===//
1525 // ParmVarDecl Implementation
1526 //===----------------------------------------------------------------------===//
1528 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
1529 SourceLocation StartLoc,
1530 SourceLocation IdLoc, IdentifierInfo *Id,
1531 QualType T, TypeSourceInfo *TInfo,
1532 StorageClass S, StorageClass SCAsWritten,
1534 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
1535 S, SCAsWritten, DefArg);
1538 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1539 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1540 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1541 0, QualType(), 0, SC_None, SC_None, 0);
1544 SourceRange ParmVarDecl::getSourceRange() const {
1545 if (!hasInheritedDefaultArg()) {
1546 SourceRange ArgRange = getDefaultArgRange();
1547 if (ArgRange.isValid())
1548 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1551 return DeclaratorDecl::getSourceRange();
1554 Expr *ParmVarDecl::getDefaultArg() {
1555 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1556 assert(!hasUninstantiatedDefaultArg() &&
1557 "Default argument is not yet instantiated!");
1559 Expr *Arg = getInit();
1560 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
1561 return E->getSubExpr();
1566 SourceRange ParmVarDecl::getDefaultArgRange() const {
1567 if (const Expr *E = getInit())
1568 return E->getSourceRange();
1570 if (hasUninstantiatedDefaultArg())
1571 return getUninstantiatedDefaultArg()->getSourceRange();
1573 return SourceRange();
1576 bool ParmVarDecl::isParameterPack() const {
1577 return isa<PackExpansionType>(getType());
1580 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1581 getASTContext().setParameterIndex(this, parameterIndex);
1582 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1585 unsigned ParmVarDecl::getParameterIndexLarge() const {
1586 return getASTContext().getParameterIndex(this);
1589 //===----------------------------------------------------------------------===//
1590 // FunctionDecl Implementation
1591 //===----------------------------------------------------------------------===//
1593 void FunctionDecl::getNameForDiagnostic(std::string &S,
1594 const PrintingPolicy &Policy,
1595 bool Qualified) const {
1596 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1597 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1599 S += TemplateSpecializationType::PrintTemplateArgumentList(
1600 TemplateArgs->data(),
1601 TemplateArgs->size(),
1606 bool FunctionDecl::isVariadic() const {
1607 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1608 return FT->isVariadic();
1612 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1613 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1614 if (I->Body || I->IsLateTemplateParsed) {
1623 bool FunctionDecl::hasTrivialBody() const
1625 Stmt *S = getBody();
1627 // Since we don't have a body for this function, we don't know if it's
1632 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1637 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1638 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1639 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
1640 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1648 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
1649 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1652 return I->Body.get(getASTContext().getExternalSource());
1653 } else if (I->IsLateTemplateParsed) {
1662 void FunctionDecl::setBody(Stmt *B) {
1665 EndRangeLoc = B->getLocEnd();
1668 void FunctionDecl::setPure(bool P) {
1671 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1672 Parent->markedVirtualFunctionPure();
1675 bool FunctionDecl::isMain() const {
1676 const TranslationUnitDecl *tunit =
1677 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1679 !tunit->getASTContext().getLangOpts().Freestanding &&
1681 getIdentifier()->isStr("main");
1684 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1685 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1686 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1687 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1688 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1689 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1691 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1692 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1694 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1695 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1697 ASTContext &Context =
1698 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1701 // The result type and first argument type are constant across all
1702 // these operators. The second argument must be exactly void*.
1703 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
1706 bool FunctionDecl::isExternC() const {
1707 if (getLinkage() != ExternalLinkage)
1710 if (getAttr<OverloadableAttr>())
1713 const DeclContext *DC = getDeclContext();
1717 ASTContext &Context = getASTContext();
1718 if (!Context.getLangOpts().CPlusPlus)
1721 return isMain() || DC->isExternCContext();
1724 bool FunctionDecl::isGlobal() const {
1725 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1726 return Method->isStatic();
1728 if (getStorageClass() == SC_Static)
1731 for (const DeclContext *DC = getDeclContext();
1733 DC = DC->getParent()) {
1734 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1735 if (!Namespace->getDeclName())
1745 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1746 redeclarable_base::setPreviousDeclaration(PrevDecl);
1748 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1749 FunctionTemplateDecl *PrevFunTmpl
1750 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1751 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1752 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1755 if (PrevDecl && PrevDecl->IsInline)
1759 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1760 return getFirstDeclaration();
1763 FunctionDecl *FunctionDecl::getCanonicalDecl() {
1764 return getFirstDeclaration();
1767 void FunctionDecl::setStorageClass(StorageClass SC) {
1768 assert(isLegalForFunction(SC));
1769 if (getStorageClass() != SC)
1770 ClearLinkageCache();
1775 /// \brief Returns a value indicating whether this function
1776 /// corresponds to a builtin function.
1778 /// The function corresponds to a built-in function if it is
1779 /// declared at translation scope or within an extern "C" block and
1780 /// its name matches with the name of a builtin. The returned value
1781 /// will be 0 for functions that do not correspond to a builtin, a
1782 /// value of type \c Builtin::ID if in the target-independent range
1783 /// \c [1,Builtin::First), or a target-specific builtin value.
1784 unsigned FunctionDecl::getBuiltinID() const {
1785 if (!getIdentifier())
1788 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1792 ASTContext &Context = getASTContext();
1793 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1796 // This function has the name of a known C library
1797 // function. Determine whether it actually refers to the C library
1798 // function or whether it just has the same name.
1800 // If this is a static function, it's not a builtin.
1801 if (getStorageClass() == SC_Static)
1804 // If this function is at translation-unit scope and we're not in
1805 // C++, it refers to the C library function.
1806 if (!Context.getLangOpts().CPlusPlus &&
1807 getDeclContext()->isTranslationUnit())
1810 // If the function is in an extern "C" linkage specification and is
1811 // not marked "overloadable", it's the real function.
1812 if (isa<LinkageSpecDecl>(getDeclContext()) &&
1813 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
1814 == LinkageSpecDecl::lang_c &&
1815 !getAttr<OverloadableAttr>())
1823 /// getNumParams - Return the number of parameters this function must have
1824 /// based on its FunctionType. This is the length of the ParamInfo array
1825 /// after it has been created.
1826 unsigned FunctionDecl::getNumParams() const {
1827 const FunctionType *FT = getType()->getAs<FunctionType>();
1828 if (isa<FunctionNoProtoType>(FT))
1830 return cast<FunctionProtoType>(FT)->getNumArgs();
1834 void FunctionDecl::setParams(ASTContext &C,
1835 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
1836 assert(ParamInfo == 0 && "Already has param info!");
1837 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
1839 // Zero params -> null pointer.
1840 if (!NewParamInfo.empty()) {
1841 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1842 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
1846 void FunctionDecl::setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls) {
1847 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
1849 if (!NewDecls.empty()) {
1850 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
1851 std::copy(NewDecls.begin(), NewDecls.end(), A);
1852 DeclsInPrototypeScope = llvm::ArrayRef<NamedDecl*>(A, NewDecls.size());
1856 /// getMinRequiredArguments - Returns the minimum number of arguments
1857 /// needed to call this function. This may be fewer than the number of
1858 /// function parameters, if some of the parameters have default
1859 /// arguments (in C++) or the last parameter is a parameter pack.
1860 unsigned FunctionDecl::getMinRequiredArguments() const {
1861 if (!getASTContext().getLangOpts().CPlusPlus)
1862 return getNumParams();
1864 unsigned NumRequiredArgs = getNumParams();
1866 // If the last parameter is a parameter pack, we don't need an argument for
1868 if (NumRequiredArgs > 0 &&
1869 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1872 // If this parameter has a default argument, we don't need an argument for
1874 while (NumRequiredArgs > 0 &&
1875 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
1878 // We might have parameter packs before the end. These can't be deduced,
1879 // but they can still handle multiple arguments.
1880 unsigned ArgIdx = NumRequiredArgs;
1881 while (ArgIdx > 0) {
1882 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1883 NumRequiredArgs = ArgIdx;
1888 return NumRequiredArgs;
1891 bool FunctionDecl::isInlined() const {
1895 if (isa<CXXMethodDecl>(this)) {
1896 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1900 switch (getTemplateSpecializationKind()) {
1901 case TSK_Undeclared:
1902 case TSK_ExplicitSpecialization:
1905 case TSK_ImplicitInstantiation:
1906 case TSK_ExplicitInstantiationDeclaration:
1907 case TSK_ExplicitInstantiationDefinition:
1912 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1913 bool HasPattern = false;
1915 HasPattern = PatternDecl->hasBody(PatternDecl);
1917 if (HasPattern && PatternDecl)
1918 return PatternDecl->isInlined();
1923 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
1924 // Only consider file-scope declarations in this test.
1925 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1928 // Only consider explicit declarations; the presence of a builtin for a
1929 // libcall shouldn't affect whether a definition is externally visible.
1930 if (Redecl->isImplicit())
1933 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
1934 return true; // Not an inline definition
1939 /// \brief For a function declaration in C or C++, determine whether this
1940 /// declaration causes the definition to be externally visible.
1942 /// Specifically, this determines if adding the current declaration to the set
1943 /// of redeclarations of the given functions causes
1944 /// isInlineDefinitionExternallyVisible to change from false to true.
1945 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1946 assert(!doesThisDeclarationHaveABody() &&
1947 "Must have a declaration without a body.");
1949 ASTContext &Context = getASTContext();
1951 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
1952 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
1953 // an externally visible definition.
1955 // FIXME: What happens if gnu_inline gets added on after the first
1957 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
1960 const FunctionDecl *Prev = this;
1961 bool FoundBody = false;
1962 while ((Prev = Prev->getPreviousDecl())) {
1963 FoundBody |= Prev->Body;
1966 // If it's not the case that both 'inline' and 'extern' are
1967 // specified on the definition, then it is always externally visible.
1968 if (!Prev->isInlineSpecified() ||
1969 Prev->getStorageClassAsWritten() != SC_Extern)
1971 } else if (Prev->isInlineSpecified() &&
1972 Prev->getStorageClassAsWritten() != SC_Extern) {
1979 if (Context.getLangOpts().CPlusPlus)
1983 // [...] If all of the file scope declarations for a function in a
1984 // translation unit include the inline function specifier without extern,
1985 // then the definition in that translation unit is an inline definition.
1986 if (isInlineSpecified() && getStorageClass() != SC_Extern)
1988 const FunctionDecl *Prev = this;
1989 bool FoundBody = false;
1990 while ((Prev = Prev->getPreviousDecl())) {
1991 FoundBody |= Prev->Body;
1992 if (RedeclForcesDefC99(Prev))
1998 /// \brief For an inline function definition in C or C++, determine whether the
1999 /// definition will be externally visible.
2001 /// Inline function definitions are always available for inlining optimizations.
2002 /// However, depending on the language dialect, declaration specifiers, and
2003 /// attributes, the definition of an inline function may or may not be
2004 /// "externally" visible to other translation units in the program.
2006 /// In C99, inline definitions are not externally visible by default. However,
2007 /// if even one of the global-scope declarations is marked "extern inline", the
2008 /// inline definition becomes externally visible (C99 6.7.4p6).
2010 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2011 /// definition, we use the GNU semantics for inline, which are nearly the
2012 /// opposite of C99 semantics. In particular, "inline" by itself will create
2013 /// an externally visible symbol, but "extern inline" will not create an
2014 /// externally visible symbol.
2015 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2016 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2017 assert(isInlined() && "Function must be inline");
2018 ASTContext &Context = getASTContext();
2020 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2021 // Note: If you change the logic here, please change
2022 // doesDeclarationForceExternallyVisibleDefinition as well.
2024 // If it's not the case that both 'inline' and 'extern' are
2025 // specified on the definition, then this inline definition is
2026 // externally visible.
2027 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2030 // If any declaration is 'inline' but not 'extern', then this definition
2031 // is externally visible.
2032 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2033 Redecl != RedeclEnd;
2035 if (Redecl->isInlineSpecified() &&
2036 Redecl->getStorageClassAsWritten() != SC_Extern)
2044 // [...] If all of the file scope declarations for a function in a
2045 // translation unit include the inline function specifier without extern,
2046 // then the definition in that translation unit is an inline definition.
2047 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2048 Redecl != RedeclEnd;
2050 if (RedeclForcesDefC99(*Redecl))
2055 // An inline definition does not provide an external definition for the
2056 // function, and does not forbid an external definition in another
2057 // translation unit.
2061 /// getOverloadedOperator - Which C++ overloaded operator this
2062 /// function represents, if any.
2063 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2064 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2065 return getDeclName().getCXXOverloadedOperator();
2070 /// getLiteralIdentifier - The literal suffix identifier this function
2071 /// represents, if any.
2072 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2073 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2074 return getDeclName().getCXXLiteralIdentifier();
2079 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2080 if (TemplateOrSpecialization.isNull())
2081 return TK_NonTemplate;
2082 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2083 return TK_FunctionTemplate;
2084 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2085 return TK_MemberSpecialization;
2086 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2087 return TK_FunctionTemplateSpecialization;
2088 if (TemplateOrSpecialization.is
2089 <DependentFunctionTemplateSpecializationInfo*>())
2090 return TK_DependentFunctionTemplateSpecialization;
2092 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2095 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2096 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2097 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2102 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2103 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2107 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2109 TemplateSpecializationKind TSK) {
2110 assert(TemplateOrSpecialization.isNull() &&
2111 "Member function is already a specialization");
2112 MemberSpecializationInfo *Info
2113 = new (C) MemberSpecializationInfo(FD, TSK);
2114 TemplateOrSpecialization = Info;
2117 bool FunctionDecl::isImplicitlyInstantiable() const {
2118 // If the function is invalid, it can't be implicitly instantiated.
2119 if (isInvalidDecl())
2122 switch (getTemplateSpecializationKind()) {
2123 case TSK_Undeclared:
2124 case TSK_ExplicitInstantiationDefinition:
2127 case TSK_ImplicitInstantiation:
2130 // It is possible to instantiate TSK_ExplicitSpecialization kind
2131 // if the FunctionDecl has a class scope specialization pattern.
2132 case TSK_ExplicitSpecialization:
2133 return getClassScopeSpecializationPattern() != 0;
2135 case TSK_ExplicitInstantiationDeclaration:
2140 // Find the actual template from which we will instantiate.
2141 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2142 bool HasPattern = false;
2144 HasPattern = PatternDecl->hasBody(PatternDecl);
2146 // C++0x [temp.explicit]p9:
2147 // Except for inline functions, other explicit instantiation declarations
2148 // have the effect of suppressing the implicit instantiation of the entity
2149 // to which they refer.
2150 if (!HasPattern || !PatternDecl)
2153 return PatternDecl->isInlined();
2156 bool FunctionDecl::isTemplateInstantiation() const {
2157 switch (getTemplateSpecializationKind()) {
2158 case TSK_Undeclared:
2159 case TSK_ExplicitSpecialization:
2161 case TSK_ImplicitInstantiation:
2162 case TSK_ExplicitInstantiationDeclaration:
2163 case TSK_ExplicitInstantiationDefinition:
2166 llvm_unreachable("All TSK values handled.");
2169 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2170 // Handle class scope explicit specialization special case.
2171 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2172 return getClassScopeSpecializationPattern();
2174 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2175 while (Primary->getInstantiatedFromMemberTemplate()) {
2176 // If we have hit a point where the user provided a specialization of
2177 // this template, we're done looking.
2178 if (Primary->isMemberSpecialization())
2181 Primary = Primary->getInstantiatedFromMemberTemplate();
2184 return Primary->getTemplatedDecl();
2187 return getInstantiatedFromMemberFunction();
2190 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
2191 if (FunctionTemplateSpecializationInfo *Info
2192 = TemplateOrSpecialization
2193 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2194 return Info->Template.getPointer();
2199 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2200 return getASTContext().getClassScopeSpecializationPattern(this);
2203 const TemplateArgumentList *
2204 FunctionDecl::getTemplateSpecializationArgs() const {
2205 if (FunctionTemplateSpecializationInfo *Info
2206 = TemplateOrSpecialization
2207 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2208 return Info->TemplateArguments;
2213 const ASTTemplateArgumentListInfo *
2214 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2215 if (FunctionTemplateSpecializationInfo *Info
2216 = TemplateOrSpecialization
2217 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2218 return Info->TemplateArgumentsAsWritten;
2224 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2225 FunctionTemplateDecl *Template,
2226 const TemplateArgumentList *TemplateArgs,
2228 TemplateSpecializationKind TSK,
2229 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2230 SourceLocation PointOfInstantiation) {
2231 assert(TSK != TSK_Undeclared &&
2232 "Must specify the type of function template specialization");
2233 FunctionTemplateSpecializationInfo *Info
2234 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2236 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2238 TemplateArgsAsWritten,
2239 PointOfInstantiation);
2240 TemplateOrSpecialization = Info;
2241 Template->addSpecialization(Info, InsertPos);
2245 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2246 const UnresolvedSetImpl &Templates,
2247 const TemplateArgumentListInfo &TemplateArgs) {
2248 assert(TemplateOrSpecialization.isNull());
2249 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2250 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2251 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2252 void *Buffer = Context.Allocate(Size);
2253 DependentFunctionTemplateSpecializationInfo *Info =
2254 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2256 TemplateOrSpecialization = Info;
2259 DependentFunctionTemplateSpecializationInfo::
2260 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2261 const TemplateArgumentListInfo &TArgs)
2262 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2264 d.NumTemplates = Ts.size();
2265 d.NumArgs = TArgs.size();
2267 FunctionTemplateDecl **TsArray =
2268 const_cast<FunctionTemplateDecl**>(getTemplates());
2269 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2270 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2272 TemplateArgumentLoc *ArgsArray =
2273 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2274 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2275 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2278 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2279 // For a function template specialization, query the specialization
2280 // information object.
2281 FunctionTemplateSpecializationInfo *FTSInfo
2282 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2284 return FTSInfo->getTemplateSpecializationKind();
2286 MemberSpecializationInfo *MSInfo
2287 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2289 return MSInfo->getTemplateSpecializationKind();
2291 return TSK_Undeclared;
2295 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2296 SourceLocation PointOfInstantiation) {
2297 if (FunctionTemplateSpecializationInfo *FTSInfo
2298 = TemplateOrSpecialization.dyn_cast<
2299 FunctionTemplateSpecializationInfo*>()) {
2300 FTSInfo->setTemplateSpecializationKind(TSK);
2301 if (TSK != TSK_ExplicitSpecialization &&
2302 PointOfInstantiation.isValid() &&
2303 FTSInfo->getPointOfInstantiation().isInvalid())
2304 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2305 } else if (MemberSpecializationInfo *MSInfo
2306 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2307 MSInfo->setTemplateSpecializationKind(TSK);
2308 if (TSK != TSK_ExplicitSpecialization &&
2309 PointOfInstantiation.isValid() &&
2310 MSInfo->getPointOfInstantiation().isInvalid())
2311 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2313 llvm_unreachable("Function cannot have a template specialization kind");
2316 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2317 if (FunctionTemplateSpecializationInfo *FTSInfo
2318 = TemplateOrSpecialization.dyn_cast<
2319 FunctionTemplateSpecializationInfo*>())
2320 return FTSInfo->getPointOfInstantiation();
2321 else if (MemberSpecializationInfo *MSInfo
2322 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2323 return MSInfo->getPointOfInstantiation();
2325 return SourceLocation();
2328 bool FunctionDecl::isOutOfLine() const {
2329 if (Decl::isOutOfLine())
2332 // If this function was instantiated from a member function of a
2333 // class template, check whether that member function was defined out-of-line.
2334 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2335 const FunctionDecl *Definition;
2336 if (FD->hasBody(Definition))
2337 return Definition->isOutOfLine();
2340 // If this function was instantiated from a function template,
2341 // check whether that function template was defined out-of-line.
2342 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2343 const FunctionDecl *Definition;
2344 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2345 return Definition->isOutOfLine();
2351 SourceRange FunctionDecl::getSourceRange() const {
2352 return SourceRange(getOuterLocStart(), EndRangeLoc);
2355 unsigned FunctionDecl::getMemoryFunctionKind() const {
2356 IdentifierInfo *FnInfo = getIdentifier();
2361 // Builtin handling.
2362 switch (getBuiltinID()) {
2363 case Builtin::BI__builtin_memset:
2364 case Builtin::BI__builtin___memset_chk:
2365 case Builtin::BImemset:
2366 return Builtin::BImemset;
2368 case Builtin::BI__builtin_memcpy:
2369 case Builtin::BI__builtin___memcpy_chk:
2370 case Builtin::BImemcpy:
2371 return Builtin::BImemcpy;
2373 case Builtin::BI__builtin_memmove:
2374 case Builtin::BI__builtin___memmove_chk:
2375 case Builtin::BImemmove:
2376 return Builtin::BImemmove;
2378 case Builtin::BIstrlcpy:
2379 return Builtin::BIstrlcpy;
2380 case Builtin::BIstrlcat:
2381 return Builtin::BIstrlcat;
2383 case Builtin::BI__builtin_memcmp:
2384 case Builtin::BImemcmp:
2385 return Builtin::BImemcmp;
2387 case Builtin::BI__builtin_strncpy:
2388 case Builtin::BI__builtin___strncpy_chk:
2389 case Builtin::BIstrncpy:
2390 return Builtin::BIstrncpy;
2392 case Builtin::BI__builtin_strncmp:
2393 case Builtin::BIstrncmp:
2394 return Builtin::BIstrncmp;
2396 case Builtin::BI__builtin_strncasecmp:
2397 case Builtin::BIstrncasecmp:
2398 return Builtin::BIstrncasecmp;
2400 case Builtin::BI__builtin_strncat:
2401 case Builtin::BI__builtin___strncat_chk:
2402 case Builtin::BIstrncat:
2403 return Builtin::BIstrncat;
2405 case Builtin::BI__builtin_strndup:
2406 case Builtin::BIstrndup:
2407 return Builtin::BIstrndup;
2409 case Builtin::BI__builtin_strlen:
2410 case Builtin::BIstrlen:
2411 return Builtin::BIstrlen;
2415 if (FnInfo->isStr("memset"))
2416 return Builtin::BImemset;
2417 else if (FnInfo->isStr("memcpy"))
2418 return Builtin::BImemcpy;
2419 else if (FnInfo->isStr("memmove"))
2420 return Builtin::BImemmove;
2421 else if (FnInfo->isStr("memcmp"))
2422 return Builtin::BImemcmp;
2423 else if (FnInfo->isStr("strncpy"))
2424 return Builtin::BIstrncpy;
2425 else if (FnInfo->isStr("strncmp"))
2426 return Builtin::BIstrncmp;
2427 else if (FnInfo->isStr("strncasecmp"))
2428 return Builtin::BIstrncasecmp;
2429 else if (FnInfo->isStr("strncat"))
2430 return Builtin::BIstrncat;
2431 else if (FnInfo->isStr("strndup"))
2432 return Builtin::BIstrndup;
2433 else if (FnInfo->isStr("strlen"))
2434 return Builtin::BIstrlen;
2441 //===----------------------------------------------------------------------===//
2442 // FieldDecl Implementation
2443 //===----------------------------------------------------------------------===//
2445 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
2446 SourceLocation StartLoc, SourceLocation IdLoc,
2447 IdentifierInfo *Id, QualType T,
2448 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2450 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
2451 BW, Mutable, HasInit);
2454 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2455 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2456 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2457 0, QualType(), 0, 0, false, false);
2460 bool FieldDecl::isAnonymousStructOrUnion() const {
2461 if (!isImplicit() || getDeclName())
2464 if (const RecordType *Record = getType()->getAs<RecordType>())
2465 return Record->getDecl()->isAnonymousStructOrUnion();
2470 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2471 assert(isBitField() && "not a bitfield");
2472 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2473 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2476 unsigned FieldDecl::getFieldIndex() const {
2477 if (CachedFieldIndex) return CachedFieldIndex - 1;
2480 const RecordDecl *RD = getParent();
2481 const FieldDecl *LastFD = 0;
2482 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
2484 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2485 I != E; ++I, ++Index) {
2486 (*I)->CachedFieldIndex = Index + 1;
2489 // Zero-length bitfields following non-bitfield members are ignored.
2490 if (getASTContext().ZeroBitfieldFollowsNonBitfield((*I), LastFD)) {
2498 assert(CachedFieldIndex && "failed to find field in parent");
2499 return CachedFieldIndex - 1;
2502 SourceRange FieldDecl::getSourceRange() const {
2503 if (const Expr *E = InitializerOrBitWidth.getPointer())
2504 return SourceRange(getInnerLocStart(), E->getLocEnd());
2505 return DeclaratorDecl::getSourceRange();
2508 void FieldDecl::setInClassInitializer(Expr *Init) {
2509 assert(!InitializerOrBitWidth.getPointer() &&
2510 "bit width or initializer already set");
2511 InitializerOrBitWidth.setPointer(Init);
2512 InitializerOrBitWidth.setInt(0);
2515 //===----------------------------------------------------------------------===//
2516 // TagDecl Implementation
2517 //===----------------------------------------------------------------------===//
2519 SourceLocation TagDecl::getOuterLocStart() const {
2520 return getTemplateOrInnerLocStart(this);
2523 SourceRange TagDecl::getSourceRange() const {
2524 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
2525 return SourceRange(getOuterLocStart(), E);
2528 TagDecl* TagDecl::getCanonicalDecl() {
2529 return getFirstDeclaration();
2532 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2533 TypedefNameDeclOrQualifier = TDD;
2535 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2536 ClearLinkageCache();
2539 void TagDecl::startDefinition() {
2540 IsBeingDefined = true;
2542 if (isa<CXXRecordDecl>(this)) {
2543 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2544 struct CXXRecordDecl::DefinitionData *Data =
2545 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
2546 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2547 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
2551 void TagDecl::completeDefinition() {
2552 assert((!isa<CXXRecordDecl>(this) ||
2553 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2554 "definition completed but not started");
2556 IsCompleteDefinition = true;
2557 IsBeingDefined = false;
2559 if (ASTMutationListener *L = getASTMutationListener())
2560 L->CompletedTagDefinition(this);
2563 TagDecl *TagDecl::getDefinition() const {
2564 if (isCompleteDefinition())
2565 return const_cast<TagDecl *>(this);
2566 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2567 return CXXRD->getDefinition();
2569 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
2571 if (R->isCompleteDefinition())
2577 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2579 // Make sure the extended qualifier info is allocated.
2581 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2582 // Set qualifier info.
2583 getExtInfo()->QualifierLoc = QualifierLoc;
2585 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2587 if (getExtInfo()->NumTemplParamLists == 0) {
2588 getASTContext().Deallocate(getExtInfo());
2589 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
2592 getExtInfo()->QualifierLoc = QualifierLoc;
2597 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2598 unsigned NumTPLists,
2599 TemplateParameterList **TPLists) {
2600 assert(NumTPLists > 0);
2601 // Make sure the extended decl info is allocated.
2603 // Allocate external info struct.
2604 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2605 // Set the template parameter lists info.
2606 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2609 //===----------------------------------------------------------------------===//
2610 // EnumDecl Implementation
2611 //===----------------------------------------------------------------------===//
2613 void EnumDecl::anchor() { }
2615 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2616 SourceLocation StartLoc, SourceLocation IdLoc,
2618 EnumDecl *PrevDecl, bool IsScoped,
2619 bool IsScopedUsingClassTag, bool IsFixed) {
2620 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
2621 IsScoped, IsScopedUsingClassTag, IsFixed);
2622 C.getTypeDeclType(Enum, PrevDecl);
2626 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2627 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2628 return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2629 false, false, false);
2632 void EnumDecl::completeDefinition(QualType NewType,
2633 QualType NewPromotionType,
2634 unsigned NumPositiveBits,
2635 unsigned NumNegativeBits) {
2636 assert(!isCompleteDefinition() && "Cannot redefine enums!");
2638 IntegerType = NewType.getTypePtr();
2639 PromotionType = NewPromotionType;
2640 setNumPositiveBits(NumPositiveBits);
2641 setNumNegativeBits(NumNegativeBits);
2642 TagDecl::completeDefinition();
2645 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2646 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2647 return MSI->getTemplateSpecializationKind();
2649 return TSK_Undeclared;
2652 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2653 SourceLocation PointOfInstantiation) {
2654 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2655 assert(MSI && "Not an instantiated member enumeration?");
2656 MSI->setTemplateSpecializationKind(TSK);
2657 if (TSK != TSK_ExplicitSpecialization &&
2658 PointOfInstantiation.isValid() &&
2659 MSI->getPointOfInstantiation().isInvalid())
2660 MSI->setPointOfInstantiation(PointOfInstantiation);
2663 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
2664 if (SpecializationInfo)
2665 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
2670 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2671 TemplateSpecializationKind TSK) {
2672 assert(!SpecializationInfo && "Member enum is already a specialization");
2673 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
2676 //===----------------------------------------------------------------------===//
2677 // RecordDecl Implementation
2678 //===----------------------------------------------------------------------===//
2680 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2681 SourceLocation StartLoc, SourceLocation IdLoc,
2682 IdentifierInfo *Id, RecordDecl *PrevDecl)
2683 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
2684 HasFlexibleArrayMember = false;
2685 AnonymousStructOrUnion = false;
2686 HasObjectMember = false;
2687 LoadedFieldsFromExternalStorage = false;
2688 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
2691 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2692 SourceLocation StartLoc, SourceLocation IdLoc,
2693 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2694 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2696 C.getTypeDeclType(R, PrevDecl);
2700 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2701 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
2702 return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2703 SourceLocation(), 0, 0);
2706 bool RecordDecl::isInjectedClassName() const {
2707 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
2708 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2711 RecordDecl::field_iterator RecordDecl::field_begin() const {
2712 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2713 LoadFieldsFromExternalStorage();
2715 return field_iterator(decl_iterator(FirstDecl));
2718 /// completeDefinition - Notes that the definition of this type is now
2720 void RecordDecl::completeDefinition() {
2721 assert(!isCompleteDefinition() && "Cannot redefine record!");
2722 TagDecl::completeDefinition();
2725 void RecordDecl::LoadFieldsFromExternalStorage() const {
2726 ExternalASTSource *Source = getASTContext().getExternalSource();
2727 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2729 // Notify that we have a RecordDecl doing some initialization.
2730 ExternalASTSource::Deserializing TheFields(Source);
2732 SmallVector<Decl*, 64> Decls;
2733 LoadedFieldsFromExternalStorage = true;
2734 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2738 case ELR_AlreadyLoaded:
2744 // Check that all decls we got were FieldDecls.
2745 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2746 assert(isa<FieldDecl>(Decls[i]));
2752 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2753 /*FieldsAlreadyLoaded=*/false);
2756 //===----------------------------------------------------------------------===//
2757 // BlockDecl Implementation
2758 //===----------------------------------------------------------------------===//
2760 void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
2761 assert(ParamInfo == 0 && "Already has param info!");
2763 // Zero params -> null pointer.
2764 if (!NewParamInfo.empty()) {
2765 NumParams = NewParamInfo.size();
2766 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2767 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2771 void BlockDecl::setCaptures(ASTContext &Context,
2772 const Capture *begin,
2774 bool capturesCXXThis) {
2775 CapturesCXXThis = capturesCXXThis;
2783 NumCaptures = end - begin;
2785 // Avoid new Capture[] because we don't want to provide a default
2787 size_t allocationSize = NumCaptures * sizeof(Capture);
2788 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2789 memcpy(buffer, begin, allocationSize);
2790 Captures = static_cast<Capture*>(buffer);
2793 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2794 for (capture_const_iterator
2795 i = capture_begin(), e = capture_end(); i != e; ++i)
2796 // Only auto vars can be captured, so no redeclaration worries.
2797 if (i->getVariable() == variable)
2803 SourceRange BlockDecl::getSourceRange() const {
2804 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2807 //===----------------------------------------------------------------------===//
2808 // Other Decl Allocation/Deallocation Method Implementations
2809 //===----------------------------------------------------------------------===//
2811 void TranslationUnitDecl::anchor() { }
2813 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2814 return new (C) TranslationUnitDecl(C);
2817 void LabelDecl::anchor() { }
2819 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2820 SourceLocation IdentL, IdentifierInfo *II) {
2821 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2824 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2825 SourceLocation IdentL, IdentifierInfo *II,
2826 SourceLocation GnuLabelL) {
2827 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2828 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
2831 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2832 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
2833 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
2836 void ValueDecl::anchor() { }
2838 void ImplicitParamDecl::anchor() { }
2840 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
2841 SourceLocation IdLoc,
2844 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
2847 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
2849 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
2850 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
2853 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
2854 SourceLocation StartLoc,
2855 const DeclarationNameInfo &NameInfo,
2856 QualType T, TypeSourceInfo *TInfo,
2857 StorageClass SC, StorageClass SCAsWritten,
2858 bool isInlineSpecified,
2859 bool hasWrittenPrototype,
2860 bool isConstexprSpecified) {
2861 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2862 T, TInfo, SC, SCAsWritten,
2864 isConstexprSpecified);
2865 New->HasWrittenPrototype = hasWrittenPrototype;
2869 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2870 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
2871 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
2872 DeclarationNameInfo(), QualType(), 0,
2873 SC_None, SC_None, false, false);
2876 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2877 return new (C) BlockDecl(DC, L);
2880 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2881 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
2882 return new (Mem) BlockDecl(0, SourceLocation());
2885 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2887 IdentifierInfo *Id, QualType T,
2888 Expr *E, const llvm::APSInt &V) {
2889 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2893 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2894 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
2895 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
2899 void IndirectFieldDecl::anchor() { }
2902 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2903 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2905 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2908 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
2910 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
2911 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
2915 SourceRange EnumConstantDecl::getSourceRange() const {
2916 SourceLocation End = getLocation();
2918 End = Init->getLocEnd();
2919 return SourceRange(getLocation(), End);
2922 void TypeDecl::anchor() { }
2924 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
2925 SourceLocation StartLoc, SourceLocation IdLoc,
2926 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2927 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
2930 void TypedefNameDecl::anchor() { }
2932 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2933 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
2934 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2937 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2938 SourceLocation StartLoc,
2939 SourceLocation IdLoc, IdentifierInfo *Id,
2940 TypeSourceInfo *TInfo) {
2941 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2944 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2945 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
2946 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2949 SourceRange TypedefDecl::getSourceRange() const {
2950 SourceLocation RangeEnd = getLocation();
2951 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2952 if (typeIsPostfix(TInfo->getType()))
2953 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2955 return SourceRange(getLocStart(), RangeEnd);
2958 SourceRange TypeAliasDecl::getSourceRange() const {
2959 SourceLocation RangeEnd = getLocStart();
2960 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2961 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2962 return SourceRange(getLocStart(), RangeEnd);
2965 void FileScopeAsmDecl::anchor() { }
2967 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
2969 SourceLocation AsmLoc,
2970 SourceLocation RParenLoc) {
2971 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
2974 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
2976 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
2977 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
2980 //===----------------------------------------------------------------------===//
2981 // ImportDecl Implementation
2982 //===----------------------------------------------------------------------===//
2984 /// \brief Retrieve the number of module identifiers needed to name the given
2986 static unsigned getNumModuleIdentifiers(Module *Mod) {
2987 unsigned Result = 1;
2988 while (Mod->Parent) {
2995 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
2997 ArrayRef<SourceLocation> IdentifierLocs)
2998 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3001 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3002 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3003 memcpy(StoredLocs, IdentifierLocs.data(),
3004 IdentifierLocs.size() * sizeof(SourceLocation));
3007 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3008 Module *Imported, SourceLocation EndLoc)
3009 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3012 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3015 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3016 SourceLocation StartLoc, Module *Imported,
3017 ArrayRef<SourceLocation> IdentifierLocs) {
3018 void *Mem = C.Allocate(sizeof(ImportDecl) +
3019 IdentifierLocs.size() * sizeof(SourceLocation));
3020 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3023 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3024 SourceLocation StartLoc,
3026 SourceLocation EndLoc) {
3027 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
3028 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
3029 Import->setImplicit();
3033 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3034 unsigned NumLocations) {
3035 void *Mem = AllocateDeserializedDecl(C, ID,
3036 (sizeof(ImportDecl) +
3037 NumLocations * sizeof(SourceLocation)));
3038 return new (Mem) ImportDecl(EmptyShell());
3041 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3042 if (!ImportedAndComplete.getInt())
3043 return ArrayRef<SourceLocation>();
3045 const SourceLocation *StoredLocs
3046 = reinterpret_cast<const SourceLocation *>(this + 1);
3047 return ArrayRef<SourceLocation>(StoredLocs,
3048 getNumModuleIdentifiers(getImportedModule()));
3051 SourceRange ImportDecl::getSourceRange() const {
3052 if (!ImportedAndComplete.getInt())
3053 return SourceRange(getLocation(),
3054 *reinterpret_cast<const SourceLocation *>(this + 1));
3056 return SourceRange(getLocation(), getIdentifierLocs().back());