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"
33 using namespace clang;
35 //===----------------------------------------------------------------------===//
36 // NamedDecl Implementation
37 //===----------------------------------------------------------------------===//
39 static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
40 // If this declaration has an explicit visibility attribute, use it.
41 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
42 switch (A->getVisibility()) {
43 case VisibilityAttr::Default:
44 return DefaultVisibility;
45 case VisibilityAttr::Hidden:
46 return HiddenVisibility;
47 case VisibilityAttr::Protected:
48 return ProtectedVisibility;
51 return DefaultVisibility;
54 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
55 // implies visibility(default).
56 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
57 for (specific_attr_iterator<AvailabilityAttr>
58 A = D->specific_attr_begin<AvailabilityAttr>(),
59 AEnd = D->specific_attr_end<AvailabilityAttr>();
61 if ((*A)->getPlatform()->getName().equals("macosx"))
62 return DefaultVisibility;
65 return llvm::Optional<Visibility>();
68 typedef NamedDecl::LinkageInfo LinkageInfo;
69 typedef std::pair<Linkage,Visibility> LVPair;
71 static LVPair merge(LVPair L, LVPair R) {
72 return LVPair(minLinkage(L.first, R.first),
73 minVisibility(L.second, R.second));
76 static LVPair merge(LVPair L, LinkageInfo R) {
77 return LVPair(minLinkage(L.first, R.linkage()),
78 minVisibility(L.second, R.visibility()));
82 /// Flags controlling the computation of linkage and visibility.
84 bool ConsiderGlobalVisibility;
85 bool ConsiderVisibilityAttributes;
86 bool ConsiderTemplateParameterTypes;
88 LVFlags() : ConsiderGlobalVisibility(true),
89 ConsiderVisibilityAttributes(true),
90 ConsiderTemplateParameterTypes(true) {
93 /// \brief Returns a set of flags that is only useful for computing the
94 /// linkage, not the visibility, of a declaration.
95 static LVFlags CreateOnlyDeclLinkage() {
97 F.ConsiderGlobalVisibility = false;
98 F.ConsiderVisibilityAttributes = false;
99 F.ConsiderTemplateParameterTypes = false;
103 /// Returns a set of flags, otherwise based on these, which ignores
104 /// off all sources of visibility except template arguments.
105 LVFlags onlyTemplateVisibility() const {
107 F.ConsiderGlobalVisibility = false;
108 F.ConsiderVisibilityAttributes = false;
109 F.ConsiderTemplateParameterTypes = false;
113 } // end anonymous namespace
115 /// \brief Get the most restrictive linkage for the types in the given
116 /// template parameter list.
118 getLVForTemplateParameterList(const TemplateParameterList *Params) {
119 LVPair LV(ExternalLinkage, DefaultVisibility);
120 for (TemplateParameterList::const_iterator P = Params->begin(),
121 PEnd = Params->end();
123 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
124 if (NTTP->isExpandedParameterPack()) {
125 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
126 QualType T = NTTP->getExpansionType(I);
127 if (!T->isDependentType())
128 LV = merge(LV, T->getLinkageAndVisibility());
133 if (!NTTP->getType()->isDependentType()) {
134 LV = merge(LV, NTTP->getType()->getLinkageAndVisibility());
139 if (TemplateTemplateParmDecl *TTP
140 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
141 LV = merge(LV, getLVForTemplateParameterList(TTP->getTemplateParameters()));
148 /// getLVForDecl - Get the linkage and visibility for the given declaration.
149 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
151 /// \brief Get the most restrictive linkage for the types and
152 /// declarations in the given template argument list.
153 static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args,
156 LVPair LV(ExternalLinkage, DefaultVisibility);
158 for (unsigned I = 0; I != NumArgs; ++I) {
159 switch (Args[I].getKind()) {
160 case TemplateArgument::Null:
161 case TemplateArgument::Integral:
162 case TemplateArgument::Expression:
165 case TemplateArgument::Type:
166 LV = merge(LV, Args[I].getAsType()->getLinkageAndVisibility());
169 case TemplateArgument::Declaration:
170 // The decl can validly be null as the representation of nullptr
171 // arguments, valid only in C++0x.
172 if (Decl *D = Args[I].getAsDecl()) {
173 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
174 LV = merge(LV, getLVForDecl(ND, F));
178 case TemplateArgument::Template:
179 case TemplateArgument::TemplateExpansion:
180 if (TemplateDecl *Template
181 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
182 LV = merge(LV, getLVForDecl(Template, F));
185 case TemplateArgument::Pack:
186 LV = merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(),
197 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
199 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
202 static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
203 const FunctionTemplateSpecializationInfo *spec) {
204 return !(spec->isExplicitSpecialization() &&
205 fn->hasAttr<VisibilityAttr>());
208 static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
209 return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
212 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
213 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
214 "Not a name having namespace scope");
215 ASTContext &Context = D->getASTContext();
217 // C++ [basic.link]p3:
218 // A name having namespace scope (3.3.6) has internal linkage if it
220 // - an object, reference, function or function template that is
221 // explicitly declared static; or,
222 // (This bullet corresponds to C99 6.2.2p3.)
223 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
224 // Explicitly declared static.
225 if (Var->getStorageClass() == SC_Static)
226 return LinkageInfo::internal();
228 // - an object or reference that is explicitly declared const
229 // and neither explicitly declared extern nor previously
230 // declared to have external linkage; or
231 // (there is no equivalent in C99)
232 if (Context.getLangOptions().CPlusPlus &&
233 Var->getType().isConstant(Context) &&
234 Var->getStorageClass() != SC_Extern &&
235 Var->getStorageClass() != SC_PrivateExtern) {
236 bool FoundExtern = false;
237 for (const VarDecl *PrevVar = Var->getPreviousDeclaration();
238 PrevVar && !FoundExtern;
239 PrevVar = PrevVar->getPreviousDeclaration())
240 if (isExternalLinkage(PrevVar->getLinkage()))
244 return LinkageInfo::internal();
246 if (Var->getStorageClass() == SC_None) {
247 const VarDecl *PrevVar = Var->getPreviousDeclaration();
248 for (; PrevVar; PrevVar = PrevVar->getPreviousDeclaration())
249 if (PrevVar->getStorageClass() == SC_PrivateExtern)
252 return PrevVar->getLinkageAndVisibility();
254 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
256 // A non-member function template can have internal linkage; any
257 // other template name shall have external linkage.
258 const FunctionDecl *Function = 0;
259 if (const FunctionTemplateDecl *FunTmpl
260 = dyn_cast<FunctionTemplateDecl>(D))
261 Function = FunTmpl->getTemplatedDecl();
263 Function = cast<FunctionDecl>(D);
265 // Explicitly declared static.
266 if (Function->getStorageClass() == SC_Static)
267 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
268 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
269 // - a data member of an anonymous union.
270 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
271 return LinkageInfo::internal();
274 if (D->isInAnonymousNamespace()) {
275 const VarDecl *Var = dyn_cast<VarDecl>(D);
276 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
277 if ((!Var || !Var->isExternC()) && (!Func || !Func->isExternC()))
278 return LinkageInfo::uniqueExternal();
281 // Set up the defaults.
284 // If the declaration of an identifier for an object has file
285 // scope and no storage-class specifier, its linkage is
289 if (F.ConsiderVisibilityAttributes) {
290 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
291 LV.setVisibility(*Vis, true);
292 F.ConsiderGlobalVisibility = false;
294 // If we're declared in a namespace with a visibility attribute,
295 // use that namespace's visibility, but don't call it explicit.
296 for (const DeclContext *DC = D->getDeclContext();
297 !isa<TranslationUnitDecl>(DC);
298 DC = DC->getParent()) {
299 if (!isa<NamespaceDecl>(DC)) continue;
300 if (llvm::Optional<Visibility> Vis
301 = cast<NamespaceDecl>(DC)->getExplicitVisibility()) {
302 LV.setVisibility(*Vis, false);
303 F.ConsiderGlobalVisibility = false;
310 // C++ [basic.link]p4:
312 // A name having namespace scope has external linkage if it is the
315 // - an object or reference, unless it has internal linkage; or
316 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
317 // GCC applies the following optimization to variables and static
318 // data members, but not to functions:
320 // Modify the variable's LV by the LV of its type unless this is
321 // C or extern "C". This follows from [basic.link]p9:
322 // A type without linkage shall not be used as the type of a
323 // variable or function with external linkage unless
324 // - the entity has C language linkage, or
325 // - the entity is declared within an unnamed namespace, or
326 // - the entity is not used or is defined in the same
328 // and [basic.link]p10:
329 // ...the types specified by all declarations referring to a
330 // given variable or function shall be identical...
331 // C does not have an equivalent rule.
333 // Ignore this if we've got an explicit attribute; the user
334 // probably knows what they're doing.
336 // Note that we don't want to make the variable non-external
337 // because of this, but unique-external linkage suits us.
338 if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) {
339 LVPair TypeLV = Var->getType()->getLinkageAndVisibility();
340 if (TypeLV.first != ExternalLinkage)
341 return LinkageInfo::uniqueExternal();
342 if (!LV.visibilityExplicit())
343 LV.mergeVisibility(TypeLV.second);
346 if (Var->getStorageClass() == SC_PrivateExtern)
347 LV.setVisibility(HiddenVisibility, true);
349 if (!Context.getLangOptions().CPlusPlus &&
350 (Var->getStorageClass() == SC_Extern ||
351 Var->getStorageClass() == SC_PrivateExtern)) {
354 // For an identifier declared with the storage-class specifier
355 // extern in a scope in which a prior declaration of that
356 // identifier is visible, if the prior declaration specifies
357 // internal or external linkage, the linkage of the identifier
358 // at the later declaration is the same as the linkage
359 // specified at the prior declaration. If no prior declaration
360 // is visible, or if the prior declaration specifies no
361 // linkage, then the identifier has external linkage.
362 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) {
363 LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
364 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
365 LV.mergeVisibility(PrevLV);
369 // - a function, unless it has internal linkage; or
370 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
371 // In theory, we can modify the function's LV by the LV of its
372 // type unless it has C linkage (see comment above about variables
373 // for justification). In practice, GCC doesn't do this, so it's
374 // just too painful to make work.
376 if (Function->getStorageClass() == SC_PrivateExtern)
377 LV.setVisibility(HiddenVisibility, true);
380 // If the declaration of an identifier for a function has no
381 // storage-class specifier, its linkage is determined exactly
382 // as if it were declared with the storage-class specifier
384 if (!Context.getLangOptions().CPlusPlus &&
385 (Function->getStorageClass() == SC_Extern ||
386 Function->getStorageClass() == SC_PrivateExtern ||
387 Function->getStorageClass() == SC_None)) {
389 // For an identifier declared with the storage-class specifier
390 // extern in a scope in which a prior declaration of that
391 // identifier is visible, if the prior declaration specifies
392 // internal or external linkage, the linkage of the identifier
393 // at the later declaration is the same as the linkage
394 // specified at the prior declaration. If no prior declaration
395 // is visible, or if the prior declaration specifies no
396 // linkage, then the identifier has external linkage.
397 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) {
398 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
399 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
400 LV.mergeVisibility(PrevLV);
404 // In C++, then if the type of the function uses a type with
405 // unique-external linkage, it's not legally usable from outside
406 // this translation unit. However, we should use the C linkage
407 // rules instead for extern "C" declarations.
408 if (Context.getLangOptions().CPlusPlus && !Function->isExternC() &&
409 Function->getType()->getLinkage() == UniqueExternalLinkage)
410 return LinkageInfo::uniqueExternal();
412 // Consider LV from the template and the template arguments unless
413 // this is an explicit specialization with a visibility attribute.
414 if (FunctionTemplateSpecializationInfo *specInfo
415 = Function->getTemplateSpecializationInfo()) {
416 if (shouldConsiderTemplateLV(Function, specInfo)) {
417 LV.merge(getLVForDecl(specInfo->getTemplate(),
418 F.onlyTemplateVisibility()));
419 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
420 LV.merge(getLVForTemplateArgumentList(templateArgs, F));
424 // - a named class (Clause 9), or an unnamed class defined in a
425 // typedef declaration in which the class has the typedef name
426 // for linkage purposes (7.1.3); or
427 // - a named enumeration (7.2), or an unnamed enumeration
428 // defined in a typedef declaration in which the enumeration
429 // has the typedef name for linkage purposes (7.1.3); or
430 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
431 // Unnamed tags have no linkage.
432 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
433 return LinkageInfo::none();
435 // If this is a class template specialization, consider the
436 // linkage of the template and template arguments.
437 if (const ClassTemplateSpecializationDecl *spec
438 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
439 if (shouldConsiderTemplateLV(spec)) {
440 // From the template.
441 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
442 F.onlyTemplateVisibility()));
444 // The arguments at which the template was instantiated.
445 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
446 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
450 // Consider -fvisibility unless the type has C linkage.
451 if (F.ConsiderGlobalVisibility)
452 F.ConsiderGlobalVisibility =
453 (Context.getLangOptions().CPlusPlus &&
454 !Tag->getDeclContext()->isExternCContext());
456 // - an enumerator belonging to an enumeration with external linkage;
457 } else if (isa<EnumConstantDecl>(D)) {
458 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
459 if (!isExternalLinkage(EnumLV.linkage()))
460 return LinkageInfo::none();
463 // - a template, unless it is a function template that has
464 // internal linkage (Clause 14);
465 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
466 if (F.ConsiderTemplateParameterTypes)
467 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
469 // - a namespace (7.3), unless it is declared within an unnamed
471 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
474 // By extension, we assign external linkage to Objective-C
476 } else if (isa<ObjCInterfaceDecl>(D)) {
479 // Everything not covered here has no linkage.
481 return LinkageInfo::none();
484 // If we ended up with non-external linkage, visibility should
485 // always be default.
486 if (LV.linkage() != ExternalLinkage)
487 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
489 // If we didn't end up with hidden visibility, consider attributes
491 if (F.ConsiderGlobalVisibility)
492 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
497 static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
498 // Only certain class members have linkage. Note that fields don't
499 // really have linkage, but it's convenient to say they do for the
500 // purposes of calculating linkage of pointer-to-data-member
501 // template arguments.
502 if (!(isa<CXXMethodDecl>(D) ||
506 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
507 return LinkageInfo::none();
511 // The flags we're going to use to compute the class's visibility.
514 // If we have an explicit visibility attribute, merge that in.
515 if (F.ConsiderVisibilityAttributes) {
516 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
517 LV.mergeVisibility(*Vis, true);
519 // Ignore global visibility later, but not this attribute.
520 F.ConsiderGlobalVisibility = false;
522 // Ignore both global visibility and attributes when computing our
523 // parent's visibility.
524 ClassF = F.onlyTemplateVisibility();
528 // Class members only have linkage if their class has external
530 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
531 if (!isExternalLinkage(LV.linkage()))
532 return LinkageInfo::none();
534 // If the class already has unique-external linkage, we can't improve.
535 if (LV.linkage() == UniqueExternalLinkage)
536 return LinkageInfo::uniqueExternal();
538 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
539 // If the type of the function uses a type with unique-external
540 // linkage, it's not legally usable from outside this translation unit.
541 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
542 return LinkageInfo::uniqueExternal();
544 TemplateSpecializationKind TSK = TSK_Undeclared;
546 // If this is a method template specialization, use the linkage for
547 // the template parameters and arguments.
548 if (FunctionTemplateSpecializationInfo *spec
549 = MD->getTemplateSpecializationInfo()) {
550 if (shouldConsiderTemplateLV(MD, spec)) {
551 LV.merge(getLVForTemplateArgumentList(*spec->TemplateArguments, F));
552 if (F.ConsiderTemplateParameterTypes)
553 LV.merge(getLVForTemplateParameterList(
554 spec->getTemplate()->getTemplateParameters()));
557 TSK = spec->getTemplateSpecializationKind();
558 } else if (MemberSpecializationInfo *MSI =
559 MD->getMemberSpecializationInfo()) {
560 TSK = MSI->getTemplateSpecializationKind();
563 // If we're paying attention to global visibility, apply
564 // -finline-visibility-hidden if this is an inline method.
566 // Note that ConsiderGlobalVisibility doesn't yet have information
567 // about whether containing classes have visibility attributes,
568 // and that's intentional.
569 if (TSK != TSK_ExplicitInstantiationDeclaration &&
570 F.ConsiderGlobalVisibility &&
571 MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
572 // InlineVisibilityHidden only applies to definitions, and
573 // isInlined() only gives meaningful answers on definitions
575 const FunctionDecl *Def = 0;
576 if (MD->hasBody(Def) && Def->isInlined())
577 LV.setVisibility(HiddenVisibility);
580 // Note that in contrast to basically every other situation, we
581 // *do* apply -fvisibility to method declarations.
583 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
584 if (const ClassTemplateSpecializationDecl *spec
585 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
586 if (shouldConsiderTemplateLV(spec)) {
587 // Merge template argument/parameter information for member
588 // class template specializations.
589 LV.merge(getLVForTemplateArgumentList(spec->getTemplateArgs(), F));
590 if (F.ConsiderTemplateParameterTypes)
591 LV.merge(getLVForTemplateParameterList(
592 spec->getSpecializedTemplate()->getTemplateParameters()));
596 // Static data members.
597 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
598 // Modify the variable's linkage by its type, but ignore the
599 // type's visibility unless it's a definition.
600 LVPair TypeLV = VD->getType()->getLinkageAndVisibility();
601 if (TypeLV.first != ExternalLinkage)
602 LV.mergeLinkage(UniqueExternalLinkage);
603 if (!LV.visibilityExplicit())
604 LV.mergeVisibility(TypeLV.second);
607 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
609 // Apply -fvisibility if desired.
610 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
611 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
617 static void clearLinkageForClass(const CXXRecordDecl *record) {
618 for (CXXRecordDecl::decl_iterator
619 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
621 if (isa<NamedDecl>(child))
622 cast<NamedDecl>(child)->ClearLinkageCache();
626 void NamedDecl::ClearLinkageCache() {
627 // Note that we can't skip clearing the linkage of children just
628 // because the parent doesn't have cached linkage: we don't cache
629 // when computing linkage for parent contexts.
631 HasCachedLinkage = 0;
633 // If we're changing the linkage of a class, we need to reset the
634 // linkage of child declarations, too.
635 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
636 clearLinkageForClass(record);
638 if (ClassTemplateDecl *temp =
639 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
640 // Clear linkage for the template pattern.
641 CXXRecordDecl *record = temp->getTemplatedDecl();
642 record->HasCachedLinkage = 0;
643 clearLinkageForClass(record);
645 // We need to clear linkage for specializations, too.
646 for (ClassTemplateDecl::spec_iterator
647 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
648 i->ClearLinkageCache();
651 // Clear cached linkage for function template decls, too.
652 if (FunctionTemplateDecl *temp =
653 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
654 temp->getTemplatedDecl()->ClearLinkageCache();
655 for (FunctionTemplateDecl::spec_iterator
656 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
657 i->ClearLinkageCache();
662 Linkage NamedDecl::getLinkage() const {
663 if (HasCachedLinkage) {
664 assert(Linkage(CachedLinkage) ==
665 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
666 return Linkage(CachedLinkage);
669 CachedLinkage = getLVForDecl(this,
670 LVFlags::CreateOnlyDeclLinkage()).linkage();
671 HasCachedLinkage = 1;
672 return Linkage(CachedLinkage);
675 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
676 LinkageInfo LI = getLVForDecl(this, LVFlags());
677 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
678 HasCachedLinkage = 1;
679 CachedLinkage = LI.linkage();
683 llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
684 // Use the most recent declaration of a variable.
685 if (const VarDecl *var = dyn_cast<VarDecl>(this))
686 return getVisibilityOf(var->getMostRecentDeclaration());
688 // Use the most recent declaration of a function, and also handle
689 // function template specializations.
690 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
691 if (llvm::Optional<Visibility> V
692 = getVisibilityOf(fn->getMostRecentDeclaration()))
695 // If the function is a specialization of a template with an
696 // explicit visibility attribute, use that.
697 if (FunctionTemplateSpecializationInfo *templateInfo
698 = fn->getTemplateSpecializationInfo())
699 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
701 return llvm::Optional<Visibility>();
704 // Otherwise, just check the declaration itself first.
705 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
708 // If there wasn't explicit visibility there, and this is a
709 // specialization of a class template, check for visibility
711 if (const ClassTemplateSpecializationDecl *spec
712 = dyn_cast<ClassTemplateSpecializationDecl>(this))
713 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
715 return llvm::Optional<Visibility>();
718 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
719 // Objective-C: treat all Objective-C declarations as having external
721 switch (D->getKind()) {
724 case Decl::TemplateTemplateParm: // count these as external
725 case Decl::NonTypeTemplateParm:
726 case Decl::ObjCAtDefsField:
727 case Decl::ObjCCategory:
728 case Decl::ObjCCategoryImpl:
729 case Decl::ObjCCompatibleAlias:
730 case Decl::ObjCForwardProtocol:
731 case Decl::ObjCImplementation:
732 case Decl::ObjCMethod:
733 case Decl::ObjCProperty:
734 case Decl::ObjCPropertyImpl:
735 case Decl::ObjCProtocol:
736 return LinkageInfo::external();
739 // Handle linkage for namespace-scope names.
740 if (D->getDeclContext()->getRedeclContext()->isFileContext())
741 return getLVForNamespaceScopeDecl(D, Flags);
743 // C++ [basic.link]p5:
744 // In addition, a member function, static data member, a named
745 // class or enumeration of class scope, or an unnamed class or
746 // enumeration defined in a class-scope typedef declaration such
747 // that the class or enumeration has the typedef name for linkage
748 // purposes (7.1.3), has external linkage if the name of the class
749 // has external linkage.
750 if (D->getDeclContext()->isRecord())
751 return getLVForClassMember(D, Flags);
753 // C++ [basic.link]p6:
754 // The name of a function declared in block scope and the name of
755 // an object declared by a block scope extern declaration have
756 // linkage. If there is a visible declaration of an entity with
757 // linkage having the same name and type, ignoring entities
758 // declared outside the innermost enclosing namespace scope, the
759 // block scope declaration declares that same entity and receives
760 // the linkage of the previous declaration. If there is more than
761 // one such matching entity, the program is ill-formed. Otherwise,
762 // if no matching entity is found, the block scope entity receives
764 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
765 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
766 if (Function->isInAnonymousNamespace() && !Function->isExternC())
767 return LinkageInfo::uniqueExternal();
770 if (Flags.ConsiderVisibilityAttributes) {
771 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
772 LV.setVisibility(*Vis);
775 if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) {
776 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
777 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
778 LV.mergeVisibility(PrevLV);
784 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
785 if (Var->getStorageClass() == SC_Extern ||
786 Var->getStorageClass() == SC_PrivateExtern) {
787 if (Var->isInAnonymousNamespace() && !Var->isExternC())
788 return LinkageInfo::uniqueExternal();
791 if (Var->getStorageClass() == SC_PrivateExtern)
792 LV.setVisibility(HiddenVisibility);
793 else if (Flags.ConsiderVisibilityAttributes) {
794 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
795 LV.setVisibility(*Vis);
798 if (const VarDecl *Prev = Var->getPreviousDeclaration()) {
799 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
800 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
801 LV.mergeVisibility(PrevLV);
808 // C++ [basic.link]p6:
809 // Names not covered by these rules have no linkage.
810 return LinkageInfo::none();
813 std::string NamedDecl::getQualifiedNameAsString() const {
814 return getQualifiedNameAsString(getASTContext().getLangOptions());
817 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
818 const DeclContext *Ctx = getDeclContext();
820 if (Ctx->isFunctionOrMethod())
821 return getNameAsString();
823 typedef SmallVector<const DeclContext *, 8> ContextsTy;
827 while (Ctx && isa<NamedDecl>(Ctx)) {
828 Contexts.push_back(Ctx);
829 Ctx = Ctx->getParent();
832 std::string QualName;
833 llvm::raw_string_ostream OS(QualName);
835 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
837 if (const ClassTemplateSpecializationDecl *Spec
838 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
839 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
840 std::string TemplateArgsStr
841 = TemplateSpecializationType::PrintTemplateArgumentList(
845 OS << Spec->getName() << TemplateArgsStr;
846 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
847 if (ND->isAnonymousNamespace())
848 OS << "<anonymous namespace>";
851 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
852 if (!RD->getIdentifier())
853 OS << "<anonymous " << RD->getKindName() << '>';
856 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
857 const FunctionProtoType *FT = 0;
858 if (FD->hasWrittenPrototype())
859 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
863 unsigned NumParams = FD->getNumParams();
864 for (unsigned i = 0; i < NumParams; ++i) {
868 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
872 if (FT->isVariadic()) {
880 OS << *cast<NamedDecl>(*I);
893 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
894 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
896 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
897 // We want to keep it, unless it nominates same namespace.
898 if (getKind() == Decl::UsingDirective) {
899 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
900 ->getOriginalNamespace() ==
901 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
902 ->getOriginalNamespace();
905 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
906 // For function declarations, we keep track of redeclarations.
907 return FD->getPreviousDeclaration() == OldD;
909 // For function templates, the underlying function declarations are linked.
910 if (const FunctionTemplateDecl *FunctionTemplate
911 = dyn_cast<FunctionTemplateDecl>(this))
912 if (const FunctionTemplateDecl *OldFunctionTemplate
913 = dyn_cast<FunctionTemplateDecl>(OldD))
914 return FunctionTemplate->getTemplatedDecl()
915 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
917 // For method declarations, we keep track of redeclarations.
918 if (isa<ObjCMethodDecl>(this))
921 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
924 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
925 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
926 cast<UsingShadowDecl>(OldD)->getTargetDecl();
928 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
929 ASTContext &Context = getASTContext();
930 return Context.getCanonicalNestedNameSpecifier(
931 cast<UsingDecl>(this)->getQualifier()) ==
932 Context.getCanonicalNestedNameSpecifier(
933 cast<UsingDecl>(OldD)->getQualifier());
936 // For non-function declarations, if the declarations are of the
937 // same kind then this must be a redeclaration, or semantic analysis
938 // would not have given us the new declaration.
939 return this->getKind() == OldD->getKind();
942 bool NamedDecl::hasLinkage() const {
943 return getLinkage() != NoLinkage;
946 NamedDecl *NamedDecl::getUnderlyingDecl() {
947 NamedDecl *ND = this;
949 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
950 ND = UD->getTargetDecl();
951 else if (ObjCCompatibleAliasDecl *AD
952 = dyn_cast<ObjCCompatibleAliasDecl>(ND))
953 return AD->getClassInterface();
959 bool NamedDecl::isCXXInstanceMember() const {
960 assert(isCXXClassMember() &&
961 "checking whether non-member is instance member");
963 const NamedDecl *D = this;
964 if (isa<UsingShadowDecl>(D))
965 D = cast<UsingShadowDecl>(D)->getTargetDecl();
967 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
969 if (isa<CXXMethodDecl>(D))
970 return cast<CXXMethodDecl>(D)->isInstance();
971 if (isa<FunctionTemplateDecl>(D))
972 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
973 ->getTemplatedDecl())->isInstance();
977 //===----------------------------------------------------------------------===//
978 // DeclaratorDecl Implementation
979 //===----------------------------------------------------------------------===//
981 template <typename DeclT>
982 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
983 if (decl->getNumTemplateParameterLists() > 0)
984 return decl->getTemplateParameterList(0)->getTemplateLoc();
986 return decl->getInnerLocStart();
989 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
990 TypeSourceInfo *TSI = getTypeSourceInfo();
991 if (TSI) return TSI->getTypeLoc().getBeginLoc();
992 return SourceLocation();
995 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
997 // Make sure the extended decl info is allocated.
999 // Save (non-extended) type source info pointer.
1000 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1001 // Allocate external info struct.
1002 DeclInfo = new (getASTContext()) ExtInfo;
1003 // Restore savedTInfo into (extended) decl info.
1004 getExtInfo()->TInfo = savedTInfo;
1006 // Set qualifier info.
1007 getExtInfo()->QualifierLoc = QualifierLoc;
1009 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1011 if (getExtInfo()->NumTemplParamLists == 0) {
1012 // Save type source info pointer.
1013 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1014 // Deallocate the extended decl info.
1015 getASTContext().Deallocate(getExtInfo());
1016 // Restore savedTInfo into (non-extended) decl info.
1017 DeclInfo = savedTInfo;
1020 getExtInfo()->QualifierLoc = QualifierLoc;
1026 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1027 unsigned NumTPLists,
1028 TemplateParameterList **TPLists) {
1029 assert(NumTPLists > 0);
1030 // Make sure the extended decl info is allocated.
1031 if (!hasExtInfo()) {
1032 // Save (non-extended) type source info pointer.
1033 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1034 // Allocate external info struct.
1035 DeclInfo = new (getASTContext()) ExtInfo;
1036 // Restore savedTInfo into (extended) decl info.
1037 getExtInfo()->TInfo = savedTInfo;
1039 // Set the template parameter lists info.
1040 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1043 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1044 return getTemplateOrInnerLocStart(this);
1049 // Helper function: returns true if QT is or contains a type
1050 // having a postfix component.
1051 bool typeIsPostfix(clang::QualType QT) {
1053 const Type* T = QT.getTypePtr();
1054 switch (T->getTypeClass()) {
1058 QT = cast<PointerType>(T)->getPointeeType();
1060 case Type::BlockPointer:
1061 QT = cast<BlockPointerType>(T)->getPointeeType();
1063 case Type::MemberPointer:
1064 QT = cast<MemberPointerType>(T)->getPointeeType();
1066 case Type::LValueReference:
1067 case Type::RValueReference:
1068 QT = cast<ReferenceType>(T)->getPointeeType();
1070 case Type::PackExpansion:
1071 QT = cast<PackExpansionType>(T)->getPattern();
1074 case Type::ConstantArray:
1075 case Type::DependentSizedArray:
1076 case Type::IncompleteArray:
1077 case Type::VariableArray:
1078 case Type::FunctionProto:
1079 case Type::FunctionNoProto:
1087 SourceRange DeclaratorDecl::getSourceRange() const {
1088 SourceLocation RangeEnd = getLocation();
1089 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1090 if (typeIsPostfix(TInfo->getType()))
1091 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1093 return SourceRange(getOuterLocStart(), RangeEnd);
1097 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1098 unsigned NumTPLists,
1099 TemplateParameterList **TPLists) {
1100 assert((NumTPLists == 0 || TPLists != 0) &&
1101 "Empty array of template parameters with positive size!");
1103 // Free previous template parameters (if any).
1104 if (NumTemplParamLists > 0) {
1105 Context.Deallocate(TemplParamLists);
1106 TemplParamLists = 0;
1107 NumTemplParamLists = 0;
1109 // Set info on matched template parameter lists (if any).
1110 if (NumTPLists > 0) {
1111 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1112 NumTemplParamLists = NumTPLists;
1113 for (unsigned i = NumTPLists; i-- > 0; )
1114 TemplParamLists[i] = TPLists[i];
1118 //===----------------------------------------------------------------------===//
1119 // VarDecl Implementation
1120 //===----------------------------------------------------------------------===//
1122 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1124 case SC_None: break;
1125 case SC_Auto: return "auto";
1126 case SC_Extern: return "extern";
1127 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1128 case SC_PrivateExtern: return "__private_extern__";
1129 case SC_Register: return "register";
1130 case SC_Static: return "static";
1133 llvm_unreachable("Invalid storage class");
1137 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1138 SourceLocation StartL, SourceLocation IdL,
1139 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1140 StorageClass S, StorageClass SCAsWritten) {
1141 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
1144 void VarDecl::setStorageClass(StorageClass SC) {
1145 assert(isLegalForVariable(SC));
1146 if (getStorageClass() != SC)
1147 ClearLinkageCache();
1149 VarDeclBits.SClass = SC;
1152 SourceRange VarDecl::getSourceRange() const {
1154 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
1155 return DeclaratorDecl::getSourceRange();
1158 bool VarDecl::isExternC() const {
1159 ASTContext &Context = getASTContext();
1160 if (!Context.getLangOptions().CPlusPlus)
1161 return (getDeclContext()->isTranslationUnit() &&
1162 getStorageClass() != SC_Static) ||
1163 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
1165 const DeclContext *DC = getDeclContext();
1166 if (DC->isFunctionOrMethod())
1169 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
1170 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1171 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
1172 return getStorageClass() != SC_Static;
1182 VarDecl *VarDecl::getCanonicalDecl() {
1183 return getFirstDeclaration();
1186 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
1187 // C++ [basic.def]p2:
1188 // A declaration is a definition unless [...] it contains the 'extern'
1189 // specifier or a linkage-specification and neither an initializer [...],
1190 // it declares a static data member in a class declaration [...].
1191 // C++ [temp.expl.spec]p15:
1192 // An explicit specialization of a static data member of a template is a
1193 // definition if the declaration includes an initializer; otherwise, it is
1195 if (isStaticDataMember()) {
1196 if (isOutOfLine() && (hasInit() ||
1197 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1200 return DeclarationOnly;
1203 // A definition of an identifier is a declaration for that identifier that
1204 // [...] causes storage to be reserved for that object.
1205 // Note: that applies for all non-file-scope objects.
1207 // If the declaration of an identifier for an object has file scope and an
1208 // initializer, the declaration is an external definition for the identifier
1211 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1212 if (hasExternalStorage())
1213 return DeclarationOnly;
1215 if (getStorageClassAsWritten() == SC_Extern ||
1216 getStorageClassAsWritten() == SC_PrivateExtern) {
1217 for (const VarDecl *PrevVar = getPreviousDeclaration();
1218 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) {
1219 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1220 return DeclarationOnly;
1224 // A declaration of an object that has file scope without an initializer,
1225 // and without a storage class specifier or the scs 'static', constitutes
1226 // a tentative definition.
1227 // No such thing in C++.
1228 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
1229 return TentativeDefinition;
1231 // What's left is (in C, block-scope) declarations without initializers or
1232 // external storage. These are definitions.
1236 VarDecl *VarDecl::getActingDefinition() {
1237 DefinitionKind Kind = isThisDeclarationADefinition();
1238 if (Kind != TentativeDefinition)
1241 VarDecl *LastTentative = 0;
1242 VarDecl *First = getFirstDeclaration();
1243 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1245 Kind = (*I)->isThisDeclarationADefinition();
1246 if (Kind == Definition)
1248 else if (Kind == TentativeDefinition)
1251 return LastTentative;
1254 bool VarDecl::isTentativeDefinitionNow() const {
1255 DefinitionKind Kind = isThisDeclarationADefinition();
1256 if (Kind != TentativeDefinition)
1259 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1260 if ((*I)->isThisDeclarationADefinition() == Definition)
1266 VarDecl *VarDecl::getDefinition() {
1267 VarDecl *First = getFirstDeclaration();
1268 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1270 if ((*I)->isThisDeclarationADefinition() == Definition)
1276 VarDecl::DefinitionKind VarDecl::hasDefinition() const {
1277 DefinitionKind Kind = DeclarationOnly;
1279 const VarDecl *First = getFirstDeclaration();
1280 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1282 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
1287 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1288 redecl_iterator I = redecls_begin(), E = redecls_end();
1289 while (I != E && !I->getInit())
1294 return I->getInit();
1299 bool VarDecl::isOutOfLine() const {
1300 if (Decl::isOutOfLine())
1303 if (!isStaticDataMember())
1306 // If this static data member was instantiated from a static data member of
1307 // a class template, check whether that static data member was defined
1309 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1310 return VD->isOutOfLine();
1315 VarDecl *VarDecl::getOutOfLineDefinition() {
1316 if (!isStaticDataMember())
1319 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1320 RD != RDEnd; ++RD) {
1321 if (RD->getLexicalDeclContext()->isFileContext())
1328 void VarDecl::setInit(Expr *I) {
1329 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1330 Eval->~EvaluatedStmt();
1331 getASTContext().Deallocate(Eval);
1337 bool VarDecl::extendsLifetimeOfTemporary() const {
1338 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
1340 const Expr *E = getInit();
1344 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1345 E = Cleanups->getSubExpr();
1347 return isa<MaterializeTemporaryExpr>(E);
1350 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
1351 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1352 return cast<VarDecl>(MSI->getInstantiatedFrom());
1357 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
1358 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1359 return MSI->getTemplateSpecializationKind();
1361 return TSK_Undeclared;
1364 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
1365 return getASTContext().getInstantiatedFromStaticDataMember(this);
1368 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1369 SourceLocation PointOfInstantiation) {
1370 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
1371 assert(MSI && "Not an instantiated static data member?");
1372 MSI->setTemplateSpecializationKind(TSK);
1373 if (TSK != TSK_ExplicitSpecialization &&
1374 PointOfInstantiation.isValid() &&
1375 MSI->getPointOfInstantiation().isInvalid())
1376 MSI->setPointOfInstantiation(PointOfInstantiation);
1379 //===----------------------------------------------------------------------===//
1380 // ParmVarDecl Implementation
1381 //===----------------------------------------------------------------------===//
1383 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
1384 SourceLocation StartLoc,
1385 SourceLocation IdLoc, IdentifierInfo *Id,
1386 QualType T, TypeSourceInfo *TInfo,
1387 StorageClass S, StorageClass SCAsWritten,
1389 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
1390 S, SCAsWritten, DefArg);
1393 SourceRange ParmVarDecl::getSourceRange() const {
1394 if (!hasInheritedDefaultArg()) {
1395 SourceRange ArgRange = getDefaultArgRange();
1396 if (ArgRange.isValid())
1397 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1400 return DeclaratorDecl::getSourceRange();
1403 Expr *ParmVarDecl::getDefaultArg() {
1404 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1405 assert(!hasUninstantiatedDefaultArg() &&
1406 "Default argument is not yet instantiated!");
1408 Expr *Arg = getInit();
1409 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
1410 return E->getSubExpr();
1415 unsigned ParmVarDecl::getNumDefaultArgTemporaries() const {
1416 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(getInit()))
1417 return E->getNumTemporaries();
1422 CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) {
1423 assert(getNumDefaultArgTemporaries() &&
1424 "Default arguments does not have any temporaries!");
1426 ExprWithCleanups *E = cast<ExprWithCleanups>(getInit());
1427 return E->getTemporary(i);
1430 SourceRange ParmVarDecl::getDefaultArgRange() const {
1431 if (const Expr *E = getInit())
1432 return E->getSourceRange();
1434 if (hasUninstantiatedDefaultArg())
1435 return getUninstantiatedDefaultArg()->getSourceRange();
1437 return SourceRange();
1440 bool ParmVarDecl::isParameterPack() const {
1441 return isa<PackExpansionType>(getType());
1444 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1445 getASTContext().setParameterIndex(this, parameterIndex);
1446 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1449 unsigned ParmVarDecl::getParameterIndexLarge() const {
1450 return getASTContext().getParameterIndex(this);
1453 //===----------------------------------------------------------------------===//
1454 // FunctionDecl Implementation
1455 //===----------------------------------------------------------------------===//
1457 void FunctionDecl::getNameForDiagnostic(std::string &S,
1458 const PrintingPolicy &Policy,
1459 bool Qualified) const {
1460 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1461 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1463 S += TemplateSpecializationType::PrintTemplateArgumentList(
1464 TemplateArgs->data(),
1465 TemplateArgs->size(),
1470 bool FunctionDecl::isVariadic() const {
1471 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1472 return FT->isVariadic();
1476 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1477 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1478 if (I->Body || I->IsLateTemplateParsed) {
1487 bool FunctionDecl::hasTrivialBody() const
1489 Stmt *S = getBody();
1491 // Since we don't have a body for this function, we don't know if it's
1496 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1501 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1502 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1503 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
1504 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1512 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
1513 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1516 return I->Body.get(getASTContext().getExternalSource());
1517 } else if (I->IsLateTemplateParsed) {
1526 void FunctionDecl::setBody(Stmt *B) {
1529 EndRangeLoc = B->getLocEnd();
1532 void FunctionDecl::setPure(bool P) {
1535 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1536 Parent->markedVirtualFunctionPure();
1539 bool FunctionDecl::isMain() const {
1540 const TranslationUnitDecl *tunit =
1541 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1543 !tunit->getASTContext().getLangOptions().Freestanding &&
1545 getIdentifier()->isStr("main");
1548 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1549 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1550 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1551 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1552 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1553 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1555 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1556 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1558 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1559 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1561 ASTContext &Context =
1562 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1565 // The result type and first argument type are constant across all
1566 // these operators. The second argument must be exactly void*.
1567 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
1570 bool FunctionDecl::isExternC() const {
1571 ASTContext &Context = getASTContext();
1572 // In C, any non-static, non-overloadable function has external
1574 if (!Context.getLangOptions().CPlusPlus)
1575 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>();
1577 const DeclContext *DC = getDeclContext();
1581 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
1582 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1583 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
1584 return getStorageClass() != SC_Static &&
1585 !getAttr<OverloadableAttr>();
1594 bool FunctionDecl::isGlobal() const {
1595 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1596 return Method->isStatic();
1598 if (getStorageClass() == SC_Static)
1601 for (const DeclContext *DC = getDeclContext();
1603 DC = DC->getParent()) {
1604 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1605 if (!Namespace->getDeclName())
1615 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1616 redeclarable_base::setPreviousDeclaration(PrevDecl);
1618 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1619 FunctionTemplateDecl *PrevFunTmpl
1620 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1621 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1622 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1625 if (PrevDecl->IsInline)
1629 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1630 return getFirstDeclaration();
1633 FunctionDecl *FunctionDecl::getCanonicalDecl() {
1634 return getFirstDeclaration();
1637 void FunctionDecl::setStorageClass(StorageClass SC) {
1638 assert(isLegalForFunction(SC));
1639 if (getStorageClass() != SC)
1640 ClearLinkageCache();
1645 /// \brief Returns a value indicating whether this function
1646 /// corresponds to a builtin function.
1648 /// The function corresponds to a built-in function if it is
1649 /// declared at translation scope or within an extern "C" block and
1650 /// its name matches with the name of a builtin. The returned value
1651 /// will be 0 for functions that do not correspond to a builtin, a
1652 /// value of type \c Builtin::ID if in the target-independent range
1653 /// \c [1,Builtin::First), or a target-specific builtin value.
1654 unsigned FunctionDecl::getBuiltinID() const {
1655 ASTContext &Context = getASTContext();
1656 if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1659 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1660 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1663 // This function has the name of a known C library
1664 // function. Determine whether it actually refers to the C library
1665 // function or whether it just has the same name.
1667 // If this is a static function, it's not a builtin.
1668 if (getStorageClass() == SC_Static)
1671 // If this function is at translation-unit scope and we're not in
1672 // C++, it refers to the C library function.
1673 if (!Context.getLangOptions().CPlusPlus &&
1674 getDeclContext()->isTranslationUnit())
1677 // If the function is in an extern "C" linkage specification and is
1678 // not marked "overloadable", it's the real function.
1679 if (isa<LinkageSpecDecl>(getDeclContext()) &&
1680 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
1681 == LinkageSpecDecl::lang_c &&
1682 !getAttr<OverloadableAttr>())
1690 /// getNumParams - Return the number of parameters this function must have
1691 /// based on its FunctionType. This is the length of the ParamInfo array
1692 /// after it has been created.
1693 unsigned FunctionDecl::getNumParams() const {
1694 const FunctionType *FT = getType()->getAs<FunctionType>();
1695 if (isa<FunctionNoProtoType>(FT))
1697 return cast<FunctionProtoType>(FT)->getNumArgs();
1701 void FunctionDecl::setParams(ASTContext &C,
1702 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
1703 assert(ParamInfo == 0 && "Already has param info!");
1704 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
1706 // Zero params -> null pointer.
1707 if (!NewParamInfo.empty()) {
1708 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1709 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
1713 /// getMinRequiredArguments - Returns the minimum number of arguments
1714 /// needed to call this function. This may be fewer than the number of
1715 /// function parameters, if some of the parameters have default
1716 /// arguments (in C++) or the last parameter is a parameter pack.
1717 unsigned FunctionDecl::getMinRequiredArguments() const {
1718 if (!getASTContext().getLangOptions().CPlusPlus)
1719 return getNumParams();
1721 unsigned NumRequiredArgs = getNumParams();
1723 // If the last parameter is a parameter pack, we don't need an argument for
1725 if (NumRequiredArgs > 0 &&
1726 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1729 // If this parameter has a default argument, we don't need an argument for
1731 while (NumRequiredArgs > 0 &&
1732 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
1735 // We might have parameter packs before the end. These can't be deduced,
1736 // but they can still handle multiple arguments.
1737 unsigned ArgIdx = NumRequiredArgs;
1738 while (ArgIdx > 0) {
1739 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1740 NumRequiredArgs = ArgIdx;
1745 return NumRequiredArgs;
1748 bool FunctionDecl::isInlined() const {
1752 if (isa<CXXMethodDecl>(this)) {
1753 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1757 switch (getTemplateSpecializationKind()) {
1758 case TSK_Undeclared:
1759 case TSK_ExplicitSpecialization:
1762 case TSK_ImplicitInstantiation:
1763 case TSK_ExplicitInstantiationDeclaration:
1764 case TSK_ExplicitInstantiationDefinition:
1769 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1770 bool HasPattern = false;
1772 HasPattern = PatternDecl->hasBody(PatternDecl);
1774 if (HasPattern && PatternDecl)
1775 return PatternDecl->isInlined();
1780 /// \brief For a function declaration in C or C++, determine whether this
1781 /// declaration causes the definition to be externally visible.
1783 /// Determines whether this is the first non-inline redeclaration of an inline
1784 /// function in a language where "inline" does not normally require an
1785 /// externally visible definition.
1786 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1787 assert(!doesThisDeclarationHaveABody() &&
1788 "Must have a declaration without a body.");
1790 ASTContext &Context = getASTContext();
1792 // In C99 mode, a function may have an inline definition (causing it to
1793 // be deferred) then redeclared later. As a special case, "extern inline"
1794 // is not required to produce an external symbol.
1795 if (Context.getLangOptions().GNUInline || !Context.getLangOptions().C99 ||
1796 Context.getLangOptions().CPlusPlus)
1798 if (getLinkage() != ExternalLinkage || isInlineSpecified())
1800 const FunctionDecl *Definition = 0;
1801 if (hasBody(Definition))
1802 return Definition->isInlined() &&
1803 Definition->isInlineDefinitionExternallyVisible();
1807 /// \brief For an inline function definition in C or C++, determine whether the
1808 /// definition will be externally visible.
1810 /// Inline function definitions are always available for inlining optimizations.
1811 /// However, depending on the language dialect, declaration specifiers, and
1812 /// attributes, the definition of an inline function may or may not be
1813 /// "externally" visible to other translation units in the program.
1815 /// In C99, inline definitions are not externally visible by default. However,
1816 /// if even one of the global-scope declarations is marked "extern inline", the
1817 /// inline definition becomes externally visible (C99 6.7.4p6).
1819 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1820 /// definition, we use the GNU semantics for inline, which are nearly the
1821 /// opposite of C99 semantics. In particular, "inline" by itself will create
1822 /// an externally visible symbol, but "extern inline" will not create an
1823 /// externally visible symbol.
1824 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
1825 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
1826 assert(isInlined() && "Function must be inline");
1827 ASTContext &Context = getASTContext();
1829 if (Context.getLangOptions().GNUInline || hasAttr<GNUInlineAttr>()) {
1830 // If it's not the case that both 'inline' and 'extern' are
1831 // specified on the definition, then this inline definition is
1832 // externally visible.
1833 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
1836 // If any declaration is 'inline' but not 'extern', then this definition
1837 // is externally visible.
1838 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1839 Redecl != RedeclEnd;
1841 if (Redecl->isInlineSpecified() &&
1842 Redecl->getStorageClassAsWritten() != SC_Extern)
1850 // [...] If all of the file scope declarations for a function in a
1851 // translation unit include the inline function specifier without extern,
1852 // then the definition in that translation unit is an inline definition.
1853 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1854 Redecl != RedeclEnd;
1856 // Only consider file-scope declarations in this test.
1857 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1860 // Only consider explicit declarations; the presence of a builtin for a
1861 // libcall shouldn't affect whether a definition is externally visible.
1862 if (Redecl->isImplicit())
1865 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
1866 return true; // Not an inline definition
1870 // An inline definition does not provide an external definition for the
1871 // function, and does not forbid an external definition in another
1872 // translation unit.
1876 /// getOverloadedOperator - Which C++ overloaded operator this
1877 /// function represents, if any.
1878 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
1879 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1880 return getDeclName().getCXXOverloadedOperator();
1885 /// getLiteralIdentifier - The literal suffix identifier this function
1886 /// represents, if any.
1887 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
1888 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
1889 return getDeclName().getCXXLiteralIdentifier();
1894 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
1895 if (TemplateOrSpecialization.isNull())
1896 return TK_NonTemplate;
1897 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
1898 return TK_FunctionTemplate;
1899 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
1900 return TK_MemberSpecialization;
1901 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
1902 return TK_FunctionTemplateSpecialization;
1903 if (TemplateOrSpecialization.is
1904 <DependentFunctionTemplateSpecializationInfo*>())
1905 return TK_DependentFunctionTemplateSpecialization;
1907 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
1910 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
1911 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
1912 return cast<FunctionDecl>(Info->getInstantiatedFrom());
1917 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
1918 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1922 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
1924 TemplateSpecializationKind TSK) {
1925 assert(TemplateOrSpecialization.isNull() &&
1926 "Member function is already a specialization");
1927 MemberSpecializationInfo *Info
1928 = new (C) MemberSpecializationInfo(FD, TSK);
1929 TemplateOrSpecialization = Info;
1932 bool FunctionDecl::isImplicitlyInstantiable() const {
1933 // If the function is invalid, it can't be implicitly instantiated.
1934 if (isInvalidDecl())
1937 switch (getTemplateSpecializationKind()) {
1938 case TSK_Undeclared:
1939 case TSK_ExplicitInstantiationDefinition:
1942 case TSK_ImplicitInstantiation:
1945 // It is possible to instantiate TSK_ExplicitSpecialization kind
1946 // if the FunctionDecl has a class scope specialization pattern.
1947 case TSK_ExplicitSpecialization:
1948 return getClassScopeSpecializationPattern() != 0;
1950 case TSK_ExplicitInstantiationDeclaration:
1955 // Find the actual template from which we will instantiate.
1956 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1957 bool HasPattern = false;
1959 HasPattern = PatternDecl->hasBody(PatternDecl);
1961 // C++0x [temp.explicit]p9:
1962 // Except for inline functions, other explicit instantiation declarations
1963 // have the effect of suppressing the implicit instantiation of the entity
1964 // to which they refer.
1965 if (!HasPattern || !PatternDecl)
1968 return PatternDecl->isInlined();
1971 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
1972 // Handle class scope explicit specialization special case.
1973 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1974 return getClassScopeSpecializationPattern();
1976 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
1977 while (Primary->getInstantiatedFromMemberTemplate()) {
1978 // If we have hit a point where the user provided a specialization of
1979 // this template, we're done looking.
1980 if (Primary->isMemberSpecialization())
1983 Primary = Primary->getInstantiatedFromMemberTemplate();
1986 return Primary->getTemplatedDecl();
1989 return getInstantiatedFromMemberFunction();
1992 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
1993 if (FunctionTemplateSpecializationInfo *Info
1994 = TemplateOrSpecialization
1995 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
1996 return Info->Template.getPointer();
2001 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2002 return getASTContext().getClassScopeSpecializationPattern(this);
2005 const TemplateArgumentList *
2006 FunctionDecl::getTemplateSpecializationArgs() const {
2007 if (FunctionTemplateSpecializationInfo *Info
2008 = TemplateOrSpecialization
2009 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2010 return Info->TemplateArguments;
2015 const ASTTemplateArgumentListInfo *
2016 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2017 if (FunctionTemplateSpecializationInfo *Info
2018 = TemplateOrSpecialization
2019 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2020 return Info->TemplateArgumentsAsWritten;
2026 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2027 FunctionTemplateDecl *Template,
2028 const TemplateArgumentList *TemplateArgs,
2030 TemplateSpecializationKind TSK,
2031 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2032 SourceLocation PointOfInstantiation) {
2033 assert(TSK != TSK_Undeclared &&
2034 "Must specify the type of function template specialization");
2035 FunctionTemplateSpecializationInfo *Info
2036 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2038 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2040 TemplateArgsAsWritten,
2041 PointOfInstantiation);
2042 TemplateOrSpecialization = Info;
2044 // Insert this function template specialization into the set of known
2045 // function template specializations.
2047 Template->addSpecialization(Info, InsertPos);
2049 // Try to insert the new node. If there is an existing node, leave it, the
2050 // set will contain the canonical decls while
2051 // FunctionTemplateDecl::findSpecialization will return
2052 // the most recent redeclarations.
2053 FunctionTemplateSpecializationInfo *Existing
2054 = Template->getSpecializations().GetOrInsertNode(Info);
2056 assert((!Existing || Existing->Function->isCanonicalDecl()) &&
2057 "Set is supposed to only contain canonical decls");
2062 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2063 const UnresolvedSetImpl &Templates,
2064 const TemplateArgumentListInfo &TemplateArgs) {
2065 assert(TemplateOrSpecialization.isNull());
2066 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2067 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2068 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2069 void *Buffer = Context.Allocate(Size);
2070 DependentFunctionTemplateSpecializationInfo *Info =
2071 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2073 TemplateOrSpecialization = Info;
2076 DependentFunctionTemplateSpecializationInfo::
2077 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2078 const TemplateArgumentListInfo &TArgs)
2079 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2081 d.NumTemplates = Ts.size();
2082 d.NumArgs = TArgs.size();
2084 FunctionTemplateDecl **TsArray =
2085 const_cast<FunctionTemplateDecl**>(getTemplates());
2086 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2087 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2089 TemplateArgumentLoc *ArgsArray =
2090 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2091 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2092 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2095 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2096 // For a function template specialization, query the specialization
2097 // information object.
2098 FunctionTemplateSpecializationInfo *FTSInfo
2099 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2101 return FTSInfo->getTemplateSpecializationKind();
2103 MemberSpecializationInfo *MSInfo
2104 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2106 return MSInfo->getTemplateSpecializationKind();
2108 return TSK_Undeclared;
2112 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2113 SourceLocation PointOfInstantiation) {
2114 if (FunctionTemplateSpecializationInfo *FTSInfo
2115 = TemplateOrSpecialization.dyn_cast<
2116 FunctionTemplateSpecializationInfo*>()) {
2117 FTSInfo->setTemplateSpecializationKind(TSK);
2118 if (TSK != TSK_ExplicitSpecialization &&
2119 PointOfInstantiation.isValid() &&
2120 FTSInfo->getPointOfInstantiation().isInvalid())
2121 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2122 } else if (MemberSpecializationInfo *MSInfo
2123 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2124 MSInfo->setTemplateSpecializationKind(TSK);
2125 if (TSK != TSK_ExplicitSpecialization &&
2126 PointOfInstantiation.isValid() &&
2127 MSInfo->getPointOfInstantiation().isInvalid())
2128 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2130 llvm_unreachable("Function cannot have a template specialization kind");
2133 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2134 if (FunctionTemplateSpecializationInfo *FTSInfo
2135 = TemplateOrSpecialization.dyn_cast<
2136 FunctionTemplateSpecializationInfo*>())
2137 return FTSInfo->getPointOfInstantiation();
2138 else if (MemberSpecializationInfo *MSInfo
2139 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2140 return MSInfo->getPointOfInstantiation();
2142 return SourceLocation();
2145 bool FunctionDecl::isOutOfLine() const {
2146 if (Decl::isOutOfLine())
2149 // If this function was instantiated from a member function of a
2150 // class template, check whether that member function was defined out-of-line.
2151 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2152 const FunctionDecl *Definition;
2153 if (FD->hasBody(Definition))
2154 return Definition->isOutOfLine();
2157 // If this function was instantiated from a function template,
2158 // check whether that function template was defined out-of-line.
2159 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2160 const FunctionDecl *Definition;
2161 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2162 return Definition->isOutOfLine();
2168 SourceRange FunctionDecl::getSourceRange() const {
2169 return SourceRange(getOuterLocStart(), EndRangeLoc);
2172 //===----------------------------------------------------------------------===//
2173 // FieldDecl Implementation
2174 //===----------------------------------------------------------------------===//
2176 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
2177 SourceLocation StartLoc, SourceLocation IdLoc,
2178 IdentifierInfo *Id, QualType T,
2179 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2181 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
2182 BW, Mutable, HasInit);
2185 bool FieldDecl::isAnonymousStructOrUnion() const {
2186 if (!isImplicit() || getDeclName())
2189 if (const RecordType *Record = getType()->getAs<RecordType>())
2190 return Record->getDecl()->isAnonymousStructOrUnion();
2195 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2196 assert(isBitField() && "not a bitfield");
2197 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2198 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2201 unsigned FieldDecl::getFieldIndex() const {
2202 if (CachedFieldIndex) return CachedFieldIndex - 1;
2205 const RecordDecl *RD = getParent();
2206 const FieldDecl *LastFD = 0;
2207 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
2209 RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2211 assert(i != e && "failed to find field in parent!");
2216 // Zero-length bitfields following non-bitfield members are ignored.
2217 if (getASTContext().ZeroBitfieldFollowsNonBitfield((*i), LastFD)) {
2227 CachedFieldIndex = index + 1;
2231 SourceRange FieldDecl::getSourceRange() const {
2232 if (const Expr *E = InitializerOrBitWidth.getPointer())
2233 return SourceRange(getInnerLocStart(), E->getLocEnd());
2234 return DeclaratorDecl::getSourceRange();
2237 void FieldDecl::setInClassInitializer(Expr *Init) {
2238 assert(!InitializerOrBitWidth.getPointer() &&
2239 "bit width or initializer already set");
2240 InitializerOrBitWidth.setPointer(Init);
2241 InitializerOrBitWidth.setInt(0);
2244 //===----------------------------------------------------------------------===//
2245 // TagDecl Implementation
2246 //===----------------------------------------------------------------------===//
2248 SourceLocation TagDecl::getOuterLocStart() const {
2249 return getTemplateOrInnerLocStart(this);
2252 SourceRange TagDecl::getSourceRange() const {
2253 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
2254 return SourceRange(getOuterLocStart(), E);
2257 TagDecl* TagDecl::getCanonicalDecl() {
2258 return getFirstDeclaration();
2261 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2262 TypedefNameDeclOrQualifier = TDD;
2264 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2265 ClearLinkageCache();
2268 void TagDecl::startDefinition() {
2269 IsBeingDefined = true;
2271 if (isa<CXXRecordDecl>(this)) {
2272 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2273 struct CXXRecordDecl::DefinitionData *Data =
2274 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
2275 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2276 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
2280 void TagDecl::completeDefinition() {
2281 assert((!isa<CXXRecordDecl>(this) ||
2282 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2283 "definition completed but not started");
2285 IsCompleteDefinition = true;
2286 IsBeingDefined = false;
2288 if (ASTMutationListener *L = getASTMutationListener())
2289 L->CompletedTagDefinition(this);
2292 TagDecl *TagDecl::getDefinition() const {
2293 if (isCompleteDefinition())
2294 return const_cast<TagDecl *>(this);
2295 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2296 return CXXRD->getDefinition();
2298 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
2300 if (R->isCompleteDefinition())
2306 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2308 // Make sure the extended qualifier info is allocated.
2310 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2311 // Set qualifier info.
2312 getExtInfo()->QualifierLoc = QualifierLoc;
2314 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2316 if (getExtInfo()->NumTemplParamLists == 0) {
2317 getASTContext().Deallocate(getExtInfo());
2318 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
2321 getExtInfo()->QualifierLoc = QualifierLoc;
2326 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2327 unsigned NumTPLists,
2328 TemplateParameterList **TPLists) {
2329 assert(NumTPLists > 0);
2330 // Make sure the extended decl info is allocated.
2332 // Allocate external info struct.
2333 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2334 // Set the template parameter lists info.
2335 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2338 //===----------------------------------------------------------------------===//
2339 // EnumDecl Implementation
2340 //===----------------------------------------------------------------------===//
2342 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2343 SourceLocation StartLoc, SourceLocation IdLoc,
2345 EnumDecl *PrevDecl, bool IsScoped,
2346 bool IsScopedUsingClassTag, bool IsFixed) {
2347 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
2348 IsScoped, IsScopedUsingClassTag, IsFixed);
2349 C.getTypeDeclType(Enum, PrevDecl);
2353 EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) {
2354 return new (C) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2355 false, false, false);
2358 void EnumDecl::completeDefinition(QualType NewType,
2359 QualType NewPromotionType,
2360 unsigned NumPositiveBits,
2361 unsigned NumNegativeBits) {
2362 assert(!isCompleteDefinition() && "Cannot redefine enums!");
2364 IntegerType = NewType.getTypePtr();
2365 PromotionType = NewPromotionType;
2366 setNumPositiveBits(NumPositiveBits);
2367 setNumNegativeBits(NumNegativeBits);
2368 TagDecl::completeDefinition();
2371 //===----------------------------------------------------------------------===//
2372 // RecordDecl Implementation
2373 //===----------------------------------------------------------------------===//
2375 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2376 SourceLocation StartLoc, SourceLocation IdLoc,
2377 IdentifierInfo *Id, RecordDecl *PrevDecl)
2378 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
2379 HasFlexibleArrayMember = false;
2380 AnonymousStructOrUnion = false;
2381 HasObjectMember = false;
2382 LoadedFieldsFromExternalStorage = false;
2383 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
2386 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2387 SourceLocation StartLoc, SourceLocation IdLoc,
2388 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2389 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2391 C.getTypeDeclType(R, PrevDecl);
2395 RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) {
2396 return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2397 SourceLocation(), 0, 0);
2400 bool RecordDecl::isInjectedClassName() const {
2401 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
2402 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2405 RecordDecl::field_iterator RecordDecl::field_begin() const {
2406 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2407 LoadFieldsFromExternalStorage();
2409 return field_iterator(decl_iterator(FirstDecl));
2412 /// completeDefinition - Notes that the definition of this type is now
2414 void RecordDecl::completeDefinition() {
2415 assert(!isCompleteDefinition() && "Cannot redefine record!");
2416 TagDecl::completeDefinition();
2419 void RecordDecl::LoadFieldsFromExternalStorage() const {
2420 ExternalASTSource *Source = getASTContext().getExternalSource();
2421 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2423 // Notify that we have a RecordDecl doing some initialization.
2424 ExternalASTSource::Deserializing TheFields(Source);
2426 SmallVector<Decl*, 64> Decls;
2427 LoadedFieldsFromExternalStorage = true;
2428 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2432 case ELR_AlreadyLoaded:
2438 // Check that all decls we got were FieldDecls.
2439 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2440 assert(isa<FieldDecl>(Decls[i]));
2446 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2447 /*FieldsAlreadyLoaded=*/false);
2450 //===----------------------------------------------------------------------===//
2451 // BlockDecl Implementation
2452 //===----------------------------------------------------------------------===//
2454 void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
2455 assert(ParamInfo == 0 && "Already has param info!");
2457 // Zero params -> null pointer.
2458 if (!NewParamInfo.empty()) {
2459 NumParams = NewParamInfo.size();
2460 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2461 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2465 void BlockDecl::setCaptures(ASTContext &Context,
2466 const Capture *begin,
2468 bool capturesCXXThis) {
2469 CapturesCXXThis = capturesCXXThis;
2477 NumCaptures = end - begin;
2479 // Avoid new Capture[] because we don't want to provide a default
2481 size_t allocationSize = NumCaptures * sizeof(Capture);
2482 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2483 memcpy(buffer, begin, allocationSize);
2484 Captures = static_cast<Capture*>(buffer);
2487 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2488 for (capture_const_iterator
2489 i = capture_begin(), e = capture_end(); i != e; ++i)
2490 // Only auto vars can be captured, so no redeclaration worries.
2491 if (i->getVariable() == variable)
2497 SourceRange BlockDecl::getSourceRange() const {
2498 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2501 //===----------------------------------------------------------------------===//
2502 // Other Decl Allocation/Deallocation Method Implementations
2503 //===----------------------------------------------------------------------===//
2505 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2506 return new (C) TranslationUnitDecl(C);
2509 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2510 SourceLocation IdentL, IdentifierInfo *II) {
2511 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2514 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2515 SourceLocation IdentL, IdentifierInfo *II,
2516 SourceLocation GnuLabelL) {
2517 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2518 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
2522 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
2523 SourceLocation StartLoc,
2524 SourceLocation IdLoc, IdentifierInfo *Id) {
2525 return new (C) NamespaceDecl(DC, StartLoc, IdLoc, Id);
2528 NamespaceDecl *NamespaceDecl::getNextNamespace() {
2529 return dyn_cast_or_null<NamespaceDecl>(
2530 NextNamespace.get(getASTContext().getExternalSource()));
2533 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
2534 SourceLocation IdLoc,
2537 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
2540 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
2541 SourceLocation StartLoc,
2542 const DeclarationNameInfo &NameInfo,
2543 QualType T, TypeSourceInfo *TInfo,
2544 StorageClass SC, StorageClass SCAsWritten,
2545 bool isInlineSpecified,
2546 bool hasWrittenPrototype,
2547 bool isConstexprSpecified) {
2548 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2549 T, TInfo, SC, SCAsWritten,
2551 isConstexprSpecified);
2552 New->HasWrittenPrototype = hasWrittenPrototype;
2556 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2557 return new (C) BlockDecl(DC, L);
2560 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2562 IdentifierInfo *Id, QualType T,
2563 Expr *E, const llvm::APSInt &V) {
2564 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2568 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2569 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2571 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2574 SourceRange EnumConstantDecl::getSourceRange() const {
2575 SourceLocation End = getLocation();
2577 End = Init->getLocEnd();
2578 return SourceRange(getLocation(), End);
2581 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
2582 SourceLocation StartLoc, SourceLocation IdLoc,
2583 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2584 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
2587 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2588 SourceLocation StartLoc,
2589 SourceLocation IdLoc, IdentifierInfo *Id,
2590 TypeSourceInfo *TInfo) {
2591 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2594 SourceRange TypedefDecl::getSourceRange() const {
2595 SourceLocation RangeEnd = getLocation();
2596 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2597 if (typeIsPostfix(TInfo->getType()))
2598 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2600 return SourceRange(getLocStart(), RangeEnd);
2603 SourceRange TypeAliasDecl::getSourceRange() const {
2604 SourceLocation RangeEnd = getLocStart();
2605 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2606 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2607 return SourceRange(getLocStart(), RangeEnd);
2610 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
2612 SourceLocation AsmLoc,
2613 SourceLocation RParenLoc) {
2614 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);