xref: /llvm-project-15.0.7/clang/lib/AST/Decl.cpp (revision 8434e60f)
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/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/Stmt.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/IdentifierTable.h"
28 #include "clang/Basic/Module.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/type_traits.h"
33 #include <algorithm>
34 
35 using namespace clang;
36 
37 Decl *clang::getPrimaryMergedDecl(Decl *D) {
38   return D->getASTContext().getPrimaryMergedDecl(D);
39 }
40 
41 //===----------------------------------------------------------------------===//
42 // NamedDecl Implementation
43 //===----------------------------------------------------------------------===//
44 
45 // Visibility rules aren't rigorously externally specified, but here
46 // are the basic principles behind what we implement:
47 //
48 // 1. An explicit visibility attribute is generally a direct expression
49 // of the user's intent and should be honored.  Only the innermost
50 // visibility attribute applies.  If no visibility attribute applies,
51 // global visibility settings are considered.
52 //
53 // 2. There is one caveat to the above: on or in a template pattern,
54 // an explicit visibility attribute is just a default rule, and
55 // visibility can be decreased by the visibility of template
56 // arguments.  But this, too, has an exception: an attribute on an
57 // explicit specialization or instantiation causes all the visibility
58 // restrictions of the template arguments to be ignored.
59 //
60 // 3. A variable that does not otherwise have explicit visibility can
61 // be restricted by the visibility of its type.
62 //
63 // 4. A visibility restriction is explicit if it comes from an
64 // attribute (or something like it), not a global visibility setting.
65 // When emitting a reference to an external symbol, visibility
66 // restrictions are ignored unless they are explicit.
67 //
68 // 5. When computing the visibility of a non-type, including a
69 // non-type member of a class, only non-type visibility restrictions
70 // are considered: the 'visibility' attribute, global value-visibility
71 // settings, and a few special cases like __private_extern.
72 //
73 // 6. When computing the visibility of a type, including a type member
74 // of a class, only type visibility restrictions are considered:
75 // the 'type_visibility' attribute and global type-visibility settings.
76 // However, a 'visibility' attribute counts as a 'type_visibility'
77 // attribute on any declaration that only has the former.
78 //
79 // The visibility of a "secondary" entity, like a template argument,
80 // is computed using the kind of that entity, not the kind of the
81 // primary entity for which we are computing visibility.  For example,
82 // the visibility of a specialization of either of these templates:
83 //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
84 //   template <class T, bool (&compare)(T, X)> class matcher;
85 // is restricted according to the type visibility of the argument 'T',
86 // the type visibility of 'bool(&)(T,X)', and the value visibility of
87 // the argument function 'compare'.  That 'has_match' is a value
88 // and 'matcher' is a type only matters when looking for attributes
89 // and settings from the immediate context.
90 
91 const unsigned IgnoreExplicitVisibilityBit = 2;
92 const unsigned IgnoreAllVisibilityBit = 4;
93 
94 /// Kinds of LV computation.  The linkage side of the computation is
95 /// always the same, but different things can change how visibility is
96 /// computed.
97 enum LVComputationKind {
98   /// Do an LV computation for, ultimately, a type.
99   /// Visibility may be restricted by type visibility settings and
100   /// the visibility of template arguments.
101   LVForType = NamedDecl::VisibilityForType,
102 
103   /// Do an LV computation for, ultimately, a non-type declaration.
104   /// Visibility may be restricted by value visibility settings and
105   /// the visibility of template arguments.
106   LVForValue = NamedDecl::VisibilityForValue,
107 
108   /// Do an LV computation for, ultimately, a type that already has
109   /// some sort of explicit visibility.  Visibility may only be
110   /// restricted by the visibility of template arguments.
111   LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
112 
113   /// Do an LV computation for, ultimately, a non-type declaration
114   /// that already has some sort of explicit visibility.  Visibility
115   /// may only be restricted by the visibility of template arguments.
116   LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
117 
118   /// Do an LV computation when we only care about the linkage.
119   LVForLinkageOnly =
120       LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
121 };
122 
123 /// Does this computation kind permit us to consider additional
124 /// visibility settings from attributes and the like?
125 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
126   return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
127 }
128 
129 /// Given an LVComputationKind, return one of the same type/value sort
130 /// that records that it already has explicit visibility.
131 static LVComputationKind
132 withExplicitVisibilityAlready(LVComputationKind oldKind) {
133   LVComputationKind newKind =
134     static_cast<LVComputationKind>(unsigned(oldKind) |
135                                    IgnoreExplicitVisibilityBit);
136   assert(oldKind != LVForType          || newKind == LVForExplicitType);
137   assert(oldKind != LVForValue         || newKind == LVForExplicitValue);
138   assert(oldKind != LVForExplicitType  || newKind == LVForExplicitType);
139   assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
140   return newKind;
141 }
142 
143 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
144                                                   LVComputationKind kind) {
145   assert(!hasExplicitVisibilityAlready(kind) &&
146          "asking for explicit visibility when we shouldn't be");
147   return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
148 }
149 
150 /// Is the given declaration a "type" or a "value" for the purposes of
151 /// visibility computation?
152 static bool usesTypeVisibility(const NamedDecl *D) {
153   return isa<TypeDecl>(D) ||
154          isa<ClassTemplateDecl>(D) ||
155          isa<ObjCInterfaceDecl>(D);
156 }
157 
158 /// Does the given declaration have member specialization information,
159 /// and if so, is it an explicit specialization?
160 template <class T> static typename
161 llvm::enable_if_c<!llvm::is_base_of<RedeclarableTemplateDecl, T>::value,
162                   bool>::type
163 isExplicitMemberSpecialization(const T *D) {
164   if (const MemberSpecializationInfo *member =
165         D->getMemberSpecializationInfo()) {
166     return member->isExplicitSpecialization();
167   }
168   return false;
169 }
170 
171 /// For templates, this question is easier: a member template can't be
172 /// explicitly instantiated, so there's a single bit indicating whether
173 /// or not this is an explicit member specialization.
174 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
175   return D->isMemberSpecialization();
176 }
177 
178 /// Given a visibility attribute, return the explicit visibility
179 /// associated with it.
180 template <class T>
181 static Visibility getVisibilityFromAttr(const T *attr) {
182   switch (attr->getVisibility()) {
183   case T::Default:
184     return DefaultVisibility;
185   case T::Hidden:
186     return HiddenVisibility;
187   case T::Protected:
188     return ProtectedVisibility;
189   }
190   llvm_unreachable("bad visibility kind");
191 }
192 
193 /// Return the explicit visibility of the given declaration.
194 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
195                                     NamedDecl::ExplicitVisibilityKind kind) {
196   // If we're ultimately computing the visibility of a type, look for
197   // a 'type_visibility' attribute before looking for 'visibility'.
198   if (kind == NamedDecl::VisibilityForType) {
199     if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
200       return getVisibilityFromAttr(A);
201     }
202   }
203 
204   // If this declaration has an explicit visibility attribute, use it.
205   if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
206     return getVisibilityFromAttr(A);
207   }
208 
209   // If we're on Mac OS X, an 'availability' for Mac OS X attribute
210   // implies visibility(default).
211   if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
212     for (specific_attr_iterator<AvailabilityAttr>
213               A = D->specific_attr_begin<AvailabilityAttr>(),
214            AEnd = D->specific_attr_end<AvailabilityAttr>();
215          A != AEnd; ++A)
216       if ((*A)->getPlatform()->getName().equals("macosx"))
217         return DefaultVisibility;
218   }
219 
220   return None;
221 }
222 
223 static LinkageInfo
224 getLVForType(const Type &T, LVComputationKind computation) {
225   if (computation == LVForLinkageOnly)
226     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
227   return T.getLinkageAndVisibility();
228 }
229 
230 /// \brief Get the most restrictive linkage for the types in the given
231 /// template parameter list.  For visibility purposes, template
232 /// parameters are part of the signature of a template.
233 static LinkageInfo
234 getLVForTemplateParameterList(const TemplateParameterList *params,
235                               LVComputationKind computation) {
236   LinkageInfo LV;
237   for (TemplateParameterList::const_iterator P = params->begin(),
238                                           PEnd = params->end();
239        P != PEnd; ++P) {
240 
241     // Template type parameters are the most common and never
242     // contribute to visibility, pack or not.
243     if (isa<TemplateTypeParmDecl>(*P))
244       continue;
245 
246     // Non-type template parameters can be restricted by the value type, e.g.
247     //   template <enum X> class A { ... };
248     // We have to be careful here, though, because we can be dealing with
249     // dependent types.
250     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
251       // Handle the non-pack case first.
252       if (!NTTP->isExpandedParameterPack()) {
253         if (!NTTP->getType()->isDependentType()) {
254           LV.merge(getLVForType(*NTTP->getType(), computation));
255         }
256         continue;
257       }
258 
259       // Look at all the types in an expanded pack.
260       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
261         QualType type = NTTP->getExpansionType(i);
262         if (!type->isDependentType())
263           LV.merge(type->getLinkageAndVisibility());
264       }
265       continue;
266     }
267 
268     // Template template parameters can be restricted by their
269     // template parameters, recursively.
270     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
271 
272     // Handle the non-pack case first.
273     if (!TTP->isExpandedParameterPack()) {
274       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
275                                              computation));
276       continue;
277     }
278 
279     // Look at all expansions in an expanded pack.
280     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
281            i != n; ++i) {
282       LV.merge(getLVForTemplateParameterList(
283           TTP->getExpansionTemplateParameters(i), computation));
284     }
285   }
286 
287   return LV;
288 }
289 
290 /// getLVForDecl - Get the linkage and visibility for the given declaration.
291 static LinkageInfo getLVForDecl(const NamedDecl *D,
292                                 LVComputationKind computation);
293 
294 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
295   const Decl *Ret = NULL;
296   const DeclContext *DC = D->getDeclContext();
297   while (DC->getDeclKind() != Decl::TranslationUnit) {
298     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
299       Ret = cast<Decl>(DC);
300     DC = DC->getParent();
301   }
302   return Ret;
303 }
304 
305 /// \brief Get the most restrictive linkage for the types and
306 /// declarations in the given template argument list.
307 ///
308 /// Note that we don't take an LVComputationKind because we always
309 /// want to honor the visibility of template arguments in the same way.
310 static LinkageInfo
311 getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args,
312                              LVComputationKind computation) {
313   LinkageInfo LV;
314 
315   for (unsigned i = 0, e = args.size(); i != e; ++i) {
316     const TemplateArgument &arg = args[i];
317     switch (arg.getKind()) {
318     case TemplateArgument::Null:
319     case TemplateArgument::Integral:
320     case TemplateArgument::Expression:
321       continue;
322 
323     case TemplateArgument::Type:
324       LV.merge(getLVForType(*arg.getAsType(), computation));
325       continue;
326 
327     case TemplateArgument::Declaration:
328       if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
329         assert(!usesTypeVisibility(ND));
330         LV.merge(getLVForDecl(ND, computation));
331       }
332       continue;
333 
334     case TemplateArgument::NullPtr:
335       LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
336       continue;
337 
338     case TemplateArgument::Template:
339     case TemplateArgument::TemplateExpansion:
340       if (TemplateDecl *Template
341                 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
342         LV.merge(getLVForDecl(Template, computation));
343       continue;
344 
345     case TemplateArgument::Pack:
346       LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray(), computation));
347       continue;
348     }
349     llvm_unreachable("bad template argument kind");
350   }
351 
352   return LV;
353 }
354 
355 static LinkageInfo
356 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
357                              LVComputationKind computation) {
358   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
359 }
360 
361 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
362                         const FunctionTemplateSpecializationInfo *specInfo) {
363   // Include visibility from the template parameters and arguments
364   // only if this is not an explicit instantiation or specialization
365   // with direct explicit visibility.  (Implicit instantiations won't
366   // have a direct attribute.)
367   if (!specInfo->isExplicitInstantiationOrSpecialization())
368     return true;
369 
370   return !fn->hasAttr<VisibilityAttr>();
371 }
372 
373 /// Merge in template-related linkage and visibility for the given
374 /// function template specialization.
375 ///
376 /// We don't need a computation kind here because we can assume
377 /// LVForValue.
378 ///
379 /// \param[out] LV the computation to use for the parent
380 static void
381 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
382                 const FunctionTemplateSpecializationInfo *specInfo,
383                 LVComputationKind computation) {
384   bool considerVisibility =
385     shouldConsiderTemplateVisibility(fn, specInfo);
386 
387   // Merge information from the template parameters.
388   FunctionTemplateDecl *temp = specInfo->getTemplate();
389   LinkageInfo tempLV =
390     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
391   LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
392 
393   // Merge information from the template arguments.
394   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
395   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
396   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
397 }
398 
399 /// Does the given declaration have a direct visibility attribute
400 /// that would match the given rules?
401 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
402                                          LVComputationKind computation) {
403   switch (computation) {
404   case LVForType:
405   case LVForExplicitType:
406     if (D->hasAttr<TypeVisibilityAttr>())
407       return true;
408     // fallthrough
409   case LVForValue:
410   case LVForExplicitValue:
411     if (D->hasAttr<VisibilityAttr>())
412       return true;
413     return false;
414   case LVForLinkageOnly:
415     return false;
416   }
417   llvm_unreachable("bad visibility computation kind");
418 }
419 
420 /// Should we consider visibility associated with the template
421 /// arguments and parameters of the given class template specialization?
422 static bool shouldConsiderTemplateVisibility(
423                                  const ClassTemplateSpecializationDecl *spec,
424                                  LVComputationKind computation) {
425   // Include visibility from the template parameters and arguments
426   // only if this is not an explicit instantiation or specialization
427   // with direct explicit visibility (and note that implicit
428   // instantiations won't have a direct attribute).
429   //
430   // Furthermore, we want to ignore template parameters and arguments
431   // for an explicit specialization when computing the visibility of a
432   // member thereof with explicit visibility.
433   //
434   // This is a bit complex; let's unpack it.
435   //
436   // An explicit class specialization is an independent, top-level
437   // declaration.  As such, if it or any of its members has an
438   // explicit visibility attribute, that must directly express the
439   // user's intent, and we should honor it.  The same logic applies to
440   // an explicit instantiation of a member of such a thing.
441 
442   // Fast path: if this is not an explicit instantiation or
443   // specialization, we always want to consider template-related
444   // visibility restrictions.
445   if (!spec->isExplicitInstantiationOrSpecialization())
446     return true;
447 
448   // This is the 'member thereof' check.
449   if (spec->isExplicitSpecialization() &&
450       hasExplicitVisibilityAlready(computation))
451     return false;
452 
453   return !hasDirectVisibilityAttribute(spec, computation);
454 }
455 
456 /// Merge in template-related linkage and visibility for the given
457 /// class template specialization.
458 static void mergeTemplateLV(LinkageInfo &LV,
459                             const ClassTemplateSpecializationDecl *spec,
460                             LVComputationKind computation) {
461   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
462 
463   // Merge information from the template parameters, but ignore
464   // visibility if we're only considering template arguments.
465 
466   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
467   LinkageInfo tempLV =
468     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
469   LV.mergeMaybeWithVisibility(tempLV,
470            considerVisibility && !hasExplicitVisibilityAlready(computation));
471 
472   // Merge information from the template arguments.  We ignore
473   // template-argument visibility if we've got an explicit
474   // instantiation with a visibility attribute.
475   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
476   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
477   if (considerVisibility)
478     LV.mergeVisibility(argsLV);
479   LV.mergeExternalVisibility(argsLV);
480 }
481 
482 static bool useInlineVisibilityHidden(const NamedDecl *D) {
483   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
484   const LangOptions &Opts = D->getASTContext().getLangOpts();
485   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
486     return false;
487 
488   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
489   if (!FD)
490     return false;
491 
492   TemplateSpecializationKind TSK = TSK_Undeclared;
493   if (FunctionTemplateSpecializationInfo *spec
494       = FD->getTemplateSpecializationInfo()) {
495     TSK = spec->getTemplateSpecializationKind();
496   } else if (MemberSpecializationInfo *MSI =
497              FD->getMemberSpecializationInfo()) {
498     TSK = MSI->getTemplateSpecializationKind();
499   }
500 
501   const FunctionDecl *Def = 0;
502   // InlineVisibilityHidden only applies to definitions, and
503   // isInlined() only gives meaningful answers on definitions
504   // anyway.
505   return TSK != TSK_ExplicitInstantiationDeclaration &&
506     TSK != TSK_ExplicitInstantiationDefinition &&
507     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
508 }
509 
510 template <typename T> static bool isFirstInExternCContext(T *D) {
511   const T *First = D->getFirstDecl();
512   return First->isInExternCContext();
513 }
514 
515 static bool isSingleLineExternC(const Decl &D) {
516   if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
517     if (SD->getLanguage() == LinkageSpecDecl::lang_c && !SD->hasBraces())
518       return true;
519   return false;
520 }
521 
522 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
523                                               LVComputationKind computation) {
524   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
525          "Not a name having namespace scope");
526   ASTContext &Context = D->getASTContext();
527 
528   // C++ [basic.link]p3:
529   //   A name having namespace scope (3.3.6) has internal linkage if it
530   //   is the name of
531   //     - an object, reference, function or function template that is
532   //       explicitly declared static; or,
533   // (This bullet corresponds to C99 6.2.2p3.)
534   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
535     // Explicitly declared static.
536     if (Var->getStorageClass() == SC_Static)
537       return LinkageInfo::internal();
538 
539     // - a non-volatile object or reference that is explicitly declared const
540     //   or constexpr and neither explicitly declared extern nor previously
541     //   declared to have external linkage; or (there is no equivalent in C99)
542     if (Context.getLangOpts().CPlusPlus &&
543         Var->getType().isConstQualified() &&
544         !Var->getType().isVolatileQualified()) {
545       const VarDecl *PrevVar = Var->getPreviousDecl();
546       if (PrevVar)
547         return getLVForDecl(PrevVar, computation);
548 
549       if (Var->getStorageClass() != SC_Extern &&
550           Var->getStorageClass() != SC_PrivateExtern &&
551           !isSingleLineExternC(*Var))
552         return LinkageInfo::internal();
553     }
554 
555     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
556          PrevVar = PrevVar->getPreviousDecl()) {
557       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
558           Var->getStorageClass() == SC_None)
559         return PrevVar->getLinkageAndVisibility();
560       // Explicitly declared static.
561       if (PrevVar->getStorageClass() == SC_Static)
562         return LinkageInfo::internal();
563     }
564   } else if (const FunctionDecl *Function = D->getAsFunction()) {
565     // C++ [temp]p4:
566     //   A non-member function template can have internal linkage; any
567     //   other template name shall have external linkage.
568 
569     // Explicitly declared static.
570     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
571       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
572   }
573   //   - a data member of an anonymous union.
574   assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
575   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
576 
577   if (D->isInAnonymousNamespace()) {
578     const VarDecl *Var = dyn_cast<VarDecl>(D);
579     const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
580     if ((!Var || !isFirstInExternCContext(Var)) &&
581         (!Func || !isFirstInExternCContext(Func)))
582       return LinkageInfo::uniqueExternal();
583   }
584 
585   // Set up the defaults.
586 
587   // C99 6.2.2p5:
588   //   If the declaration of an identifier for an object has file
589   //   scope and no storage-class specifier, its linkage is
590   //   external.
591   LinkageInfo LV;
592 
593   if (!hasExplicitVisibilityAlready(computation)) {
594     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
595       LV.mergeVisibility(*Vis, true);
596     } else {
597       // If we're declared in a namespace with a visibility attribute,
598       // use that namespace's visibility, and it still counts as explicit.
599       for (const DeclContext *DC = D->getDeclContext();
600            !isa<TranslationUnitDecl>(DC);
601            DC = DC->getParent()) {
602         const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
603         if (!ND) continue;
604         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
605           LV.mergeVisibility(*Vis, true);
606           break;
607         }
608       }
609     }
610 
611     // Add in global settings if the above didn't give us direct visibility.
612     if (!LV.isVisibilityExplicit()) {
613       // Use global type/value visibility as appropriate.
614       Visibility globalVisibility;
615       if (computation == LVForValue) {
616         globalVisibility = Context.getLangOpts().getValueVisibilityMode();
617       } else {
618         assert(computation == LVForType);
619         globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
620       }
621       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
622 
623       // If we're paying attention to global visibility, apply
624       // -finline-visibility-hidden if this is an inline method.
625       if (useInlineVisibilityHidden(D))
626         LV.mergeVisibility(HiddenVisibility, true);
627     }
628   }
629 
630   // C++ [basic.link]p4:
631 
632   //   A name having namespace scope has external linkage if it is the
633   //   name of
634   //
635   //     - an object or reference, unless it has internal linkage; or
636   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
637     // GCC applies the following optimization to variables and static
638     // data members, but not to functions:
639     //
640     // Modify the variable's LV by the LV of its type unless this is
641     // C or extern "C".  This follows from [basic.link]p9:
642     //   A type without linkage shall not be used as the type of a
643     //   variable or function with external linkage unless
644     //    - the entity has C language linkage, or
645     //    - the entity is declared within an unnamed namespace, or
646     //    - the entity is not used or is defined in the same
647     //      translation unit.
648     // and [basic.link]p10:
649     //   ...the types specified by all declarations referring to a
650     //   given variable or function shall be identical...
651     // C does not have an equivalent rule.
652     //
653     // Ignore this if we've got an explicit attribute;  the user
654     // probably knows what they're doing.
655     //
656     // Note that we don't want to make the variable non-external
657     // because of this, but unique-external linkage suits us.
658     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
659       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
660       if (TypeLV.getLinkage() != ExternalLinkage)
661         return LinkageInfo::uniqueExternal();
662       if (!LV.isVisibilityExplicit())
663         LV.mergeVisibility(TypeLV);
664     }
665 
666     if (Var->getStorageClass() == SC_PrivateExtern)
667       LV.mergeVisibility(HiddenVisibility, true);
668 
669     // Note that Sema::MergeVarDecl already takes care of implementing
670     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
671     // to do it here.
672 
673   //     - a function, unless it has internal linkage; or
674   } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
675     // In theory, we can modify the function's LV by the LV of its
676     // type unless it has C linkage (see comment above about variables
677     // for justification).  In practice, GCC doesn't do this, so it's
678     // just too painful to make work.
679 
680     if (Function->getStorageClass() == SC_PrivateExtern)
681       LV.mergeVisibility(HiddenVisibility, true);
682 
683     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
684     // merging storage classes and visibility attributes, so we don't have to
685     // look at previous decls in here.
686 
687     // In C++, then if the type of the function uses a type with
688     // unique-external linkage, it's not legally usable from outside
689     // this translation unit.  However, we should use the C linkage
690     // rules instead for extern "C" declarations.
691     if (Context.getLangOpts().CPlusPlus &&
692         !Function->isInExternCContext()) {
693       // Only look at the type-as-written. If this function has an auto-deduced
694       // return type, we can't compute the linkage of that type because it could
695       // require looking at the linkage of this function, and we don't need this
696       // for correctness because the type is not part of the function's
697       // signature.
698       // FIXME: This is a hack. We should be able to solve this circularity and
699       // the one in getLVForClassMember for Functions some other way.
700       QualType TypeAsWritten = Function->getType();
701       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
702         TypeAsWritten = TSI->getType();
703       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
704         return LinkageInfo::uniqueExternal();
705     }
706 
707     // Consider LV from the template and the template arguments.
708     // We're at file scope, so we do not need to worry about nested
709     // specializations.
710     if (FunctionTemplateSpecializationInfo *specInfo
711                                = Function->getTemplateSpecializationInfo()) {
712       mergeTemplateLV(LV, Function, specInfo, computation);
713     }
714 
715   //     - a named class (Clause 9), or an unnamed class defined in a
716   //       typedef declaration in which the class has the typedef name
717   //       for linkage purposes (7.1.3); or
718   //     - a named enumeration (7.2), or an unnamed enumeration
719   //       defined in a typedef declaration in which the enumeration
720   //       has the typedef name for linkage purposes (7.1.3); or
721   } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
722     // Unnamed tags have no linkage.
723     if (!Tag->hasNameForLinkage())
724       return LinkageInfo::none();
725 
726     // If this is a class template specialization, consider the
727     // linkage of the template and template arguments.  We're at file
728     // scope, so we do not need to worry about nested specializations.
729     if (const ClassTemplateSpecializationDecl *spec
730           = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
731       mergeTemplateLV(LV, spec, computation);
732     }
733 
734   //     - an enumerator belonging to an enumeration with external linkage;
735   } else if (isa<EnumConstantDecl>(D)) {
736     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
737                                       computation);
738     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
739       return LinkageInfo::none();
740     LV.merge(EnumLV);
741 
742   //     - a template, unless it is a function template that has
743   //       internal linkage (Clause 14);
744   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
745     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
746     LinkageInfo tempLV =
747       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
748     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
749 
750   //     - a namespace (7.3), unless it is declared within an unnamed
751   //       namespace.
752   } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
753     return LV;
754 
755   // By extension, we assign external linkage to Objective-C
756   // interfaces.
757   } else if (isa<ObjCInterfaceDecl>(D)) {
758     // fallout
759 
760   // Everything not covered here has no linkage.
761   } else {
762     return LinkageInfo::none();
763   }
764 
765   // If we ended up with non-external linkage, visibility should
766   // always be default.
767   if (LV.getLinkage() != ExternalLinkage)
768     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
769 
770   return LV;
771 }
772 
773 static LinkageInfo getLVForClassMember(const NamedDecl *D,
774                                        LVComputationKind computation) {
775   // Only certain class members have linkage.  Note that fields don't
776   // really have linkage, but it's convenient to say they do for the
777   // purposes of calculating linkage of pointer-to-data-member
778   // template arguments.
779   //
780   // Templates also don't officially have linkage, but since we ignore
781   // the C++ standard and look at template arguments when determining
782   // linkage and visibility of a template specialization, we might hit
783   // a template template argument that way. If we do, we need to
784   // consider its linkage.
785   if (!(isa<CXXMethodDecl>(D) ||
786         isa<VarDecl>(D) ||
787         isa<FieldDecl>(D) ||
788         isa<IndirectFieldDecl>(D) ||
789         isa<TagDecl>(D) ||
790         isa<TemplateDecl>(D)))
791     return LinkageInfo::none();
792 
793   LinkageInfo LV;
794 
795   // If we have an explicit visibility attribute, merge that in.
796   if (!hasExplicitVisibilityAlready(computation)) {
797     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
798       LV.mergeVisibility(*Vis, true);
799     // If we're paying attention to global visibility, apply
800     // -finline-visibility-hidden if this is an inline method.
801     //
802     // Note that we do this before merging information about
803     // the class visibility.
804     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
805       LV.mergeVisibility(HiddenVisibility, true);
806   }
807 
808   // If this class member has an explicit visibility attribute, the only
809   // thing that can change its visibility is the template arguments, so
810   // only look for them when processing the class.
811   LVComputationKind classComputation = computation;
812   if (LV.isVisibilityExplicit())
813     classComputation = withExplicitVisibilityAlready(computation);
814 
815   LinkageInfo classLV =
816     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
817   // If the class already has unique-external linkage, we can't improve.
818   if (classLV.getLinkage() == UniqueExternalLinkage)
819     return LinkageInfo::uniqueExternal();
820 
821   if (!isExternallyVisible(classLV.getLinkage()))
822     return LinkageInfo::none();
823 
824 
825   // Otherwise, don't merge in classLV yet, because in certain cases
826   // we need to completely ignore the visibility from it.
827 
828   // Specifically, if this decl exists and has an explicit attribute.
829   const NamedDecl *explicitSpecSuppressor = 0;
830 
831   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
832     // If the type of the function uses a type with unique-external
833     // linkage, it's not legally usable from outside this translation unit.
834     // But only look at the type-as-written. If this function has an auto-deduced
835     // return type, we can't compute the linkage of that type because it could
836     // require looking at the linkage of this function, and we don't need this
837     // for correctness because the type is not part of the function's
838     // signature.
839     // FIXME: This is a hack. We should be able to solve this circularity and the
840     // one in getLVForNamespaceScopeDecl for Functions some other way.
841     {
842       QualType TypeAsWritten = MD->getType();
843       if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
844         TypeAsWritten = TSI->getType();
845       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
846         return LinkageInfo::uniqueExternal();
847     }
848     // If this is a method template specialization, use the linkage for
849     // the template parameters and arguments.
850     if (FunctionTemplateSpecializationInfo *spec
851            = MD->getTemplateSpecializationInfo()) {
852       mergeTemplateLV(LV, MD, spec, computation);
853       if (spec->isExplicitSpecialization()) {
854         explicitSpecSuppressor = MD;
855       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
856         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
857       }
858     } else if (isExplicitMemberSpecialization(MD)) {
859       explicitSpecSuppressor = MD;
860     }
861 
862   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
863     if (const ClassTemplateSpecializationDecl *spec
864         = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
865       mergeTemplateLV(LV, spec, computation);
866       if (spec->isExplicitSpecialization()) {
867         explicitSpecSuppressor = spec;
868       } else {
869         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
870         if (isExplicitMemberSpecialization(temp)) {
871           explicitSpecSuppressor = temp->getTemplatedDecl();
872         }
873       }
874     } else if (isExplicitMemberSpecialization(RD)) {
875       explicitSpecSuppressor = RD;
876     }
877 
878   // Static data members.
879   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
880     // Modify the variable's linkage by its type, but ignore the
881     // type's visibility unless it's a definition.
882     LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
883     if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
884       LV.mergeVisibility(typeLV);
885     LV.mergeExternalVisibility(typeLV);
886 
887     if (isExplicitMemberSpecialization(VD)) {
888       explicitSpecSuppressor = VD;
889     }
890 
891   // Template members.
892   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
893     bool considerVisibility =
894       (!LV.isVisibilityExplicit() &&
895        !classLV.isVisibilityExplicit() &&
896        !hasExplicitVisibilityAlready(computation));
897     LinkageInfo tempLV =
898       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
899     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
900 
901     if (const RedeclarableTemplateDecl *redeclTemp =
902           dyn_cast<RedeclarableTemplateDecl>(temp)) {
903       if (isExplicitMemberSpecialization(redeclTemp)) {
904         explicitSpecSuppressor = temp->getTemplatedDecl();
905       }
906     }
907   }
908 
909   // We should never be looking for an attribute directly on a template.
910   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
911 
912   // If this member is an explicit member specialization, and it has
913   // an explicit attribute, ignore visibility from the parent.
914   bool considerClassVisibility = true;
915   if (explicitSpecSuppressor &&
916       // optimization: hasDVA() is true only with explicit visibility.
917       LV.isVisibilityExplicit() &&
918       classLV.getVisibility() != DefaultVisibility &&
919       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
920     considerClassVisibility = false;
921   }
922 
923   // Finally, merge in information from the class.
924   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
925   return LV;
926 }
927 
928 void NamedDecl::anchor() { }
929 
930 static LinkageInfo computeLVForDecl(const NamedDecl *D,
931                                     LVComputationKind computation);
932 
933 bool NamedDecl::isLinkageValid() const {
934   if (!hasCachedLinkage())
935     return true;
936 
937   return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
938          getCachedLinkage();
939 }
940 
941 Linkage NamedDecl::getLinkageInternal() const {
942   // We don't care about visibility here, so ask for the cheapest
943   // possible visibility analysis.
944   return getLVForDecl(this, LVForLinkageOnly).getLinkage();
945 }
946 
947 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
948   LVComputationKind computation =
949     (usesTypeVisibility(this) ? LVForType : LVForValue);
950   return getLVForDecl(this, computation);
951 }
952 
953 static Optional<Visibility>
954 getExplicitVisibilityAux(const NamedDecl *ND,
955                          NamedDecl::ExplicitVisibilityKind kind,
956                          bool IsMostRecent) {
957   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
958 
959   // Check the declaration itself first.
960   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
961     return V;
962 
963   // If this is a member class of a specialization of a class template
964   // and the corresponding decl has explicit visibility, use that.
965   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
966     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
967     if (InstantiatedFrom)
968       return getVisibilityOf(InstantiatedFrom, kind);
969   }
970 
971   // If there wasn't explicit visibility there, and this is a
972   // specialization of a class template, check for visibility
973   // on the pattern.
974   if (const ClassTemplateSpecializationDecl *spec
975         = dyn_cast<ClassTemplateSpecializationDecl>(ND))
976     return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
977                            kind);
978 
979   // Use the most recent declaration.
980   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
981     const NamedDecl *MostRecent = ND->getMostRecentDecl();
982     if (MostRecent != ND)
983       return getExplicitVisibilityAux(MostRecent, kind, true);
984   }
985 
986   if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
987     if (Var->isStaticDataMember()) {
988       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
989       if (InstantiatedFrom)
990         return getVisibilityOf(InstantiatedFrom, kind);
991     }
992 
993     return None;
994   }
995   // Also handle function template specializations.
996   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
997     // If the function is a specialization of a template with an
998     // explicit visibility attribute, use that.
999     if (FunctionTemplateSpecializationInfo *templateInfo
1000           = fn->getTemplateSpecializationInfo())
1001       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1002                              kind);
1003 
1004     // If the function is a member of a specialization of a class template
1005     // and the corresponding decl has explicit visibility, use that.
1006     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1007     if (InstantiatedFrom)
1008       return getVisibilityOf(InstantiatedFrom, kind);
1009 
1010     return None;
1011   }
1012 
1013   // The visibility of a template is stored in the templated decl.
1014   if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
1015     return getVisibilityOf(TD->getTemplatedDecl(), kind);
1016 
1017   return None;
1018 }
1019 
1020 Optional<Visibility>
1021 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1022   return getExplicitVisibilityAux(this, kind, false);
1023 }
1024 
1025 static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1026                                    LVComputationKind computation) {
1027   // This lambda has its linkage/visibility determined by its owner.
1028   if (ContextDecl) {
1029     if (isa<ParmVarDecl>(ContextDecl))
1030       DC = ContextDecl->getDeclContext()->getRedeclContext();
1031     else
1032       return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1033   }
1034 
1035   if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1036     return getLVForDecl(ND, computation);
1037 
1038   return LinkageInfo::external();
1039 }
1040 
1041 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1042                                      LVComputationKind computation) {
1043   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1044     if (Function->isInAnonymousNamespace() &&
1045         !Function->isInExternCContext())
1046       return LinkageInfo::uniqueExternal();
1047 
1048     // This is a "void f();" which got merged with a file static.
1049     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1050       return LinkageInfo::internal();
1051 
1052     LinkageInfo LV;
1053     if (!hasExplicitVisibilityAlready(computation)) {
1054       if (Optional<Visibility> Vis =
1055               getExplicitVisibility(Function, computation))
1056         LV.mergeVisibility(*Vis, true);
1057     }
1058 
1059     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1060     // merging storage classes and visibility attributes, so we don't have to
1061     // look at previous decls in here.
1062 
1063     return LV;
1064   }
1065 
1066   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1067     if (Var->hasExternalStorage()) {
1068       if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
1069         return LinkageInfo::uniqueExternal();
1070 
1071       LinkageInfo LV;
1072       if (Var->getStorageClass() == SC_PrivateExtern)
1073         LV.mergeVisibility(HiddenVisibility, true);
1074       else if (!hasExplicitVisibilityAlready(computation)) {
1075         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1076           LV.mergeVisibility(*Vis, true);
1077       }
1078 
1079       if (const VarDecl *Prev = Var->getPreviousDecl()) {
1080         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1081         if (PrevLV.getLinkage())
1082           LV.setLinkage(PrevLV.getLinkage());
1083         LV.mergeVisibility(PrevLV);
1084       }
1085 
1086       return LV;
1087     }
1088 
1089     if (!Var->isStaticLocal())
1090       return LinkageInfo::none();
1091   }
1092 
1093   ASTContext &Context = D->getASTContext();
1094   if (!Context.getLangOpts().CPlusPlus)
1095     return LinkageInfo::none();
1096 
1097   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1098   if (!OuterD)
1099     return LinkageInfo::none();
1100 
1101   LinkageInfo LV;
1102   if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1103     if (!BD->getBlockManglingNumber())
1104       return LinkageInfo::none();
1105 
1106     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1107                          BD->getBlockManglingContextDecl(), computation);
1108   } else {
1109     const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1110     if (!FD->isInlined() &&
1111         FD->getTemplateSpecializationKind() == TSK_Undeclared)
1112       return LinkageInfo::none();
1113 
1114     LV = getLVForDecl(FD, computation);
1115   }
1116   if (!isExternallyVisible(LV.getLinkage()))
1117     return LinkageInfo::none();
1118   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1119                      LV.isVisibilityExplicit());
1120 }
1121 
1122 static inline const CXXRecordDecl*
1123 getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1124   const CXXRecordDecl *Ret = Record;
1125   while (Record && Record->isLambda()) {
1126     Ret = Record;
1127     if (!Record->getParent()) break;
1128     // Get the Containing Class of this Lambda Class
1129     Record = dyn_cast_or_null<CXXRecordDecl>(
1130       Record->getParent()->getParent());
1131   }
1132   return Ret;
1133 }
1134 
1135 static LinkageInfo computeLVForDecl(const NamedDecl *D,
1136                                     LVComputationKind computation) {
1137   // Objective-C: treat all Objective-C declarations as having external
1138   // linkage.
1139   switch (D->getKind()) {
1140     default:
1141       break;
1142     case Decl::ParmVar:
1143       return LinkageInfo::none();
1144     case Decl::TemplateTemplateParm: // count these as external
1145     case Decl::NonTypeTemplateParm:
1146     case Decl::ObjCAtDefsField:
1147     case Decl::ObjCCategory:
1148     case Decl::ObjCCategoryImpl:
1149     case Decl::ObjCCompatibleAlias:
1150     case Decl::ObjCImplementation:
1151     case Decl::ObjCMethod:
1152     case Decl::ObjCProperty:
1153     case Decl::ObjCPropertyImpl:
1154     case Decl::ObjCProtocol:
1155       return LinkageInfo::external();
1156 
1157     case Decl::CXXRecord: {
1158       const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1159       if (Record->isLambda()) {
1160         if (!Record->getLambdaManglingNumber()) {
1161           // This lambda has no mangling number, so it's internal.
1162           return LinkageInfo::internal();
1163         }
1164 
1165         // This lambda has its linkage/visibility determined:
1166         //  - either by the outermost lambda if that lambda has no mangling
1167         //    number.
1168         //  - or by the parent of the outer most lambda
1169         // This prevents infinite recursion in settings such as nested lambdas
1170         // used in NSDMI's, for e.g.
1171         //  struct L {
1172         //    int t{};
1173         //    int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1174         //  };
1175         const CXXRecordDecl *OuterMostLambda =
1176             getOutermostEnclosingLambda(Record);
1177         if (!OuterMostLambda->getLambdaManglingNumber())
1178           return LinkageInfo::internal();
1179 
1180         return getLVForClosure(
1181                   OuterMostLambda->getDeclContext()->getRedeclContext(),
1182                   OuterMostLambda->getLambdaContextDecl(), computation);
1183       }
1184 
1185       break;
1186     }
1187   }
1188 
1189   // Handle linkage for namespace-scope names.
1190   if (D->getDeclContext()->getRedeclContext()->isFileContext())
1191     return getLVForNamespaceScopeDecl(D, computation);
1192 
1193   // C++ [basic.link]p5:
1194   //   In addition, a member function, static data member, a named
1195   //   class or enumeration of class scope, or an unnamed class or
1196   //   enumeration defined in a class-scope typedef declaration such
1197   //   that the class or enumeration has the typedef name for linkage
1198   //   purposes (7.1.3), has external linkage if the name of the class
1199   //   has external linkage.
1200   if (D->getDeclContext()->isRecord())
1201     return getLVForClassMember(D, computation);
1202 
1203   // C++ [basic.link]p6:
1204   //   The name of a function declared in block scope and the name of
1205   //   an object declared by a block scope extern declaration have
1206   //   linkage. If there is a visible declaration of an entity with
1207   //   linkage having the same name and type, ignoring entities
1208   //   declared outside the innermost enclosing namespace scope, the
1209   //   block scope declaration declares that same entity and receives
1210   //   the linkage of the previous declaration. If there is more than
1211   //   one such matching entity, the program is ill-formed. Otherwise,
1212   //   if no matching entity is found, the block scope entity receives
1213   //   external linkage.
1214   if (D->getDeclContext()->isFunctionOrMethod())
1215     return getLVForLocalDecl(D, computation);
1216 
1217   // C++ [basic.link]p6:
1218   //   Names not covered by these rules have no linkage.
1219   return LinkageInfo::none();
1220 }
1221 
1222 namespace clang {
1223 class LinkageComputer {
1224 public:
1225   static LinkageInfo getLVForDecl(const NamedDecl *D,
1226                                   LVComputationKind computation) {
1227     if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1228       return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1229 
1230     LinkageInfo LV = computeLVForDecl(D, computation);
1231     if (D->hasCachedLinkage())
1232       assert(D->getCachedLinkage() == LV.getLinkage());
1233 
1234     D->setCachedLinkage(LV.getLinkage());
1235 
1236 #ifndef NDEBUG
1237     // In C (because of gnu inline) and in c++ with microsoft extensions an
1238     // static can follow an extern, so we can have two decls with different
1239     // linkages.
1240     const LangOptions &Opts = D->getASTContext().getLangOpts();
1241     if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1242       return LV;
1243 
1244     // We have just computed the linkage for this decl. By induction we know
1245     // that all other computed linkages match, check that the one we just
1246     // computed
1247     // also does.
1248     NamedDecl *Old = NULL;
1249     for (NamedDecl::redecl_iterator I = D->redecls_begin(),
1250                                     E = D->redecls_end();
1251          I != E; ++I) {
1252       NamedDecl *T = cast<NamedDecl>(*I);
1253       if (T == D)
1254         continue;
1255       if (T->hasCachedLinkage()) {
1256         Old = T;
1257         break;
1258       }
1259     }
1260     assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1261 #endif
1262 
1263     return LV;
1264   }
1265 };
1266 }
1267 
1268 static LinkageInfo getLVForDecl(const NamedDecl *D,
1269                                 LVComputationKind computation) {
1270   return clang::LinkageComputer::getLVForDecl(D, computation);
1271 }
1272 
1273 std::string NamedDecl::getQualifiedNameAsString() const {
1274   std::string QualName;
1275   llvm::raw_string_ostream OS(QualName);
1276   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1277   return OS.str();
1278 }
1279 
1280 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1281   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1282 }
1283 
1284 void NamedDecl::printQualifiedName(raw_ostream &OS,
1285                                    const PrintingPolicy &P) const {
1286   const DeclContext *Ctx = getDeclContext();
1287 
1288   if (Ctx->isFunctionOrMethod()) {
1289     printName(OS);
1290     return;
1291   }
1292 
1293   typedef SmallVector<const DeclContext *, 8> ContextsTy;
1294   ContextsTy Contexts;
1295 
1296   // Collect contexts.
1297   while (Ctx && isa<NamedDecl>(Ctx)) {
1298     Contexts.push_back(Ctx);
1299     Ctx = Ctx->getParent();
1300   }
1301 
1302   for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1303        I != E; ++I) {
1304     if (const ClassTemplateSpecializationDecl *Spec
1305           = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
1306       OS << Spec->getName();
1307       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1308       TemplateSpecializationType::PrintTemplateArgumentList(OS,
1309                                                             TemplateArgs.data(),
1310                                                             TemplateArgs.size(),
1311                                                             P);
1312     } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
1313       if (ND->isAnonymousNamespace())
1314         OS << "<anonymous namespace>";
1315       else
1316         OS << *ND;
1317     } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1318       if (!RD->getIdentifier())
1319         OS << "<anonymous " << RD->getKindName() << '>';
1320       else
1321         OS << *RD;
1322     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1323       const FunctionProtoType *FT = 0;
1324       if (FD->hasWrittenPrototype())
1325         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1326 
1327       OS << *FD << '(';
1328       if (FT) {
1329         unsigned NumParams = FD->getNumParams();
1330         for (unsigned i = 0; i < NumParams; ++i) {
1331           if (i)
1332             OS << ", ";
1333           OS << FD->getParamDecl(i)->getType().stream(P);
1334         }
1335 
1336         if (FT->isVariadic()) {
1337           if (NumParams > 0)
1338             OS << ", ";
1339           OS << "...";
1340         }
1341       }
1342       OS << ')';
1343     } else {
1344       OS << *cast<NamedDecl>(*I);
1345     }
1346     OS << "::";
1347   }
1348 
1349   if (getDeclName())
1350     OS << *this;
1351   else
1352     OS << "<anonymous>";
1353 }
1354 
1355 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1356                                      const PrintingPolicy &Policy,
1357                                      bool Qualified) const {
1358   if (Qualified)
1359     printQualifiedName(OS, Policy);
1360   else
1361     printName(OS);
1362 }
1363 
1364 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
1365   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1366 
1367   // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1368   // We want to keep it, unless it nominates same namespace.
1369   if (getKind() == Decl::UsingDirective) {
1370     return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1371              ->getOriginalNamespace() ==
1372            cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1373              ->getOriginalNamespace();
1374   }
1375 
1376   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1377     // For function declarations, we keep track of redeclarations.
1378     return FD->getPreviousDecl() == OldD;
1379 
1380   // For function templates, the underlying function declarations are linked.
1381   if (const FunctionTemplateDecl *FunctionTemplate
1382         = dyn_cast<FunctionTemplateDecl>(this))
1383     if (const FunctionTemplateDecl *OldFunctionTemplate
1384           = dyn_cast<FunctionTemplateDecl>(OldD))
1385       return FunctionTemplate->getTemplatedDecl()
1386                ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
1387 
1388   // For method declarations, we keep track of redeclarations.
1389   if (isa<ObjCMethodDecl>(this))
1390     return false;
1391 
1392   if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1393     return true;
1394 
1395   if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1396     return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1397            cast<UsingShadowDecl>(OldD)->getTargetDecl();
1398 
1399   if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1400     ASTContext &Context = getASTContext();
1401     return Context.getCanonicalNestedNameSpecifier(
1402                                      cast<UsingDecl>(this)->getQualifier()) ==
1403            Context.getCanonicalNestedNameSpecifier(
1404                                         cast<UsingDecl>(OldD)->getQualifier());
1405   }
1406 
1407   if (isa<UnresolvedUsingValueDecl>(this) &&
1408       isa<UnresolvedUsingValueDecl>(OldD)) {
1409     ASTContext &Context = getASTContext();
1410     return Context.getCanonicalNestedNameSpecifier(
1411                       cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1412            Context.getCanonicalNestedNameSpecifier(
1413                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1414   }
1415 
1416   // A typedef of an Objective-C class type can replace an Objective-C class
1417   // declaration or definition, and vice versa.
1418   if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1419       (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1420     return true;
1421 
1422   // For non-function declarations, if the declarations are of the
1423   // same kind then this must be a redeclaration, or semantic analysis
1424   // would not have given us the new declaration.
1425   return this->getKind() == OldD->getKind();
1426 }
1427 
1428 bool NamedDecl::hasLinkage() const {
1429   return getFormalLinkage() != NoLinkage;
1430 }
1431 
1432 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1433   NamedDecl *ND = this;
1434   while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1435     ND = UD->getTargetDecl();
1436 
1437   if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1438     return AD->getClassInterface();
1439 
1440   return ND;
1441 }
1442 
1443 bool NamedDecl::isCXXInstanceMember() const {
1444   if (!isCXXClassMember())
1445     return false;
1446 
1447   const NamedDecl *D = this;
1448   if (isa<UsingShadowDecl>(D))
1449     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1450 
1451   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1452     return true;
1453   if (const CXXMethodDecl *MD =
1454           dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1455     return MD->isInstance();
1456   return false;
1457 }
1458 
1459 //===----------------------------------------------------------------------===//
1460 // DeclaratorDecl Implementation
1461 //===----------------------------------------------------------------------===//
1462 
1463 template <typename DeclT>
1464 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1465   if (decl->getNumTemplateParameterLists() > 0)
1466     return decl->getTemplateParameterList(0)->getTemplateLoc();
1467   else
1468     return decl->getInnerLocStart();
1469 }
1470 
1471 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1472   TypeSourceInfo *TSI = getTypeSourceInfo();
1473   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1474   return SourceLocation();
1475 }
1476 
1477 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1478   if (QualifierLoc) {
1479     // Make sure the extended decl info is allocated.
1480     if (!hasExtInfo()) {
1481       // Save (non-extended) type source info pointer.
1482       TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1483       // Allocate external info struct.
1484       DeclInfo = new (getASTContext()) ExtInfo;
1485       // Restore savedTInfo into (extended) decl info.
1486       getExtInfo()->TInfo = savedTInfo;
1487     }
1488     // Set qualifier info.
1489     getExtInfo()->QualifierLoc = QualifierLoc;
1490   } else {
1491     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1492     if (hasExtInfo()) {
1493       if (getExtInfo()->NumTemplParamLists == 0) {
1494         // Save type source info pointer.
1495         TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1496         // Deallocate the extended decl info.
1497         getASTContext().Deallocate(getExtInfo());
1498         // Restore savedTInfo into (non-extended) decl info.
1499         DeclInfo = savedTInfo;
1500       }
1501       else
1502         getExtInfo()->QualifierLoc = QualifierLoc;
1503     }
1504   }
1505 }
1506 
1507 void
1508 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1509                                               unsigned NumTPLists,
1510                                               TemplateParameterList **TPLists) {
1511   assert(NumTPLists > 0);
1512   // Make sure the extended decl info is allocated.
1513   if (!hasExtInfo()) {
1514     // Save (non-extended) type source info pointer.
1515     TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1516     // Allocate external info struct.
1517     DeclInfo = new (getASTContext()) ExtInfo;
1518     // Restore savedTInfo into (extended) decl info.
1519     getExtInfo()->TInfo = savedTInfo;
1520   }
1521   // Set the template parameter lists info.
1522   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1523 }
1524 
1525 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1526   return getTemplateOrInnerLocStart(this);
1527 }
1528 
1529 namespace {
1530 
1531 // Helper function: returns true if QT is or contains a type
1532 // having a postfix component.
1533 bool typeIsPostfix(clang::QualType QT) {
1534   while (true) {
1535     const Type* T = QT.getTypePtr();
1536     switch (T->getTypeClass()) {
1537     default:
1538       return false;
1539     case Type::Pointer:
1540       QT = cast<PointerType>(T)->getPointeeType();
1541       break;
1542     case Type::BlockPointer:
1543       QT = cast<BlockPointerType>(T)->getPointeeType();
1544       break;
1545     case Type::MemberPointer:
1546       QT = cast<MemberPointerType>(T)->getPointeeType();
1547       break;
1548     case Type::LValueReference:
1549     case Type::RValueReference:
1550       QT = cast<ReferenceType>(T)->getPointeeType();
1551       break;
1552     case Type::PackExpansion:
1553       QT = cast<PackExpansionType>(T)->getPattern();
1554       break;
1555     case Type::Paren:
1556     case Type::ConstantArray:
1557     case Type::DependentSizedArray:
1558     case Type::IncompleteArray:
1559     case Type::VariableArray:
1560     case Type::FunctionProto:
1561     case Type::FunctionNoProto:
1562       return true;
1563     }
1564   }
1565 }
1566 
1567 } // namespace
1568 
1569 SourceRange DeclaratorDecl::getSourceRange() const {
1570   SourceLocation RangeEnd = getLocation();
1571   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1572     // If the declaration has no name or the type extends past the name take the
1573     // end location of the type.
1574     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1575       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1576   }
1577   return SourceRange(getOuterLocStart(), RangeEnd);
1578 }
1579 
1580 void
1581 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1582                                              unsigned NumTPLists,
1583                                              TemplateParameterList **TPLists) {
1584   assert((NumTPLists == 0 || TPLists != 0) &&
1585          "Empty array of template parameters with positive size!");
1586 
1587   // Free previous template parameters (if any).
1588   if (NumTemplParamLists > 0) {
1589     Context.Deallocate(TemplParamLists);
1590     TemplParamLists = 0;
1591     NumTemplParamLists = 0;
1592   }
1593   // Set info on matched template parameter lists (if any).
1594   if (NumTPLists > 0) {
1595     TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1596     NumTemplParamLists = NumTPLists;
1597     for (unsigned i = NumTPLists; i-- > 0; )
1598       TemplParamLists[i] = TPLists[i];
1599   }
1600 }
1601 
1602 //===----------------------------------------------------------------------===//
1603 // VarDecl Implementation
1604 //===----------------------------------------------------------------------===//
1605 
1606 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1607   switch (SC) {
1608   case SC_None:                 break;
1609   case SC_Auto:                 return "auto";
1610   case SC_Extern:               return "extern";
1611   case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1612   case SC_PrivateExtern:        return "__private_extern__";
1613   case SC_Register:             return "register";
1614   case SC_Static:               return "static";
1615   }
1616 
1617   llvm_unreachable("Invalid storage class");
1618 }
1619 
1620 VarDecl::VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1621                  SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1622                  TypeSourceInfo *TInfo, StorageClass SC)
1623     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
1624   assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
1625   assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
1626   AllBits = 0;
1627   VarDeclBits.SClass = SC;
1628   // Everything else is implicitly initialized to false.
1629 }
1630 
1631 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1632                          SourceLocation StartL, SourceLocation IdL,
1633                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1634                          StorageClass S) {
1635   return new (C, DC) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
1636 }
1637 
1638 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1639   return new (C, ID) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1640                              QualType(), 0, SC_None);
1641 }
1642 
1643 void VarDecl::setStorageClass(StorageClass SC) {
1644   assert(isLegalForVariable(SC));
1645   VarDeclBits.SClass = SC;
1646 }
1647 
1648 SourceRange VarDecl::getSourceRange() const {
1649   if (const Expr *Init = getInit()) {
1650     SourceLocation InitEnd = Init->getLocEnd();
1651     // If Init is implicit, ignore its source range and fallback on
1652     // DeclaratorDecl::getSourceRange() to handle postfix elements.
1653     if (InitEnd.isValid() && InitEnd != getLocation())
1654       return SourceRange(getOuterLocStart(), InitEnd);
1655   }
1656   return DeclaratorDecl::getSourceRange();
1657 }
1658 
1659 template<typename T>
1660 static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
1661   // C++ [dcl.link]p1: All function types, function names with external linkage,
1662   // and variable names with external linkage have a language linkage.
1663   if (!D.hasExternalFormalLinkage())
1664     return NoLanguageLinkage;
1665 
1666   // Language linkage is a C++ concept, but saying that everything else in C has
1667   // C language linkage fits the implementation nicely.
1668   ASTContext &Context = D.getASTContext();
1669   if (!Context.getLangOpts().CPlusPlus)
1670     return CLanguageLinkage;
1671 
1672   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1673   // language linkage of the names of class members and the function type of
1674   // class member functions.
1675   const DeclContext *DC = D.getDeclContext();
1676   if (DC->isRecord())
1677     return CXXLanguageLinkage;
1678 
1679   // If the first decl is in an extern "C" context, any other redeclaration
1680   // will have C language linkage. If the first one is not in an extern "C"
1681   // context, we would have reported an error for any other decl being in one.
1682   if (isFirstInExternCContext(&D))
1683     return CLanguageLinkage;
1684   return CXXLanguageLinkage;
1685 }
1686 
1687 template<typename T>
1688 static bool isExternCTemplate(const T &D) {
1689   // Since the context is ignored for class members, they can only have C++
1690   // language linkage or no language linkage.
1691   const DeclContext *DC = D.getDeclContext();
1692   if (DC->isRecord()) {
1693     assert(D.getASTContext().getLangOpts().CPlusPlus);
1694     return false;
1695   }
1696 
1697   return D.getLanguageLinkage() == CLanguageLinkage;
1698 }
1699 
1700 LanguageLinkage VarDecl::getLanguageLinkage() const {
1701   return getLanguageLinkageTemplate(*this);
1702 }
1703 
1704 bool VarDecl::isExternC() const {
1705   return isExternCTemplate(*this);
1706 }
1707 
1708 bool VarDecl::isInExternCContext() const {
1709   return getLexicalDeclContext()->isExternCContext();
1710 }
1711 
1712 bool VarDecl::isInExternCXXContext() const {
1713   return getLexicalDeclContext()->isExternCXXContext();
1714 }
1715 
1716 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1717 
1718 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1719   ASTContext &C) const
1720 {
1721   // C++ [basic.def]p2:
1722   //   A declaration is a definition unless [...] it contains the 'extern'
1723   //   specifier or a linkage-specification and neither an initializer [...],
1724   //   it declares a static data member in a class declaration [...].
1725   // C++1y [temp.expl.spec]p15:
1726   //   An explicit specialization of a static data member or an explicit
1727   //   specialization of a static data member template is a definition if the
1728   //   declaration includes an initializer; otherwise, it is a declaration.
1729   //
1730   // FIXME: How do you declare (but not define) a partial specialization of
1731   // a static data member template outside the containing class?
1732   if (isStaticDataMember()) {
1733     if (isOutOfLine() &&
1734         (hasInit() ||
1735          // If the first declaration is out-of-line, this may be an
1736          // instantiation of an out-of-line partial specialization of a variable
1737          // template for which we have not yet instantiated the initializer.
1738          (getFirstDecl()->isOutOfLine()
1739               ? getTemplateSpecializationKind() == TSK_Undeclared
1740               : getTemplateSpecializationKind() !=
1741                     TSK_ExplicitSpecialization) ||
1742          isa<VarTemplatePartialSpecializationDecl>(this)))
1743       return Definition;
1744     else
1745       return DeclarationOnly;
1746   }
1747   // C99 6.7p5:
1748   //   A definition of an identifier is a declaration for that identifier that
1749   //   [...] causes storage to be reserved for that object.
1750   // Note: that applies for all non-file-scope objects.
1751   // C99 6.9.2p1:
1752   //   If the declaration of an identifier for an object has file scope and an
1753   //   initializer, the declaration is an external definition for the identifier
1754   if (hasInit())
1755     return Definition;
1756 
1757   if (hasAttr<AliasAttr>())
1758     return Definition;
1759 
1760   // A variable template specialization (other than a static data member
1761   // template or an explicit specialization) is a declaration until we
1762   // instantiate its initializer.
1763   if (isa<VarTemplateSpecializationDecl>(this) &&
1764       getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1765     return DeclarationOnly;
1766 
1767   if (hasExternalStorage())
1768     return DeclarationOnly;
1769 
1770   // [dcl.link] p7:
1771   //   A declaration directly contained in a linkage-specification is treated
1772   //   as if it contains the extern specifier for the purpose of determining
1773   //   the linkage of the declared name and whether it is a definition.
1774   if (isSingleLineExternC(*this))
1775     return DeclarationOnly;
1776 
1777   // C99 6.9.2p2:
1778   //   A declaration of an object that has file scope without an initializer,
1779   //   and without a storage class specifier or the scs 'static', constitutes
1780   //   a tentative definition.
1781   // No such thing in C++.
1782   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1783     return TentativeDefinition;
1784 
1785   // What's left is (in C, block-scope) declarations without initializers or
1786   // external storage. These are definitions.
1787   return Definition;
1788 }
1789 
1790 VarDecl *VarDecl::getActingDefinition() {
1791   DefinitionKind Kind = isThisDeclarationADefinition();
1792   if (Kind != TentativeDefinition)
1793     return 0;
1794 
1795   VarDecl *LastTentative = 0;
1796   VarDecl *First = getFirstDecl();
1797   for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1798        I != E; ++I) {
1799     Kind = (*I)->isThisDeclarationADefinition();
1800     if (Kind == Definition)
1801       return 0;
1802     else if (Kind == TentativeDefinition)
1803       LastTentative = *I;
1804   }
1805   return LastTentative;
1806 }
1807 
1808 VarDecl *VarDecl::getDefinition(ASTContext &C) {
1809   VarDecl *First = getFirstDecl();
1810   for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1811        I != E; ++I) {
1812     if ((*I)->isThisDeclarationADefinition(C) == Definition)
1813       return *I;
1814   }
1815   return 0;
1816 }
1817 
1818 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1819   DefinitionKind Kind = DeclarationOnly;
1820 
1821   const VarDecl *First = getFirstDecl();
1822   for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1823        I != E; ++I) {
1824     Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
1825     if (Kind == Definition)
1826       break;
1827   }
1828 
1829   return Kind;
1830 }
1831 
1832 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1833   redecl_iterator I = redecls_begin(), E = redecls_end();
1834   while (I != E && !I->getInit())
1835     ++I;
1836 
1837   if (I != E) {
1838     D = *I;
1839     return I->getInit();
1840   }
1841   return 0;
1842 }
1843 
1844 bool VarDecl::isOutOfLine() const {
1845   if (Decl::isOutOfLine())
1846     return true;
1847 
1848   if (!isStaticDataMember())
1849     return false;
1850 
1851   // If this static data member was instantiated from a static data member of
1852   // a class template, check whether that static data member was defined
1853   // out-of-line.
1854   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1855     return VD->isOutOfLine();
1856 
1857   return false;
1858 }
1859 
1860 VarDecl *VarDecl::getOutOfLineDefinition() {
1861   if (!isStaticDataMember())
1862     return 0;
1863 
1864   for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1865        RD != RDEnd; ++RD) {
1866     if (RD->getLexicalDeclContext()->isFileContext())
1867       return *RD;
1868   }
1869 
1870   return 0;
1871 }
1872 
1873 void VarDecl::setInit(Expr *I) {
1874   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1875     Eval->~EvaluatedStmt();
1876     getASTContext().Deallocate(Eval);
1877   }
1878 
1879   Init = I;
1880 }
1881 
1882 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1883   const LangOptions &Lang = C.getLangOpts();
1884 
1885   if (!Lang.CPlusPlus)
1886     return false;
1887 
1888   // In C++11, any variable of reference type can be used in a constant
1889   // expression if it is initialized by a constant expression.
1890   if (Lang.CPlusPlus11 && getType()->isReferenceType())
1891     return true;
1892 
1893   // Only const objects can be used in constant expressions in C++. C++98 does
1894   // not require the variable to be non-volatile, but we consider this to be a
1895   // defect.
1896   if (!getType().isConstQualified() || getType().isVolatileQualified())
1897     return false;
1898 
1899   // In C++, const, non-volatile variables of integral or enumeration types
1900   // can be used in constant expressions.
1901   if (getType()->isIntegralOrEnumerationType())
1902     return true;
1903 
1904   // Additionally, in C++11, non-volatile constexpr variables can be used in
1905   // constant expressions.
1906   return Lang.CPlusPlus11 && isConstexpr();
1907 }
1908 
1909 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1910 /// form, which contains extra information on the evaluated value of the
1911 /// initializer.
1912 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1913   EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1914   if (!Eval) {
1915     Stmt *S = Init.get<Stmt *>();
1916     // Note: EvaluatedStmt contains an APValue, which usually holds
1917     // resources not allocated from the ASTContext.  We need to do some
1918     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
1919     // where we can detect whether there's anything to clean up or not.
1920     Eval = new (getASTContext()) EvaluatedStmt;
1921     Eval->Value = S;
1922     Init = Eval;
1923   }
1924   return Eval;
1925 }
1926 
1927 APValue *VarDecl::evaluateValue() const {
1928   SmallVector<PartialDiagnosticAt, 8> Notes;
1929   return evaluateValue(Notes);
1930 }
1931 
1932 namespace {
1933 // Destroy an APValue that was allocated in an ASTContext.
1934 void DestroyAPValue(void* UntypedValue) {
1935   static_cast<APValue*>(UntypedValue)->~APValue();
1936 }
1937 } // namespace
1938 
1939 APValue *VarDecl::evaluateValue(
1940     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1941   EvaluatedStmt *Eval = ensureEvaluatedStmt();
1942 
1943   // We only produce notes indicating why an initializer is non-constant the
1944   // first time it is evaluated. FIXME: The notes won't always be emitted the
1945   // first time we try evaluation, so might not be produced at all.
1946   if (Eval->WasEvaluated)
1947     return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
1948 
1949   const Expr *Init = cast<Expr>(Eval->Value);
1950   assert(!Init->isValueDependent());
1951 
1952   if (Eval->IsEvaluating) {
1953     // FIXME: Produce a diagnostic for self-initialization.
1954     Eval->CheckedICE = true;
1955     Eval->IsICE = false;
1956     return 0;
1957   }
1958 
1959   Eval->IsEvaluating = true;
1960 
1961   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1962                                             this, Notes);
1963 
1964   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
1965   // or that it's empty (so that there's nothing to clean up) if evaluation
1966   // failed.
1967   if (!Result)
1968     Eval->Evaluated = APValue();
1969   else if (Eval->Evaluated.needsCleanup())
1970     getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
1971 
1972   Eval->IsEvaluating = false;
1973   Eval->WasEvaluated = true;
1974 
1975   // In C++11, we have determined whether the initializer was a constant
1976   // expression as a side-effect.
1977   if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
1978     Eval->CheckedICE = true;
1979     Eval->IsICE = Result && Notes.empty();
1980   }
1981 
1982   return Result ? &Eval->Evaluated : 0;
1983 }
1984 
1985 bool VarDecl::checkInitIsICE() const {
1986   // Initializers of weak variables are never ICEs.
1987   if (isWeak())
1988     return false;
1989 
1990   EvaluatedStmt *Eval = ensureEvaluatedStmt();
1991   if (Eval->CheckedICE)
1992     // We have already checked whether this subexpression is an
1993     // integral constant expression.
1994     return Eval->IsICE;
1995 
1996   const Expr *Init = cast<Expr>(Eval->Value);
1997   assert(!Init->isValueDependent());
1998 
1999   // In C++11, evaluate the initializer to check whether it's a constant
2000   // expression.
2001   if (getASTContext().getLangOpts().CPlusPlus11) {
2002     SmallVector<PartialDiagnosticAt, 8> Notes;
2003     evaluateValue(Notes);
2004     return Eval->IsICE;
2005   }
2006 
2007   // It's an ICE whether or not the definition we found is
2008   // out-of-line.  See DR 721 and the discussion in Clang PR
2009   // 6206 for details.
2010 
2011   if (Eval->CheckingICE)
2012     return false;
2013   Eval->CheckingICE = true;
2014 
2015   Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2016   Eval->CheckingICE = false;
2017   Eval->CheckedICE = true;
2018   return Eval->IsICE;
2019 }
2020 
2021 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2022   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2023     return cast<VarDecl>(MSI->getInstantiatedFrom());
2024 
2025   return 0;
2026 }
2027 
2028 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2029   if (const VarTemplateSpecializationDecl *Spec =
2030           dyn_cast<VarTemplateSpecializationDecl>(this))
2031     return Spec->getSpecializationKind();
2032 
2033   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2034     return MSI->getTemplateSpecializationKind();
2035 
2036   return TSK_Undeclared;
2037 }
2038 
2039 SourceLocation VarDecl::getPointOfInstantiation() const {
2040   if (const VarTemplateSpecializationDecl *Spec =
2041           dyn_cast<VarTemplateSpecializationDecl>(this))
2042     return Spec->getPointOfInstantiation();
2043 
2044   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2045     return MSI->getPointOfInstantiation();
2046 
2047   return SourceLocation();
2048 }
2049 
2050 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2051   return getASTContext().getTemplateOrSpecializationInfo(this)
2052       .dyn_cast<VarTemplateDecl *>();
2053 }
2054 
2055 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2056   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2057 }
2058 
2059 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2060   if (isStaticDataMember())
2061     // FIXME: Remove ?
2062     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2063     return getASTContext().getTemplateOrSpecializationInfo(this)
2064         .dyn_cast<MemberSpecializationInfo *>();
2065   return 0;
2066 }
2067 
2068 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2069                                          SourceLocation PointOfInstantiation) {
2070   assert((isa<VarTemplateSpecializationDecl>(this) ||
2071           getMemberSpecializationInfo()) &&
2072          "not a variable or static data member template specialization");
2073 
2074   if (VarTemplateSpecializationDecl *Spec =
2075           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2076     Spec->setSpecializationKind(TSK);
2077     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2078         Spec->getPointOfInstantiation().isInvalid())
2079       Spec->setPointOfInstantiation(PointOfInstantiation);
2080   }
2081 
2082   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2083     MSI->setTemplateSpecializationKind(TSK);
2084     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2085         MSI->getPointOfInstantiation().isInvalid())
2086       MSI->setPointOfInstantiation(PointOfInstantiation);
2087   }
2088 }
2089 
2090 void
2091 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2092                                             TemplateSpecializationKind TSK) {
2093   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2094          "Previous template or instantiation?");
2095   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2096 }
2097 
2098 //===----------------------------------------------------------------------===//
2099 // ParmVarDecl Implementation
2100 //===----------------------------------------------------------------------===//
2101 
2102 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2103                                  SourceLocation StartLoc,
2104                                  SourceLocation IdLoc, IdentifierInfo *Id,
2105                                  QualType T, TypeSourceInfo *TInfo,
2106                                  StorageClass S, Expr *DefArg) {
2107   return new (C, DC) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
2108                                  S, DefArg);
2109 }
2110 
2111 QualType ParmVarDecl::getOriginalType() const {
2112   TypeSourceInfo *TSI = getTypeSourceInfo();
2113   QualType T = TSI ? TSI->getType() : getType();
2114   if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2115     return DT->getOriginalType();
2116   return T;
2117 }
2118 
2119 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2120   return new (C, ID) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
2121                                  0, QualType(), 0, SC_None, 0);
2122 }
2123 
2124 SourceRange ParmVarDecl::getSourceRange() const {
2125   if (!hasInheritedDefaultArg()) {
2126     SourceRange ArgRange = getDefaultArgRange();
2127     if (ArgRange.isValid())
2128       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2129   }
2130 
2131   // DeclaratorDecl considers the range of postfix types as overlapping with the
2132   // declaration name, but this is not the case with parameters in ObjC methods.
2133   if (isa<ObjCMethodDecl>(getDeclContext()))
2134     return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2135 
2136   return DeclaratorDecl::getSourceRange();
2137 }
2138 
2139 Expr *ParmVarDecl::getDefaultArg() {
2140   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2141   assert(!hasUninstantiatedDefaultArg() &&
2142          "Default argument is not yet instantiated!");
2143 
2144   Expr *Arg = getInit();
2145   if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2146     return E->getSubExpr();
2147 
2148   return Arg;
2149 }
2150 
2151 SourceRange ParmVarDecl::getDefaultArgRange() const {
2152   if (const Expr *E = getInit())
2153     return E->getSourceRange();
2154 
2155   if (hasUninstantiatedDefaultArg())
2156     return getUninstantiatedDefaultArg()->getSourceRange();
2157 
2158   return SourceRange();
2159 }
2160 
2161 bool ParmVarDecl::isParameterPack() const {
2162   return isa<PackExpansionType>(getType());
2163 }
2164 
2165 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2166   getASTContext().setParameterIndex(this, parameterIndex);
2167   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2168 }
2169 
2170 unsigned ParmVarDecl::getParameterIndexLarge() const {
2171   return getASTContext().getParameterIndex(this);
2172 }
2173 
2174 //===----------------------------------------------------------------------===//
2175 // FunctionDecl Implementation
2176 //===----------------------------------------------------------------------===//
2177 
2178 void FunctionDecl::getNameForDiagnostic(
2179     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2180   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2181   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2182   if (TemplateArgs)
2183     TemplateSpecializationType::PrintTemplateArgumentList(
2184         OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
2185 }
2186 
2187 bool FunctionDecl::isVariadic() const {
2188   if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2189     return FT->isVariadic();
2190   return false;
2191 }
2192 
2193 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2194   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
2195     if (I->Body || I->IsLateTemplateParsed) {
2196       Definition = *I;
2197       return true;
2198     }
2199   }
2200 
2201   return false;
2202 }
2203 
2204 bool FunctionDecl::hasTrivialBody() const
2205 {
2206   Stmt *S = getBody();
2207   if (!S) {
2208     // Since we don't have a body for this function, we don't know if it's
2209     // trivial or not.
2210     return false;
2211   }
2212 
2213   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2214     return true;
2215   return false;
2216 }
2217 
2218 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2219   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
2220     if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2221         I->hasAttr<AliasAttr>()) {
2222       Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
2223       return true;
2224     }
2225   }
2226 
2227   return false;
2228 }
2229 
2230 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2231   if (!hasBody(Definition))
2232     return 0;
2233 
2234   if (Definition->Body)
2235     return Definition->Body.get(getASTContext().getExternalSource());
2236 
2237   return 0;
2238 }
2239 
2240 void FunctionDecl::setBody(Stmt *B) {
2241   Body = B;
2242   if (B)
2243     EndRangeLoc = B->getLocEnd();
2244 }
2245 
2246 void FunctionDecl::setPure(bool P) {
2247   IsPure = P;
2248   if (P)
2249     if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2250       Parent->markedVirtualFunctionPure();
2251 }
2252 
2253 template<std::size_t Len>
2254 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2255   IdentifierInfo *II = ND->getIdentifier();
2256   return II && II->isStr(Str);
2257 }
2258 
2259 bool FunctionDecl::isMain() const {
2260   const TranslationUnitDecl *tunit =
2261     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2262   return tunit &&
2263          !tunit->getASTContext().getLangOpts().Freestanding &&
2264          isNamed(this, "main");
2265 }
2266 
2267 bool FunctionDecl::isMSVCRTEntryPoint() const {
2268   const TranslationUnitDecl *TUnit =
2269       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2270   if (!TUnit)
2271     return false;
2272 
2273   // Even though we aren't really targeting MSVCRT if we are freestanding,
2274   // semantic analysis for these functions remains the same.
2275 
2276   // MSVCRT entry points only exist on MSVCRT targets.
2277   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2278     return false;
2279 
2280   // Nameless functions like constructors cannot be entry points.
2281   if (!getIdentifier())
2282     return false;
2283 
2284   return llvm::StringSwitch<bool>(getName())
2285       .Cases("main",     // an ANSI console app
2286              "wmain",    // a Unicode console App
2287              "WinMain",  // an ANSI GUI app
2288              "wWinMain", // a Unicode GUI app
2289              "DllMain",  // a DLL
2290              true)
2291       .Default(false);
2292 }
2293 
2294 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2295   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2296   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2297          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2298          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2299          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2300 
2301   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2302     return false;
2303 
2304   const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2305   if (proto->getNumParams() != 2 || proto->isVariadic())
2306     return false;
2307 
2308   ASTContext &Context =
2309     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2310       ->getASTContext();
2311 
2312   // The result type and first argument type are constant across all
2313   // these operators.  The second argument must be exactly void*.
2314   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2315 }
2316 
2317 static bool isNamespaceStd(const DeclContext *DC) {
2318   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC->getRedeclContext());
2319   return ND && isNamed(ND, "std") &&
2320          ND->getParent()->getRedeclContext()->isTranslationUnit();
2321 }
2322 
2323 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2324   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2325     return false;
2326   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2327       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2328       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2329       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2330     return false;
2331 
2332   if (isa<CXXRecordDecl>(getDeclContext()))
2333     return false;
2334 
2335   // This can only fail for an invalid 'operator new' declaration.
2336   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2337     return false;
2338 
2339   const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
2340   if (FPT->getNumParams() > 2 || FPT->isVariadic())
2341     return false;
2342 
2343   // If this is a single-parameter function, it must be a replaceable global
2344   // allocation or deallocation function.
2345   if (FPT->getNumParams() == 1)
2346     return true;
2347 
2348   // Otherwise, we're looking for a second parameter whose type is
2349   // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
2350   QualType Ty = FPT->getParamType(1);
2351   ASTContext &Ctx = getASTContext();
2352   if (Ctx.getLangOpts().SizedDeallocation &&
2353       Ctx.hasSameType(Ty, Ctx.getSizeType()))
2354     return true;
2355   if (!Ty->isReferenceType())
2356     return false;
2357   Ty = Ty->getPointeeType();
2358   if (Ty.getCVRQualifiers() != Qualifiers::Const)
2359     return false;
2360   // FIXME: Recognise nothrow_t in an inline namespace inside std?
2361   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2362   return RD && isNamed(RD, "nothrow_t") && isNamespaceStd(RD->getDeclContext());
2363 }
2364 
2365 FunctionDecl *
2366 FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2367   ASTContext &Ctx = getASTContext();
2368   if (!Ctx.getLangOpts().SizedDeallocation)
2369     return 0;
2370 
2371   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2372     return 0;
2373   if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2374       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2375     return 0;
2376   if (isa<CXXRecordDecl>(getDeclContext()))
2377     return 0;
2378 
2379   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2380     return 0;
2381 
2382   if (getNumParams() != 2 || isVariadic() ||
2383       !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
2384                        Ctx.getSizeType()))
2385     return 0;
2386 
2387   // This is a sized deallocation function. Find the corresponding unsized
2388   // deallocation function.
2389   lookup_const_result R = getDeclContext()->lookup(getDeclName());
2390   for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2391        ++RI)
2392     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2393       if (FD->getNumParams() == 1 && !FD->isVariadic())
2394         return FD;
2395   return 0;
2396 }
2397 
2398 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2399   return getLanguageLinkageTemplate(*this);
2400 }
2401 
2402 bool FunctionDecl::isExternC() const {
2403   return isExternCTemplate(*this);
2404 }
2405 
2406 bool FunctionDecl::isInExternCContext() const {
2407   return getLexicalDeclContext()->isExternCContext();
2408 }
2409 
2410 bool FunctionDecl::isInExternCXXContext() const {
2411   return getLexicalDeclContext()->isExternCXXContext();
2412 }
2413 
2414 bool FunctionDecl::isGlobal() const {
2415   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2416     return Method->isStatic();
2417 
2418   if (getCanonicalDecl()->getStorageClass() == SC_Static)
2419     return false;
2420 
2421   for (const DeclContext *DC = getDeclContext();
2422        DC->isNamespace();
2423        DC = DC->getParent()) {
2424     if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2425       if (!Namespace->getDeclName())
2426         return false;
2427       break;
2428     }
2429   }
2430 
2431   return true;
2432 }
2433 
2434 bool FunctionDecl::isNoReturn() const {
2435   return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2436          hasAttr<C11NoReturnAttr>() ||
2437          getType()->getAs<FunctionType>()->getNoReturnAttr();
2438 }
2439 
2440 void
2441 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2442   redeclarable_base::setPreviousDecl(PrevDecl);
2443 
2444   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2445     FunctionTemplateDecl *PrevFunTmpl
2446       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2447     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2448     FunTmpl->setPreviousDecl(PrevFunTmpl);
2449   }
2450 
2451   if (PrevDecl && PrevDecl->IsInline)
2452     IsInline = true;
2453 }
2454 
2455 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2456   return getFirstDecl();
2457 }
2458 
2459 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2460 
2461 /// \brief Returns a value indicating whether this function
2462 /// corresponds to a builtin function.
2463 ///
2464 /// The function corresponds to a built-in function if it is
2465 /// declared at translation scope or within an extern "C" block and
2466 /// its name matches with the name of a builtin. The returned value
2467 /// will be 0 for functions that do not correspond to a builtin, a
2468 /// value of type \c Builtin::ID if in the target-independent range
2469 /// \c [1,Builtin::First), or a target-specific builtin value.
2470 unsigned FunctionDecl::getBuiltinID() const {
2471   if (!getIdentifier())
2472     return 0;
2473 
2474   unsigned BuiltinID = getIdentifier()->getBuiltinID();
2475   if (!BuiltinID)
2476     return 0;
2477 
2478   ASTContext &Context = getASTContext();
2479   if (Context.getLangOpts().CPlusPlus) {
2480     const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2481         getFirstDecl()->getDeclContext());
2482     // In C++, the first declaration of a builtin is always inside an implicit
2483     // extern "C".
2484     // FIXME: A recognised library function may not be directly in an extern "C"
2485     // declaration, for instance "extern "C" { namespace std { decl } }".
2486     if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2487       return 0;
2488   }
2489 
2490   // If the function is marked "overloadable", it has a different mangled name
2491   // and is not the C library function.
2492   if (hasAttr<OverloadableAttr>())
2493     return 0;
2494 
2495   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2496     return BuiltinID;
2497 
2498   // This function has the name of a known C library
2499   // function. Determine whether it actually refers to the C library
2500   // function or whether it just has the same name.
2501 
2502   // If this is a static function, it's not a builtin.
2503   if (getStorageClass() == SC_Static)
2504     return 0;
2505 
2506   return BuiltinID;
2507 }
2508 
2509 
2510 /// getNumParams - Return the number of parameters this function must have
2511 /// based on its FunctionType.  This is the length of the ParamInfo array
2512 /// after it has been created.
2513 unsigned FunctionDecl::getNumParams() const {
2514   const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
2515   return FPT ? FPT->getNumParams() : 0;
2516 }
2517 
2518 void FunctionDecl::setParams(ASTContext &C,
2519                              ArrayRef<ParmVarDecl *> NewParamInfo) {
2520   assert(ParamInfo == 0 && "Already has param info!");
2521   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2522 
2523   // Zero params -> null pointer.
2524   if (!NewParamInfo.empty()) {
2525     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2526     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2527   }
2528 }
2529 
2530 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2531   assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2532 
2533   if (!NewDecls.empty()) {
2534     NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2535     std::copy(NewDecls.begin(), NewDecls.end(), A);
2536     DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
2537   }
2538 }
2539 
2540 /// getMinRequiredArguments - Returns the minimum number of arguments
2541 /// needed to call this function. This may be fewer than the number of
2542 /// function parameters, if some of the parameters have default
2543 /// arguments (in C++) or the last parameter is a parameter pack.
2544 unsigned FunctionDecl::getMinRequiredArguments() const {
2545   if (!getASTContext().getLangOpts().CPlusPlus)
2546     return getNumParams();
2547 
2548   unsigned NumRequiredArgs = getNumParams();
2549 
2550   // If the last parameter is a parameter pack, we don't need an argument for
2551   // it.
2552   if (NumRequiredArgs > 0 &&
2553       getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2554     --NumRequiredArgs;
2555 
2556   // If this parameter has a default argument, we don't need an argument for
2557   // it.
2558   while (NumRequiredArgs > 0 &&
2559          getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
2560     --NumRequiredArgs;
2561 
2562   // We might have parameter packs before the end. These can't be deduced,
2563   // but they can still handle multiple arguments.
2564   unsigned ArgIdx = NumRequiredArgs;
2565   while (ArgIdx > 0) {
2566     if (getParamDecl(ArgIdx - 1)->isParameterPack())
2567       NumRequiredArgs = ArgIdx;
2568 
2569     --ArgIdx;
2570   }
2571 
2572   return NumRequiredArgs;
2573 }
2574 
2575 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2576   // Only consider file-scope declarations in this test.
2577   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2578     return false;
2579 
2580   // Only consider explicit declarations; the presence of a builtin for a
2581   // libcall shouldn't affect whether a definition is externally visible.
2582   if (Redecl->isImplicit())
2583     return false;
2584 
2585   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2586     return true; // Not an inline definition
2587 
2588   return false;
2589 }
2590 
2591 /// \brief For a function declaration in C or C++, determine whether this
2592 /// declaration causes the definition to be externally visible.
2593 ///
2594 /// Specifically, this determines if adding the current declaration to the set
2595 /// of redeclarations of the given functions causes
2596 /// isInlineDefinitionExternallyVisible to change from false to true.
2597 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2598   assert(!doesThisDeclarationHaveABody() &&
2599          "Must have a declaration without a body.");
2600 
2601   ASTContext &Context = getASTContext();
2602 
2603   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2604     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2605     // an externally visible definition.
2606     //
2607     // FIXME: What happens if gnu_inline gets added on after the first
2608     // declaration?
2609     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2610       return false;
2611 
2612     const FunctionDecl *Prev = this;
2613     bool FoundBody = false;
2614     while ((Prev = Prev->getPreviousDecl())) {
2615       FoundBody |= Prev->Body.isValid();
2616 
2617       if (Prev->Body) {
2618         // If it's not the case that both 'inline' and 'extern' are
2619         // specified on the definition, then it is always externally visible.
2620         if (!Prev->isInlineSpecified() ||
2621             Prev->getStorageClass() != SC_Extern)
2622           return false;
2623       } else if (Prev->isInlineSpecified() &&
2624                  Prev->getStorageClass() != SC_Extern) {
2625         return false;
2626       }
2627     }
2628     return FoundBody;
2629   }
2630 
2631   if (Context.getLangOpts().CPlusPlus)
2632     return false;
2633 
2634   // C99 6.7.4p6:
2635   //   [...] If all of the file scope declarations for a function in a
2636   //   translation unit include the inline function specifier without extern,
2637   //   then the definition in that translation unit is an inline definition.
2638   if (isInlineSpecified() && getStorageClass() != SC_Extern)
2639     return false;
2640   const FunctionDecl *Prev = this;
2641   bool FoundBody = false;
2642   while ((Prev = Prev->getPreviousDecl())) {
2643     FoundBody |= Prev->Body.isValid();
2644     if (RedeclForcesDefC99(Prev))
2645       return false;
2646   }
2647   return FoundBody;
2648 }
2649 
2650 /// \brief For an inline function definition in C, or for a gnu_inline function
2651 /// in C++, determine whether the definition will be externally visible.
2652 ///
2653 /// Inline function definitions are always available for inlining optimizations.
2654 /// However, depending on the language dialect, declaration specifiers, and
2655 /// attributes, the definition of an inline function may or may not be
2656 /// "externally" visible to other translation units in the program.
2657 ///
2658 /// In C99, inline definitions are not externally visible by default. However,
2659 /// if even one of the global-scope declarations is marked "extern inline", the
2660 /// inline definition becomes externally visible (C99 6.7.4p6).
2661 ///
2662 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2663 /// definition, we use the GNU semantics for inline, which are nearly the
2664 /// opposite of C99 semantics. In particular, "inline" by itself will create
2665 /// an externally visible symbol, but "extern inline" will not create an
2666 /// externally visible symbol.
2667 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2668   assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2669   assert(isInlined() && "Function must be inline");
2670   ASTContext &Context = getASTContext();
2671 
2672   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2673     // Note: If you change the logic here, please change
2674     // doesDeclarationForceExternallyVisibleDefinition as well.
2675     //
2676     // If it's not the case that both 'inline' and 'extern' are
2677     // specified on the definition, then this inline definition is
2678     // externally visible.
2679     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2680       return true;
2681 
2682     // If any declaration is 'inline' but not 'extern', then this definition
2683     // is externally visible.
2684     for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2685          Redecl != RedeclEnd;
2686          ++Redecl) {
2687       if (Redecl->isInlineSpecified() &&
2688           Redecl->getStorageClass() != SC_Extern)
2689         return true;
2690     }
2691 
2692     return false;
2693   }
2694 
2695   // The rest of this function is C-only.
2696   assert(!Context.getLangOpts().CPlusPlus &&
2697          "should not use C inline rules in C++");
2698 
2699   // C99 6.7.4p6:
2700   //   [...] If all of the file scope declarations for a function in a
2701   //   translation unit include the inline function specifier without extern,
2702   //   then the definition in that translation unit is an inline definition.
2703   for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2704        Redecl != RedeclEnd;
2705        ++Redecl) {
2706     if (RedeclForcesDefC99(*Redecl))
2707       return true;
2708   }
2709 
2710   // C99 6.7.4p6:
2711   //   An inline definition does not provide an external definition for the
2712   //   function, and does not forbid an external definition in another
2713   //   translation unit.
2714   return false;
2715 }
2716 
2717 /// getOverloadedOperator - Which C++ overloaded operator this
2718 /// function represents, if any.
2719 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2720   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2721     return getDeclName().getCXXOverloadedOperator();
2722   else
2723     return OO_None;
2724 }
2725 
2726 /// getLiteralIdentifier - The literal suffix identifier this function
2727 /// represents, if any.
2728 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2729   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2730     return getDeclName().getCXXLiteralIdentifier();
2731   else
2732     return 0;
2733 }
2734 
2735 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2736   if (TemplateOrSpecialization.isNull())
2737     return TK_NonTemplate;
2738   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2739     return TK_FunctionTemplate;
2740   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2741     return TK_MemberSpecialization;
2742   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2743     return TK_FunctionTemplateSpecialization;
2744   if (TemplateOrSpecialization.is
2745                                <DependentFunctionTemplateSpecializationInfo*>())
2746     return TK_DependentFunctionTemplateSpecialization;
2747 
2748   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2749 }
2750 
2751 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2752   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2753     return cast<FunctionDecl>(Info->getInstantiatedFrom());
2754 
2755   return 0;
2756 }
2757 
2758 void
2759 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2760                                                FunctionDecl *FD,
2761                                                TemplateSpecializationKind TSK) {
2762   assert(TemplateOrSpecialization.isNull() &&
2763          "Member function is already a specialization");
2764   MemberSpecializationInfo *Info
2765     = new (C) MemberSpecializationInfo(FD, TSK);
2766   TemplateOrSpecialization = Info;
2767 }
2768 
2769 bool FunctionDecl::isImplicitlyInstantiable() const {
2770   // If the function is invalid, it can't be implicitly instantiated.
2771   if (isInvalidDecl())
2772     return false;
2773 
2774   switch (getTemplateSpecializationKind()) {
2775   case TSK_Undeclared:
2776   case TSK_ExplicitInstantiationDefinition:
2777     return false;
2778 
2779   case TSK_ImplicitInstantiation:
2780     return true;
2781 
2782   // It is possible to instantiate TSK_ExplicitSpecialization kind
2783   // if the FunctionDecl has a class scope specialization pattern.
2784   case TSK_ExplicitSpecialization:
2785     return getClassScopeSpecializationPattern() != 0;
2786 
2787   case TSK_ExplicitInstantiationDeclaration:
2788     // Handled below.
2789     break;
2790   }
2791 
2792   // Find the actual template from which we will instantiate.
2793   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2794   bool HasPattern = false;
2795   if (PatternDecl)
2796     HasPattern = PatternDecl->hasBody(PatternDecl);
2797 
2798   // C++0x [temp.explicit]p9:
2799   //   Except for inline functions, other explicit instantiation declarations
2800   //   have the effect of suppressing the implicit instantiation of the entity
2801   //   to which they refer.
2802   if (!HasPattern || !PatternDecl)
2803     return true;
2804 
2805   return PatternDecl->isInlined();
2806 }
2807 
2808 bool FunctionDecl::isTemplateInstantiation() const {
2809   switch (getTemplateSpecializationKind()) {
2810     case TSK_Undeclared:
2811     case TSK_ExplicitSpecialization:
2812       return false;
2813     case TSK_ImplicitInstantiation:
2814     case TSK_ExplicitInstantiationDeclaration:
2815     case TSK_ExplicitInstantiationDefinition:
2816       return true;
2817   }
2818   llvm_unreachable("All TSK values handled.");
2819 }
2820 
2821 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2822   // Handle class scope explicit specialization special case.
2823   if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2824     return getClassScopeSpecializationPattern();
2825 
2826   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2827     while (Primary->getInstantiatedFromMemberTemplate()) {
2828       // If we have hit a point where the user provided a specialization of
2829       // this template, we're done looking.
2830       if (Primary->isMemberSpecialization())
2831         break;
2832 
2833       Primary = Primary->getInstantiatedFromMemberTemplate();
2834     }
2835 
2836     return Primary->getTemplatedDecl();
2837   }
2838 
2839   return getInstantiatedFromMemberFunction();
2840 }
2841 
2842 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
2843   if (FunctionTemplateSpecializationInfo *Info
2844         = TemplateOrSpecialization
2845             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2846     return Info->Template.getPointer();
2847   }
2848   return 0;
2849 }
2850 
2851 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2852     return getASTContext().getClassScopeSpecializationPattern(this);
2853 }
2854 
2855 const TemplateArgumentList *
2856 FunctionDecl::getTemplateSpecializationArgs() const {
2857   if (FunctionTemplateSpecializationInfo *Info
2858         = TemplateOrSpecialization
2859             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2860     return Info->TemplateArguments;
2861   }
2862   return 0;
2863 }
2864 
2865 const ASTTemplateArgumentListInfo *
2866 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2867   if (FunctionTemplateSpecializationInfo *Info
2868         = TemplateOrSpecialization
2869             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2870     return Info->TemplateArgumentsAsWritten;
2871   }
2872   return 0;
2873 }
2874 
2875 void
2876 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2877                                                 FunctionTemplateDecl *Template,
2878                                      const TemplateArgumentList *TemplateArgs,
2879                                                 void *InsertPos,
2880                                                 TemplateSpecializationKind TSK,
2881                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
2882                                           SourceLocation PointOfInstantiation) {
2883   assert(TSK != TSK_Undeclared &&
2884          "Must specify the type of function template specialization");
2885   FunctionTemplateSpecializationInfo *Info
2886     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2887   if (!Info)
2888     Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2889                                                       TemplateArgs,
2890                                                       TemplateArgsAsWritten,
2891                                                       PointOfInstantiation);
2892   TemplateOrSpecialization = Info;
2893   Template->addSpecialization(Info, InsertPos);
2894 }
2895 
2896 void
2897 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2898                                     const UnresolvedSetImpl &Templates,
2899                              const TemplateArgumentListInfo &TemplateArgs) {
2900   assert(TemplateOrSpecialization.isNull());
2901   size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2902   Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2903   Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2904   void *Buffer = Context.Allocate(Size);
2905   DependentFunctionTemplateSpecializationInfo *Info =
2906     new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2907                                                              TemplateArgs);
2908   TemplateOrSpecialization = Info;
2909 }
2910 
2911 DependentFunctionTemplateSpecializationInfo::
2912 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2913                                       const TemplateArgumentListInfo &TArgs)
2914   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2915 
2916   d.NumTemplates = Ts.size();
2917   d.NumArgs = TArgs.size();
2918 
2919   FunctionTemplateDecl **TsArray =
2920     const_cast<FunctionTemplateDecl**>(getTemplates());
2921   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2922     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2923 
2924   TemplateArgumentLoc *ArgsArray =
2925     const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2926   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2927     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2928 }
2929 
2930 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2931   // For a function template specialization, query the specialization
2932   // information object.
2933   FunctionTemplateSpecializationInfo *FTSInfo
2934     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2935   if (FTSInfo)
2936     return FTSInfo->getTemplateSpecializationKind();
2937 
2938   MemberSpecializationInfo *MSInfo
2939     = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2940   if (MSInfo)
2941     return MSInfo->getTemplateSpecializationKind();
2942 
2943   return TSK_Undeclared;
2944 }
2945 
2946 void
2947 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2948                                           SourceLocation PointOfInstantiation) {
2949   if (FunctionTemplateSpecializationInfo *FTSInfo
2950         = TemplateOrSpecialization.dyn_cast<
2951                                     FunctionTemplateSpecializationInfo*>()) {
2952     FTSInfo->setTemplateSpecializationKind(TSK);
2953     if (TSK != TSK_ExplicitSpecialization &&
2954         PointOfInstantiation.isValid() &&
2955         FTSInfo->getPointOfInstantiation().isInvalid())
2956       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2957   } else if (MemberSpecializationInfo *MSInfo
2958              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2959     MSInfo->setTemplateSpecializationKind(TSK);
2960     if (TSK != TSK_ExplicitSpecialization &&
2961         PointOfInstantiation.isValid() &&
2962         MSInfo->getPointOfInstantiation().isInvalid())
2963       MSInfo->setPointOfInstantiation(PointOfInstantiation);
2964   } else
2965     llvm_unreachable("Function cannot have a template specialization kind");
2966 }
2967 
2968 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2969   if (FunctionTemplateSpecializationInfo *FTSInfo
2970         = TemplateOrSpecialization.dyn_cast<
2971                                         FunctionTemplateSpecializationInfo*>())
2972     return FTSInfo->getPointOfInstantiation();
2973   else if (MemberSpecializationInfo *MSInfo
2974              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2975     return MSInfo->getPointOfInstantiation();
2976 
2977   return SourceLocation();
2978 }
2979 
2980 bool FunctionDecl::isOutOfLine() const {
2981   if (Decl::isOutOfLine())
2982     return true;
2983 
2984   // If this function was instantiated from a member function of a
2985   // class template, check whether that member function was defined out-of-line.
2986   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2987     const FunctionDecl *Definition;
2988     if (FD->hasBody(Definition))
2989       return Definition->isOutOfLine();
2990   }
2991 
2992   // If this function was instantiated from a function template,
2993   // check whether that function template was defined out-of-line.
2994   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2995     const FunctionDecl *Definition;
2996     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2997       return Definition->isOutOfLine();
2998   }
2999 
3000   return false;
3001 }
3002 
3003 SourceRange FunctionDecl::getSourceRange() const {
3004   return SourceRange(getOuterLocStart(), EndRangeLoc);
3005 }
3006 
3007 unsigned FunctionDecl::getMemoryFunctionKind() const {
3008   IdentifierInfo *FnInfo = getIdentifier();
3009 
3010   if (!FnInfo)
3011     return 0;
3012 
3013   // Builtin handling.
3014   switch (getBuiltinID()) {
3015   case Builtin::BI__builtin_memset:
3016   case Builtin::BI__builtin___memset_chk:
3017   case Builtin::BImemset:
3018     return Builtin::BImemset;
3019 
3020   case Builtin::BI__builtin_memcpy:
3021   case Builtin::BI__builtin___memcpy_chk:
3022   case Builtin::BImemcpy:
3023     return Builtin::BImemcpy;
3024 
3025   case Builtin::BI__builtin_memmove:
3026   case Builtin::BI__builtin___memmove_chk:
3027   case Builtin::BImemmove:
3028     return Builtin::BImemmove;
3029 
3030   case Builtin::BIstrlcpy:
3031     return Builtin::BIstrlcpy;
3032   case Builtin::BIstrlcat:
3033     return Builtin::BIstrlcat;
3034 
3035   case Builtin::BI__builtin_memcmp:
3036   case Builtin::BImemcmp:
3037     return Builtin::BImemcmp;
3038 
3039   case Builtin::BI__builtin_strncpy:
3040   case Builtin::BI__builtin___strncpy_chk:
3041   case Builtin::BIstrncpy:
3042     return Builtin::BIstrncpy;
3043 
3044   case Builtin::BI__builtin_strncmp:
3045   case Builtin::BIstrncmp:
3046     return Builtin::BIstrncmp;
3047 
3048   case Builtin::BI__builtin_strncasecmp:
3049   case Builtin::BIstrncasecmp:
3050     return Builtin::BIstrncasecmp;
3051 
3052   case Builtin::BI__builtin_strncat:
3053   case Builtin::BI__builtin___strncat_chk:
3054   case Builtin::BIstrncat:
3055     return Builtin::BIstrncat;
3056 
3057   case Builtin::BI__builtin_strndup:
3058   case Builtin::BIstrndup:
3059     return Builtin::BIstrndup;
3060 
3061   case Builtin::BI__builtin_strlen:
3062   case Builtin::BIstrlen:
3063     return Builtin::BIstrlen;
3064 
3065   default:
3066     if (isExternC()) {
3067       if (FnInfo->isStr("memset"))
3068         return Builtin::BImemset;
3069       else if (FnInfo->isStr("memcpy"))
3070         return Builtin::BImemcpy;
3071       else if (FnInfo->isStr("memmove"))
3072         return Builtin::BImemmove;
3073       else if (FnInfo->isStr("memcmp"))
3074         return Builtin::BImemcmp;
3075       else if (FnInfo->isStr("strncpy"))
3076         return Builtin::BIstrncpy;
3077       else if (FnInfo->isStr("strncmp"))
3078         return Builtin::BIstrncmp;
3079       else if (FnInfo->isStr("strncasecmp"))
3080         return Builtin::BIstrncasecmp;
3081       else if (FnInfo->isStr("strncat"))
3082         return Builtin::BIstrncat;
3083       else if (FnInfo->isStr("strndup"))
3084         return Builtin::BIstrndup;
3085       else if (FnInfo->isStr("strlen"))
3086         return Builtin::BIstrlen;
3087     }
3088     break;
3089   }
3090   return 0;
3091 }
3092 
3093 //===----------------------------------------------------------------------===//
3094 // FieldDecl Implementation
3095 //===----------------------------------------------------------------------===//
3096 
3097 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3098                              SourceLocation StartLoc, SourceLocation IdLoc,
3099                              IdentifierInfo *Id, QualType T,
3100                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3101                              InClassInitStyle InitStyle) {
3102   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3103                                BW, Mutable, InitStyle);
3104 }
3105 
3106 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3107   return new (C, ID) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
3108                                0, QualType(), 0, 0, false, ICIS_NoInit);
3109 }
3110 
3111 bool FieldDecl::isAnonymousStructOrUnion() const {
3112   if (!isImplicit() || getDeclName())
3113     return false;
3114 
3115   if (const RecordType *Record = getType()->getAs<RecordType>())
3116     return Record->getDecl()->isAnonymousStructOrUnion();
3117 
3118   return false;
3119 }
3120 
3121 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3122   assert(isBitField() && "not a bitfield");
3123   Expr *BitWidth = InitializerOrBitWidth.getPointer();
3124   return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3125 }
3126 
3127 unsigned FieldDecl::getFieldIndex() const {
3128   const FieldDecl *Canonical = getCanonicalDecl();
3129   if (Canonical != this)
3130     return Canonical->getFieldIndex();
3131 
3132   if (CachedFieldIndex) return CachedFieldIndex - 1;
3133 
3134   unsigned Index = 0;
3135   const RecordDecl *RD = getParent();
3136 
3137   for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
3138        I != E; ++I, ++Index)
3139     I->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3140 
3141   assert(CachedFieldIndex && "failed to find field in parent");
3142   return CachedFieldIndex - 1;
3143 }
3144 
3145 SourceRange FieldDecl::getSourceRange() const {
3146   if (const Expr *E = InitializerOrBitWidth.getPointer())
3147     return SourceRange(getInnerLocStart(), E->getLocEnd());
3148   return DeclaratorDecl::getSourceRange();
3149 }
3150 
3151 void FieldDecl::setBitWidth(Expr *Width) {
3152   assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
3153          "bit width or initializer already set");
3154   InitializerOrBitWidth.setPointer(Width);
3155 }
3156 
3157 void FieldDecl::setInClassInitializer(Expr *Init) {
3158   assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
3159          "bit width or initializer already set");
3160   InitializerOrBitWidth.setPointer(Init);
3161 }
3162 
3163 //===----------------------------------------------------------------------===//
3164 // TagDecl Implementation
3165 //===----------------------------------------------------------------------===//
3166 
3167 SourceLocation TagDecl::getOuterLocStart() const {
3168   return getTemplateOrInnerLocStart(this);
3169 }
3170 
3171 SourceRange TagDecl::getSourceRange() const {
3172   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3173   return SourceRange(getOuterLocStart(), E);
3174 }
3175 
3176 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3177 
3178 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3179   NamedDeclOrQualifier = TDD;
3180   if (TypeForDecl)
3181     assert(TypeForDecl->isLinkageValid());
3182   assert(isLinkageValid());
3183 }
3184 
3185 void TagDecl::startDefinition() {
3186   IsBeingDefined = true;
3187 
3188   if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
3189     struct CXXRecordDecl::DefinitionData *Data =
3190       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3191     for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
3192       cast<CXXRecordDecl>(*I)->DefinitionData = Data;
3193   }
3194 }
3195 
3196 void TagDecl::completeDefinition() {
3197   assert((!isa<CXXRecordDecl>(this) ||
3198           cast<CXXRecordDecl>(this)->hasDefinition()) &&
3199          "definition completed but not started");
3200 
3201   IsCompleteDefinition = true;
3202   IsBeingDefined = false;
3203 
3204   if (ASTMutationListener *L = getASTMutationListener())
3205     L->CompletedTagDefinition(this);
3206 }
3207 
3208 TagDecl *TagDecl::getDefinition() const {
3209   if (isCompleteDefinition())
3210     return const_cast<TagDecl *>(this);
3211 
3212   // If it's possible for us to have an out-of-date definition, check now.
3213   if (MayHaveOutOfDateDef) {
3214     if (IdentifierInfo *II = getIdentifier()) {
3215       if (II->isOutOfDate()) {
3216         updateOutOfDate(*II);
3217       }
3218     }
3219   }
3220 
3221   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3222     return CXXRD->getDefinition();
3223 
3224   for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
3225        R != REnd; ++R)
3226     if (R->isCompleteDefinition())
3227       return *R;
3228 
3229   return 0;
3230 }
3231 
3232 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3233   if (QualifierLoc) {
3234     // Make sure the extended qualifier info is allocated.
3235     if (!hasExtInfo())
3236       NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3237     // Set qualifier info.
3238     getExtInfo()->QualifierLoc = QualifierLoc;
3239   } else {
3240     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3241     if (hasExtInfo()) {
3242       if (getExtInfo()->NumTemplParamLists == 0) {
3243         getASTContext().Deallocate(getExtInfo());
3244         NamedDeclOrQualifier = (TypedefNameDecl*) 0;
3245       }
3246       else
3247         getExtInfo()->QualifierLoc = QualifierLoc;
3248     }
3249   }
3250 }
3251 
3252 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3253                                             unsigned NumTPLists,
3254                                             TemplateParameterList **TPLists) {
3255   assert(NumTPLists > 0);
3256   // Make sure the extended decl info is allocated.
3257   if (!hasExtInfo())
3258     // Allocate external info struct.
3259     NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3260   // Set the template parameter lists info.
3261   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3262 }
3263 
3264 //===----------------------------------------------------------------------===//
3265 // EnumDecl Implementation
3266 //===----------------------------------------------------------------------===//
3267 
3268 void EnumDecl::anchor() { }
3269 
3270 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3271                            SourceLocation StartLoc, SourceLocation IdLoc,
3272                            IdentifierInfo *Id,
3273                            EnumDecl *PrevDecl, bool IsScoped,
3274                            bool IsScopedUsingClassTag, bool IsFixed) {
3275   EnumDecl *Enum = new (C, DC) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
3276                                         IsScoped, IsScopedUsingClassTag,
3277                                         IsFixed);
3278   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3279   C.getTypeDeclType(Enum, PrevDecl);
3280   return Enum;
3281 }
3282 
3283 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3284   EnumDecl *Enum = new (C, ID) EnumDecl(0, SourceLocation(), SourceLocation(),
3285                                         0, 0, false, false, false);
3286   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3287   return Enum;
3288 }
3289 
3290 SourceRange EnumDecl::getIntegerTypeRange() const {
3291   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3292     return TI->getTypeLoc().getSourceRange();
3293   return SourceRange();
3294 }
3295 
3296 void EnumDecl::completeDefinition(QualType NewType,
3297                                   QualType NewPromotionType,
3298                                   unsigned NumPositiveBits,
3299                                   unsigned NumNegativeBits) {
3300   assert(!isCompleteDefinition() && "Cannot redefine enums!");
3301   if (!IntegerType)
3302     IntegerType = NewType.getTypePtr();
3303   PromotionType = NewPromotionType;
3304   setNumPositiveBits(NumPositiveBits);
3305   setNumNegativeBits(NumNegativeBits);
3306   TagDecl::completeDefinition();
3307 }
3308 
3309 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3310   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3311     return MSI->getTemplateSpecializationKind();
3312 
3313   return TSK_Undeclared;
3314 }
3315 
3316 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3317                                          SourceLocation PointOfInstantiation) {
3318   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3319   assert(MSI && "Not an instantiated member enumeration?");
3320   MSI->setTemplateSpecializationKind(TSK);
3321   if (TSK != TSK_ExplicitSpecialization &&
3322       PointOfInstantiation.isValid() &&
3323       MSI->getPointOfInstantiation().isInvalid())
3324     MSI->setPointOfInstantiation(PointOfInstantiation);
3325 }
3326 
3327 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3328   if (SpecializationInfo)
3329     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3330 
3331   return 0;
3332 }
3333 
3334 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3335                                             TemplateSpecializationKind TSK) {
3336   assert(!SpecializationInfo && "Member enum is already a specialization");
3337   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3338 }
3339 
3340 //===----------------------------------------------------------------------===//
3341 // RecordDecl Implementation
3342 //===----------------------------------------------------------------------===//
3343 
3344 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3345                        SourceLocation StartLoc, SourceLocation IdLoc,
3346                        IdentifierInfo *Id, RecordDecl *PrevDecl)
3347   : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
3348   HasFlexibleArrayMember = false;
3349   AnonymousStructOrUnion = false;
3350   HasObjectMember = false;
3351   HasVolatileMember = false;
3352   LoadedFieldsFromExternalStorage = false;
3353   assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3354 }
3355 
3356 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3357                                SourceLocation StartLoc, SourceLocation IdLoc,
3358                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
3359   RecordDecl* R = new (C, DC) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3360                                          PrevDecl);
3361   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3362 
3363   C.getTypeDeclType(R, PrevDecl);
3364   return R;
3365 }
3366 
3367 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3368   RecordDecl *R = new (C, ID) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3369                                          SourceLocation(), 0, 0);
3370   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3371   return R;
3372 }
3373 
3374 bool RecordDecl::isInjectedClassName() const {
3375   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3376     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3377 }
3378 
3379 RecordDecl::field_iterator RecordDecl::field_begin() const {
3380   if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3381     LoadFieldsFromExternalStorage();
3382 
3383   return field_iterator(decl_iterator(FirstDecl));
3384 }
3385 
3386 /// completeDefinition - Notes that the definition of this type is now
3387 /// complete.
3388 void RecordDecl::completeDefinition() {
3389   assert(!isCompleteDefinition() && "Cannot redefine record!");
3390   TagDecl::completeDefinition();
3391 }
3392 
3393 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3394 /// This which can be turned on with an attribute, pragma, or the
3395 /// -mms-bitfields command-line option.
3396 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3397   return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3398 }
3399 
3400 static bool isFieldOrIndirectField(Decl::Kind K) {
3401   return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3402 }
3403 
3404 void RecordDecl::LoadFieldsFromExternalStorage() const {
3405   ExternalASTSource *Source = getASTContext().getExternalSource();
3406   assert(hasExternalLexicalStorage() && Source && "No external storage?");
3407 
3408   // Notify that we have a RecordDecl doing some initialization.
3409   ExternalASTSource::Deserializing TheFields(Source);
3410 
3411   SmallVector<Decl*, 64> Decls;
3412   LoadedFieldsFromExternalStorage = true;
3413   switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3414                                            Decls)) {
3415   case ELR_Success:
3416     break;
3417 
3418   case ELR_AlreadyLoaded:
3419   case ELR_Failure:
3420     return;
3421   }
3422 
3423 #ifndef NDEBUG
3424   // Check that all decls we got were FieldDecls.
3425   for (unsigned i=0, e=Decls.size(); i != e; ++i)
3426     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3427 #endif
3428 
3429   if (Decls.empty())
3430     return;
3431 
3432   llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3433                                                  /*FieldsAlreadyLoaded=*/false);
3434 }
3435 
3436 //===----------------------------------------------------------------------===//
3437 // BlockDecl Implementation
3438 //===----------------------------------------------------------------------===//
3439 
3440 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3441   assert(ParamInfo == 0 && "Already has param info!");
3442 
3443   // Zero params -> null pointer.
3444   if (!NewParamInfo.empty()) {
3445     NumParams = NewParamInfo.size();
3446     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3447     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3448   }
3449 }
3450 
3451 void BlockDecl::setCaptures(ASTContext &Context,
3452                             const Capture *begin,
3453                             const Capture *end,
3454                             bool capturesCXXThis) {
3455   CapturesCXXThis = capturesCXXThis;
3456 
3457   if (begin == end) {
3458     NumCaptures = 0;
3459     Captures = 0;
3460     return;
3461   }
3462 
3463   NumCaptures = end - begin;
3464 
3465   // Avoid new Capture[] because we don't want to provide a default
3466   // constructor.
3467   size_t allocationSize = NumCaptures * sizeof(Capture);
3468   void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3469   memcpy(buffer, begin, allocationSize);
3470   Captures = static_cast<Capture*>(buffer);
3471 }
3472 
3473 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3474   for (capture_const_iterator
3475          i = capture_begin(), e = capture_end(); i != e; ++i)
3476     // Only auto vars can be captured, so no redeclaration worries.
3477     if (i->getVariable() == variable)
3478       return true;
3479 
3480   return false;
3481 }
3482 
3483 SourceRange BlockDecl::getSourceRange() const {
3484   return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3485 }
3486 
3487 //===----------------------------------------------------------------------===//
3488 // Other Decl Allocation/Deallocation Method Implementations
3489 //===----------------------------------------------------------------------===//
3490 
3491 void TranslationUnitDecl::anchor() { }
3492 
3493 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3494   return new (C, (DeclContext*)0) TranslationUnitDecl(C);
3495 }
3496 
3497 void LabelDecl::anchor() { }
3498 
3499 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3500                              SourceLocation IdentL, IdentifierInfo *II) {
3501   return new (C, DC) LabelDecl(DC, IdentL, II, 0, IdentL);
3502 }
3503 
3504 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3505                              SourceLocation IdentL, IdentifierInfo *II,
3506                              SourceLocation GnuLabelL) {
3507   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3508   return new (C, DC) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
3509 }
3510 
3511 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3512   return new (C, ID) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
3513 }
3514 
3515 void ValueDecl::anchor() { }
3516 
3517 bool ValueDecl::isWeak() const {
3518   for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3519     if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3520       return true;
3521 
3522   return isWeakImported();
3523 }
3524 
3525 void ImplicitParamDecl::anchor() { }
3526 
3527 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3528                                              SourceLocation IdLoc,
3529                                              IdentifierInfo *Id,
3530                                              QualType Type) {
3531   return new (C, DC) ImplicitParamDecl(DC, IdLoc, Id, Type);
3532 }
3533 
3534 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3535                                                          unsigned ID) {
3536   return new (C, ID) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3537 }
3538 
3539 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3540                                    SourceLocation StartLoc,
3541                                    const DeclarationNameInfo &NameInfo,
3542                                    QualType T, TypeSourceInfo *TInfo,
3543                                    StorageClass SC,
3544                                    bool isInlineSpecified,
3545                                    bool hasWrittenPrototype,
3546                                    bool isConstexprSpecified) {
3547   FunctionDecl *New =
3548       new (C, DC) FunctionDecl(Function, DC, StartLoc, NameInfo, T, TInfo, SC,
3549                                isInlineSpecified, isConstexprSpecified);
3550   New->HasWrittenPrototype = hasWrittenPrototype;
3551   return New;
3552 }
3553 
3554 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3555   return new (C, ID) FunctionDecl(Function, 0, SourceLocation(),
3556                                   DeclarationNameInfo(), QualType(), 0,
3557                                   SC_None, false, false);
3558 }
3559 
3560 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3561   return new (C, DC) BlockDecl(DC, L);
3562 }
3563 
3564 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3565   return new (C, ID) BlockDecl(0, SourceLocation());
3566 }
3567 
3568 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3569                                    unsigned NumParams) {
3570   return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3571       CapturedDecl(DC, NumParams);
3572 }
3573 
3574 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3575                                                unsigned NumParams) {
3576   return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3577       CapturedDecl(0, NumParams);
3578 }
3579 
3580 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3581                                            SourceLocation L,
3582                                            IdentifierInfo *Id, QualType T,
3583                                            Expr *E, const llvm::APSInt &V) {
3584   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
3585 }
3586 
3587 EnumConstantDecl *
3588 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3589   return new (C, ID) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3590                                       llvm::APSInt());
3591 }
3592 
3593 void IndirectFieldDecl::anchor() { }
3594 
3595 IndirectFieldDecl *
3596 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3597                           IdentifierInfo *Id, QualType T, NamedDecl **CH,
3598                           unsigned CHS) {
3599   return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3600 }
3601 
3602 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3603                                                          unsigned ID) {
3604   return new (C, ID) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3605                                        QualType(), 0, 0);
3606 }
3607 
3608 SourceRange EnumConstantDecl::getSourceRange() const {
3609   SourceLocation End = getLocation();
3610   if (Init)
3611     End = Init->getLocEnd();
3612   return SourceRange(getLocation(), End);
3613 }
3614 
3615 void TypeDecl::anchor() { }
3616 
3617 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
3618                                  SourceLocation StartLoc, SourceLocation IdLoc,
3619                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3620   return new (C, DC) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
3621 }
3622 
3623 void TypedefNameDecl::anchor() { }
3624 
3625 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3626   return new (C, ID) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3627 }
3628 
3629 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3630                                      SourceLocation StartLoc,
3631                                      SourceLocation IdLoc, IdentifierInfo *Id,
3632                                      TypeSourceInfo *TInfo) {
3633   return new (C, DC) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3634 }
3635 
3636 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3637   return new (C, ID) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3638 }
3639 
3640 SourceRange TypedefDecl::getSourceRange() const {
3641   SourceLocation RangeEnd = getLocation();
3642   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3643     if (typeIsPostfix(TInfo->getType()))
3644       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3645   }
3646   return SourceRange(getLocStart(), RangeEnd);
3647 }
3648 
3649 SourceRange TypeAliasDecl::getSourceRange() const {
3650   SourceLocation RangeEnd = getLocStart();
3651   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3652     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3653   return SourceRange(getLocStart(), RangeEnd);
3654 }
3655 
3656 void FileScopeAsmDecl::anchor() { }
3657 
3658 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3659                                            StringLiteral *Str,
3660                                            SourceLocation AsmLoc,
3661                                            SourceLocation RParenLoc) {
3662   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
3663 }
3664 
3665 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3666                                                        unsigned ID) {
3667   return new (C, ID) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3668 }
3669 
3670 void EmptyDecl::anchor() {}
3671 
3672 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3673   return new (C, DC) EmptyDecl(DC, L);
3674 }
3675 
3676 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3677   return new (C, ID) EmptyDecl(0, SourceLocation());
3678 }
3679 
3680 //===----------------------------------------------------------------------===//
3681 // ImportDecl Implementation
3682 //===----------------------------------------------------------------------===//
3683 
3684 /// \brief Retrieve the number of module identifiers needed to name the given
3685 /// module.
3686 static unsigned getNumModuleIdentifiers(Module *Mod) {
3687   unsigned Result = 1;
3688   while (Mod->Parent) {
3689     Mod = Mod->Parent;
3690     ++Result;
3691   }
3692   return Result;
3693 }
3694 
3695 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3696                        Module *Imported,
3697                        ArrayRef<SourceLocation> IdentifierLocs)
3698   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3699     NextLocalImport()
3700 {
3701   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3702   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3703   memcpy(StoredLocs, IdentifierLocs.data(),
3704          IdentifierLocs.size() * sizeof(SourceLocation));
3705 }
3706 
3707 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3708                        Module *Imported, SourceLocation EndLoc)
3709   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3710     NextLocalImport()
3711 {
3712   *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3713 }
3714 
3715 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3716                                SourceLocation StartLoc, Module *Imported,
3717                                ArrayRef<SourceLocation> IdentifierLocs) {
3718   return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3719       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3720 }
3721 
3722 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3723                                        SourceLocation StartLoc,
3724                                        Module *Imported,
3725                                        SourceLocation EndLoc) {
3726   ImportDecl *Import =
3727       new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3728                                                      Imported, EndLoc);
3729   Import->setImplicit();
3730   return Import;
3731 }
3732 
3733 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3734                                            unsigned NumLocations) {
3735   return new (C, ID, NumLocations * sizeof(SourceLocation))
3736       ImportDecl(EmptyShell());
3737 }
3738 
3739 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3740   if (!ImportedAndComplete.getInt())
3741     return None;
3742 
3743   const SourceLocation *StoredLocs
3744     = reinterpret_cast<const SourceLocation *>(this + 1);
3745   return ArrayRef<SourceLocation>(StoredLocs,
3746                                   getNumModuleIdentifiers(getImportedModule()));
3747 }
3748 
3749 SourceRange ImportDecl::getSourceRange() const {
3750   if (!ImportedAndComplete.getInt())
3751     return SourceRange(getLocation(),
3752                        *reinterpret_cast<const SourceLocation *>(this + 1));
3753 
3754   return SourceRange(getLocation(), getIdentifierLocs().back());
3755 }
3756