1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Decl subclasses.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/AST/Stmt.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/ASTMutationListener.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/IdentifierTable.h"
27 #include "clang/Basic/Module.h"
28 #include "clang/Basic/Specifiers.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/Support/ErrorHandling.h"
34 using namespace clang;
36 //===----------------------------------------------------------------------===//
37 // NamedDecl Implementation
38 //===----------------------------------------------------------------------===//
40 static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
41 // If this declaration has an explicit visibility attribute, use it.
42 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
43 switch (A->getVisibility()) {
44 case VisibilityAttr::Default:
45 return DefaultVisibility;
46 case VisibilityAttr::Hidden:
47 return HiddenVisibility;
48 case VisibilityAttr::Protected:
49 return ProtectedVisibility;
53 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
54 // implies visibility(default).
55 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
56 for (specific_attr_iterator<AvailabilityAttr>
57 A = D->specific_attr_begin<AvailabilityAttr>(),
58 AEnd = D->specific_attr_end<AvailabilityAttr>();
60 if ((*A)->getPlatform()->getName().equals("macosx"))
61 return DefaultVisibility;
64 return llvm::Optional<Visibility>();
67 typedef NamedDecl::LinkageInfo LinkageInfo;
69 static LinkageInfo getLVForType(QualType T) {
70 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
71 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
74 /// \brief Get the most restrictive linkage for the types in the given
75 /// template parameter list.
77 getLVForTemplateParameterList(const TemplateParameterList *Params) {
78 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
79 for (TemplateParameterList::const_iterator P = Params->begin(),
82 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
83 if (NTTP->isExpandedParameterPack()) {
84 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
85 QualType T = NTTP->getExpansionType(I);
86 if (!T->isDependentType())
87 LV.merge(getLVForType(T));
92 if (!NTTP->getType()->isDependentType()) {
93 LV.merge(getLVForType(NTTP->getType()));
98 if (TemplateTemplateParmDecl *TTP
99 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
100 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
107 /// getLVForDecl - Get the linkage and visibility for the given declaration.
108 static LinkageInfo getLVForDecl(const NamedDecl *D, bool OnlyTemplate);
110 /// \brief Get the most restrictive linkage for the types and
111 /// declarations in the given template argument list.
112 static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args,
115 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
117 for (unsigned I = 0; I != NumArgs; ++I) {
118 switch (Args[I].getKind()) {
119 case TemplateArgument::Null:
120 case TemplateArgument::Integral:
121 case TemplateArgument::Expression:
124 case TemplateArgument::Type:
125 LV.mergeWithMin(getLVForType(Args[I].getAsType()));
128 case TemplateArgument::Declaration:
129 // The decl can validly be null as the representation of nullptr
130 // arguments, valid only in C++0x.
131 if (Decl *D = Args[I].getAsDecl()) {
132 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
133 LV.mergeWithMin(getLVForDecl(ND, OnlyTemplate));
137 case TemplateArgument::Template:
138 case TemplateArgument::TemplateExpansion:
139 if (TemplateDecl *Template
140 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
141 LV.mergeWithMin(getLVForDecl(Template, OnlyTemplate));
144 case TemplateArgument::Pack:
145 LV.mergeWithMin(getLVForTemplateArgumentList(Args[I].pack_begin(),
156 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
158 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), OnlyTemplate);
161 static bool shouldConsiderTemplateVis(const FunctionDecl *fn,
162 const FunctionTemplateSpecializationInfo *spec) {
163 return !fn->hasAttr<VisibilityAttr>() || spec->isExplicitSpecialization();
167 shouldConsiderTemplateVis(const ClassTemplateSpecializationDecl *d) {
168 return !d->hasAttr<VisibilityAttr>() || d->isExplicitSpecialization();
171 static bool useInlineVisibilityHidden(const NamedDecl *D) {
172 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
173 const LangOptions &Opts = D->getASTContext().getLangOpts();
174 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
177 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
181 TemplateSpecializationKind TSK = TSK_Undeclared;
182 if (FunctionTemplateSpecializationInfo *spec
183 = FD->getTemplateSpecializationInfo()) {
184 TSK = spec->getTemplateSpecializationKind();
185 } else if (MemberSpecializationInfo *MSI =
186 FD->getMemberSpecializationInfo()) {
187 TSK = MSI->getTemplateSpecializationKind();
190 const FunctionDecl *Def = 0;
191 // InlineVisibilityHidden only applies to definitions, and
192 // isInlined() only gives meaningful answers on definitions
194 return TSK != TSK_ExplicitInstantiationDeclaration &&
195 TSK != TSK_ExplicitInstantiationDefinition &&
196 FD->hasBody(Def) && Def->isInlined();
199 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
201 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
202 "Not a name having namespace scope");
203 ASTContext &Context = D->getASTContext();
205 // C++ [basic.link]p3:
206 // A name having namespace scope (3.3.6) has internal linkage if it
208 // - an object, reference, function or function template that is
209 // explicitly declared static; or,
210 // (This bullet corresponds to C99 6.2.2p3.)
211 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
212 // Explicitly declared static.
213 if (Var->getStorageClass() == SC_Static)
214 return LinkageInfo::internal();
216 // - an object or reference that is explicitly declared const
217 // and neither explicitly declared extern nor previously
218 // declared to have external linkage; or
219 // (there is no equivalent in C99)
220 if (Context.getLangOpts().CPlusPlus &&
221 Var->getType().isConstant(Context) &&
222 Var->getStorageClass() != SC_Extern &&
223 Var->getStorageClass() != SC_PrivateExtern) {
224 bool FoundExtern = false;
225 for (const VarDecl *PrevVar = Var->getPreviousDecl();
226 PrevVar && !FoundExtern;
227 PrevVar = PrevVar->getPreviousDecl())
228 if (isExternalLinkage(PrevVar->getLinkage()))
232 return LinkageInfo::internal();
234 if (Var->getStorageClass() == SC_None) {
235 const VarDecl *PrevVar = Var->getPreviousDecl();
236 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
237 if (PrevVar->getStorageClass() == SC_PrivateExtern)
240 return PrevVar->getLinkageAndVisibility();
242 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
244 // A non-member function template can have internal linkage; any
245 // other template name shall have external linkage.
246 const FunctionDecl *Function = 0;
247 if (const FunctionTemplateDecl *FunTmpl
248 = dyn_cast<FunctionTemplateDecl>(D))
249 Function = FunTmpl->getTemplatedDecl();
251 Function = cast<FunctionDecl>(D);
253 // Explicitly declared static.
254 if (Function->getStorageClass() == SC_Static)
255 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
256 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
257 // - a data member of an anonymous union.
258 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
259 return LinkageInfo::internal();
262 if (D->isInAnonymousNamespace()) {
263 const VarDecl *Var = dyn_cast<VarDecl>(D);
264 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
265 if ((!Var || !Var->getDeclContext()->isExternCContext()) &&
266 (!Func || !Func->getDeclContext()->isExternCContext()))
267 return LinkageInfo::uniqueExternal();
270 // Set up the defaults.
273 // If the declaration of an identifier for an object has file
274 // scope and no storage-class specifier, its linkage is
279 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
280 LV.mergeVisibility(*Vis, true);
282 // If we're declared in a namespace with a visibility attribute,
283 // use that namespace's visibility, but don't call it explicit.
284 for (const DeclContext *DC = D->getDeclContext();
285 !isa<TranslationUnitDecl>(DC);
286 DC = DC->getParent()) {
287 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
289 if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
290 LV.mergeVisibility(*Vis, true);
298 LV.mergeVisibility(Context.getLangOpts().getVisibilityMode());
299 // If we're paying attention to global visibility, apply
300 // -finline-visibility-hidden if this is an inline method.
301 if (!LV.visibilityExplicit() && useInlineVisibilityHidden(D))
302 LV.mergeVisibility(HiddenVisibility, true);
305 // C++ [basic.link]p4:
307 // A name having namespace scope has external linkage if it is the
310 // - an object or reference, unless it has internal linkage; or
311 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
312 // GCC applies the following optimization to variables and static
313 // data members, but not to functions:
315 // Modify the variable's LV by the LV of its type unless this is
316 // C or extern "C". This follows from [basic.link]p9:
317 // A type without linkage shall not be used as the type of a
318 // variable or function with external linkage unless
319 // - the entity has C language linkage, or
320 // - the entity is declared within an unnamed namespace, or
321 // - the entity is not used or is defined in the same
323 // and [basic.link]p10:
324 // ...the types specified by all declarations referring to a
325 // given variable or function shall be identical...
326 // C does not have an equivalent rule.
328 // Ignore this if we've got an explicit attribute; the user
329 // probably knows what they're doing.
331 // Note that we don't want to make the variable non-external
332 // because of this, but unique-external linkage suits us.
333 if (Context.getLangOpts().CPlusPlus &&
334 !Var->getDeclContext()->isExternCContext()) {
335 LinkageInfo TypeLV = getLVForType(Var->getType());
336 if (TypeLV.linkage() != ExternalLinkage)
337 return LinkageInfo::uniqueExternal();
338 LV.mergeVisibility(TypeLV);
341 if (Var->getStorageClass() == SC_PrivateExtern)
342 LV.mergeVisibility(HiddenVisibility, true);
344 if (!Context.getLangOpts().CPlusPlus &&
345 (Var->getStorageClass() == SC_Extern ||
346 Var->getStorageClass() == SC_PrivateExtern)) {
349 // For an identifier declared with the storage-class specifier
350 // extern in a scope in which a prior declaration of that
351 // identifier is visible, if the prior declaration specifies
352 // internal or external linkage, the linkage of the identifier
353 // at the later declaration is the same as the linkage
354 // specified at the prior declaration. If no prior declaration
355 // is visible, or if the prior declaration specifies no
356 // linkage, then the identifier has external linkage.
357 if (const VarDecl *PrevVar = Var->getPreviousDecl()) {
358 LinkageInfo PrevLV = getLVForDecl(PrevVar, OnlyTemplate);
359 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
360 LV.mergeVisibility(PrevLV);
364 // - a function, unless it has internal linkage; or
365 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
366 // In theory, we can modify the function's LV by the LV of its
367 // type unless it has C linkage (see comment above about variables
368 // for justification). In practice, GCC doesn't do this, so it's
369 // just too painful to make work.
371 if (Function->getStorageClass() == SC_PrivateExtern)
372 LV.mergeVisibility(HiddenVisibility, true);
375 // If the declaration of an identifier for a function has no
376 // storage-class specifier, its linkage is determined exactly
377 // as if it were declared with the storage-class specifier
379 if (!Context.getLangOpts().CPlusPlus &&
380 (Function->getStorageClass() == SC_Extern ||
381 Function->getStorageClass() == SC_PrivateExtern ||
382 Function->getStorageClass() == SC_None)) {
384 // For an identifier declared with the storage-class specifier
385 // extern in a scope in which a prior declaration of that
386 // identifier is visible, if the prior declaration specifies
387 // internal or external linkage, the linkage of the identifier
388 // at the later declaration is the same as the linkage
389 // specified at the prior declaration. If no prior declaration
390 // is visible, or if the prior declaration specifies no
391 // linkage, then the identifier has external linkage.
392 if (const FunctionDecl *PrevFunc = Function->getPreviousDecl()) {
393 LinkageInfo PrevLV = getLVForDecl(PrevFunc, OnlyTemplate);
394 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
395 LV.mergeVisibility(PrevLV);
399 // In C++, then if the type of the function uses a type with
400 // unique-external linkage, it's not legally usable from outside
401 // this translation unit. However, we should use the C linkage
402 // rules instead for extern "C" declarations.
403 if (Context.getLangOpts().CPlusPlus &&
404 !Function->getDeclContext()->isExternCContext() &&
405 Function->getType()->getLinkage() == UniqueExternalLinkage)
406 return LinkageInfo::uniqueExternal();
408 // Consider LV from the template and the template arguments unless
409 // this is an explicit specialization with a visibility attribute.
410 if (FunctionTemplateSpecializationInfo *specInfo
411 = Function->getTemplateSpecializationInfo()) {
412 LinkageInfo TempLV = getLVForDecl(specInfo->getTemplate(), true);
413 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
414 LinkageInfo ArgsLV = getLVForTemplateArgumentList(templateArgs,
416 if (shouldConsiderTemplateVis(Function, specInfo)) {
417 LV.mergeWithMin(TempLV);
418 LV.mergeWithMin(ArgsLV);
420 LV.mergeLinkage(TempLV);
421 LV.mergeLinkage(ArgsLV);
425 // - a named class (Clause 9), or an unnamed class defined in a
426 // typedef declaration in which the class has the typedef name
427 // for linkage purposes (7.1.3); or
428 // - a named enumeration (7.2), or an unnamed enumeration
429 // defined in a typedef declaration in which the enumeration
430 // has the typedef name for linkage purposes (7.1.3); or
431 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
432 // Unnamed tags have no linkage.
433 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
434 return LinkageInfo::none();
436 // If this is a class template specialization, consider the
437 // linkage of the template and template arguments.
438 if (const ClassTemplateSpecializationDecl *spec
439 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
440 // From the template.
441 LinkageInfo TempLV = getLVForDecl(spec->getSpecializedTemplate(), true);
443 // The arguments at which the template was instantiated.
444 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
445 LinkageInfo ArgsLV = getLVForTemplateArgumentList(TemplateArgs,
447 if (shouldConsiderTemplateVis(spec)) {
448 LV.mergeWithMin(TempLV);
449 LV.mergeWithMin(ArgsLV);
451 LV.mergeLinkage(TempLV);
452 LV.mergeLinkage(ArgsLV);
456 // - an enumerator belonging to an enumeration with external linkage;
457 } else if (isa<EnumConstantDecl>(D)) {
458 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
460 if (!isExternalLinkage(EnumLV.linkage()))
461 return LinkageInfo::none();
464 // - a template, unless it is a function template that has
465 // internal linkage (Clause 14);
466 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
467 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
468 // - a namespace (7.3), unless it is declared within an unnamed
470 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
473 // By extension, we assign external linkage to Objective-C
475 } else if (isa<ObjCInterfaceDecl>(D)) {
478 // Everything not covered here has no linkage.
480 return LinkageInfo::none();
483 // If we ended up with non-external linkage, visibility should
484 // always be default.
485 if (LV.linkage() != ExternalLinkage)
486 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
491 static LinkageInfo getLVForClassMember(const NamedDecl *D, bool OnlyTemplate) {
492 // Only certain class members have linkage. Note that fields don't
493 // really have linkage, but it's convenient to say they do for the
494 // purposes of calculating linkage of pointer-to-data-member
495 // template arguments.
496 if (!(isa<CXXMethodDecl>(D) ||
500 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
501 return LinkageInfo::none();
505 // If we have an explicit visibility attribute, merge that in.
507 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility())
508 LV.mergeVisibility(*Vis, true);
509 // If we're paying attention to global visibility, apply
510 // -finline-visibility-hidden if this is an inline method.
512 // Note that we do this before merging information about
513 // the class visibility.
514 if (!LV.visibilityExplicit() && useInlineVisibilityHidden(D))
515 LV.mergeVisibility(HiddenVisibility, true);
518 // If this class member has an explicit visibility attribute, the only
519 // thing that can change its visibility is the template arguments, so
520 // only look for them when processing the class.
521 bool ClassOnlyTemplate = LV.visibilityExplicit() ? true : OnlyTemplate;
523 // If this member has an visibility attribute, ClassF will exclude
524 // attributes on the class or command line options, keeping only information
525 // about the template instantiation. If the member has no visibility
526 // attributes, mergeWithMin behaves like merge, so in both cases mergeWithMin
527 // produces the desired result.
528 LV.mergeWithMin(getLVForDecl(cast<RecordDecl>(D->getDeclContext()),
530 if (!isExternalLinkage(LV.linkage()))
531 return LinkageInfo::none();
533 // If the class already has unique-external linkage, we can't improve.
534 if (LV.linkage() == UniqueExternalLinkage)
535 return LinkageInfo::uniqueExternal();
538 LV.mergeVisibility(D->getASTContext().getLangOpts().getVisibilityMode());
540 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
541 // If the type of the function uses a type with unique-external
542 // linkage, it's not legally usable from outside this translation unit.
543 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
544 return LinkageInfo::uniqueExternal();
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 const TemplateArgumentList &TemplateArgs = *spec->TemplateArguments;
551 LinkageInfo ArgsLV = getLVForTemplateArgumentList(TemplateArgs,
553 TemplateParameterList *TemplateParams =
554 spec->getTemplate()->getTemplateParameters();
555 LinkageInfo ParamsLV = getLVForTemplateParameterList(TemplateParams);
556 if (shouldConsiderTemplateVis(MD, spec)) {
557 LV.mergeWithMin(ArgsLV);
559 LV.mergeWithMin(ParamsLV);
561 LV.mergeLinkage(ArgsLV);
563 LV.mergeLinkage(ParamsLV);
567 // Note that in contrast to basically every other situation, we
568 // *do* apply -fvisibility to method declarations.
570 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
571 if (const ClassTemplateSpecializationDecl *spec
572 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
573 // Merge template argument/parameter information for member
574 // class template specializations.
575 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
576 LinkageInfo ArgsLV = getLVForTemplateArgumentList(TemplateArgs,
578 TemplateParameterList *TemplateParams =
579 spec->getSpecializedTemplate()->getTemplateParameters();
580 LinkageInfo ParamsLV = getLVForTemplateParameterList(TemplateParams);
581 if (shouldConsiderTemplateVis(spec)) {
582 LV.mergeWithMin(ArgsLV);
584 LV.mergeWithMin(ParamsLV);
586 LV.mergeLinkage(ArgsLV);
588 LV.mergeLinkage(ParamsLV);
592 // Static data members.
593 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
594 // Modify the variable's linkage by its type, but ignore the
595 // type's visibility unless it's a definition.
596 LinkageInfo TypeLV = getLVForType(VD->getType());
597 if (TypeLV.linkage() != ExternalLinkage)
598 LV.mergeLinkage(UniqueExternalLinkage);
599 LV.mergeVisibility(TypeLV);
605 static void clearLinkageForClass(const CXXRecordDecl *record) {
606 for (CXXRecordDecl::decl_iterator
607 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
609 if (isa<NamedDecl>(child))
610 cast<NamedDecl>(child)->ClearLinkageCache();
614 void NamedDecl::anchor() { }
616 void NamedDecl::ClearLinkageCache() {
617 // Note that we can't skip clearing the linkage of children just
618 // because the parent doesn't have cached linkage: we don't cache
619 // when computing linkage for parent contexts.
621 HasCachedLinkage = 0;
623 // If we're changing the linkage of a class, we need to reset the
624 // linkage of child declarations, too.
625 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
626 clearLinkageForClass(record);
628 if (ClassTemplateDecl *temp =
629 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
630 // Clear linkage for the template pattern.
631 CXXRecordDecl *record = temp->getTemplatedDecl();
632 record->HasCachedLinkage = 0;
633 clearLinkageForClass(record);
635 // We need to clear linkage for specializations, too.
636 for (ClassTemplateDecl::spec_iterator
637 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
638 i->ClearLinkageCache();
641 // Clear cached linkage for function template decls, too.
642 if (FunctionTemplateDecl *temp =
643 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
644 temp->getTemplatedDecl()->ClearLinkageCache();
645 for (FunctionTemplateDecl::spec_iterator
646 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
647 i->ClearLinkageCache();
652 Linkage NamedDecl::getLinkage() const {
653 if (HasCachedLinkage) {
654 assert(Linkage(CachedLinkage) ==
655 getLVForDecl(this, true).linkage());
656 return Linkage(CachedLinkage);
659 CachedLinkage = getLVForDecl(this, true).linkage();
660 HasCachedLinkage = 1;
661 return Linkage(CachedLinkage);
664 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
665 LinkageInfo LI = getLVForDecl(this, false);
666 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
667 HasCachedLinkage = 1;
668 CachedLinkage = LI.linkage();
672 llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
673 // Use the most recent declaration of a variable.
674 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
675 if (llvm::Optional<Visibility> V =
676 getVisibilityOf(Var->getMostRecentDecl()))
679 if (Var->isStaticDataMember()) {
680 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
681 if (InstantiatedFrom)
682 return getVisibilityOf(InstantiatedFrom);
685 return llvm::Optional<Visibility>();
687 // Use the most recent declaration of a function, and also handle
688 // function template specializations.
689 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
690 if (llvm::Optional<Visibility> V
691 = getVisibilityOf(fn->getMostRecentDecl()))
694 // If the function is a specialization of a template with an
695 // explicit visibility attribute, use that.
696 if (FunctionTemplateSpecializationInfo *templateInfo
697 = fn->getTemplateSpecializationInfo())
698 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
700 // If the function is a member of a specialization of a class template
701 // and the corresponding decl has explicit visibility, use that.
702 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
703 if (InstantiatedFrom)
704 return getVisibilityOf(InstantiatedFrom);
706 return llvm::Optional<Visibility>();
709 // Otherwise, just check the declaration itself first.
710 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
713 // The visibility of a template is stored in the templated decl.
714 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
715 return getVisibilityOf(TD->getTemplatedDecl());
717 // If there wasn't explicit visibility there, and this is a
718 // specialization of a class template, check for visibility
720 if (const ClassTemplateSpecializationDecl *spec
721 = dyn_cast<ClassTemplateSpecializationDecl>(this))
722 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
724 // If this is a member class of a specialization of a class template
725 // and the corresponding decl has explicit visibility, use that.
726 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
727 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
728 if (InstantiatedFrom)
729 return getVisibilityOf(InstantiatedFrom);
732 return llvm::Optional<Visibility>();
735 static LinkageInfo getLVForDecl(const NamedDecl *D, bool OnlyTemplate) {
736 // Objective-C: treat all Objective-C declarations as having external
738 switch (D->getKind()) {
742 return LinkageInfo::none();
743 case Decl::TemplateTemplateParm: // count these as external
744 case Decl::NonTypeTemplateParm:
745 case Decl::ObjCAtDefsField:
746 case Decl::ObjCCategory:
747 case Decl::ObjCCategoryImpl:
748 case Decl::ObjCCompatibleAlias:
749 case Decl::ObjCImplementation:
750 case Decl::ObjCMethod:
751 case Decl::ObjCProperty:
752 case Decl::ObjCPropertyImpl:
753 case Decl::ObjCProtocol:
754 return LinkageInfo::external();
756 case Decl::CXXRecord: {
757 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
758 if (Record->isLambda()) {
759 if (!Record->getLambdaManglingNumber()) {
760 // This lambda has no mangling number, so it's internal.
761 return LinkageInfo::internal();
764 // This lambda has its linkage/visibility determined by its owner.
765 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
766 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
767 if (isa<ParmVarDecl>(ContextDecl))
768 DC = ContextDecl->getDeclContext()->getRedeclContext();
770 return getLVForDecl(cast<NamedDecl>(ContextDecl),
774 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
775 return getLVForDecl(ND, OnlyTemplate);
777 return LinkageInfo::external();
784 // Handle linkage for namespace-scope names.
785 if (D->getDeclContext()->getRedeclContext()->isFileContext())
786 return getLVForNamespaceScopeDecl(D, OnlyTemplate);
788 // C++ [basic.link]p5:
789 // In addition, a member function, static data member, a named
790 // class or enumeration of class scope, or an unnamed class or
791 // enumeration defined in a class-scope typedef declaration such
792 // that the class or enumeration has the typedef name for linkage
793 // purposes (7.1.3), has external linkage if the name of the class
794 // has external linkage.
795 if (D->getDeclContext()->isRecord())
796 return getLVForClassMember(D, OnlyTemplate);
798 // C++ [basic.link]p6:
799 // The name of a function declared in block scope and the name of
800 // an object declared by a block scope extern declaration have
801 // linkage. If there is a visible declaration of an entity with
802 // linkage having the same name and type, ignoring entities
803 // declared outside the innermost enclosing namespace scope, the
804 // block scope declaration declares that same entity and receives
805 // the linkage of the previous declaration. If there is more than
806 // one such matching entity, the program is ill-formed. Otherwise,
807 // if no matching entity is found, the block scope entity receives
809 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
810 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
811 if (Function->isInAnonymousNamespace() &&
812 !Function->getDeclContext()->isExternCContext())
813 return LinkageInfo::uniqueExternal();
817 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
818 LV.mergeVisibility(*Vis, true);
821 if (const FunctionDecl *Prev = Function->getPreviousDecl()) {
822 LinkageInfo PrevLV = getLVForDecl(Prev, OnlyTemplate);
823 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
824 LV.mergeVisibility(PrevLV);
830 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
831 if (Var->getStorageClass() == SC_Extern ||
832 Var->getStorageClass() == SC_PrivateExtern) {
833 if (Var->isInAnonymousNamespace() &&
834 !Var->getDeclContext()->isExternCContext())
835 return LinkageInfo::uniqueExternal();
838 if (Var->getStorageClass() == SC_PrivateExtern)
839 LV.mergeVisibility(HiddenVisibility, true);
840 else if (!OnlyTemplate) {
841 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
842 LV.mergeVisibility(*Vis, true);
845 if (const VarDecl *Prev = Var->getPreviousDecl()) {
846 LinkageInfo PrevLV = getLVForDecl(Prev, OnlyTemplate);
847 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
848 LV.mergeVisibility(PrevLV);
855 // C++ [basic.link]p6:
856 // Names not covered by these rules have no linkage.
857 return LinkageInfo::none();
860 std::string NamedDecl::getQualifiedNameAsString() const {
861 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
864 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
865 const DeclContext *Ctx = getDeclContext();
867 if (Ctx->isFunctionOrMethod())
868 return getNameAsString();
870 typedef SmallVector<const DeclContext *, 8> ContextsTy;
874 while (Ctx && isa<NamedDecl>(Ctx)) {
875 Contexts.push_back(Ctx);
876 Ctx = Ctx->getParent();
879 std::string QualName;
880 llvm::raw_string_ostream OS(QualName);
882 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
884 if (const ClassTemplateSpecializationDecl *Spec
885 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
886 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
887 std::string TemplateArgsStr
888 = TemplateSpecializationType::PrintTemplateArgumentList(
892 OS << Spec->getName() << TemplateArgsStr;
893 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
894 if (ND->isAnonymousNamespace())
895 OS << "<anonymous namespace>";
898 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
899 if (!RD->getIdentifier())
900 OS << "<anonymous " << RD->getKindName() << '>';
903 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
904 const FunctionProtoType *FT = 0;
905 if (FD->hasWrittenPrototype())
906 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
910 unsigned NumParams = FD->getNumParams();
911 for (unsigned i = 0; i < NumParams; ++i) {
914 OS << FD->getParamDecl(i)->getType().stream(P);
917 if (FT->isVariadic()) {
925 OS << *cast<NamedDecl>(*I);
938 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
939 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
941 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
942 // We want to keep it, unless it nominates same namespace.
943 if (getKind() == Decl::UsingDirective) {
944 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
945 ->getOriginalNamespace() ==
946 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
947 ->getOriginalNamespace();
950 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
951 // For function declarations, we keep track of redeclarations.
952 return FD->getPreviousDecl() == OldD;
954 // For function templates, the underlying function declarations are linked.
955 if (const FunctionTemplateDecl *FunctionTemplate
956 = dyn_cast<FunctionTemplateDecl>(this))
957 if (const FunctionTemplateDecl *OldFunctionTemplate
958 = dyn_cast<FunctionTemplateDecl>(OldD))
959 return FunctionTemplate->getTemplatedDecl()
960 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
962 // For method declarations, we keep track of redeclarations.
963 if (isa<ObjCMethodDecl>(this))
966 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
969 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
970 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
971 cast<UsingShadowDecl>(OldD)->getTargetDecl();
973 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
974 ASTContext &Context = getASTContext();
975 return Context.getCanonicalNestedNameSpecifier(
976 cast<UsingDecl>(this)->getQualifier()) ==
977 Context.getCanonicalNestedNameSpecifier(
978 cast<UsingDecl>(OldD)->getQualifier());
981 // A typedef of an Objective-C class type can replace an Objective-C class
982 // declaration or definition, and vice versa.
983 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
984 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
987 // For non-function declarations, if the declarations are of the
988 // same kind then this must be a redeclaration, or semantic analysis
989 // would not have given us the new declaration.
990 return this->getKind() == OldD->getKind();
993 bool NamedDecl::hasLinkage() const {
994 return getLinkage() != NoLinkage;
997 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
998 NamedDecl *ND = this;
999 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1000 ND = UD->getTargetDecl();
1002 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1003 return AD->getClassInterface();
1008 bool NamedDecl::isCXXInstanceMember() const {
1009 if (!isCXXClassMember())
1012 const NamedDecl *D = this;
1013 if (isa<UsingShadowDecl>(D))
1014 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1016 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
1018 if (isa<CXXMethodDecl>(D))
1019 return cast<CXXMethodDecl>(D)->isInstance();
1020 if (isa<FunctionTemplateDecl>(D))
1021 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1022 ->getTemplatedDecl())->isInstance();
1026 //===----------------------------------------------------------------------===//
1027 // DeclaratorDecl Implementation
1028 //===----------------------------------------------------------------------===//
1030 template <typename DeclT>
1031 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1032 if (decl->getNumTemplateParameterLists() > 0)
1033 return decl->getTemplateParameterList(0)->getTemplateLoc();
1035 return decl->getInnerLocStart();
1038 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1039 TypeSourceInfo *TSI = getTypeSourceInfo();
1040 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1041 return SourceLocation();
1044 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1046 // Make sure the extended decl info is allocated.
1047 if (!hasExtInfo()) {
1048 // Save (non-extended) type source info pointer.
1049 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1050 // Allocate external info struct.
1051 DeclInfo = new (getASTContext()) ExtInfo;
1052 // Restore savedTInfo into (extended) decl info.
1053 getExtInfo()->TInfo = savedTInfo;
1055 // Set qualifier info.
1056 getExtInfo()->QualifierLoc = QualifierLoc;
1058 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1060 if (getExtInfo()->NumTemplParamLists == 0) {
1061 // Save type source info pointer.
1062 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1063 // Deallocate the extended decl info.
1064 getASTContext().Deallocate(getExtInfo());
1065 // Restore savedTInfo into (non-extended) decl info.
1066 DeclInfo = savedTInfo;
1069 getExtInfo()->QualifierLoc = QualifierLoc;
1075 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1076 unsigned NumTPLists,
1077 TemplateParameterList **TPLists) {
1078 assert(NumTPLists > 0);
1079 // Make sure the extended decl info is allocated.
1080 if (!hasExtInfo()) {
1081 // Save (non-extended) type source info pointer.
1082 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1083 // Allocate external info struct.
1084 DeclInfo = new (getASTContext()) ExtInfo;
1085 // Restore savedTInfo into (extended) decl info.
1086 getExtInfo()->TInfo = savedTInfo;
1088 // Set the template parameter lists info.
1089 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1092 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1093 return getTemplateOrInnerLocStart(this);
1098 // Helper function: returns true if QT is or contains a type
1099 // having a postfix component.
1100 bool typeIsPostfix(clang::QualType QT) {
1102 const Type* T = QT.getTypePtr();
1103 switch (T->getTypeClass()) {
1107 QT = cast<PointerType>(T)->getPointeeType();
1109 case Type::BlockPointer:
1110 QT = cast<BlockPointerType>(T)->getPointeeType();
1112 case Type::MemberPointer:
1113 QT = cast<MemberPointerType>(T)->getPointeeType();
1115 case Type::LValueReference:
1116 case Type::RValueReference:
1117 QT = cast<ReferenceType>(T)->getPointeeType();
1119 case Type::PackExpansion:
1120 QT = cast<PackExpansionType>(T)->getPattern();
1123 case Type::ConstantArray:
1124 case Type::DependentSizedArray:
1125 case Type::IncompleteArray:
1126 case Type::VariableArray:
1127 case Type::FunctionProto:
1128 case Type::FunctionNoProto:
1136 SourceRange DeclaratorDecl::getSourceRange() const {
1137 SourceLocation RangeEnd = getLocation();
1138 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1139 if (typeIsPostfix(TInfo->getType()))
1140 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1142 return SourceRange(getOuterLocStart(), RangeEnd);
1146 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1147 unsigned NumTPLists,
1148 TemplateParameterList **TPLists) {
1149 assert((NumTPLists == 0 || TPLists != 0) &&
1150 "Empty array of template parameters with positive size!");
1152 // Free previous template parameters (if any).
1153 if (NumTemplParamLists > 0) {
1154 Context.Deallocate(TemplParamLists);
1155 TemplParamLists = 0;
1156 NumTemplParamLists = 0;
1158 // Set info on matched template parameter lists (if any).
1159 if (NumTPLists > 0) {
1160 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1161 NumTemplParamLists = NumTPLists;
1162 for (unsigned i = NumTPLists; i-- > 0; )
1163 TemplParamLists[i] = TPLists[i];
1167 //===----------------------------------------------------------------------===//
1168 // VarDecl Implementation
1169 //===----------------------------------------------------------------------===//
1171 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1173 case SC_None: break;
1174 case SC_Auto: return "auto";
1175 case SC_Extern: return "extern";
1176 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1177 case SC_PrivateExtern: return "__private_extern__";
1178 case SC_Register: return "register";
1179 case SC_Static: return "static";
1182 llvm_unreachable("Invalid storage class");
1185 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1186 SourceLocation StartL, SourceLocation IdL,
1187 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1188 StorageClass S, StorageClass SCAsWritten) {
1189 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
1192 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1193 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1194 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1195 QualType(), 0, SC_None, SC_None);
1198 void VarDecl::setStorageClass(StorageClass SC) {
1199 assert(isLegalForVariable(SC));
1200 if (getStorageClass() != SC)
1201 ClearLinkageCache();
1203 VarDeclBits.SClass = SC;
1206 SourceRange VarDecl::getSourceRange() const {
1208 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
1209 return DeclaratorDecl::getSourceRange();
1212 bool VarDecl::isExternC() const {
1213 if (getLinkage() != ExternalLinkage)
1216 const DeclContext *DC = getDeclContext();
1220 ASTContext &Context = getASTContext();
1221 if (!Context.getLangOpts().CPlusPlus)
1223 return DC->isExternCContext();
1226 VarDecl *VarDecl::getCanonicalDecl() {
1227 return getFirstDeclaration();
1230 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1231 ASTContext &C) const
1233 // C++ [basic.def]p2:
1234 // A declaration is a definition unless [...] it contains the 'extern'
1235 // specifier or a linkage-specification and neither an initializer [...],
1236 // it declares a static data member in a class declaration [...].
1237 // C++ [temp.expl.spec]p15:
1238 // An explicit specialization of a static data member of a template is a
1239 // definition if the declaration includes an initializer; otherwise, it is
1241 if (isStaticDataMember()) {
1242 if (isOutOfLine() && (hasInit() ||
1243 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1246 return DeclarationOnly;
1249 // A definition of an identifier is a declaration for that identifier that
1250 // [...] causes storage to be reserved for that object.
1251 // Note: that applies for all non-file-scope objects.
1253 // If the declaration of an identifier for an object has file scope and an
1254 // initializer, the declaration is an external definition for the identifier
1257 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1258 if (hasExternalStorage())
1259 return DeclarationOnly;
1261 if (getStorageClassAsWritten() == SC_Extern ||
1262 getStorageClassAsWritten() == SC_PrivateExtern) {
1263 for (const VarDecl *PrevVar = getPreviousDecl();
1264 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
1265 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1266 return DeclarationOnly;
1270 // A declaration of an object that has file scope without an initializer,
1271 // and without a storage class specifier or the scs 'static', constitutes
1272 // a tentative definition.
1273 // No such thing in C++.
1274 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1275 return TentativeDefinition;
1277 // What's left is (in C, block-scope) declarations without initializers or
1278 // external storage. These are definitions.
1282 VarDecl *VarDecl::getActingDefinition() {
1283 DefinitionKind Kind = isThisDeclarationADefinition();
1284 if (Kind != TentativeDefinition)
1287 VarDecl *LastTentative = 0;
1288 VarDecl *First = getFirstDeclaration();
1289 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1291 Kind = (*I)->isThisDeclarationADefinition();
1292 if (Kind == Definition)
1294 else if (Kind == TentativeDefinition)
1297 return LastTentative;
1300 bool VarDecl::isTentativeDefinitionNow() const {
1301 DefinitionKind Kind = isThisDeclarationADefinition();
1302 if (Kind != TentativeDefinition)
1305 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1306 if ((*I)->isThisDeclarationADefinition() == Definition)
1312 VarDecl *VarDecl::getDefinition(ASTContext &C) {
1313 VarDecl *First = getFirstDeclaration();
1314 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1316 if ((*I)->isThisDeclarationADefinition(C) == Definition)
1322 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1323 DefinitionKind Kind = DeclarationOnly;
1325 const VarDecl *First = getFirstDeclaration();
1326 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1328 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
1329 if (Kind == Definition)
1336 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1337 redecl_iterator I = redecls_begin(), E = redecls_end();
1338 while (I != E && !I->getInit())
1343 return I->getInit();
1348 bool VarDecl::isOutOfLine() const {
1349 if (Decl::isOutOfLine())
1352 if (!isStaticDataMember())
1355 // If this static data member was instantiated from a static data member of
1356 // a class template, check whether that static data member was defined
1358 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1359 return VD->isOutOfLine();
1364 VarDecl *VarDecl::getOutOfLineDefinition() {
1365 if (!isStaticDataMember())
1368 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1369 RD != RDEnd; ++RD) {
1370 if (RD->getLexicalDeclContext()->isFileContext())
1377 void VarDecl::setInit(Expr *I) {
1378 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1379 Eval->~EvaluatedStmt();
1380 getASTContext().Deallocate(Eval);
1386 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1387 const LangOptions &Lang = C.getLangOpts();
1389 if (!Lang.CPlusPlus)
1392 // In C++11, any variable of reference type can be used in a constant
1393 // expression if it is initialized by a constant expression.
1394 if (Lang.CPlusPlus0x && getType()->isReferenceType())
1397 // Only const objects can be used in constant expressions in C++. C++98 does
1398 // not require the variable to be non-volatile, but we consider this to be a
1400 if (!getType().isConstQualified() || getType().isVolatileQualified())
1403 // In C++, const, non-volatile variables of integral or enumeration types
1404 // can be used in constant expressions.
1405 if (getType()->isIntegralOrEnumerationType())
1408 // Additionally, in C++11, non-volatile constexpr variables can be used in
1409 // constant expressions.
1410 return Lang.CPlusPlus0x && isConstexpr();
1413 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1414 /// form, which contains extra information on the evaluated value of the
1416 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1417 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1419 Stmt *S = Init.get<Stmt *>();
1420 Eval = new (getASTContext()) EvaluatedStmt;
1427 APValue *VarDecl::evaluateValue() const {
1428 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1429 return evaluateValue(Notes);
1432 APValue *VarDecl::evaluateValue(
1433 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1434 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1436 // We only produce notes indicating why an initializer is non-constant the
1437 // first time it is evaluated. FIXME: The notes won't always be emitted the
1438 // first time we try evaluation, so might not be produced at all.
1439 if (Eval->WasEvaluated)
1440 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
1442 const Expr *Init = cast<Expr>(Eval->Value);
1443 assert(!Init->isValueDependent());
1445 if (Eval->IsEvaluating) {
1446 // FIXME: Produce a diagnostic for self-initialization.
1447 Eval->CheckedICE = true;
1448 Eval->IsICE = false;
1452 Eval->IsEvaluating = true;
1454 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1457 // Ensure the result is an uninitialized APValue if evaluation fails.
1459 Eval->Evaluated = APValue();
1461 Eval->IsEvaluating = false;
1462 Eval->WasEvaluated = true;
1464 // In C++11, we have determined whether the initializer was a constant
1465 // expression as a side-effect.
1466 if (getASTContext().getLangOpts().CPlusPlus0x && !Eval->CheckedICE) {
1467 Eval->CheckedICE = true;
1468 Eval->IsICE = Result && Notes.empty();
1471 return Result ? &Eval->Evaluated : 0;
1474 bool VarDecl::checkInitIsICE() const {
1475 // Initializers of weak variables are never ICEs.
1479 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1480 if (Eval->CheckedICE)
1481 // We have already checked whether this subexpression is an
1482 // integral constant expression.
1485 const Expr *Init = cast<Expr>(Eval->Value);
1486 assert(!Init->isValueDependent());
1488 // In C++11, evaluate the initializer to check whether it's a constant
1490 if (getASTContext().getLangOpts().CPlusPlus0x) {
1491 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1492 evaluateValue(Notes);
1496 // It's an ICE whether or not the definition we found is
1497 // out-of-line. See DR 721 and the discussion in Clang PR
1498 // 6206 for details.
1500 if (Eval->CheckingICE)
1502 Eval->CheckingICE = true;
1504 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1505 Eval->CheckingICE = false;
1506 Eval->CheckedICE = true;
1510 bool VarDecl::extendsLifetimeOfTemporary() const {
1511 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
1513 const Expr *E = getInit();
1517 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1518 E = Cleanups->getSubExpr();
1520 return isa<MaterializeTemporaryExpr>(E);
1523 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
1524 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1525 return cast<VarDecl>(MSI->getInstantiatedFrom());
1530 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
1531 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1532 return MSI->getTemplateSpecializationKind();
1534 return TSK_Undeclared;
1537 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
1538 return getASTContext().getInstantiatedFromStaticDataMember(this);
1541 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1542 SourceLocation PointOfInstantiation) {
1543 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
1544 assert(MSI && "Not an instantiated static data member?");
1545 MSI->setTemplateSpecializationKind(TSK);
1546 if (TSK != TSK_ExplicitSpecialization &&
1547 PointOfInstantiation.isValid() &&
1548 MSI->getPointOfInstantiation().isInvalid())
1549 MSI->setPointOfInstantiation(PointOfInstantiation);
1552 //===----------------------------------------------------------------------===//
1553 // ParmVarDecl Implementation
1554 //===----------------------------------------------------------------------===//
1556 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
1557 SourceLocation StartLoc,
1558 SourceLocation IdLoc, IdentifierInfo *Id,
1559 QualType T, TypeSourceInfo *TInfo,
1560 StorageClass S, StorageClass SCAsWritten,
1562 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
1563 S, SCAsWritten, DefArg);
1566 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1567 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1568 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1569 0, QualType(), 0, SC_None, SC_None, 0);
1572 SourceRange ParmVarDecl::getSourceRange() const {
1573 if (!hasInheritedDefaultArg()) {
1574 SourceRange ArgRange = getDefaultArgRange();
1575 if (ArgRange.isValid())
1576 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1579 return DeclaratorDecl::getSourceRange();
1582 Expr *ParmVarDecl::getDefaultArg() {
1583 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1584 assert(!hasUninstantiatedDefaultArg() &&
1585 "Default argument is not yet instantiated!");
1587 Expr *Arg = getInit();
1588 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
1589 return E->getSubExpr();
1594 SourceRange ParmVarDecl::getDefaultArgRange() const {
1595 if (const Expr *E = getInit())
1596 return E->getSourceRange();
1598 if (hasUninstantiatedDefaultArg())
1599 return getUninstantiatedDefaultArg()->getSourceRange();
1601 return SourceRange();
1604 bool ParmVarDecl::isParameterPack() const {
1605 return isa<PackExpansionType>(getType());
1608 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1609 getASTContext().setParameterIndex(this, parameterIndex);
1610 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1613 unsigned ParmVarDecl::getParameterIndexLarge() const {
1614 return getASTContext().getParameterIndex(this);
1617 //===----------------------------------------------------------------------===//
1618 // FunctionDecl Implementation
1619 //===----------------------------------------------------------------------===//
1621 void FunctionDecl::getNameForDiagnostic(std::string &S,
1622 const PrintingPolicy &Policy,
1623 bool Qualified) const {
1624 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1625 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1627 S += TemplateSpecializationType::PrintTemplateArgumentList(
1628 TemplateArgs->data(),
1629 TemplateArgs->size(),
1634 bool FunctionDecl::isVariadic() const {
1635 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1636 return FT->isVariadic();
1640 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1641 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1642 if (I->Body || I->IsLateTemplateParsed) {
1651 bool FunctionDecl::hasTrivialBody() const
1653 Stmt *S = getBody();
1655 // Since we don't have a body for this function, we don't know if it's
1660 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1665 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1666 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1667 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
1668 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1676 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
1677 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1680 return I->Body.get(getASTContext().getExternalSource());
1681 } else if (I->IsLateTemplateParsed) {
1690 void FunctionDecl::setBody(Stmt *B) {
1693 EndRangeLoc = B->getLocEnd();
1696 void FunctionDecl::setPure(bool P) {
1699 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1700 Parent->markedVirtualFunctionPure();
1703 void FunctionDecl::setConstexpr(bool IC) {
1705 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(this);
1707 CD->getParent()->markedConstructorConstexpr(CD);
1710 bool FunctionDecl::isMain() const {
1711 const TranslationUnitDecl *tunit =
1712 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1714 !tunit->getASTContext().getLangOpts().Freestanding &&
1716 getIdentifier()->isStr("main");
1719 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1720 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1721 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1722 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1723 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1724 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1726 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1727 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1729 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1730 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1732 ASTContext &Context =
1733 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1736 // The result type and first argument type are constant across all
1737 // these operators. The second argument must be exactly void*.
1738 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
1741 bool FunctionDecl::isExternC() const {
1742 if (getLinkage() != ExternalLinkage)
1745 if (getAttr<OverloadableAttr>())
1748 const DeclContext *DC = getDeclContext();
1752 ASTContext &Context = getASTContext();
1753 if (!Context.getLangOpts().CPlusPlus)
1756 return isMain() || DC->isExternCContext();
1759 bool FunctionDecl::isGlobal() const {
1760 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1761 return Method->isStatic();
1763 if (getStorageClass() == SC_Static)
1766 for (const DeclContext *DC = getDeclContext();
1768 DC = DC->getParent()) {
1769 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1770 if (!Namespace->getDeclName())
1780 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1781 redeclarable_base::setPreviousDeclaration(PrevDecl);
1783 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1784 FunctionTemplateDecl *PrevFunTmpl
1785 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1786 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1787 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1790 if (PrevDecl && PrevDecl->IsInline)
1794 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1795 return getFirstDeclaration();
1798 FunctionDecl *FunctionDecl::getCanonicalDecl() {
1799 return getFirstDeclaration();
1802 void FunctionDecl::setStorageClass(StorageClass SC) {
1803 assert(isLegalForFunction(SC));
1804 if (getStorageClass() != SC)
1805 ClearLinkageCache();
1810 /// \brief Returns a value indicating whether this function
1811 /// corresponds to a builtin function.
1813 /// The function corresponds to a built-in function if it is
1814 /// declared at translation scope or within an extern "C" block and
1815 /// its name matches with the name of a builtin. The returned value
1816 /// will be 0 for functions that do not correspond to a builtin, a
1817 /// value of type \c Builtin::ID if in the target-independent range
1818 /// \c [1,Builtin::First), or a target-specific builtin value.
1819 unsigned FunctionDecl::getBuiltinID() const {
1820 if (!getIdentifier())
1823 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1827 ASTContext &Context = getASTContext();
1828 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1831 // This function has the name of a known C library
1832 // function. Determine whether it actually refers to the C library
1833 // function or whether it just has the same name.
1835 // If this is a static function, it's not a builtin.
1836 if (getStorageClass() == SC_Static)
1839 // If this function is at translation-unit scope and we're not in
1840 // C++, it refers to the C library function.
1841 if (!Context.getLangOpts().CPlusPlus &&
1842 getDeclContext()->isTranslationUnit())
1845 // If the function is in an extern "C" linkage specification and is
1846 // not marked "overloadable", it's the real function.
1847 if (isa<LinkageSpecDecl>(getDeclContext()) &&
1848 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
1849 == LinkageSpecDecl::lang_c &&
1850 !getAttr<OverloadableAttr>())
1858 /// getNumParams - Return the number of parameters this function must have
1859 /// based on its FunctionType. This is the length of the ParamInfo array
1860 /// after it has been created.
1861 unsigned FunctionDecl::getNumParams() const {
1862 const FunctionType *FT = getType()->getAs<FunctionType>();
1863 if (isa<FunctionNoProtoType>(FT))
1865 return cast<FunctionProtoType>(FT)->getNumArgs();
1869 void FunctionDecl::setParams(ASTContext &C,
1870 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
1871 assert(ParamInfo == 0 && "Already has param info!");
1872 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
1874 // Zero params -> null pointer.
1875 if (!NewParamInfo.empty()) {
1876 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1877 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
1881 void FunctionDecl::setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls) {
1882 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
1884 if (!NewDecls.empty()) {
1885 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
1886 std::copy(NewDecls.begin(), NewDecls.end(), A);
1887 DeclsInPrototypeScope = llvm::ArrayRef<NamedDecl*>(A, NewDecls.size());
1891 /// getMinRequiredArguments - Returns the minimum number of arguments
1892 /// needed to call this function. This may be fewer than the number of
1893 /// function parameters, if some of the parameters have default
1894 /// arguments (in C++) or the last parameter is a parameter pack.
1895 unsigned FunctionDecl::getMinRequiredArguments() const {
1896 if (!getASTContext().getLangOpts().CPlusPlus)
1897 return getNumParams();
1899 unsigned NumRequiredArgs = getNumParams();
1901 // If the last parameter is a parameter pack, we don't need an argument for
1903 if (NumRequiredArgs > 0 &&
1904 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1907 // If this parameter has a default argument, we don't need an argument for
1909 while (NumRequiredArgs > 0 &&
1910 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
1913 // We might have parameter packs before the end. These can't be deduced,
1914 // but they can still handle multiple arguments.
1915 unsigned ArgIdx = NumRequiredArgs;
1916 while (ArgIdx > 0) {
1917 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1918 NumRequiredArgs = ArgIdx;
1923 return NumRequiredArgs;
1926 bool FunctionDecl::isInlined() const {
1930 if (isa<CXXMethodDecl>(this)) {
1931 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1935 switch (getTemplateSpecializationKind()) {
1936 case TSK_Undeclared:
1937 case TSK_ExplicitSpecialization:
1940 case TSK_ImplicitInstantiation:
1941 case TSK_ExplicitInstantiationDeclaration:
1942 case TSK_ExplicitInstantiationDefinition:
1947 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1948 bool HasPattern = false;
1950 HasPattern = PatternDecl->hasBody(PatternDecl);
1952 if (HasPattern && PatternDecl)
1953 return PatternDecl->isInlined();
1958 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
1959 // Only consider file-scope declarations in this test.
1960 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1963 // Only consider explicit declarations; the presence of a builtin for a
1964 // libcall shouldn't affect whether a definition is externally visible.
1965 if (Redecl->isImplicit())
1968 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
1969 return true; // Not an inline definition
1974 /// \brief For a function declaration in C or C++, determine whether this
1975 /// declaration causes the definition to be externally visible.
1977 /// Specifically, this determines if adding the current declaration to the set
1978 /// of redeclarations of the given functions causes
1979 /// isInlineDefinitionExternallyVisible to change from false to true.
1980 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1981 assert(!doesThisDeclarationHaveABody() &&
1982 "Must have a declaration without a body.");
1984 ASTContext &Context = getASTContext();
1986 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
1987 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
1988 // an externally visible definition.
1990 // FIXME: What happens if gnu_inline gets added on after the first
1992 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
1995 const FunctionDecl *Prev = this;
1996 bool FoundBody = false;
1997 while ((Prev = Prev->getPreviousDecl())) {
1998 FoundBody |= Prev->Body;
2001 // If it's not the case that both 'inline' and 'extern' are
2002 // specified on the definition, then it is always externally visible.
2003 if (!Prev->isInlineSpecified() ||
2004 Prev->getStorageClassAsWritten() != SC_Extern)
2006 } else if (Prev->isInlineSpecified() &&
2007 Prev->getStorageClassAsWritten() != SC_Extern) {
2014 if (Context.getLangOpts().CPlusPlus)
2018 // [...] If all of the file scope declarations for a function in a
2019 // translation unit include the inline function specifier without extern,
2020 // then the definition in that translation unit is an inline definition.
2021 if (isInlineSpecified() && getStorageClass() != SC_Extern)
2023 const FunctionDecl *Prev = this;
2024 bool FoundBody = false;
2025 while ((Prev = Prev->getPreviousDecl())) {
2026 FoundBody |= Prev->Body;
2027 if (RedeclForcesDefC99(Prev))
2033 /// \brief For an inline function definition in C or C++, determine whether the
2034 /// definition will be externally visible.
2036 /// Inline function definitions are always available for inlining optimizations.
2037 /// However, depending on the language dialect, declaration specifiers, and
2038 /// attributes, the definition of an inline function may or may not be
2039 /// "externally" visible to other translation units in the program.
2041 /// In C99, inline definitions are not externally visible by default. However,
2042 /// if even one of the global-scope declarations is marked "extern inline", the
2043 /// inline definition becomes externally visible (C99 6.7.4p6).
2045 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2046 /// definition, we use the GNU semantics for inline, which are nearly the
2047 /// opposite of C99 semantics. In particular, "inline" by itself will create
2048 /// an externally visible symbol, but "extern inline" will not create an
2049 /// externally visible symbol.
2050 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2051 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2052 assert(isInlined() && "Function must be inline");
2053 ASTContext &Context = getASTContext();
2055 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2056 // Note: If you change the logic here, please change
2057 // doesDeclarationForceExternallyVisibleDefinition as well.
2059 // If it's not the case that both 'inline' and 'extern' are
2060 // specified on the definition, then this inline definition is
2061 // externally visible.
2062 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2065 // If any declaration is 'inline' but not 'extern', then this definition
2066 // is externally visible.
2067 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2068 Redecl != RedeclEnd;
2070 if (Redecl->isInlineSpecified() &&
2071 Redecl->getStorageClassAsWritten() != SC_Extern)
2079 // [...] If all of the file scope declarations for a function in a
2080 // translation unit include the inline function specifier without extern,
2081 // then the definition in that translation unit is an inline definition.
2082 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2083 Redecl != RedeclEnd;
2085 if (RedeclForcesDefC99(*Redecl))
2090 // An inline definition does not provide an external definition for the
2091 // function, and does not forbid an external definition in another
2092 // translation unit.
2096 /// getOverloadedOperator - Which C++ overloaded operator this
2097 /// function represents, if any.
2098 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2099 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2100 return getDeclName().getCXXOverloadedOperator();
2105 /// getLiteralIdentifier - The literal suffix identifier this function
2106 /// represents, if any.
2107 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2108 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2109 return getDeclName().getCXXLiteralIdentifier();
2114 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2115 if (TemplateOrSpecialization.isNull())
2116 return TK_NonTemplate;
2117 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2118 return TK_FunctionTemplate;
2119 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2120 return TK_MemberSpecialization;
2121 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2122 return TK_FunctionTemplateSpecialization;
2123 if (TemplateOrSpecialization.is
2124 <DependentFunctionTemplateSpecializationInfo*>())
2125 return TK_DependentFunctionTemplateSpecialization;
2127 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2130 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2131 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2132 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2137 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2138 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2142 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2144 TemplateSpecializationKind TSK) {
2145 assert(TemplateOrSpecialization.isNull() &&
2146 "Member function is already a specialization");
2147 MemberSpecializationInfo *Info
2148 = new (C) MemberSpecializationInfo(FD, TSK);
2149 TemplateOrSpecialization = Info;
2152 bool FunctionDecl::isImplicitlyInstantiable() const {
2153 // If the function is invalid, it can't be implicitly instantiated.
2154 if (isInvalidDecl())
2157 switch (getTemplateSpecializationKind()) {
2158 case TSK_Undeclared:
2159 case TSK_ExplicitInstantiationDefinition:
2162 case TSK_ImplicitInstantiation:
2165 // It is possible to instantiate TSK_ExplicitSpecialization kind
2166 // if the FunctionDecl has a class scope specialization pattern.
2167 case TSK_ExplicitSpecialization:
2168 return getClassScopeSpecializationPattern() != 0;
2170 case TSK_ExplicitInstantiationDeclaration:
2175 // Find the actual template from which we will instantiate.
2176 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2177 bool HasPattern = false;
2179 HasPattern = PatternDecl->hasBody(PatternDecl);
2181 // C++0x [temp.explicit]p9:
2182 // Except for inline functions, other explicit instantiation declarations
2183 // have the effect of suppressing the implicit instantiation of the entity
2184 // to which they refer.
2185 if (!HasPattern || !PatternDecl)
2188 return PatternDecl->isInlined();
2191 bool FunctionDecl::isTemplateInstantiation() const {
2192 switch (getTemplateSpecializationKind()) {
2193 case TSK_Undeclared:
2194 case TSK_ExplicitSpecialization:
2196 case TSK_ImplicitInstantiation:
2197 case TSK_ExplicitInstantiationDeclaration:
2198 case TSK_ExplicitInstantiationDefinition:
2201 llvm_unreachable("All TSK values handled.");
2204 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2205 // Handle class scope explicit specialization special case.
2206 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2207 return getClassScopeSpecializationPattern();
2209 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2210 while (Primary->getInstantiatedFromMemberTemplate()) {
2211 // If we have hit a point where the user provided a specialization of
2212 // this template, we're done looking.
2213 if (Primary->isMemberSpecialization())
2216 Primary = Primary->getInstantiatedFromMemberTemplate();
2219 return Primary->getTemplatedDecl();
2222 return getInstantiatedFromMemberFunction();
2225 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
2226 if (FunctionTemplateSpecializationInfo *Info
2227 = TemplateOrSpecialization
2228 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2229 return Info->Template.getPointer();
2234 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2235 return getASTContext().getClassScopeSpecializationPattern(this);
2238 const TemplateArgumentList *
2239 FunctionDecl::getTemplateSpecializationArgs() const {
2240 if (FunctionTemplateSpecializationInfo *Info
2241 = TemplateOrSpecialization
2242 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2243 return Info->TemplateArguments;
2248 const ASTTemplateArgumentListInfo *
2249 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2250 if (FunctionTemplateSpecializationInfo *Info
2251 = TemplateOrSpecialization
2252 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2253 return Info->TemplateArgumentsAsWritten;
2259 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2260 FunctionTemplateDecl *Template,
2261 const TemplateArgumentList *TemplateArgs,
2263 TemplateSpecializationKind TSK,
2264 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2265 SourceLocation PointOfInstantiation) {
2266 assert(TSK != TSK_Undeclared &&
2267 "Must specify the type of function template specialization");
2268 FunctionTemplateSpecializationInfo *Info
2269 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2271 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2273 TemplateArgsAsWritten,
2274 PointOfInstantiation);
2275 TemplateOrSpecialization = Info;
2276 Template->addSpecialization(Info, InsertPos);
2280 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2281 const UnresolvedSetImpl &Templates,
2282 const TemplateArgumentListInfo &TemplateArgs) {
2283 assert(TemplateOrSpecialization.isNull());
2284 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2285 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2286 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2287 void *Buffer = Context.Allocate(Size);
2288 DependentFunctionTemplateSpecializationInfo *Info =
2289 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2291 TemplateOrSpecialization = Info;
2294 DependentFunctionTemplateSpecializationInfo::
2295 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2296 const TemplateArgumentListInfo &TArgs)
2297 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2299 d.NumTemplates = Ts.size();
2300 d.NumArgs = TArgs.size();
2302 FunctionTemplateDecl **TsArray =
2303 const_cast<FunctionTemplateDecl**>(getTemplates());
2304 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2305 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2307 TemplateArgumentLoc *ArgsArray =
2308 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2309 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2310 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2313 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2314 // For a function template specialization, query the specialization
2315 // information object.
2316 FunctionTemplateSpecializationInfo *FTSInfo
2317 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2319 return FTSInfo->getTemplateSpecializationKind();
2321 MemberSpecializationInfo *MSInfo
2322 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2324 return MSInfo->getTemplateSpecializationKind();
2326 return TSK_Undeclared;
2330 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2331 SourceLocation PointOfInstantiation) {
2332 if (FunctionTemplateSpecializationInfo *FTSInfo
2333 = TemplateOrSpecialization.dyn_cast<
2334 FunctionTemplateSpecializationInfo*>()) {
2335 FTSInfo->setTemplateSpecializationKind(TSK);
2336 if (TSK != TSK_ExplicitSpecialization &&
2337 PointOfInstantiation.isValid() &&
2338 FTSInfo->getPointOfInstantiation().isInvalid())
2339 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2340 } else if (MemberSpecializationInfo *MSInfo
2341 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2342 MSInfo->setTemplateSpecializationKind(TSK);
2343 if (TSK != TSK_ExplicitSpecialization &&
2344 PointOfInstantiation.isValid() &&
2345 MSInfo->getPointOfInstantiation().isInvalid())
2346 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2348 llvm_unreachable("Function cannot have a template specialization kind");
2351 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2352 if (FunctionTemplateSpecializationInfo *FTSInfo
2353 = TemplateOrSpecialization.dyn_cast<
2354 FunctionTemplateSpecializationInfo*>())
2355 return FTSInfo->getPointOfInstantiation();
2356 else if (MemberSpecializationInfo *MSInfo
2357 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2358 return MSInfo->getPointOfInstantiation();
2360 return SourceLocation();
2363 bool FunctionDecl::isOutOfLine() const {
2364 if (Decl::isOutOfLine())
2367 // If this function was instantiated from a member function of a
2368 // class template, check whether that member function was defined out-of-line.
2369 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2370 const FunctionDecl *Definition;
2371 if (FD->hasBody(Definition))
2372 return Definition->isOutOfLine();
2375 // If this function was instantiated from a function template,
2376 // check whether that function template was defined out-of-line.
2377 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2378 const FunctionDecl *Definition;
2379 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2380 return Definition->isOutOfLine();
2386 SourceRange FunctionDecl::getSourceRange() const {
2387 return SourceRange(getOuterLocStart(), EndRangeLoc);
2390 unsigned FunctionDecl::getMemoryFunctionKind() const {
2391 IdentifierInfo *FnInfo = getIdentifier();
2396 // Builtin handling.
2397 switch (getBuiltinID()) {
2398 case Builtin::BI__builtin_memset:
2399 case Builtin::BI__builtin___memset_chk:
2400 case Builtin::BImemset:
2401 return Builtin::BImemset;
2403 case Builtin::BI__builtin_memcpy:
2404 case Builtin::BI__builtin___memcpy_chk:
2405 case Builtin::BImemcpy:
2406 return Builtin::BImemcpy;
2408 case Builtin::BI__builtin_memmove:
2409 case Builtin::BI__builtin___memmove_chk:
2410 case Builtin::BImemmove:
2411 return Builtin::BImemmove;
2413 case Builtin::BIstrlcpy:
2414 return Builtin::BIstrlcpy;
2415 case Builtin::BIstrlcat:
2416 return Builtin::BIstrlcat;
2418 case Builtin::BI__builtin_memcmp:
2419 case Builtin::BImemcmp:
2420 return Builtin::BImemcmp;
2422 case Builtin::BI__builtin_strncpy:
2423 case Builtin::BI__builtin___strncpy_chk:
2424 case Builtin::BIstrncpy:
2425 return Builtin::BIstrncpy;
2427 case Builtin::BI__builtin_strncmp:
2428 case Builtin::BIstrncmp:
2429 return Builtin::BIstrncmp;
2431 case Builtin::BI__builtin_strncasecmp:
2432 case Builtin::BIstrncasecmp:
2433 return Builtin::BIstrncasecmp;
2435 case Builtin::BI__builtin_strncat:
2436 case Builtin::BI__builtin___strncat_chk:
2437 case Builtin::BIstrncat:
2438 return Builtin::BIstrncat;
2440 case Builtin::BI__builtin_strndup:
2441 case Builtin::BIstrndup:
2442 return Builtin::BIstrndup;
2444 case Builtin::BI__builtin_strlen:
2445 case Builtin::BIstrlen:
2446 return Builtin::BIstrlen;
2450 if (FnInfo->isStr("memset"))
2451 return Builtin::BImemset;
2452 else if (FnInfo->isStr("memcpy"))
2453 return Builtin::BImemcpy;
2454 else if (FnInfo->isStr("memmove"))
2455 return Builtin::BImemmove;
2456 else if (FnInfo->isStr("memcmp"))
2457 return Builtin::BImemcmp;
2458 else if (FnInfo->isStr("strncpy"))
2459 return Builtin::BIstrncpy;
2460 else if (FnInfo->isStr("strncmp"))
2461 return Builtin::BIstrncmp;
2462 else if (FnInfo->isStr("strncasecmp"))
2463 return Builtin::BIstrncasecmp;
2464 else if (FnInfo->isStr("strncat"))
2465 return Builtin::BIstrncat;
2466 else if (FnInfo->isStr("strndup"))
2467 return Builtin::BIstrndup;
2468 else if (FnInfo->isStr("strlen"))
2469 return Builtin::BIstrlen;
2476 //===----------------------------------------------------------------------===//
2477 // FieldDecl Implementation
2478 //===----------------------------------------------------------------------===//
2480 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
2481 SourceLocation StartLoc, SourceLocation IdLoc,
2482 IdentifierInfo *Id, QualType T,
2483 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2484 InClassInitStyle InitStyle) {
2485 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
2486 BW, Mutable, InitStyle);
2489 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2490 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2491 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2492 0, QualType(), 0, 0, false, ICIS_NoInit);
2495 bool FieldDecl::isAnonymousStructOrUnion() const {
2496 if (!isImplicit() || getDeclName())
2499 if (const RecordType *Record = getType()->getAs<RecordType>())
2500 return Record->getDecl()->isAnonymousStructOrUnion();
2505 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2506 assert(isBitField() && "not a bitfield");
2507 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2508 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2511 unsigned FieldDecl::getFieldIndex() const {
2512 if (CachedFieldIndex) return CachedFieldIndex - 1;
2515 const RecordDecl *RD = getParent();
2516 const FieldDecl *LastFD = 0;
2517 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
2519 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2520 I != E; ++I, ++Index) {
2521 I->CachedFieldIndex = Index + 1;
2524 // Zero-length bitfields following non-bitfield members are ignored.
2525 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
2533 assert(CachedFieldIndex && "failed to find field in parent");
2534 return CachedFieldIndex - 1;
2537 SourceRange FieldDecl::getSourceRange() const {
2538 if (const Expr *E = InitializerOrBitWidth.getPointer())
2539 return SourceRange(getInnerLocStart(), E->getLocEnd());
2540 return DeclaratorDecl::getSourceRange();
2543 void FieldDecl::setBitWidth(Expr *Width) {
2544 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2545 "bit width or initializer already set");
2546 InitializerOrBitWidth.setPointer(Width);
2549 void FieldDecl::setInClassInitializer(Expr *Init) {
2550 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
2551 "bit width or initializer already set");
2552 InitializerOrBitWidth.setPointer(Init);
2555 //===----------------------------------------------------------------------===//
2556 // TagDecl Implementation
2557 //===----------------------------------------------------------------------===//
2559 SourceLocation TagDecl::getOuterLocStart() const {
2560 return getTemplateOrInnerLocStart(this);
2563 SourceRange TagDecl::getSourceRange() const {
2564 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
2565 return SourceRange(getOuterLocStart(), E);
2568 TagDecl* TagDecl::getCanonicalDecl() {
2569 return getFirstDeclaration();
2572 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2573 TypedefNameDeclOrQualifier = TDD;
2575 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2576 ClearLinkageCache();
2579 void TagDecl::startDefinition() {
2580 IsBeingDefined = true;
2582 if (isa<CXXRecordDecl>(this)) {
2583 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2584 struct CXXRecordDecl::DefinitionData *Data =
2585 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
2586 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2587 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
2591 void TagDecl::completeDefinition() {
2592 assert((!isa<CXXRecordDecl>(this) ||
2593 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2594 "definition completed but not started");
2596 IsCompleteDefinition = true;
2597 IsBeingDefined = false;
2599 if (ASTMutationListener *L = getASTMutationListener())
2600 L->CompletedTagDefinition(this);
2603 TagDecl *TagDecl::getDefinition() const {
2604 if (isCompleteDefinition())
2605 return const_cast<TagDecl *>(this);
2606 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2607 return CXXRD->getDefinition();
2609 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
2611 if (R->isCompleteDefinition())
2617 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2619 // Make sure the extended qualifier info is allocated.
2621 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2622 // Set qualifier info.
2623 getExtInfo()->QualifierLoc = QualifierLoc;
2625 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2627 if (getExtInfo()->NumTemplParamLists == 0) {
2628 getASTContext().Deallocate(getExtInfo());
2629 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
2632 getExtInfo()->QualifierLoc = QualifierLoc;
2637 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2638 unsigned NumTPLists,
2639 TemplateParameterList **TPLists) {
2640 assert(NumTPLists > 0);
2641 // Make sure the extended decl info is allocated.
2643 // Allocate external info struct.
2644 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2645 // Set the template parameter lists info.
2646 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2649 //===----------------------------------------------------------------------===//
2650 // EnumDecl Implementation
2651 //===----------------------------------------------------------------------===//
2653 void EnumDecl::anchor() { }
2655 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2656 SourceLocation StartLoc, SourceLocation IdLoc,
2658 EnumDecl *PrevDecl, bool IsScoped,
2659 bool IsScopedUsingClassTag, bool IsFixed) {
2660 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
2661 IsScoped, IsScopedUsingClassTag, IsFixed);
2662 C.getTypeDeclType(Enum, PrevDecl);
2666 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2667 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2668 return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2669 false, false, false);
2672 void EnumDecl::completeDefinition(QualType NewType,
2673 QualType NewPromotionType,
2674 unsigned NumPositiveBits,
2675 unsigned NumNegativeBits) {
2676 assert(!isCompleteDefinition() && "Cannot redefine enums!");
2678 IntegerType = NewType.getTypePtr();
2679 PromotionType = NewPromotionType;
2680 setNumPositiveBits(NumPositiveBits);
2681 setNumNegativeBits(NumNegativeBits);
2682 TagDecl::completeDefinition();
2685 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2686 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2687 return MSI->getTemplateSpecializationKind();
2689 return TSK_Undeclared;
2692 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2693 SourceLocation PointOfInstantiation) {
2694 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2695 assert(MSI && "Not an instantiated member enumeration?");
2696 MSI->setTemplateSpecializationKind(TSK);
2697 if (TSK != TSK_ExplicitSpecialization &&
2698 PointOfInstantiation.isValid() &&
2699 MSI->getPointOfInstantiation().isInvalid())
2700 MSI->setPointOfInstantiation(PointOfInstantiation);
2703 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
2704 if (SpecializationInfo)
2705 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
2710 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2711 TemplateSpecializationKind TSK) {
2712 assert(!SpecializationInfo && "Member enum is already a specialization");
2713 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
2716 //===----------------------------------------------------------------------===//
2717 // RecordDecl Implementation
2718 //===----------------------------------------------------------------------===//
2720 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2721 SourceLocation StartLoc, SourceLocation IdLoc,
2722 IdentifierInfo *Id, RecordDecl *PrevDecl)
2723 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
2724 HasFlexibleArrayMember = false;
2725 AnonymousStructOrUnion = false;
2726 HasObjectMember = false;
2727 LoadedFieldsFromExternalStorage = false;
2728 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
2731 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2732 SourceLocation StartLoc, SourceLocation IdLoc,
2733 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2734 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2736 C.getTypeDeclType(R, PrevDecl);
2740 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2741 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
2742 return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2743 SourceLocation(), 0, 0);
2746 bool RecordDecl::isInjectedClassName() const {
2747 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
2748 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2751 RecordDecl::field_iterator RecordDecl::field_begin() const {
2752 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2753 LoadFieldsFromExternalStorage();
2755 return field_iterator(decl_iterator(FirstDecl));
2758 /// completeDefinition - Notes that the definition of this type is now
2760 void RecordDecl::completeDefinition() {
2761 assert(!isCompleteDefinition() && "Cannot redefine record!");
2762 TagDecl::completeDefinition();
2765 void RecordDecl::LoadFieldsFromExternalStorage() const {
2766 ExternalASTSource *Source = getASTContext().getExternalSource();
2767 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2769 // Notify that we have a RecordDecl doing some initialization.
2770 ExternalASTSource::Deserializing TheFields(Source);
2772 SmallVector<Decl*, 64> Decls;
2773 LoadedFieldsFromExternalStorage = true;
2774 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2778 case ELR_AlreadyLoaded:
2784 // Check that all decls we got were FieldDecls.
2785 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2786 assert(isa<FieldDecl>(Decls[i]));
2792 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2793 /*FieldsAlreadyLoaded=*/false);
2796 //===----------------------------------------------------------------------===//
2797 // BlockDecl Implementation
2798 //===----------------------------------------------------------------------===//
2800 void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
2801 assert(ParamInfo == 0 && "Already has param info!");
2803 // Zero params -> null pointer.
2804 if (!NewParamInfo.empty()) {
2805 NumParams = NewParamInfo.size();
2806 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2807 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2811 void BlockDecl::setCaptures(ASTContext &Context,
2812 const Capture *begin,
2814 bool capturesCXXThis) {
2815 CapturesCXXThis = capturesCXXThis;
2823 NumCaptures = end - begin;
2825 // Avoid new Capture[] because we don't want to provide a default
2827 size_t allocationSize = NumCaptures * sizeof(Capture);
2828 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2829 memcpy(buffer, begin, allocationSize);
2830 Captures = static_cast<Capture*>(buffer);
2833 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2834 for (capture_const_iterator
2835 i = capture_begin(), e = capture_end(); i != e; ++i)
2836 // Only auto vars can be captured, so no redeclaration worries.
2837 if (i->getVariable() == variable)
2843 SourceRange BlockDecl::getSourceRange() const {
2844 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2847 //===----------------------------------------------------------------------===//
2848 // Other Decl Allocation/Deallocation Method Implementations
2849 //===----------------------------------------------------------------------===//
2851 void TranslationUnitDecl::anchor() { }
2853 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2854 return new (C) TranslationUnitDecl(C);
2857 void LabelDecl::anchor() { }
2859 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2860 SourceLocation IdentL, IdentifierInfo *II) {
2861 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2864 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2865 SourceLocation IdentL, IdentifierInfo *II,
2866 SourceLocation GnuLabelL) {
2867 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2868 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
2871 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2872 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
2873 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
2876 void ValueDecl::anchor() { }
2878 void ImplicitParamDecl::anchor() { }
2880 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
2881 SourceLocation IdLoc,
2884 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
2887 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
2889 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
2890 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
2893 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
2894 SourceLocation StartLoc,
2895 const DeclarationNameInfo &NameInfo,
2896 QualType T, TypeSourceInfo *TInfo,
2897 StorageClass SC, StorageClass SCAsWritten,
2898 bool isInlineSpecified,
2899 bool hasWrittenPrototype,
2900 bool isConstexprSpecified) {
2901 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2902 T, TInfo, SC, SCAsWritten,
2904 isConstexprSpecified);
2905 New->HasWrittenPrototype = hasWrittenPrototype;
2909 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2910 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
2911 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
2912 DeclarationNameInfo(), QualType(), 0,
2913 SC_None, SC_None, false, false);
2916 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2917 return new (C) BlockDecl(DC, L);
2920 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2921 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
2922 return new (Mem) BlockDecl(0, SourceLocation());
2925 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2927 IdentifierInfo *Id, QualType T,
2928 Expr *E, const llvm::APSInt &V) {
2929 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2933 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2934 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
2935 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
2939 void IndirectFieldDecl::anchor() { }
2942 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2943 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2945 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2948 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
2950 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
2951 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
2955 SourceRange EnumConstantDecl::getSourceRange() const {
2956 SourceLocation End = getLocation();
2958 End = Init->getLocEnd();
2959 return SourceRange(getLocation(), End);
2962 void TypeDecl::anchor() { }
2964 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
2965 SourceLocation StartLoc, SourceLocation IdLoc,
2966 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2967 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
2970 void TypedefNameDecl::anchor() { }
2972 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2973 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
2974 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2977 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2978 SourceLocation StartLoc,
2979 SourceLocation IdLoc, IdentifierInfo *Id,
2980 TypeSourceInfo *TInfo) {
2981 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2984 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2985 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
2986 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2989 SourceRange TypedefDecl::getSourceRange() const {
2990 SourceLocation RangeEnd = getLocation();
2991 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2992 if (typeIsPostfix(TInfo->getType()))
2993 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2995 return SourceRange(getLocStart(), RangeEnd);
2998 SourceRange TypeAliasDecl::getSourceRange() const {
2999 SourceLocation RangeEnd = getLocStart();
3000 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3001 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3002 return SourceRange(getLocStart(), RangeEnd);
3005 void FileScopeAsmDecl::anchor() { }
3007 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3009 SourceLocation AsmLoc,
3010 SourceLocation RParenLoc) {
3011 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
3014 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3016 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3017 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3020 //===----------------------------------------------------------------------===//
3021 // ImportDecl Implementation
3022 //===----------------------------------------------------------------------===//
3024 /// \brief Retrieve the number of module identifiers needed to name the given
3026 static unsigned getNumModuleIdentifiers(Module *Mod) {
3027 unsigned Result = 1;
3028 while (Mod->Parent) {
3035 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3037 ArrayRef<SourceLocation> IdentifierLocs)
3038 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3041 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3042 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3043 memcpy(StoredLocs, IdentifierLocs.data(),
3044 IdentifierLocs.size() * sizeof(SourceLocation));
3047 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3048 Module *Imported, SourceLocation EndLoc)
3049 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3052 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3055 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3056 SourceLocation StartLoc, Module *Imported,
3057 ArrayRef<SourceLocation> IdentifierLocs) {
3058 void *Mem = C.Allocate(sizeof(ImportDecl) +
3059 IdentifierLocs.size() * sizeof(SourceLocation));
3060 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3063 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3064 SourceLocation StartLoc,
3066 SourceLocation EndLoc) {
3067 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
3068 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
3069 Import->setImplicit();
3073 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3074 unsigned NumLocations) {
3075 void *Mem = AllocateDeserializedDecl(C, ID,
3076 (sizeof(ImportDecl) +
3077 NumLocations * sizeof(SourceLocation)));
3078 return new (Mem) ImportDecl(EmptyShell());
3081 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3082 if (!ImportedAndComplete.getInt())
3083 return ArrayRef<SourceLocation>();
3085 const SourceLocation *StoredLocs
3086 = reinterpret_cast<const SourceLocation *>(this + 1);
3087 return ArrayRef<SourceLocation>(StoredLocs,
3088 getNumModuleIdentifiers(getImportedModule()));
3091 SourceRange ImportDecl::getSourceRange() const {
3092 if (!ImportedAndComplete.getInt())
3093 return SourceRange(getLocation(),
3094 *reinterpret_cast<const SourceLocation *>(this + 1));
3096 return SourceRange(getLocation(), getIdentifierLocs().back());