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