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