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