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/Specifiers.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/Support/ErrorHandling.h"
31 using namespace clang;
33 //===----------------------------------------------------------------------===//
34 // NamedDecl Implementation
35 //===----------------------------------------------------------------------===//
37 static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
38 // If this declaration has an explicit visibility attribute, use it.
39 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
40 switch (A->getVisibility()) {
41 case VisibilityAttr::Default:
42 return DefaultVisibility;
43 case VisibilityAttr::Hidden:
44 return HiddenVisibility;
45 case VisibilityAttr::Protected:
46 return ProtectedVisibility;
49 return DefaultVisibility;
52 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
53 // implies visibility(default).
54 if (D->getASTContext().Target.getTriple().isOSDarwin()) {
55 for (specific_attr_iterator<AvailabilityAttr>
56 A = D->specific_attr_begin<AvailabilityAttr>(),
57 AEnd = D->specific_attr_end<AvailabilityAttr>();
59 if ((*A)->getPlatform()->getName().equals("macosx"))
60 return DefaultVisibility;
63 return llvm::Optional<Visibility>();
66 typedef NamedDecl::LinkageInfo LinkageInfo;
67 typedef std::pair<Linkage,Visibility> LVPair;
69 static LVPair merge(LVPair L, LVPair R) {
70 return LVPair(minLinkage(L.first, R.first),
71 minVisibility(L.second, R.second));
74 static LVPair merge(LVPair L, LinkageInfo R) {
75 return LVPair(minLinkage(L.first, R.linkage()),
76 minVisibility(L.second, R.visibility()));
80 /// Flags controlling the computation of linkage and visibility.
82 bool ConsiderGlobalVisibility;
83 bool ConsiderVisibilityAttributes;
84 bool ConsiderTemplateParameterTypes;
86 LVFlags() : ConsiderGlobalVisibility(true),
87 ConsiderVisibilityAttributes(true),
88 ConsiderTemplateParameterTypes(true) {
91 /// \brief Returns a set of flags that is only useful for computing the
92 /// linkage, not the visibility, of a declaration.
93 static LVFlags CreateOnlyDeclLinkage() {
95 F.ConsiderGlobalVisibility = false;
96 F.ConsiderVisibilityAttributes = false;
97 F.ConsiderTemplateParameterTypes = false;
101 /// Returns a set of flags, otherwise based on these, which ignores
102 /// off all sources of visibility except template arguments.
103 LVFlags onlyTemplateVisibility() const {
105 F.ConsiderGlobalVisibility = false;
106 F.ConsiderVisibilityAttributes = false;
107 F.ConsiderTemplateParameterTypes = false;
111 } // end anonymous namespace
113 /// \brief Get the most restrictive linkage for the types in the given
114 /// template parameter list.
116 getLVForTemplateParameterList(const TemplateParameterList *Params) {
117 LVPair LV(ExternalLinkage, DefaultVisibility);
118 for (TemplateParameterList::const_iterator P = Params->begin(),
119 PEnd = Params->end();
121 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
122 if (NTTP->isExpandedParameterPack()) {
123 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
124 QualType T = NTTP->getExpansionType(I);
125 if (!T->isDependentType())
126 LV = merge(LV, T->getLinkageAndVisibility());
131 if (!NTTP->getType()->isDependentType()) {
132 LV = merge(LV, NTTP->getType()->getLinkageAndVisibility());
137 if (TemplateTemplateParmDecl *TTP
138 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
139 LV = merge(LV, getLVForTemplateParameterList(TTP->getTemplateParameters()));
146 /// getLVForDecl - Get the linkage and visibility for the given declaration.
147 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
149 /// \brief Get the most restrictive linkage for the types and
150 /// declarations in the given template argument list.
151 static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args,
154 LVPair LV(ExternalLinkage, DefaultVisibility);
156 for (unsigned I = 0; I != NumArgs; ++I) {
157 switch (Args[I].getKind()) {
158 case TemplateArgument::Null:
159 case TemplateArgument::Integral:
160 case TemplateArgument::Expression:
163 case TemplateArgument::Type:
164 LV = merge(LV, Args[I].getAsType()->getLinkageAndVisibility());
167 case TemplateArgument::Declaration:
168 // The decl can validly be null as the representation of nullptr
169 // arguments, valid only in C++0x.
170 if (Decl *D = Args[I].getAsDecl()) {
171 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
172 LV = merge(LV, getLVForDecl(ND, F));
176 case TemplateArgument::Template:
177 case TemplateArgument::TemplateExpansion:
178 if (TemplateDecl *Template
179 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
180 LV = merge(LV, getLVForDecl(Template, F));
183 case TemplateArgument::Pack:
184 LV = merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(),
195 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
197 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
200 static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
201 const FunctionTemplateSpecializationInfo *spec) {
202 return !(spec->isExplicitSpecialization() &&
203 fn->hasAttr<VisibilityAttr>());
206 static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
207 return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
210 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
211 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
212 "Not a name having namespace scope");
213 ASTContext &Context = D->getASTContext();
215 // C++ [basic.link]p3:
216 // A name having namespace scope (3.3.6) has internal linkage if it
218 // - an object, reference, function or function template that is
219 // explicitly declared static; or,
220 // (This bullet corresponds to C99 6.2.2p3.)
221 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
222 // Explicitly declared static.
223 if (Var->getStorageClass() == SC_Static)
224 return LinkageInfo::internal();
226 // - an object or reference that is explicitly declared const
227 // and neither explicitly declared extern nor previously
228 // declared to have external linkage; or
229 // (there is no equivalent in C99)
230 if (Context.getLangOptions().CPlusPlus &&
231 Var->getType().isConstant(Context) &&
232 Var->getStorageClass() != SC_Extern &&
233 Var->getStorageClass() != SC_PrivateExtern) {
234 bool FoundExtern = false;
235 for (const VarDecl *PrevVar = Var->getPreviousDeclaration();
236 PrevVar && !FoundExtern;
237 PrevVar = PrevVar->getPreviousDeclaration())
238 if (isExternalLinkage(PrevVar->getLinkage()))
242 return LinkageInfo::internal();
244 if (Var->getStorageClass() == SC_None) {
245 const VarDecl *PrevVar = Var->getPreviousDeclaration();
246 for (; PrevVar; PrevVar = PrevVar->getPreviousDeclaration())
247 if (PrevVar->getStorageClass() == SC_PrivateExtern)
250 return PrevVar->getLinkageAndVisibility();
252 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
254 // A non-member function template can have internal linkage; any
255 // other template name shall have external linkage.
256 const FunctionDecl *Function = 0;
257 if (const FunctionTemplateDecl *FunTmpl
258 = dyn_cast<FunctionTemplateDecl>(D))
259 Function = FunTmpl->getTemplatedDecl();
261 Function = cast<FunctionDecl>(D);
263 // Explicitly declared static.
264 if (Function->getStorageClass() == SC_Static)
265 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
266 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
267 // - a data member of an anonymous union.
268 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
269 return LinkageInfo::internal();
272 if (D->isInAnonymousNamespace()) {
273 const VarDecl *Var = dyn_cast<VarDecl>(D);
274 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
275 if ((!Var || !Var->isExternC()) && (!Func || !Func->isExternC()))
276 return LinkageInfo::uniqueExternal();
279 // Set up the defaults.
282 // If the declaration of an identifier for an object has file
283 // scope and no storage-class specifier, its linkage is
287 if (F.ConsiderVisibilityAttributes) {
288 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
289 LV.setVisibility(*Vis, true);
290 F.ConsiderGlobalVisibility = false;
292 // If we're declared in a namespace with a visibility attribute,
293 // use that namespace's visibility, but don't call it explicit.
294 for (const DeclContext *DC = D->getDeclContext();
295 !isa<TranslationUnitDecl>(DC);
296 DC = DC->getParent()) {
297 if (!isa<NamespaceDecl>(DC)) continue;
298 if (llvm::Optional<Visibility> Vis
299 = cast<NamespaceDecl>(DC)->getExplicitVisibility()) {
300 LV.setVisibility(*Vis, false);
301 F.ConsiderGlobalVisibility = false;
308 // C++ [basic.link]p4:
310 // A name having namespace scope has external linkage if it is the
313 // - an object or reference, unless it has internal linkage; or
314 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
315 // GCC applies the following optimization to variables and static
316 // data members, but not to functions:
318 // Modify the variable's LV by the LV of its type unless this is
319 // C or extern "C". This follows from [basic.link]p9:
320 // A type without linkage shall not be used as the type of a
321 // variable or function with external linkage unless
322 // - the entity has C language linkage, or
323 // - the entity is declared within an unnamed namespace, or
324 // - the entity is not used or is defined in the same
326 // and [basic.link]p10:
327 // ...the types specified by all declarations referring to a
328 // given variable or function shall be identical...
329 // C does not have an equivalent rule.
331 // Ignore this if we've got an explicit attribute; the user
332 // probably knows what they're doing.
334 // Note that we don't want to make the variable non-external
335 // because of this, but unique-external linkage suits us.
336 if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) {
337 LVPair TypeLV = Var->getType()->getLinkageAndVisibility();
338 if (TypeLV.first != ExternalLinkage)
339 return LinkageInfo::uniqueExternal();
340 if (!LV.visibilityExplicit())
341 LV.mergeVisibility(TypeLV.second);
344 if (Var->getStorageClass() == SC_PrivateExtern)
345 LV.setVisibility(HiddenVisibility, true);
347 if (!Context.getLangOptions().CPlusPlus &&
348 (Var->getStorageClass() == SC_Extern ||
349 Var->getStorageClass() == SC_PrivateExtern)) {
352 // For an identifier declared with the storage-class specifier
353 // extern in a scope in which a prior declaration of that
354 // identifier is visible, if the prior declaration specifies
355 // internal or external linkage, the linkage of the identifier
356 // at the later declaration is the same as the linkage
357 // specified at the prior declaration. If no prior declaration
358 // is visible, or if the prior declaration specifies no
359 // linkage, then the identifier has external linkage.
360 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) {
361 LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
362 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
363 LV.mergeVisibility(PrevLV);
367 // - a function, unless it has internal linkage; or
368 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
369 // In theory, we can modify the function's LV by the LV of its
370 // type unless it has C linkage (see comment above about variables
371 // for justification). In practice, GCC doesn't do this, so it's
372 // just too painful to make work.
374 if (Function->getStorageClass() == SC_PrivateExtern)
375 LV.setVisibility(HiddenVisibility, true);
378 // If the declaration of an identifier for a function has no
379 // storage-class specifier, its linkage is determined exactly
380 // as if it were declared with the storage-class specifier
382 if (!Context.getLangOptions().CPlusPlus &&
383 (Function->getStorageClass() == SC_Extern ||
384 Function->getStorageClass() == SC_PrivateExtern ||
385 Function->getStorageClass() == SC_None)) {
387 // For an identifier declared with the storage-class specifier
388 // extern in a scope in which a prior declaration of that
389 // identifier is visible, if the prior declaration specifies
390 // internal or external linkage, the linkage of the identifier
391 // at the later declaration is the same as the linkage
392 // specified at the prior declaration. If no prior declaration
393 // is visible, or if the prior declaration specifies no
394 // linkage, then the identifier has external linkage.
395 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) {
396 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
397 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
398 LV.mergeVisibility(PrevLV);
402 // In C++, then if the type of the function uses a type with
403 // unique-external linkage, it's not legally usable from outside
404 // this translation unit. However, we should use the C linkage
405 // rules instead for extern "C" declarations.
406 if (Context.getLangOptions().CPlusPlus && !Function->isExternC() &&
407 Function->getType()->getLinkage() == UniqueExternalLinkage)
408 return LinkageInfo::uniqueExternal();
410 // Consider LV from the template and the template arguments unless
411 // this is an explicit specialization with a visibility attribute.
412 if (FunctionTemplateSpecializationInfo *specInfo
413 = Function->getTemplateSpecializationInfo()) {
414 if (shouldConsiderTemplateLV(Function, specInfo)) {
415 LV.merge(getLVForDecl(specInfo->getTemplate(),
416 F.onlyTemplateVisibility()));
417 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
418 LV.merge(getLVForTemplateArgumentList(templateArgs, F));
422 // - a named class (Clause 9), or an unnamed class defined in a
423 // typedef declaration in which the class has the typedef name
424 // for linkage purposes (7.1.3); or
425 // - a named enumeration (7.2), or an unnamed enumeration
426 // defined in a typedef declaration in which the enumeration
427 // has the typedef name for linkage purposes (7.1.3); or
428 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
429 // Unnamed tags have no linkage.
430 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
431 return LinkageInfo::none();
433 // If this is a class template specialization, consider the
434 // linkage of the template and template arguments.
435 if (const ClassTemplateSpecializationDecl *spec
436 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
437 if (shouldConsiderTemplateLV(spec)) {
438 // From the template.
439 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
440 F.onlyTemplateVisibility()));
442 // The arguments at which the template was instantiated.
443 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
444 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
448 // Consider -fvisibility unless the type has C linkage.
449 if (F.ConsiderGlobalVisibility)
450 F.ConsiderGlobalVisibility =
451 (Context.getLangOptions().CPlusPlus &&
452 !Tag->getDeclContext()->isExternCContext());
454 // - an enumerator belonging to an enumeration with external linkage;
455 } else if (isa<EnumConstantDecl>(D)) {
456 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
457 if (!isExternalLinkage(EnumLV.linkage()))
458 return LinkageInfo::none();
461 // - a template, unless it is a function template that has
462 // internal linkage (Clause 14);
463 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
464 if (F.ConsiderTemplateParameterTypes)
465 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
467 // - a namespace (7.3), unless it is declared within an unnamed
469 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
472 // By extension, we assign external linkage to Objective-C
474 } else if (isa<ObjCInterfaceDecl>(D)) {
477 // Everything not covered here has no linkage.
479 return LinkageInfo::none();
482 // If we ended up with non-external linkage, visibility should
483 // always be default.
484 if (LV.linkage() != ExternalLinkage)
485 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
487 // If we didn't end up with hidden visibility, consider attributes
489 if (F.ConsiderGlobalVisibility)
490 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
495 static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
496 // Only certain class members have linkage. Note that fields don't
497 // really have linkage, but it's convenient to say they do for the
498 // purposes of calculating linkage of pointer-to-data-member
499 // template arguments.
500 if (!(isa<CXXMethodDecl>(D) ||
504 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
505 return LinkageInfo::none();
509 // The flags we're going to use to compute the class's visibility.
512 // If we have an explicit visibility attribute, merge that in.
513 if (F.ConsiderVisibilityAttributes) {
514 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
515 LV.mergeVisibility(*Vis, true);
517 // Ignore global visibility later, but not this attribute.
518 F.ConsiderGlobalVisibility = false;
520 // Ignore both global visibility and attributes when computing our
521 // parent's visibility.
522 ClassF = F.onlyTemplateVisibility();
526 // Class members only have linkage if their class has external
528 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
529 if (!isExternalLinkage(LV.linkage()))
530 return LinkageInfo::none();
532 // If the class already has unique-external linkage, we can't improve.
533 if (LV.linkage() == UniqueExternalLinkage)
534 return LinkageInfo::uniqueExternal();
536 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
537 // If the type of the function uses a type with unique-external
538 // linkage, it's not legally usable from outside this translation unit.
539 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
540 return LinkageInfo::uniqueExternal();
542 TemplateSpecializationKind TSK = TSK_Undeclared;
544 // If this is a method template specialization, use the linkage for
545 // the template parameters and arguments.
546 if (FunctionTemplateSpecializationInfo *spec
547 = MD->getTemplateSpecializationInfo()) {
548 if (shouldConsiderTemplateLV(MD, spec)) {
549 LV.merge(getLVForTemplateArgumentList(*spec->TemplateArguments, F));
550 if (F.ConsiderTemplateParameterTypes)
551 LV.merge(getLVForTemplateParameterList(
552 spec->getTemplate()->getTemplateParameters()));
555 TSK = spec->getTemplateSpecializationKind();
556 } else if (MemberSpecializationInfo *MSI =
557 MD->getMemberSpecializationInfo()) {
558 TSK = MSI->getTemplateSpecializationKind();
561 // If we're paying attention to global visibility, apply
562 // -finline-visibility-hidden if this is an inline method.
564 // Note that ConsiderGlobalVisibility doesn't yet have information
565 // about whether containing classes have visibility attributes,
566 // and that's intentional.
567 if (TSK != TSK_ExplicitInstantiationDeclaration &&
568 F.ConsiderGlobalVisibility &&
569 MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
570 // InlineVisibilityHidden only applies to definitions, and
571 // isInlined() only gives meaningful answers on definitions
573 const FunctionDecl *Def = 0;
574 if (MD->hasBody(Def) && Def->isInlined())
575 LV.setVisibility(HiddenVisibility);
578 // Note that in contrast to basically every other situation, we
579 // *do* apply -fvisibility to method declarations.
581 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
582 if (const ClassTemplateSpecializationDecl *spec
583 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
584 if (shouldConsiderTemplateLV(spec)) {
585 // Merge template argument/parameter information for member
586 // class template specializations.
587 LV.merge(getLVForTemplateArgumentList(spec->getTemplateArgs(), F));
588 if (F.ConsiderTemplateParameterTypes)
589 LV.merge(getLVForTemplateParameterList(
590 spec->getSpecializedTemplate()->getTemplateParameters()));
594 // Static data members.
595 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
596 // Modify the variable's linkage by its type, but ignore the
597 // type's visibility unless it's a definition.
598 LVPair TypeLV = VD->getType()->getLinkageAndVisibility();
599 if (TypeLV.first != ExternalLinkage)
600 LV.mergeLinkage(UniqueExternalLinkage);
601 if (!LV.visibilityExplicit())
602 LV.mergeVisibility(TypeLV.second);
605 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
607 // Apply -fvisibility if desired.
608 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
609 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
615 static void clearLinkageForClass(const CXXRecordDecl *record) {
616 for (CXXRecordDecl::decl_iterator
617 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
619 if (isa<NamedDecl>(child))
620 cast<NamedDecl>(child)->ClearLinkageCache();
624 void NamedDecl::ClearLinkageCache() {
625 // Note that we can't skip clearing the linkage of children just
626 // because the parent doesn't have cached linkage: we don't cache
627 // when computing linkage for parent contexts.
629 HasCachedLinkage = 0;
631 // If we're changing the linkage of a class, we need to reset the
632 // linkage of child declarations, too.
633 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
634 clearLinkageForClass(record);
636 if (ClassTemplateDecl *temp =
637 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
638 // Clear linkage for the template pattern.
639 CXXRecordDecl *record = temp->getTemplatedDecl();
640 record->HasCachedLinkage = 0;
641 clearLinkageForClass(record);
643 // We need to clear linkage for specializations, too.
644 for (ClassTemplateDecl::spec_iterator
645 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
646 i->ClearLinkageCache();
649 // Clear cached linkage for function template decls, too.
650 if (FunctionTemplateDecl *temp =
651 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
652 temp->getTemplatedDecl()->ClearLinkageCache();
653 for (FunctionTemplateDecl::spec_iterator
654 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
655 i->ClearLinkageCache();
660 Linkage NamedDecl::getLinkage() const {
661 if (HasCachedLinkage) {
662 assert(Linkage(CachedLinkage) ==
663 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
664 return Linkage(CachedLinkage);
667 CachedLinkage = getLVForDecl(this,
668 LVFlags::CreateOnlyDeclLinkage()).linkage();
669 HasCachedLinkage = 1;
670 return Linkage(CachedLinkage);
673 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
674 LinkageInfo LI = getLVForDecl(this, LVFlags());
675 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
676 HasCachedLinkage = 1;
677 CachedLinkage = LI.linkage();
681 llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
682 // Use the most recent declaration of a variable.
683 if (const VarDecl *var = dyn_cast<VarDecl>(this))
684 return getVisibilityOf(var->getMostRecentDeclaration());
686 // Use the most recent declaration of a function, and also handle
687 // function template specializations.
688 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
689 if (llvm::Optional<Visibility> V
690 = getVisibilityOf(fn->getMostRecentDeclaration()))
693 // If the function is a specialization of a template with an
694 // explicit visibility attribute, use that.
695 if (FunctionTemplateSpecializationInfo *templateInfo
696 = fn->getTemplateSpecializationInfo())
697 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
699 return llvm::Optional<Visibility>();
702 // Otherwise, just check the declaration itself first.
703 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
706 // If there wasn't explicit visibility there, and this is a
707 // specialization of a class template, check for visibility
709 if (const ClassTemplateSpecializationDecl *spec
710 = dyn_cast<ClassTemplateSpecializationDecl>(this))
711 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
713 return llvm::Optional<Visibility>();
716 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
717 // Objective-C: treat all Objective-C declarations as having external
719 switch (D->getKind()) {
722 case Decl::TemplateTemplateParm: // count these as external
723 case Decl::NonTypeTemplateParm:
724 case Decl::ObjCAtDefsField:
725 case Decl::ObjCCategory:
726 case Decl::ObjCCategoryImpl:
727 case Decl::ObjCCompatibleAlias:
728 case Decl::ObjCForwardProtocol:
729 case Decl::ObjCImplementation:
730 case Decl::ObjCMethod:
731 case Decl::ObjCProperty:
732 case Decl::ObjCPropertyImpl:
733 case Decl::ObjCProtocol:
734 return LinkageInfo::external();
737 // Handle linkage for namespace-scope names.
738 if (D->getDeclContext()->getRedeclContext()->isFileContext())
739 return getLVForNamespaceScopeDecl(D, Flags);
741 // C++ [basic.link]p5:
742 // In addition, a member function, static data member, a named
743 // class or enumeration of class scope, or an unnamed class or
744 // enumeration defined in a class-scope typedef declaration such
745 // that the class or enumeration has the typedef name for linkage
746 // purposes (7.1.3), has external linkage if the name of the class
747 // has external linkage.
748 if (D->getDeclContext()->isRecord())
749 return getLVForClassMember(D, Flags);
751 // C++ [basic.link]p6:
752 // The name of a function declared in block scope and the name of
753 // an object declared by a block scope extern declaration have
754 // linkage. If there is a visible declaration of an entity with
755 // linkage having the same name and type, ignoring entities
756 // declared outside the innermost enclosing namespace scope, the
757 // block scope declaration declares that same entity and receives
758 // the linkage of the previous declaration. If there is more than
759 // one such matching entity, the program is ill-formed. Otherwise,
760 // if no matching entity is found, the block scope entity receives
762 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
763 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
764 if (Function->isInAnonymousNamespace() && !Function->isExternC())
765 return LinkageInfo::uniqueExternal();
768 if (Flags.ConsiderVisibilityAttributes) {
769 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
770 LV.setVisibility(*Vis);
773 if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) {
774 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
775 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
776 LV.mergeVisibility(PrevLV);
782 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
783 if (Var->getStorageClass() == SC_Extern ||
784 Var->getStorageClass() == SC_PrivateExtern) {
785 if (Var->isInAnonymousNamespace() && !Var->isExternC())
786 return LinkageInfo::uniqueExternal();
789 if (Var->getStorageClass() == SC_PrivateExtern)
790 LV.setVisibility(HiddenVisibility);
791 else if (Flags.ConsiderVisibilityAttributes) {
792 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
793 LV.setVisibility(*Vis);
796 if (const VarDecl *Prev = Var->getPreviousDeclaration()) {
797 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
798 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
799 LV.mergeVisibility(PrevLV);
806 // C++ [basic.link]p6:
807 // Names not covered by these rules have no linkage.
808 return LinkageInfo::none();
811 std::string NamedDecl::getQualifiedNameAsString() const {
812 return getQualifiedNameAsString(getASTContext().getLangOptions());
815 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
816 const DeclContext *Ctx = getDeclContext();
818 if (Ctx->isFunctionOrMethod())
819 return getNameAsString();
821 typedef llvm::SmallVector<const DeclContext *, 8> ContextsTy;
825 while (Ctx && isa<NamedDecl>(Ctx)) {
826 Contexts.push_back(Ctx);
827 Ctx = Ctx->getParent();
830 std::string QualName;
831 llvm::raw_string_ostream OS(QualName);
833 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
835 if (const ClassTemplateSpecializationDecl *Spec
836 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
837 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
838 std::string TemplateArgsStr
839 = TemplateSpecializationType::PrintTemplateArgumentList(
843 OS << Spec->getName() << TemplateArgsStr;
844 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
845 if (ND->isAnonymousNamespace())
846 OS << "<anonymous namespace>";
849 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
850 if (!RD->getIdentifier())
851 OS << "<anonymous " << RD->getKindName() << '>';
854 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
855 const FunctionProtoType *FT = 0;
856 if (FD->hasWrittenPrototype())
857 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
861 unsigned NumParams = FD->getNumParams();
862 for (unsigned i = 0; i < NumParams; ++i) {
866 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
870 if (FT->isVariadic()) {
878 OS << cast<NamedDecl>(*I);
891 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
892 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
894 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
895 // We want to keep it, unless it nominates same namespace.
896 if (getKind() == Decl::UsingDirective) {
897 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
898 ->getOriginalNamespace() ==
899 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
900 ->getOriginalNamespace();
903 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
904 // For function declarations, we keep track of redeclarations.
905 return FD->getPreviousDeclaration() == OldD;
907 // For function templates, the underlying function declarations are linked.
908 if (const FunctionTemplateDecl *FunctionTemplate
909 = dyn_cast<FunctionTemplateDecl>(this))
910 if (const FunctionTemplateDecl *OldFunctionTemplate
911 = dyn_cast<FunctionTemplateDecl>(OldD))
912 return FunctionTemplate->getTemplatedDecl()
913 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
915 // For method declarations, we keep track of redeclarations.
916 if (isa<ObjCMethodDecl>(this))
919 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
922 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
923 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
924 cast<UsingShadowDecl>(OldD)->getTargetDecl();
926 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
927 ASTContext &Context = getASTContext();
928 return Context.getCanonicalNestedNameSpecifier(
929 cast<UsingDecl>(this)->getQualifier()) ==
930 Context.getCanonicalNestedNameSpecifier(
931 cast<UsingDecl>(OldD)->getQualifier());
934 // For non-function declarations, if the declarations are of the
935 // same kind then this must be a redeclaration, or semantic analysis
936 // would not have given us the new declaration.
937 return this->getKind() == OldD->getKind();
940 bool NamedDecl::hasLinkage() const {
941 return getLinkage() != NoLinkage;
944 NamedDecl *NamedDecl::getUnderlyingDecl() {
945 NamedDecl *ND = this;
947 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
948 ND = UD->getTargetDecl();
949 else if (ObjCCompatibleAliasDecl *AD
950 = dyn_cast<ObjCCompatibleAliasDecl>(ND))
951 return AD->getClassInterface();
957 bool NamedDecl::isCXXInstanceMember() const {
958 assert(isCXXClassMember() &&
959 "checking whether non-member is instance member");
961 const NamedDecl *D = this;
962 if (isa<UsingShadowDecl>(D))
963 D = cast<UsingShadowDecl>(D)->getTargetDecl();
965 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
967 if (isa<CXXMethodDecl>(D))
968 return cast<CXXMethodDecl>(D)->isInstance();
969 if (isa<FunctionTemplateDecl>(D))
970 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
971 ->getTemplatedDecl())->isInstance();
975 //===----------------------------------------------------------------------===//
976 // DeclaratorDecl Implementation
977 //===----------------------------------------------------------------------===//
979 template <typename DeclT>
980 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
981 if (decl->getNumTemplateParameterLists() > 0)
982 return decl->getTemplateParameterList(0)->getTemplateLoc();
984 return decl->getInnerLocStart();
987 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
988 TypeSourceInfo *TSI = getTypeSourceInfo();
989 if (TSI) return TSI->getTypeLoc().getBeginLoc();
990 return SourceLocation();
993 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
995 // Make sure the extended decl info is allocated.
997 // Save (non-extended) type source info pointer.
998 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
999 // Allocate external info struct.
1000 DeclInfo = new (getASTContext()) ExtInfo;
1001 // Restore savedTInfo into (extended) decl info.
1002 getExtInfo()->TInfo = savedTInfo;
1004 // Set qualifier info.
1005 getExtInfo()->QualifierLoc = QualifierLoc;
1008 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1010 if (getExtInfo()->NumTemplParamLists == 0) {
1011 // Save type source info pointer.
1012 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1013 // Deallocate the extended decl info.
1014 getASTContext().Deallocate(getExtInfo());
1015 // Restore savedTInfo into (non-extended) decl info.
1016 DeclInfo = savedTInfo;
1019 getExtInfo()->QualifierLoc = QualifierLoc;
1025 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1026 unsigned NumTPLists,
1027 TemplateParameterList **TPLists) {
1028 assert(NumTPLists > 0);
1029 // Make sure the extended decl info is allocated.
1030 if (!hasExtInfo()) {
1031 // Save (non-extended) type source info pointer.
1032 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1033 // Allocate external info struct.
1034 DeclInfo = new (getASTContext()) ExtInfo;
1035 // Restore savedTInfo into (extended) decl info.
1036 getExtInfo()->TInfo = savedTInfo;
1038 // Set the template parameter lists info.
1039 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1042 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1043 return getTemplateOrInnerLocStart(this);
1048 // Helper function: returns true if QT is or contains a type
1049 // having a postfix component.
1050 bool typeIsPostfix(clang::QualType QT) {
1052 const Type* T = QT.getTypePtr();
1053 switch (T->getTypeClass()) {
1057 QT = cast<PointerType>(T)->getPointeeType();
1059 case Type::BlockPointer:
1060 QT = cast<BlockPointerType>(T)->getPointeeType();
1062 case Type::MemberPointer:
1063 QT = cast<MemberPointerType>(T)->getPointeeType();
1065 case Type::LValueReference:
1066 case Type::RValueReference:
1067 QT = cast<ReferenceType>(T)->getPointeeType();
1069 case Type::PackExpansion:
1070 QT = cast<PackExpansionType>(T)->getPattern();
1073 case Type::ConstantArray:
1074 case Type::DependentSizedArray:
1075 case Type::IncompleteArray:
1076 case Type::VariableArray:
1077 case Type::FunctionProto:
1078 case Type::FunctionNoProto:
1086 SourceRange DeclaratorDecl::getSourceRange() const {
1087 SourceLocation RangeEnd = getLocation();
1088 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1089 if (typeIsPostfix(TInfo->getType()))
1090 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1092 return SourceRange(getOuterLocStart(), RangeEnd);
1096 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1097 unsigned NumTPLists,
1098 TemplateParameterList **TPLists) {
1099 assert((NumTPLists == 0 || TPLists != 0) &&
1100 "Empty array of template parameters with positive size!");
1102 // Free previous template parameters (if any).
1103 if (NumTemplParamLists > 0) {
1104 Context.Deallocate(TemplParamLists);
1105 TemplParamLists = 0;
1106 NumTemplParamLists = 0;
1108 // Set info on matched template parameter lists (if any).
1109 if (NumTPLists > 0) {
1110 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1111 NumTemplParamLists = NumTPLists;
1112 for (unsigned i = NumTPLists; i-- > 0; )
1113 TemplParamLists[i] = TPLists[i];
1117 //===----------------------------------------------------------------------===//
1118 // VarDecl Implementation
1119 //===----------------------------------------------------------------------===//
1121 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1123 case SC_None: break;
1124 case SC_Auto: return "auto"; break;
1125 case SC_Extern: return "extern"; break;
1126 case SC_PrivateExtern: return "__private_extern__"; break;
1127 case SC_Register: return "register"; break;
1128 case SC_Static: return "static"; break;
1131 assert(0 && "Invalid storage class");
1135 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1136 SourceLocation StartL, SourceLocation IdL,
1137 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1138 StorageClass S, StorageClass SCAsWritten) {
1139 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
1142 void VarDecl::setStorageClass(StorageClass SC) {
1143 assert(isLegalForVariable(SC));
1144 if (getStorageClass() != SC)
1145 ClearLinkageCache();
1147 VarDeclBits.SClass = SC;
1150 SourceRange VarDecl::getSourceRange() const {
1152 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
1153 return DeclaratorDecl::getSourceRange();
1156 bool VarDecl::isExternC() const {
1157 ASTContext &Context = getASTContext();
1158 if (!Context.getLangOptions().CPlusPlus)
1159 return (getDeclContext()->isTranslationUnit() &&
1160 getStorageClass() != SC_Static) ||
1161 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
1163 const DeclContext *DC = getDeclContext();
1164 if (DC->isFunctionOrMethod())
1167 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
1168 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1169 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
1170 return getStorageClass() != SC_Static;
1180 VarDecl *VarDecl::getCanonicalDecl() {
1181 return getFirstDeclaration();
1184 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
1185 // C++ [basic.def]p2:
1186 // A declaration is a definition unless [...] it contains the 'extern'
1187 // specifier or a linkage-specification and neither an initializer [...],
1188 // it declares a static data member in a class declaration [...].
1189 // C++ [temp.expl.spec]p15:
1190 // An explicit specialization of a static data member of a template is a
1191 // definition if the declaration includes an initializer; otherwise, it is
1193 if (isStaticDataMember()) {
1194 if (isOutOfLine() && (hasInit() ||
1195 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1198 return DeclarationOnly;
1201 // A definition of an identifier is a declaration for that identifier that
1202 // [...] causes storage to be reserved for that object.
1203 // Note: that applies for all non-file-scope objects.
1205 // If the declaration of an identifier for an object has file scope and an
1206 // initializer, the declaration is an external definition for the identifier
1209 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1210 if (hasExternalStorage())
1211 return DeclarationOnly;
1213 if (getStorageClassAsWritten() == SC_Extern ||
1214 getStorageClassAsWritten() == SC_PrivateExtern) {
1215 for (const VarDecl *PrevVar = getPreviousDeclaration();
1216 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) {
1217 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1218 return DeclarationOnly;
1222 // A declaration of an object that has file scope without an initializer,
1223 // and without a storage class specifier or the scs 'static', constitutes
1224 // a tentative definition.
1225 // No such thing in C++.
1226 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
1227 return TentativeDefinition;
1229 // What's left is (in C, block-scope) declarations without initializers or
1230 // external storage. These are definitions.
1234 VarDecl *VarDecl::getActingDefinition() {
1235 DefinitionKind Kind = isThisDeclarationADefinition();
1236 if (Kind != TentativeDefinition)
1239 VarDecl *LastTentative = 0;
1240 VarDecl *First = getFirstDeclaration();
1241 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1243 Kind = (*I)->isThisDeclarationADefinition();
1244 if (Kind == Definition)
1246 else if (Kind == TentativeDefinition)
1249 return LastTentative;
1252 bool VarDecl::isTentativeDefinitionNow() const {
1253 DefinitionKind Kind = isThisDeclarationADefinition();
1254 if (Kind != TentativeDefinition)
1257 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1258 if ((*I)->isThisDeclarationADefinition() == Definition)
1264 VarDecl *VarDecl::getDefinition() {
1265 VarDecl *First = getFirstDeclaration();
1266 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1268 if ((*I)->isThisDeclarationADefinition() == Definition)
1274 VarDecl::DefinitionKind VarDecl::hasDefinition() const {
1275 DefinitionKind Kind = DeclarationOnly;
1277 const VarDecl *First = getFirstDeclaration();
1278 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1280 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
1285 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1286 redecl_iterator I = redecls_begin(), E = redecls_end();
1287 while (I != E && !I->getInit())
1292 return I->getInit();
1297 bool VarDecl::isOutOfLine() const {
1298 if (Decl::isOutOfLine())
1301 if (!isStaticDataMember())
1304 // If this static data member was instantiated from a static data member of
1305 // a class template, check whether that static data member was defined
1307 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1308 return VD->isOutOfLine();
1313 VarDecl *VarDecl::getOutOfLineDefinition() {
1314 if (!isStaticDataMember())
1317 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1318 RD != RDEnd; ++RD) {
1319 if (RD->getLexicalDeclContext()->isFileContext())
1326 void VarDecl::setInit(Expr *I) {
1327 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1328 Eval->~EvaluatedStmt();
1329 getASTContext().Deallocate(Eval);
1335 bool VarDecl::extendsLifetimeOfTemporary() const {
1336 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
1338 const Expr *E = getInit();
1342 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1343 E = Cleanups->getSubExpr();
1345 return isa<MaterializeTemporaryExpr>(E);
1348 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
1349 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1350 return cast<VarDecl>(MSI->getInstantiatedFrom());
1355 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
1356 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1357 return MSI->getTemplateSpecializationKind();
1359 return TSK_Undeclared;
1362 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
1363 return getASTContext().getInstantiatedFromStaticDataMember(this);
1366 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1367 SourceLocation PointOfInstantiation) {
1368 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
1369 assert(MSI && "Not an instantiated static data member?");
1370 MSI->setTemplateSpecializationKind(TSK);
1371 if (TSK != TSK_ExplicitSpecialization &&
1372 PointOfInstantiation.isValid() &&
1373 MSI->getPointOfInstantiation().isInvalid())
1374 MSI->setPointOfInstantiation(PointOfInstantiation);
1377 //===----------------------------------------------------------------------===//
1378 // ParmVarDecl Implementation
1379 //===----------------------------------------------------------------------===//
1381 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
1382 SourceLocation StartLoc,
1383 SourceLocation IdLoc, IdentifierInfo *Id,
1384 QualType T, TypeSourceInfo *TInfo,
1385 StorageClass S, StorageClass SCAsWritten,
1387 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
1388 S, SCAsWritten, DefArg);
1391 Expr *ParmVarDecl::getDefaultArg() {
1392 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1393 assert(!hasUninstantiatedDefaultArg() &&
1394 "Default argument is not yet instantiated!");
1396 Expr *Arg = getInit();
1397 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
1398 return E->getSubExpr();
1403 unsigned ParmVarDecl::getNumDefaultArgTemporaries() const {
1404 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(getInit()))
1405 return E->getNumTemporaries();
1410 CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) {
1411 assert(getNumDefaultArgTemporaries() &&
1412 "Default arguments does not have any temporaries!");
1414 ExprWithCleanups *E = cast<ExprWithCleanups>(getInit());
1415 return E->getTemporary(i);
1418 SourceRange ParmVarDecl::getDefaultArgRange() const {
1419 if (const Expr *E = getInit())
1420 return E->getSourceRange();
1422 if (hasUninstantiatedDefaultArg())
1423 return getUninstantiatedDefaultArg()->getSourceRange();
1425 return SourceRange();
1428 bool ParmVarDecl::isParameterPack() const {
1429 return isa<PackExpansionType>(getType());
1432 //===----------------------------------------------------------------------===//
1433 // FunctionDecl Implementation
1434 //===----------------------------------------------------------------------===//
1436 void FunctionDecl::getNameForDiagnostic(std::string &S,
1437 const PrintingPolicy &Policy,
1438 bool Qualified) const {
1439 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1440 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1442 S += TemplateSpecializationType::PrintTemplateArgumentList(
1443 TemplateArgs->data(),
1444 TemplateArgs->size(),
1449 bool FunctionDecl::isVariadic() const {
1450 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1451 return FT->isVariadic();
1455 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1456 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1457 if (I->Body || I->IsLateTemplateParsed) {
1466 bool FunctionDecl::hasTrivialBody() const
1468 Stmt *S = getBody();
1470 // Since we don't have a body for this function, we don't know if it's
1475 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1480 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1481 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1482 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
1483 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1491 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
1492 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1495 return I->Body.get(getASTContext().getExternalSource());
1496 } else if (I->IsLateTemplateParsed) {
1505 void FunctionDecl::setBody(Stmt *B) {
1508 EndRangeLoc = B->getLocEnd();
1511 void FunctionDecl::setPure(bool P) {
1514 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1515 Parent->markedVirtualFunctionPure();
1518 bool FunctionDecl::isMain() const {
1519 const TranslationUnitDecl *tunit =
1520 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1522 !tunit->getASTContext().getLangOptions().Freestanding &&
1524 getIdentifier()->isStr("main");
1527 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1528 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1529 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1530 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1531 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1532 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1534 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1535 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1537 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1538 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1540 ASTContext &Context =
1541 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1544 // The result type and first argument type are constant across all
1545 // these operators. The second argument must be exactly void*.
1546 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
1549 bool FunctionDecl::isExternC() const {
1550 ASTContext &Context = getASTContext();
1551 // In C, any non-static, non-overloadable function has external
1553 if (!Context.getLangOptions().CPlusPlus)
1554 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>();
1556 const DeclContext *DC = getDeclContext();
1560 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
1561 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1562 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
1563 return getStorageClass() != SC_Static &&
1564 !getAttr<OverloadableAttr>();
1573 bool FunctionDecl::isGlobal() const {
1574 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1575 return Method->isStatic();
1577 if (getStorageClass() == SC_Static)
1580 for (const DeclContext *DC = getDeclContext();
1582 DC = DC->getParent()) {
1583 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1584 if (!Namespace->getDeclName())
1594 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1595 redeclarable_base::setPreviousDeclaration(PrevDecl);
1597 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1598 FunctionTemplateDecl *PrevFunTmpl
1599 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1600 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1601 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1604 if (PrevDecl->IsInline)
1608 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1609 return getFirstDeclaration();
1612 FunctionDecl *FunctionDecl::getCanonicalDecl() {
1613 return getFirstDeclaration();
1616 void FunctionDecl::setStorageClass(StorageClass SC) {
1617 assert(isLegalForFunction(SC));
1618 if (getStorageClass() != SC)
1619 ClearLinkageCache();
1624 /// \brief Returns a value indicating whether this function
1625 /// corresponds to a builtin function.
1627 /// The function corresponds to a built-in function if it is
1628 /// declared at translation scope or within an extern "C" block and
1629 /// its name matches with the name of a builtin. The returned value
1630 /// will be 0 for functions that do not correspond to a builtin, a
1631 /// value of type \c Builtin::ID if in the target-independent range
1632 /// \c [1,Builtin::First), or a target-specific builtin value.
1633 unsigned FunctionDecl::getBuiltinID() const {
1634 ASTContext &Context = getASTContext();
1635 if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1638 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1639 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1642 // This function has the name of a known C library
1643 // function. Determine whether it actually refers to the C library
1644 // function or whether it just has the same name.
1646 // If this is a static function, it's not a builtin.
1647 if (getStorageClass() == SC_Static)
1650 // If this function is at translation-unit scope and we're not in
1651 // C++, it refers to the C library function.
1652 if (!Context.getLangOptions().CPlusPlus &&
1653 getDeclContext()->isTranslationUnit())
1656 // If the function is in an extern "C" linkage specification and is
1657 // not marked "overloadable", it's the real function.
1658 if (isa<LinkageSpecDecl>(getDeclContext()) &&
1659 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
1660 == LinkageSpecDecl::lang_c &&
1661 !getAttr<OverloadableAttr>())
1669 /// getNumParams - Return the number of parameters this function must have
1670 /// based on its FunctionType. This is the length of the ParamInfo array
1671 /// after it has been created.
1672 unsigned FunctionDecl::getNumParams() const {
1673 const FunctionType *FT = getType()->getAs<FunctionType>();
1674 if (isa<FunctionNoProtoType>(FT))
1676 return cast<FunctionProtoType>(FT)->getNumArgs();
1680 void FunctionDecl::setParams(ASTContext &C,
1681 ParmVarDecl **NewParamInfo, unsigned NumParams) {
1682 assert(ParamInfo == 0 && "Already has param info!");
1683 assert(NumParams == getNumParams() && "Parameter count mismatch!");
1685 // Zero params -> null pointer.
1687 void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams);
1688 ParamInfo = new (Mem) ParmVarDecl*[NumParams];
1689 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
1691 // Update source range. The check below allows us to set EndRangeLoc before
1692 // setting the parameters.
1693 if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation())
1694 EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd();
1698 /// getMinRequiredArguments - Returns the minimum number of arguments
1699 /// needed to call this function. This may be fewer than the number of
1700 /// function parameters, if some of the parameters have default
1701 /// arguments (in C++) or the last parameter is a parameter pack.
1702 unsigned FunctionDecl::getMinRequiredArguments() const {
1703 if (!getASTContext().getLangOptions().CPlusPlus)
1704 return getNumParams();
1706 unsigned NumRequiredArgs = getNumParams();
1708 // If the last parameter is a parameter pack, we don't need an argument for
1710 if (NumRequiredArgs > 0 &&
1711 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1714 // If this parameter has a default argument, we don't need an argument for
1716 while (NumRequiredArgs > 0 &&
1717 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
1720 // We might have parameter packs before the end. These can't be deduced,
1721 // but they can still handle multiple arguments.
1722 unsigned ArgIdx = NumRequiredArgs;
1723 while (ArgIdx > 0) {
1724 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1725 NumRequiredArgs = ArgIdx;
1730 return NumRequiredArgs;
1733 bool FunctionDecl::isInlined() const {
1737 if (isa<CXXMethodDecl>(this)) {
1738 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1742 switch (getTemplateSpecializationKind()) {
1743 case TSK_Undeclared:
1744 case TSK_ExplicitSpecialization:
1747 case TSK_ImplicitInstantiation:
1748 case TSK_ExplicitInstantiationDeclaration:
1749 case TSK_ExplicitInstantiationDefinition:
1754 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1755 bool HasPattern = false;
1757 HasPattern = PatternDecl->hasBody(PatternDecl);
1759 if (HasPattern && PatternDecl)
1760 return PatternDecl->isInlined();
1765 /// \brief For an inline function definition in C or C++, determine whether the
1766 /// definition will be externally visible.
1768 /// Inline function definitions are always available for inlining optimizations.
1769 /// However, depending on the language dialect, declaration specifiers, and
1770 /// attributes, the definition of an inline function may or may not be
1771 /// "externally" visible to other translation units in the program.
1773 /// In C99, inline definitions are not externally visible by default. However,
1774 /// if even one of the global-scope declarations is marked "extern inline", the
1775 /// inline definition becomes externally visible (C99 6.7.4p6).
1777 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1778 /// definition, we use the GNU semantics for inline, which are nearly the
1779 /// opposite of C99 semantics. In particular, "inline" by itself will create
1780 /// an externally visible symbol, but "extern inline" will not create an
1781 /// externally visible symbol.
1782 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
1783 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
1784 assert(isInlined() && "Function must be inline");
1785 ASTContext &Context = getASTContext();
1787 if (Context.getLangOptions().GNUInline || hasAttr<GNUInlineAttr>()) {
1788 // If it's not the case that both 'inline' and 'extern' are
1789 // specified on the definition, then this inline definition is
1790 // externally visible.
1791 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
1794 // If any declaration is 'inline' but not 'extern', then this definition
1795 // is externally visible.
1796 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1797 Redecl != RedeclEnd;
1799 if (Redecl->isInlineSpecified() &&
1800 Redecl->getStorageClassAsWritten() != SC_Extern)
1808 // [...] If all of the file scope declarations for a function in a
1809 // translation unit include the inline function specifier without extern,
1810 // then the definition in that translation unit is an inline definition.
1811 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1812 Redecl != RedeclEnd;
1814 // Only consider file-scope declarations in this test.
1815 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1818 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
1819 return true; // Not an inline definition
1823 // An inline definition does not provide an external definition for the
1824 // function, and does not forbid an external definition in another
1825 // translation unit.
1829 /// getOverloadedOperator - Which C++ overloaded operator this
1830 /// function represents, if any.
1831 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
1832 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1833 return getDeclName().getCXXOverloadedOperator();
1838 /// getLiteralIdentifier - The literal suffix identifier this function
1839 /// represents, if any.
1840 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
1841 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
1842 return getDeclName().getCXXLiteralIdentifier();
1847 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
1848 if (TemplateOrSpecialization.isNull())
1849 return TK_NonTemplate;
1850 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
1851 return TK_FunctionTemplate;
1852 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
1853 return TK_MemberSpecialization;
1854 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
1855 return TK_FunctionTemplateSpecialization;
1856 if (TemplateOrSpecialization.is
1857 <DependentFunctionTemplateSpecializationInfo*>())
1858 return TK_DependentFunctionTemplateSpecialization;
1860 assert(false && "Did we miss a TemplateOrSpecialization type?");
1861 return TK_NonTemplate;
1864 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
1865 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
1866 return cast<FunctionDecl>(Info->getInstantiatedFrom());
1871 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
1872 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1876 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
1878 TemplateSpecializationKind TSK) {
1879 assert(TemplateOrSpecialization.isNull() &&
1880 "Member function is already a specialization");
1881 MemberSpecializationInfo *Info
1882 = new (C) MemberSpecializationInfo(FD, TSK);
1883 TemplateOrSpecialization = Info;
1886 bool FunctionDecl::isImplicitlyInstantiable() const {
1887 // If the function is invalid, it can't be implicitly instantiated.
1888 if (isInvalidDecl())
1891 switch (getTemplateSpecializationKind()) {
1892 case TSK_Undeclared:
1893 case TSK_ExplicitSpecialization:
1894 case TSK_ExplicitInstantiationDefinition:
1897 case TSK_ImplicitInstantiation:
1900 case TSK_ExplicitInstantiationDeclaration:
1905 // Find the actual template from which we will instantiate.
1906 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1907 bool HasPattern = false;
1909 HasPattern = PatternDecl->hasBody(PatternDecl);
1911 // C++0x [temp.explicit]p9:
1912 // Except for inline functions, other explicit instantiation declarations
1913 // have the effect of suppressing the implicit instantiation of the entity
1914 // to which they refer.
1915 if (!HasPattern || !PatternDecl)
1918 return PatternDecl->isInlined();
1921 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
1922 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
1923 while (Primary->getInstantiatedFromMemberTemplate()) {
1924 // If we have hit a point where the user provided a specialization of
1925 // this template, we're done looking.
1926 if (Primary->isMemberSpecialization())
1929 Primary = Primary->getInstantiatedFromMemberTemplate();
1932 return Primary->getTemplatedDecl();
1935 return getInstantiatedFromMemberFunction();
1938 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
1939 if (FunctionTemplateSpecializationInfo *Info
1940 = TemplateOrSpecialization
1941 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1942 return Info->Template.getPointer();
1947 const TemplateArgumentList *
1948 FunctionDecl::getTemplateSpecializationArgs() const {
1949 if (FunctionTemplateSpecializationInfo *Info
1950 = TemplateOrSpecialization
1951 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1952 return Info->TemplateArguments;
1957 const TemplateArgumentListInfo *
1958 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
1959 if (FunctionTemplateSpecializationInfo *Info
1960 = TemplateOrSpecialization
1961 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1962 return Info->TemplateArgumentsAsWritten;
1968 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
1969 FunctionTemplateDecl *Template,
1970 const TemplateArgumentList *TemplateArgs,
1972 TemplateSpecializationKind TSK,
1973 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1974 SourceLocation PointOfInstantiation) {
1975 assert(TSK != TSK_Undeclared &&
1976 "Must specify the type of function template specialization");
1977 FunctionTemplateSpecializationInfo *Info
1978 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
1980 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
1982 TemplateArgsAsWritten,
1983 PointOfInstantiation);
1984 TemplateOrSpecialization = Info;
1986 // Insert this function template specialization into the set of known
1987 // function template specializations.
1989 Template->addSpecialization(Info, InsertPos);
1991 // Try to insert the new node. If there is an existing node, leave it, the
1992 // set will contain the canonical decls while
1993 // FunctionTemplateDecl::findSpecialization will return
1994 // the most recent redeclarations.
1995 FunctionTemplateSpecializationInfo *Existing
1996 = Template->getSpecializations().GetOrInsertNode(Info);
1998 assert((!Existing || Existing->Function->isCanonicalDecl()) &&
1999 "Set is supposed to only contain canonical decls");
2004 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2005 const UnresolvedSetImpl &Templates,
2006 const TemplateArgumentListInfo &TemplateArgs) {
2007 assert(TemplateOrSpecialization.isNull());
2008 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2009 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2010 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2011 void *Buffer = Context.Allocate(Size);
2012 DependentFunctionTemplateSpecializationInfo *Info =
2013 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2015 TemplateOrSpecialization = Info;
2018 DependentFunctionTemplateSpecializationInfo::
2019 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2020 const TemplateArgumentListInfo &TArgs)
2021 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2023 d.NumTemplates = Ts.size();
2024 d.NumArgs = TArgs.size();
2026 FunctionTemplateDecl **TsArray =
2027 const_cast<FunctionTemplateDecl**>(getTemplates());
2028 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2029 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2031 TemplateArgumentLoc *ArgsArray =
2032 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2033 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2034 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2037 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2038 // For a function template specialization, query the specialization
2039 // information object.
2040 FunctionTemplateSpecializationInfo *FTSInfo
2041 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2043 return FTSInfo->getTemplateSpecializationKind();
2045 MemberSpecializationInfo *MSInfo
2046 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2048 return MSInfo->getTemplateSpecializationKind();
2050 return TSK_Undeclared;
2054 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2055 SourceLocation PointOfInstantiation) {
2056 if (FunctionTemplateSpecializationInfo *FTSInfo
2057 = TemplateOrSpecialization.dyn_cast<
2058 FunctionTemplateSpecializationInfo*>()) {
2059 FTSInfo->setTemplateSpecializationKind(TSK);
2060 if (TSK != TSK_ExplicitSpecialization &&
2061 PointOfInstantiation.isValid() &&
2062 FTSInfo->getPointOfInstantiation().isInvalid())
2063 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2064 } else if (MemberSpecializationInfo *MSInfo
2065 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2066 MSInfo->setTemplateSpecializationKind(TSK);
2067 if (TSK != TSK_ExplicitSpecialization &&
2068 PointOfInstantiation.isValid() &&
2069 MSInfo->getPointOfInstantiation().isInvalid())
2070 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2072 assert(false && "Function cannot have a template specialization kind");
2075 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2076 if (FunctionTemplateSpecializationInfo *FTSInfo
2077 = TemplateOrSpecialization.dyn_cast<
2078 FunctionTemplateSpecializationInfo*>())
2079 return FTSInfo->getPointOfInstantiation();
2080 else if (MemberSpecializationInfo *MSInfo
2081 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2082 return MSInfo->getPointOfInstantiation();
2084 return SourceLocation();
2087 bool FunctionDecl::isOutOfLine() const {
2088 if (Decl::isOutOfLine())
2091 // If this function was instantiated from a member function of a
2092 // class template, check whether that member function was defined out-of-line.
2093 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2094 const FunctionDecl *Definition;
2095 if (FD->hasBody(Definition))
2096 return Definition->isOutOfLine();
2099 // If this function was instantiated from a function template,
2100 // check whether that function template was defined out-of-line.
2101 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2102 const FunctionDecl *Definition;
2103 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2104 return Definition->isOutOfLine();
2110 SourceRange FunctionDecl::getSourceRange() const {
2111 return SourceRange(getOuterLocStart(), EndRangeLoc);
2114 //===----------------------------------------------------------------------===//
2115 // FieldDecl Implementation
2116 //===----------------------------------------------------------------------===//
2118 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
2119 SourceLocation StartLoc, SourceLocation IdLoc,
2120 IdentifierInfo *Id, QualType T,
2121 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2123 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
2124 BW, Mutable, HasInit);
2127 bool FieldDecl::isAnonymousStructOrUnion() const {
2128 if (!isImplicit() || getDeclName())
2131 if (const RecordType *Record = getType()->getAs<RecordType>())
2132 return Record->getDecl()->isAnonymousStructOrUnion();
2137 unsigned FieldDecl::getFieldIndex() const {
2138 if (CachedFieldIndex) return CachedFieldIndex - 1;
2141 const RecordDecl *RD = getParent();
2142 const FieldDecl *LastFD = 0;
2143 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
2145 RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2147 assert(i != e && "failed to find field in parent!");
2152 // Zero-length bitfields following non-bitfield members are ignored.
2153 if (getASTContext().ZeroBitfieldFollowsNonBitfield((*i), LastFD)) {
2163 CachedFieldIndex = index + 1;
2167 SourceRange FieldDecl::getSourceRange() const {
2169 return SourceRange(getInnerLocStart(), getBitWidth()->getLocEnd());
2170 return DeclaratorDecl::getSourceRange();
2173 void FieldDecl::setInClassInitializer(Expr *Init) {
2174 assert(!InitializerOrBitWidth.getPointer() &&
2175 "bit width or initializer already set");
2176 InitializerOrBitWidth.setPointer(Init);
2177 InitializerOrBitWidth.setInt(0);
2180 //===----------------------------------------------------------------------===//
2181 // TagDecl Implementation
2182 //===----------------------------------------------------------------------===//
2184 SourceLocation TagDecl::getOuterLocStart() const {
2185 return getTemplateOrInnerLocStart(this);
2188 SourceRange TagDecl::getSourceRange() const {
2189 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
2190 return SourceRange(getOuterLocStart(), E);
2193 TagDecl* TagDecl::getCanonicalDecl() {
2194 return getFirstDeclaration();
2197 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2198 TypedefNameDeclOrQualifier = TDD;
2200 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2201 ClearLinkageCache();
2204 void TagDecl::startDefinition() {
2205 IsBeingDefined = true;
2207 if (isa<CXXRecordDecl>(this)) {
2208 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2209 struct CXXRecordDecl::DefinitionData *Data =
2210 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
2211 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2212 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
2216 void TagDecl::completeDefinition() {
2217 assert((!isa<CXXRecordDecl>(this) ||
2218 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2219 "definition completed but not started");
2221 IsDefinition = true;
2222 IsBeingDefined = false;
2224 if (ASTMutationListener *L = getASTMutationListener())
2225 L->CompletedTagDefinition(this);
2228 TagDecl* TagDecl::getDefinition() const {
2230 return const_cast<TagDecl *>(this);
2231 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2232 return CXXRD->getDefinition();
2234 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
2236 if (R->isDefinition())
2242 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2244 // Make sure the extended qualifier info is allocated.
2246 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2247 // Set qualifier info.
2248 getExtInfo()->QualifierLoc = QualifierLoc;
2251 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2253 if (getExtInfo()->NumTemplParamLists == 0) {
2254 getASTContext().Deallocate(getExtInfo());
2255 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
2258 getExtInfo()->QualifierLoc = QualifierLoc;
2263 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2264 unsigned NumTPLists,
2265 TemplateParameterList **TPLists) {
2266 assert(NumTPLists > 0);
2267 // Make sure the extended decl info is allocated.
2269 // Allocate external info struct.
2270 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2271 // Set the template parameter lists info.
2272 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2275 //===----------------------------------------------------------------------===//
2276 // EnumDecl Implementation
2277 //===----------------------------------------------------------------------===//
2279 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2280 SourceLocation StartLoc, SourceLocation IdLoc,
2282 EnumDecl *PrevDecl, bool IsScoped,
2283 bool IsScopedUsingClassTag, bool IsFixed) {
2284 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
2285 IsScoped, IsScopedUsingClassTag, IsFixed);
2286 C.getTypeDeclType(Enum, PrevDecl);
2290 EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) {
2291 return new (C) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2292 false, false, false);
2295 void EnumDecl::completeDefinition(QualType NewType,
2296 QualType NewPromotionType,
2297 unsigned NumPositiveBits,
2298 unsigned NumNegativeBits) {
2299 assert(!isDefinition() && "Cannot redefine enums!");
2301 IntegerType = NewType.getTypePtr();
2302 PromotionType = NewPromotionType;
2303 setNumPositiveBits(NumPositiveBits);
2304 setNumNegativeBits(NumNegativeBits);
2305 TagDecl::completeDefinition();
2308 //===----------------------------------------------------------------------===//
2309 // RecordDecl Implementation
2310 //===----------------------------------------------------------------------===//
2312 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2313 SourceLocation StartLoc, SourceLocation IdLoc,
2314 IdentifierInfo *Id, RecordDecl *PrevDecl)
2315 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
2316 HasFlexibleArrayMember = false;
2317 AnonymousStructOrUnion = false;
2318 HasObjectMember = false;
2319 LoadedFieldsFromExternalStorage = false;
2320 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
2323 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2324 SourceLocation StartLoc, SourceLocation IdLoc,
2325 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2326 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2328 C.getTypeDeclType(R, PrevDecl);
2332 RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) {
2333 return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2334 SourceLocation(), 0, 0);
2337 bool RecordDecl::isInjectedClassName() const {
2338 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
2339 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2342 RecordDecl::field_iterator RecordDecl::field_begin() const {
2343 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2344 LoadFieldsFromExternalStorage();
2346 return field_iterator(decl_iterator(FirstDecl));
2349 /// completeDefinition - Notes that the definition of this type is now
2351 void RecordDecl::completeDefinition() {
2352 assert(!isDefinition() && "Cannot redefine record!");
2353 TagDecl::completeDefinition();
2356 void RecordDecl::LoadFieldsFromExternalStorage() const {
2357 ExternalASTSource *Source = getASTContext().getExternalSource();
2358 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2360 // Notify that we have a RecordDecl doing some initialization.
2361 ExternalASTSource::Deserializing TheFields(Source);
2363 llvm::SmallVector<Decl*, 64> Decls;
2364 LoadedFieldsFromExternalStorage = true;
2365 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2369 case ELR_AlreadyLoaded:
2375 // Check that all decls we got were FieldDecls.
2376 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2377 assert(isa<FieldDecl>(Decls[i]));
2383 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls);
2386 //===----------------------------------------------------------------------===//
2387 // BlockDecl Implementation
2388 //===----------------------------------------------------------------------===//
2390 void BlockDecl::setParams(ParmVarDecl **NewParamInfo,
2392 assert(ParamInfo == 0 && "Already has param info!");
2394 // Zero params -> null pointer.
2397 void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams);
2398 ParamInfo = new (Mem) ParmVarDecl*[NumParams];
2399 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
2403 void BlockDecl::setCaptures(ASTContext &Context,
2404 const Capture *begin,
2406 bool capturesCXXThis) {
2407 CapturesCXXThis = capturesCXXThis;
2415 NumCaptures = end - begin;
2417 // Avoid new Capture[] because we don't want to provide a default
2419 size_t allocationSize = NumCaptures * sizeof(Capture);
2420 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2421 memcpy(buffer, begin, allocationSize);
2422 Captures = static_cast<Capture*>(buffer);
2425 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2426 for (capture_const_iterator
2427 i = capture_begin(), e = capture_end(); i != e; ++i)
2428 // Only auto vars can be captured, so no redeclaration worries.
2429 if (i->getVariable() == variable)
2435 SourceRange BlockDecl::getSourceRange() const {
2436 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2439 //===----------------------------------------------------------------------===//
2440 // Other Decl Allocation/Deallocation Method Implementations
2441 //===----------------------------------------------------------------------===//
2443 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2444 return new (C) TranslationUnitDecl(C);
2447 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2448 SourceLocation IdentL, IdentifierInfo *II) {
2449 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2452 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2453 SourceLocation IdentL, IdentifierInfo *II,
2454 SourceLocation GnuLabelL) {
2455 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2456 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
2460 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
2461 SourceLocation StartLoc,
2462 SourceLocation IdLoc, IdentifierInfo *Id) {
2463 return new (C) NamespaceDecl(DC, StartLoc, IdLoc, Id);
2466 NamespaceDecl *NamespaceDecl::getNextNamespace() {
2467 return dyn_cast_or_null<NamespaceDecl>(
2468 NextNamespace.get(getASTContext().getExternalSource()));
2471 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
2472 SourceLocation IdLoc,
2475 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
2478 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
2479 SourceLocation StartLoc,
2480 const DeclarationNameInfo &NameInfo,
2481 QualType T, TypeSourceInfo *TInfo,
2482 StorageClass SC, StorageClass SCAsWritten,
2483 bool isInlineSpecified,
2484 bool hasWrittenPrototype) {
2485 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2486 T, TInfo, SC, SCAsWritten,
2488 New->HasWrittenPrototype = hasWrittenPrototype;
2492 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2493 return new (C) BlockDecl(DC, L);
2496 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2498 IdentifierInfo *Id, QualType T,
2499 Expr *E, const llvm::APSInt &V) {
2500 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2504 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2505 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2507 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2510 SourceRange EnumConstantDecl::getSourceRange() const {
2511 SourceLocation End = getLocation();
2513 End = Init->getLocEnd();
2514 return SourceRange(getLocation(), End);
2517 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
2518 SourceLocation StartLoc, SourceLocation IdLoc,
2519 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2520 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
2523 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2524 SourceLocation StartLoc,
2525 SourceLocation IdLoc, IdentifierInfo *Id,
2526 TypeSourceInfo *TInfo) {
2527 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2530 SourceRange TypedefDecl::getSourceRange() const {
2531 SourceLocation RangeEnd = getLocation();
2532 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2533 if (typeIsPostfix(TInfo->getType()))
2534 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2536 return SourceRange(getLocStart(), RangeEnd);
2539 SourceRange TypeAliasDecl::getSourceRange() const {
2540 SourceLocation RangeEnd = getLocStart();
2541 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2542 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2543 return SourceRange(getLocStart(), RangeEnd);
2546 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
2548 SourceLocation AsmLoc,
2549 SourceLocation RParenLoc) {
2550 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);