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