xref: /llvm-project-15.0.7/clang/lib/AST/Decl.cpp (revision b1cdada0)
1 //===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Decl subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/Decl.h"
14 #include "Linkage.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/CanonicalType.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DeclarationName.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/ODRHash.h"
31 #include "clang/AST/PrettyDeclStackTrace.h"
32 #include "clang/AST/PrettyPrinter.h"
33 #include "clang/AST/Redeclarable.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/Basic/Builtins.h"
39 #include "clang/Basic/IdentifierTable.h"
40 #include "clang/Basic/LLVM.h"
41 #include "clang/Basic/LangOptions.h"
42 #include "clang/Basic/Linkage.h"
43 #include "clang/Basic/Module.h"
44 #include "clang/Basic/PartialDiagnostic.h"
45 #include "clang/Basic/SanitizerBlacklist.h"
46 #include "clang/Basic/Sanitizers.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/TargetCXXABI.h"
51 #include "clang/Basic/TargetInfo.h"
52 #include "clang/Basic/Visibility.h"
53 #include "llvm/ADT/APSInt.h"
54 #include "llvm/ADT/ArrayRef.h"
55 #include "llvm/ADT/None.h"
56 #include "llvm/ADT/Optional.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/StringSwitch.h"
61 #include "llvm/ADT/Triple.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstddef>
68 #include <cstring>
69 #include <memory>
70 #include <string>
71 #include <tuple>
72 #include <type_traits>
73 
74 using namespace clang;
75 
76 Decl *clang::getPrimaryMergedDecl(Decl *D) {
77   return D->getASTContext().getPrimaryMergedDecl(D);
78 }
79 
80 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
81   SourceLocation Loc = this->Loc;
82   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
83   if (Loc.isValid()) {
84     Loc.print(OS, Context.getSourceManager());
85     OS << ": ";
86   }
87   OS << Message;
88 
89   if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
90     OS << " '";
91     ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
92     OS << "'";
93   }
94 
95   OS << '\n';
96 }
97 
98 // Defined here so that it can be inlined into its direct callers.
99 bool Decl::isOutOfLine() const {
100   return !getLexicalDeclContext()->Equals(getDeclContext());
101 }
102 
103 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
104     : Decl(TranslationUnit, nullptr, SourceLocation()),
105       DeclContext(TranslationUnit), Ctx(ctx) {}
106 
107 //===----------------------------------------------------------------------===//
108 // NamedDecl Implementation
109 //===----------------------------------------------------------------------===//
110 
111 // Visibility rules aren't rigorously externally specified, but here
112 // are the basic principles behind what we implement:
113 //
114 // 1. An explicit visibility attribute is generally a direct expression
115 // of the user's intent and should be honored.  Only the innermost
116 // visibility attribute applies.  If no visibility attribute applies,
117 // global visibility settings are considered.
118 //
119 // 2. There is one caveat to the above: on or in a template pattern,
120 // an explicit visibility attribute is just a default rule, and
121 // visibility can be decreased by the visibility of template
122 // arguments.  But this, too, has an exception: an attribute on an
123 // explicit specialization or instantiation causes all the visibility
124 // restrictions of the template arguments to be ignored.
125 //
126 // 3. A variable that does not otherwise have explicit visibility can
127 // be restricted by the visibility of its type.
128 //
129 // 4. A visibility restriction is explicit if it comes from an
130 // attribute (or something like it), not a global visibility setting.
131 // When emitting a reference to an external symbol, visibility
132 // restrictions are ignored unless they are explicit.
133 //
134 // 5. When computing the visibility of a non-type, including a
135 // non-type member of a class, only non-type visibility restrictions
136 // are considered: the 'visibility' attribute, global value-visibility
137 // settings, and a few special cases like __private_extern.
138 //
139 // 6. When computing the visibility of a type, including a type member
140 // of a class, only type visibility restrictions are considered:
141 // the 'type_visibility' attribute and global type-visibility settings.
142 // However, a 'visibility' attribute counts as a 'type_visibility'
143 // attribute on any declaration that only has the former.
144 //
145 // The visibility of a "secondary" entity, like a template argument,
146 // is computed using the kind of that entity, not the kind of the
147 // primary entity for which we are computing visibility.  For example,
148 // the visibility of a specialization of either of these templates:
149 //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
150 //   template <class T, bool (&compare)(T, X)> class matcher;
151 // is restricted according to the type visibility of the argument 'T',
152 // the type visibility of 'bool(&)(T,X)', and the value visibility of
153 // the argument function 'compare'.  That 'has_match' is a value
154 // and 'matcher' is a type only matters when looking for attributes
155 // and settings from the immediate context.
156 
157 /// Does this computation kind permit us to consider additional
158 /// visibility settings from attributes and the like?
159 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
160   return computation.IgnoreExplicitVisibility;
161 }
162 
163 /// Given an LVComputationKind, return one of the same type/value sort
164 /// that records that it already has explicit visibility.
165 static LVComputationKind
166 withExplicitVisibilityAlready(LVComputationKind Kind) {
167   Kind.IgnoreExplicitVisibility = true;
168   return Kind;
169 }
170 
171 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
172                                                   LVComputationKind kind) {
173   assert(!kind.IgnoreExplicitVisibility &&
174          "asking for explicit visibility when we shouldn't be");
175   return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
176 }
177 
178 /// Is the given declaration a "type" or a "value" for the purposes of
179 /// visibility computation?
180 static bool usesTypeVisibility(const NamedDecl *D) {
181   return isa<TypeDecl>(D) ||
182          isa<ClassTemplateDecl>(D) ||
183          isa<ObjCInterfaceDecl>(D);
184 }
185 
186 /// Does the given declaration have member specialization information,
187 /// and if so, is it an explicit specialization?
188 template <class T> static typename
189 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
190 isExplicitMemberSpecialization(const T *D) {
191   if (const MemberSpecializationInfo *member =
192         D->getMemberSpecializationInfo()) {
193     return member->isExplicitSpecialization();
194   }
195   return false;
196 }
197 
198 /// For templates, this question is easier: a member template can't be
199 /// explicitly instantiated, so there's a single bit indicating whether
200 /// or not this is an explicit member specialization.
201 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
202   return D->isMemberSpecialization();
203 }
204 
205 /// Given a visibility attribute, return the explicit visibility
206 /// associated with it.
207 template <class T>
208 static Visibility getVisibilityFromAttr(const T *attr) {
209   switch (attr->getVisibility()) {
210   case T::Default:
211     return DefaultVisibility;
212   case T::Hidden:
213     return HiddenVisibility;
214   case T::Protected:
215     return ProtectedVisibility;
216   }
217   llvm_unreachable("bad visibility kind");
218 }
219 
220 /// Return the explicit visibility of the given declaration.
221 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
222                                     NamedDecl::ExplicitVisibilityKind kind) {
223   // If we're ultimately computing the visibility of a type, look for
224   // a 'type_visibility' attribute before looking for 'visibility'.
225   if (kind == NamedDecl::VisibilityForType) {
226     if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
227       return getVisibilityFromAttr(A);
228     }
229   }
230 
231   // If this declaration has an explicit visibility attribute, use it.
232   if (const auto *A = D->getAttr<VisibilityAttr>()) {
233     return getVisibilityFromAttr(A);
234   }
235 
236   return None;
237 }
238 
239 LinkageInfo LinkageComputer::getLVForType(const Type &T,
240                                           LVComputationKind computation) {
241   if (computation.IgnoreAllVisibility)
242     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
243   return getTypeLinkageAndVisibility(&T);
244 }
245 
246 /// Get the most restrictive linkage for the types in the given
247 /// template parameter list.  For visibility purposes, template
248 /// parameters are part of the signature of a template.
249 LinkageInfo LinkageComputer::getLVForTemplateParameterList(
250     const TemplateParameterList *Params, LVComputationKind computation) {
251   LinkageInfo LV;
252   for (const NamedDecl *P : *Params) {
253     // Template type parameters are the most common and never
254     // contribute to visibility, pack or not.
255     if (isa<TemplateTypeParmDecl>(P))
256       continue;
257 
258     // Non-type template parameters can be restricted by the value type, e.g.
259     //   template <enum X> class A { ... };
260     // We have to be careful here, though, because we can be dealing with
261     // dependent types.
262     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
263       // Handle the non-pack case first.
264       if (!NTTP->isExpandedParameterPack()) {
265         if (!NTTP->getType()->isDependentType()) {
266           LV.merge(getLVForType(*NTTP->getType(), computation));
267         }
268         continue;
269       }
270 
271       // Look at all the types in an expanded pack.
272       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
273         QualType type = NTTP->getExpansionType(i);
274         if (!type->isDependentType())
275           LV.merge(getTypeLinkageAndVisibility(type));
276       }
277       continue;
278     }
279 
280     // Template template parameters can be restricted by their
281     // template parameters, recursively.
282     const auto *TTP = cast<TemplateTemplateParmDecl>(P);
283 
284     // Handle the non-pack case first.
285     if (!TTP->isExpandedParameterPack()) {
286       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
287                                              computation));
288       continue;
289     }
290 
291     // Look at all expansions in an expanded pack.
292     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
293            i != n; ++i) {
294       LV.merge(getLVForTemplateParameterList(
295           TTP->getExpansionTemplateParameters(i), computation));
296     }
297   }
298 
299   return LV;
300 }
301 
302 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
303   const Decl *Ret = nullptr;
304   const DeclContext *DC = D->getDeclContext();
305   while (DC->getDeclKind() != Decl::TranslationUnit) {
306     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
307       Ret = cast<Decl>(DC);
308     DC = DC->getParent();
309   }
310   return Ret;
311 }
312 
313 /// Get the most restrictive linkage for the types and
314 /// declarations in the given template argument list.
315 ///
316 /// Note that we don't take an LVComputationKind because we always
317 /// want to honor the visibility of template arguments in the same way.
318 LinkageInfo
319 LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
320                                               LVComputationKind computation) {
321   LinkageInfo LV;
322 
323   for (const TemplateArgument &Arg : Args) {
324     switch (Arg.getKind()) {
325     case TemplateArgument::Null:
326     case TemplateArgument::Integral:
327     case TemplateArgument::Expression:
328       continue;
329 
330     case TemplateArgument::Type:
331       LV.merge(getLVForType(*Arg.getAsType(), computation));
332       continue;
333 
334     case TemplateArgument::Declaration: {
335       const NamedDecl *ND = Arg.getAsDecl();
336       assert(!usesTypeVisibility(ND));
337       LV.merge(getLVForDecl(ND, computation));
338       continue;
339     }
340 
341     case TemplateArgument::NullPtr:
342       LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
343       continue;
344 
345     case TemplateArgument::Template:
346     case TemplateArgument::TemplateExpansion:
347       if (TemplateDecl *Template =
348               Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
349         LV.merge(getLVForDecl(Template, computation));
350       continue;
351 
352     case TemplateArgument::Pack:
353       LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
354       continue;
355     }
356     llvm_unreachable("bad template argument kind");
357   }
358 
359   return LV;
360 }
361 
362 LinkageInfo
363 LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
364                                               LVComputationKind computation) {
365   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
366 }
367 
368 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
369                         const FunctionTemplateSpecializationInfo *specInfo) {
370   // Include visibility from the template parameters and arguments
371   // only if this is not an explicit instantiation or specialization
372   // with direct explicit visibility.  (Implicit instantiations won't
373   // have a direct attribute.)
374   if (!specInfo->isExplicitInstantiationOrSpecialization())
375     return true;
376 
377   return !fn->hasAttr<VisibilityAttr>();
378 }
379 
380 /// Merge in template-related linkage and visibility for the given
381 /// function template specialization.
382 ///
383 /// We don't need a computation kind here because we can assume
384 /// LVForValue.
385 ///
386 /// \param[out] LV the computation to use for the parent
387 void LinkageComputer::mergeTemplateLV(
388     LinkageInfo &LV, const FunctionDecl *fn,
389     const FunctionTemplateSpecializationInfo *specInfo,
390     LVComputationKind computation) {
391   bool considerVisibility =
392     shouldConsiderTemplateVisibility(fn, specInfo);
393 
394   // Merge information from the template parameters.
395   FunctionTemplateDecl *temp = specInfo->getTemplate();
396   LinkageInfo tempLV =
397     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
398   LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
399 
400   // Merge information from the template arguments.
401   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
402   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
403   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
404 }
405 
406 /// Does the given declaration have a direct visibility attribute
407 /// that would match the given rules?
408 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
409                                          LVComputationKind computation) {
410   if (computation.IgnoreAllVisibility)
411     return false;
412 
413   return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
414          D->hasAttr<VisibilityAttr>();
415 }
416 
417 /// Should we consider visibility associated with the template
418 /// arguments and parameters of the given class template specialization?
419 static bool shouldConsiderTemplateVisibility(
420                                  const ClassTemplateSpecializationDecl *spec,
421                                  LVComputationKind computation) {
422   // Include visibility from the template parameters and arguments
423   // only if this is not an explicit instantiation or specialization
424   // with direct explicit visibility (and note that implicit
425   // instantiations won't have a direct attribute).
426   //
427   // Furthermore, we want to ignore template parameters and arguments
428   // for an explicit specialization when computing the visibility of a
429   // member thereof with explicit visibility.
430   //
431   // This is a bit complex; let's unpack it.
432   //
433   // An explicit class specialization is an independent, top-level
434   // declaration.  As such, if it or any of its members has an
435   // explicit visibility attribute, that must directly express the
436   // user's intent, and we should honor it.  The same logic applies to
437   // an explicit instantiation of a member of such a thing.
438 
439   // Fast path: if this is not an explicit instantiation or
440   // specialization, we always want to consider template-related
441   // visibility restrictions.
442   if (!spec->isExplicitInstantiationOrSpecialization())
443     return true;
444 
445   // This is the 'member thereof' check.
446   if (spec->isExplicitSpecialization() &&
447       hasExplicitVisibilityAlready(computation))
448     return false;
449 
450   return !hasDirectVisibilityAttribute(spec, computation);
451 }
452 
453 /// Merge in template-related linkage and visibility for the given
454 /// class template specialization.
455 void LinkageComputer::mergeTemplateLV(
456     LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
457     LVComputationKind computation) {
458   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
459 
460   // Merge information from the template parameters, but ignore
461   // visibility if we're only considering template arguments.
462 
463   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
464   LinkageInfo tempLV =
465     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
466   LV.mergeMaybeWithVisibility(tempLV,
467            considerVisibility && !hasExplicitVisibilityAlready(computation));
468 
469   // Merge information from the template arguments.  We ignore
470   // template-argument visibility if we've got an explicit
471   // instantiation with a visibility attribute.
472   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
473   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
474   if (considerVisibility)
475     LV.mergeVisibility(argsLV);
476   LV.mergeExternalVisibility(argsLV);
477 }
478 
479 /// Should we consider visibility associated with the template
480 /// arguments and parameters of the given variable template
481 /// specialization? As usual, follow class template specialization
482 /// logic up to initialization.
483 static bool shouldConsiderTemplateVisibility(
484                                  const VarTemplateSpecializationDecl *spec,
485                                  LVComputationKind computation) {
486   // Include visibility from the template parameters and arguments
487   // only if this is not an explicit instantiation or specialization
488   // with direct explicit visibility (and note that implicit
489   // instantiations won't have a direct attribute).
490   if (!spec->isExplicitInstantiationOrSpecialization())
491     return true;
492 
493   // An explicit variable specialization is an independent, top-level
494   // declaration.  As such, if it has an explicit visibility attribute,
495   // that must directly express the user's intent, and we should honor
496   // it.
497   if (spec->isExplicitSpecialization() &&
498       hasExplicitVisibilityAlready(computation))
499     return false;
500 
501   return !hasDirectVisibilityAttribute(spec, computation);
502 }
503 
504 /// Merge in template-related linkage and visibility for the given
505 /// variable template specialization. As usual, follow class template
506 /// specialization logic up to initialization.
507 void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
508                                       const VarTemplateSpecializationDecl *spec,
509                                       LVComputationKind computation) {
510   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
511 
512   // Merge information from the template parameters, but ignore
513   // visibility if we're only considering template arguments.
514 
515   VarTemplateDecl *temp = spec->getSpecializedTemplate();
516   LinkageInfo tempLV =
517     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
518   LV.mergeMaybeWithVisibility(tempLV,
519            considerVisibility && !hasExplicitVisibilityAlready(computation));
520 
521   // Merge information from the template arguments.  We ignore
522   // template-argument visibility if we've got an explicit
523   // instantiation with a visibility attribute.
524   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
525   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
526   if (considerVisibility)
527     LV.mergeVisibility(argsLV);
528   LV.mergeExternalVisibility(argsLV);
529 }
530 
531 static bool useInlineVisibilityHidden(const NamedDecl *D) {
532   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
533   const LangOptions &Opts = D->getASTContext().getLangOpts();
534   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
535     return false;
536 
537   const auto *FD = dyn_cast<FunctionDecl>(D);
538   if (!FD)
539     return false;
540 
541   TemplateSpecializationKind TSK = TSK_Undeclared;
542   if (FunctionTemplateSpecializationInfo *spec
543       = FD->getTemplateSpecializationInfo()) {
544     TSK = spec->getTemplateSpecializationKind();
545   } else if (MemberSpecializationInfo *MSI =
546              FD->getMemberSpecializationInfo()) {
547     TSK = MSI->getTemplateSpecializationKind();
548   }
549 
550   const FunctionDecl *Def = nullptr;
551   // InlineVisibilityHidden only applies to definitions, and
552   // isInlined() only gives meaningful answers on definitions
553   // anyway.
554   return TSK != TSK_ExplicitInstantiationDeclaration &&
555     TSK != TSK_ExplicitInstantiationDefinition &&
556     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
557 }
558 
559 template <typename T> static bool isFirstInExternCContext(T *D) {
560   const T *First = D->getFirstDecl();
561   return First->isInExternCContext();
562 }
563 
564 static bool isSingleLineLanguageLinkage(const Decl &D) {
565   if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
566     if (!SD->hasBraces())
567       return true;
568   return false;
569 }
570 
571 /// Determine whether D is declared in the purview of a named module.
572 static bool isInModulePurview(const NamedDecl *D) {
573   if (auto *M = D->getOwningModule())
574     return M->isModulePurview();
575   return false;
576 }
577 
578 static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
579   // FIXME: Handle isModulePrivate.
580   switch (D->getModuleOwnershipKind()) {
581   case Decl::ModuleOwnershipKind::Unowned:
582   case Decl::ModuleOwnershipKind::ModulePrivate:
583     return false;
584   case Decl::ModuleOwnershipKind::Visible:
585   case Decl::ModuleOwnershipKind::VisibleWhenImported:
586     return isInModulePurview(D);
587   }
588   llvm_unreachable("unexpected module ownership kind");
589 }
590 
591 static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
592   // Internal linkage declarations within a module interface unit are modeled
593   // as "module-internal linkage", which means that they have internal linkage
594   // formally but can be indirectly accessed from outside the module via inline
595   // functions and templates defined within the module.
596   if (isInModulePurview(D))
597     return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
598 
599   return LinkageInfo::internal();
600 }
601 
602 static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
603   // C++ Modules TS [basic.link]/6.8:
604   //   - A name declared at namespace scope that does not have internal linkage
605   //     by the previous rules and that is introduced by a non-exported
606   //     declaration has module linkage.
607   if (isInModulePurview(D) && !isExportedFromModuleInterfaceUnit(
608                                   cast<NamedDecl>(D->getCanonicalDecl())))
609     return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
610 
611   return LinkageInfo::external();
612 }
613 
614 static StorageClass getStorageClass(const Decl *D) {
615   if (auto *TD = dyn_cast<TemplateDecl>(D))
616     D = TD->getTemplatedDecl();
617   if (D) {
618     if (auto *VD = dyn_cast<VarDecl>(D))
619       return VD->getStorageClass();
620     if (auto *FD = dyn_cast<FunctionDecl>(D))
621       return FD->getStorageClass();
622   }
623   return SC_None;
624 }
625 
626 LinkageInfo
627 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
628                                             LVComputationKind computation,
629                                             bool IgnoreVarTypeLinkage) {
630   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
631          "Not a name having namespace scope");
632   ASTContext &Context = D->getASTContext();
633 
634   // C++ [basic.link]p3:
635   //   A name having namespace scope (3.3.6) has internal linkage if it
636   //   is the name of
637 
638   if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
639     // - a variable, variable template, function, or function template
640     //   that is explicitly declared static; or
641     // (This bullet corresponds to C99 6.2.2p3.)
642     return getInternalLinkageFor(D);
643   }
644 
645   if (const auto *Var = dyn_cast<VarDecl>(D)) {
646     // - a non-template variable of non-volatile const-qualified type, unless
647     //   - it is explicitly declared extern, or
648     //   - it is inline or exported, or
649     //   - it was previously declared and the prior declaration did not have
650     //     internal linkage
651     // (There is no equivalent in C99.)
652     if (Context.getLangOpts().CPlusPlus &&
653         Var->getType().isConstQualified() &&
654         !Var->getType().isVolatileQualified() &&
655         !Var->isInline() &&
656         !isExportedFromModuleInterfaceUnit(Var) &&
657         !isa<VarTemplateSpecializationDecl>(Var) &&
658         !Var->getDescribedVarTemplate()) {
659       const VarDecl *PrevVar = Var->getPreviousDecl();
660       if (PrevVar)
661         return getLVForDecl(PrevVar, computation);
662 
663       if (Var->getStorageClass() != SC_Extern &&
664           Var->getStorageClass() != SC_PrivateExtern &&
665           !isSingleLineLanguageLinkage(*Var))
666         return getInternalLinkageFor(Var);
667     }
668 
669     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
670          PrevVar = PrevVar->getPreviousDecl()) {
671       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
672           Var->getStorageClass() == SC_None)
673         return getDeclLinkageAndVisibility(PrevVar);
674       // Explicitly declared static.
675       if (PrevVar->getStorageClass() == SC_Static)
676         return getInternalLinkageFor(Var);
677     }
678   } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
679     //   - a data member of an anonymous union.
680     const VarDecl *VD = IFD->getVarDecl();
681     assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
682     return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
683   }
684   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
685 
686   // FIXME: This gives internal linkage to names that should have no linkage
687   // (those not covered by [basic.link]p6).
688   if (D->isInAnonymousNamespace()) {
689     const auto *Var = dyn_cast<VarDecl>(D);
690     const auto *Func = dyn_cast<FunctionDecl>(D);
691     // FIXME: The check for extern "C" here is not justified by the standard
692     // wording, but we retain it from the pre-DR1113 model to avoid breaking
693     // code.
694     //
695     // C++11 [basic.link]p4:
696     //   An unnamed namespace or a namespace declared directly or indirectly
697     //   within an unnamed namespace has internal linkage.
698     if ((!Var || !isFirstInExternCContext(Var)) &&
699         (!Func || !isFirstInExternCContext(Func)))
700       return getInternalLinkageFor(D);
701   }
702 
703   // Set up the defaults.
704 
705   // C99 6.2.2p5:
706   //   If the declaration of an identifier for an object has file
707   //   scope and no storage-class specifier, its linkage is
708   //   external.
709   LinkageInfo LV = getExternalLinkageFor(D);
710 
711   if (!hasExplicitVisibilityAlready(computation)) {
712     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
713       LV.mergeVisibility(*Vis, true);
714     } else {
715       // If we're declared in a namespace with a visibility attribute,
716       // use that namespace's visibility, and it still counts as explicit.
717       for (const DeclContext *DC = D->getDeclContext();
718            !isa<TranslationUnitDecl>(DC);
719            DC = DC->getParent()) {
720         const auto *ND = dyn_cast<NamespaceDecl>(DC);
721         if (!ND) continue;
722         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
723           LV.mergeVisibility(*Vis, true);
724           break;
725         }
726       }
727     }
728 
729     // Add in global settings if the above didn't give us direct visibility.
730     if (!LV.isVisibilityExplicit()) {
731       // Use global type/value visibility as appropriate.
732       Visibility globalVisibility =
733           computation.isValueVisibility()
734               ? Context.getLangOpts().getValueVisibilityMode()
735               : Context.getLangOpts().getTypeVisibilityMode();
736       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
737 
738       // If we're paying attention to global visibility, apply
739       // -finline-visibility-hidden if this is an inline method.
740       if (useInlineVisibilityHidden(D))
741         LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
742     }
743   }
744 
745   // C++ [basic.link]p4:
746 
747   //   A name having namespace scope that has not been given internal linkage
748   //   above and that is the name of
749   //   [...bullets...]
750   //   has its linkage determined as follows:
751   //     - if the enclosing namespace has internal linkage, the name has
752   //       internal linkage; [handled above]
753   //     - otherwise, if the declaration of the name is attached to a named
754   //       module and is not exported, the name has module linkage;
755   //     - otherwise, the name has external linkage.
756   // LV is currently set up to handle the last two bullets.
757   //
758   //   The bullets are:
759 
760   //     - a variable; or
761   if (const auto *Var = dyn_cast<VarDecl>(D)) {
762     // GCC applies the following optimization to variables and static
763     // data members, but not to functions:
764     //
765     // Modify the variable's LV by the LV of its type unless this is
766     // C or extern "C".  This follows from [basic.link]p9:
767     //   A type without linkage shall not be used as the type of a
768     //   variable or function with external linkage unless
769     //    - the entity has C language linkage, or
770     //    - the entity is declared within an unnamed namespace, or
771     //    - the entity is not used or is defined in the same
772     //      translation unit.
773     // and [basic.link]p10:
774     //   ...the types specified by all declarations referring to a
775     //   given variable or function shall be identical...
776     // C does not have an equivalent rule.
777     //
778     // Ignore this if we've got an explicit attribute;  the user
779     // probably knows what they're doing.
780     //
781     // Note that we don't want to make the variable non-external
782     // because of this, but unique-external linkage suits us.
783     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
784         !IgnoreVarTypeLinkage) {
785       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
786       if (!isExternallyVisible(TypeLV.getLinkage()))
787         return LinkageInfo::uniqueExternal();
788       if (!LV.isVisibilityExplicit())
789         LV.mergeVisibility(TypeLV);
790     }
791 
792     if (Var->getStorageClass() == SC_PrivateExtern)
793       LV.mergeVisibility(HiddenVisibility, true);
794 
795     // Note that Sema::MergeVarDecl already takes care of implementing
796     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
797     // to do it here.
798 
799     // As per function and class template specializations (below),
800     // consider LV for the template and template arguments.  We're at file
801     // scope, so we do not need to worry about nested specializations.
802     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
803       mergeTemplateLV(LV, spec, computation);
804     }
805 
806   //     - a function; or
807   } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
808     // In theory, we can modify the function's LV by the LV of its
809     // type unless it has C linkage (see comment above about variables
810     // for justification).  In practice, GCC doesn't do this, so it's
811     // just too painful to make work.
812 
813     if (Function->getStorageClass() == SC_PrivateExtern)
814       LV.mergeVisibility(HiddenVisibility, true);
815 
816     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
817     // merging storage classes and visibility attributes, so we don't have to
818     // look at previous decls in here.
819 
820     // In C++, then if the type of the function uses a type with
821     // unique-external linkage, it's not legally usable from outside
822     // this translation unit.  However, we should use the C linkage
823     // rules instead for extern "C" declarations.
824     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
825       // Only look at the type-as-written. Otherwise, deducing the return type
826       // of a function could change its linkage.
827       QualType TypeAsWritten = Function->getType();
828       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
829         TypeAsWritten = TSI->getType();
830       if (!isExternallyVisible(TypeAsWritten->getLinkage()))
831         return LinkageInfo::uniqueExternal();
832     }
833 
834     // Consider LV from the template and the template arguments.
835     // We're at file scope, so we do not need to worry about nested
836     // specializations.
837     if (FunctionTemplateSpecializationInfo *specInfo
838                                = Function->getTemplateSpecializationInfo()) {
839       mergeTemplateLV(LV, Function, specInfo, computation);
840     }
841 
842   //     - a named class (Clause 9), or an unnamed class defined in a
843   //       typedef declaration in which the class has the typedef name
844   //       for linkage purposes (7.1.3); or
845   //     - a named enumeration (7.2), or an unnamed enumeration
846   //       defined in a typedef declaration in which the enumeration
847   //       has the typedef name for linkage purposes (7.1.3); or
848   } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
849     // Unnamed tags have no linkage.
850     if (!Tag->hasNameForLinkage())
851       return LinkageInfo::none();
852 
853     // If this is a class template specialization, consider the
854     // linkage of the template and template arguments.  We're at file
855     // scope, so we do not need to worry about nested specializations.
856     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
857       mergeTemplateLV(LV, spec, computation);
858     }
859 
860   // FIXME: This is not part of the C++ standard any more.
861   //     - an enumerator belonging to an enumeration with external linkage; or
862   } else if (isa<EnumConstantDecl>(D)) {
863     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
864                                       computation);
865     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
866       return LinkageInfo::none();
867     LV.merge(EnumLV);
868 
869   //     - a template
870   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
871     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
872     LinkageInfo tempLV =
873       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
874     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
875 
876   //     An unnamed namespace or a namespace declared directly or indirectly
877   //     within an unnamed namespace has internal linkage. All other namespaces
878   //     have external linkage.
879   //
880   // We handled names in anonymous namespaces above.
881   } else if (isa<NamespaceDecl>(D)) {
882     return LV;
883 
884   // By extension, we assign external linkage to Objective-C
885   // interfaces.
886   } else if (isa<ObjCInterfaceDecl>(D)) {
887     // fallout
888 
889   } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
890     // A typedef declaration has linkage if it gives a type a name for
891     // linkage purposes.
892     if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
893       return LinkageInfo::none();
894 
895   // Everything not covered here has no linkage.
896   } else {
897     return LinkageInfo::none();
898   }
899 
900   // If we ended up with non-externally-visible linkage, visibility should
901   // always be default.
902   if (!isExternallyVisible(LV.getLinkage()))
903     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
904 
905   // Mark the symbols as hidden when compiling for the device.
906   if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice)
907     LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
908 
909   return LV;
910 }
911 
912 LinkageInfo
913 LinkageComputer::getLVForClassMember(const NamedDecl *D,
914                                      LVComputationKind computation,
915                                      bool IgnoreVarTypeLinkage) {
916   // Only certain class members have linkage.  Note that fields don't
917   // really have linkage, but it's convenient to say they do for the
918   // purposes of calculating linkage of pointer-to-data-member
919   // template arguments.
920   //
921   // Templates also don't officially have linkage, but since we ignore
922   // the C++ standard and look at template arguments when determining
923   // linkage and visibility of a template specialization, we might hit
924   // a template template argument that way. If we do, we need to
925   // consider its linkage.
926   if (!(isa<CXXMethodDecl>(D) ||
927         isa<VarDecl>(D) ||
928         isa<FieldDecl>(D) ||
929         isa<IndirectFieldDecl>(D) ||
930         isa<TagDecl>(D) ||
931         isa<TemplateDecl>(D)))
932     return LinkageInfo::none();
933 
934   LinkageInfo LV;
935 
936   // If we have an explicit visibility attribute, merge that in.
937   if (!hasExplicitVisibilityAlready(computation)) {
938     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
939       LV.mergeVisibility(*Vis, true);
940     // If we're paying attention to global visibility, apply
941     // -finline-visibility-hidden if this is an inline method.
942     //
943     // Note that we do this before merging information about
944     // the class visibility.
945     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
946       LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
947   }
948 
949   // If this class member has an explicit visibility attribute, the only
950   // thing that can change its visibility is the template arguments, so
951   // only look for them when processing the class.
952   LVComputationKind classComputation = computation;
953   if (LV.isVisibilityExplicit())
954     classComputation = withExplicitVisibilityAlready(computation);
955 
956   LinkageInfo classLV =
957     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
958   // The member has the same linkage as the class. If that's not externally
959   // visible, we don't need to compute anything about the linkage.
960   // FIXME: If we're only computing linkage, can we bail out here?
961   if (!isExternallyVisible(classLV.getLinkage()))
962     return classLV;
963 
964 
965   // Otherwise, don't merge in classLV yet, because in certain cases
966   // we need to completely ignore the visibility from it.
967 
968   // Specifically, if this decl exists and has an explicit attribute.
969   const NamedDecl *explicitSpecSuppressor = nullptr;
970 
971   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
972     // Only look at the type-as-written. Otherwise, deducing the return type
973     // of a function could change its linkage.
974     QualType TypeAsWritten = MD->getType();
975     if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
976       TypeAsWritten = TSI->getType();
977     if (!isExternallyVisible(TypeAsWritten->getLinkage()))
978       return LinkageInfo::uniqueExternal();
979 
980     // If this is a method template specialization, use the linkage for
981     // the template parameters and arguments.
982     if (FunctionTemplateSpecializationInfo *spec
983            = MD->getTemplateSpecializationInfo()) {
984       mergeTemplateLV(LV, MD, spec, computation);
985       if (spec->isExplicitSpecialization()) {
986         explicitSpecSuppressor = MD;
987       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
988         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
989       }
990     } else if (isExplicitMemberSpecialization(MD)) {
991       explicitSpecSuppressor = MD;
992     }
993 
994   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
995     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
996       mergeTemplateLV(LV, spec, computation);
997       if (spec->isExplicitSpecialization()) {
998         explicitSpecSuppressor = spec;
999       } else {
1000         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1001         if (isExplicitMemberSpecialization(temp)) {
1002           explicitSpecSuppressor = temp->getTemplatedDecl();
1003         }
1004       }
1005     } else if (isExplicitMemberSpecialization(RD)) {
1006       explicitSpecSuppressor = RD;
1007     }
1008 
1009   // Static data members.
1010   } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1011     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1012       mergeTemplateLV(LV, spec, computation);
1013 
1014     // Modify the variable's linkage by its type, but ignore the
1015     // type's visibility unless it's a definition.
1016     if (!IgnoreVarTypeLinkage) {
1017       LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1018       // FIXME: If the type's linkage is not externally visible, we can
1019       // give this static data member UniqueExternalLinkage.
1020       if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1021         LV.mergeVisibility(typeLV);
1022       LV.mergeExternalVisibility(typeLV);
1023     }
1024 
1025     if (isExplicitMemberSpecialization(VD)) {
1026       explicitSpecSuppressor = VD;
1027     }
1028 
1029   // Template members.
1030   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1031     bool considerVisibility =
1032       (!LV.isVisibilityExplicit() &&
1033        !classLV.isVisibilityExplicit() &&
1034        !hasExplicitVisibilityAlready(computation));
1035     LinkageInfo tempLV =
1036       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1037     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1038 
1039     if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1040       if (isExplicitMemberSpecialization(redeclTemp)) {
1041         explicitSpecSuppressor = temp->getTemplatedDecl();
1042       }
1043     }
1044   }
1045 
1046   // We should never be looking for an attribute directly on a template.
1047   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1048 
1049   // If this member is an explicit member specialization, and it has
1050   // an explicit attribute, ignore visibility from the parent.
1051   bool considerClassVisibility = true;
1052   if (explicitSpecSuppressor &&
1053       // optimization: hasDVA() is true only with explicit visibility.
1054       LV.isVisibilityExplicit() &&
1055       classLV.getVisibility() != DefaultVisibility &&
1056       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1057     considerClassVisibility = false;
1058   }
1059 
1060   // Finally, merge in information from the class.
1061   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1062   return LV;
1063 }
1064 
1065 void NamedDecl::anchor() {}
1066 
1067 bool NamedDecl::isLinkageValid() const {
1068   if (!hasCachedLinkage())
1069     return true;
1070 
1071   Linkage L = LinkageComputer{}
1072                   .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1073                   .getLinkage();
1074   return L == getCachedLinkage();
1075 }
1076 
1077 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1078   StringRef name = getName();
1079   if (name.empty()) return SFF_None;
1080 
1081   if (name.front() == 'C')
1082     if (name == "CFStringCreateWithFormat" ||
1083         name == "CFStringCreateWithFormatAndArguments" ||
1084         name == "CFStringAppendFormat" ||
1085         name == "CFStringAppendFormatAndArguments")
1086       return SFF_CFString;
1087   return SFF_None;
1088 }
1089 
1090 Linkage NamedDecl::getLinkageInternal() const {
1091   // We don't care about visibility here, so ask for the cheapest
1092   // possible visibility analysis.
1093   return LinkageComputer{}
1094       .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1095       .getLinkage();
1096 }
1097 
1098 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1099   return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1100 }
1101 
1102 static Optional<Visibility>
1103 getExplicitVisibilityAux(const NamedDecl *ND,
1104                          NamedDecl::ExplicitVisibilityKind kind,
1105                          bool IsMostRecent) {
1106   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1107 
1108   // Check the declaration itself first.
1109   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1110     return V;
1111 
1112   // If this is a member class of a specialization of a class template
1113   // and the corresponding decl has explicit visibility, use that.
1114   if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1115     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1116     if (InstantiatedFrom)
1117       return getVisibilityOf(InstantiatedFrom, kind);
1118   }
1119 
1120   // If there wasn't explicit visibility there, and this is a
1121   // specialization of a class template, check for visibility
1122   // on the pattern.
1123   if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1124     // Walk all the template decl till this point to see if there are
1125     // explicit visibility attributes.
1126     const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1127     while (TD != nullptr) {
1128       auto Vis = getVisibilityOf(TD, kind);
1129       if (Vis != None)
1130         return Vis;
1131       TD = TD->getPreviousDecl();
1132     }
1133     return None;
1134   }
1135 
1136   // Use the most recent declaration.
1137   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1138     const NamedDecl *MostRecent = ND->getMostRecentDecl();
1139     if (MostRecent != ND)
1140       return getExplicitVisibilityAux(MostRecent, kind, true);
1141   }
1142 
1143   if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1144     if (Var->isStaticDataMember()) {
1145       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1146       if (InstantiatedFrom)
1147         return getVisibilityOf(InstantiatedFrom, kind);
1148     }
1149 
1150     if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1151       return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1152                              kind);
1153 
1154     return None;
1155   }
1156   // Also handle function template specializations.
1157   if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1158     // If the function is a specialization of a template with an
1159     // explicit visibility attribute, use that.
1160     if (FunctionTemplateSpecializationInfo *templateInfo
1161           = fn->getTemplateSpecializationInfo())
1162       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1163                              kind);
1164 
1165     // If the function is a member of a specialization of a class template
1166     // and the corresponding decl has explicit visibility, use that.
1167     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1168     if (InstantiatedFrom)
1169       return getVisibilityOf(InstantiatedFrom, kind);
1170 
1171     return None;
1172   }
1173 
1174   // The visibility of a template is stored in the templated decl.
1175   if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1176     return getVisibilityOf(TD->getTemplatedDecl(), kind);
1177 
1178   return None;
1179 }
1180 
1181 Optional<Visibility>
1182 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1183   return getExplicitVisibilityAux(this, kind, false);
1184 }
1185 
1186 LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1187                                              Decl *ContextDecl,
1188                                              LVComputationKind computation) {
1189   // This lambda has its linkage/visibility determined by its owner.
1190   const NamedDecl *Owner;
1191   if (!ContextDecl)
1192     Owner = dyn_cast<NamedDecl>(DC);
1193   else if (isa<ParmVarDecl>(ContextDecl))
1194     Owner =
1195         dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1196   else
1197     Owner = cast<NamedDecl>(ContextDecl);
1198 
1199   if (!Owner)
1200     return LinkageInfo::none();
1201 
1202   // If the owner has a deduced type, we need to skip querying the linkage and
1203   // visibility of that type, because it might involve this closure type.  The
1204   // only effect of this is that we might give a lambda VisibleNoLinkage rather
1205   // than NoLinkage when we don't strictly need to, which is benign.
1206   auto *VD = dyn_cast<VarDecl>(Owner);
1207   LinkageInfo OwnerLV =
1208       VD && VD->getType()->getContainedDeducedType()
1209           ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1210           : getLVForDecl(Owner, computation);
1211 
1212   // A lambda never formally has linkage. But if the owner is externally
1213   // visible, then the lambda is too. We apply the same rules to blocks.
1214   if (!isExternallyVisible(OwnerLV.getLinkage()))
1215     return LinkageInfo::none();
1216   return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1217                      OwnerLV.isVisibilityExplicit());
1218 }
1219 
1220 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1221                                                LVComputationKind computation) {
1222   if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1223     if (Function->isInAnonymousNamespace() &&
1224         !isFirstInExternCContext(Function))
1225       return getInternalLinkageFor(Function);
1226 
1227     // This is a "void f();" which got merged with a file static.
1228     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1229       return getInternalLinkageFor(Function);
1230 
1231     LinkageInfo LV;
1232     if (!hasExplicitVisibilityAlready(computation)) {
1233       if (Optional<Visibility> Vis =
1234               getExplicitVisibility(Function, computation))
1235         LV.mergeVisibility(*Vis, true);
1236     }
1237 
1238     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1239     // merging storage classes and visibility attributes, so we don't have to
1240     // look at previous decls in here.
1241 
1242     return LV;
1243   }
1244 
1245   if (const auto *Var = dyn_cast<VarDecl>(D)) {
1246     if (Var->hasExternalStorage()) {
1247       if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1248         return getInternalLinkageFor(Var);
1249 
1250       LinkageInfo LV;
1251       if (Var->getStorageClass() == SC_PrivateExtern)
1252         LV.mergeVisibility(HiddenVisibility, true);
1253       else if (!hasExplicitVisibilityAlready(computation)) {
1254         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1255           LV.mergeVisibility(*Vis, true);
1256       }
1257 
1258       if (const VarDecl *Prev = Var->getPreviousDecl()) {
1259         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1260         if (PrevLV.getLinkage())
1261           LV.setLinkage(PrevLV.getLinkage());
1262         LV.mergeVisibility(PrevLV);
1263       }
1264 
1265       return LV;
1266     }
1267 
1268     if (!Var->isStaticLocal())
1269       return LinkageInfo::none();
1270   }
1271 
1272   ASTContext &Context = D->getASTContext();
1273   if (!Context.getLangOpts().CPlusPlus)
1274     return LinkageInfo::none();
1275 
1276   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1277   if (!OuterD || OuterD->isInvalidDecl())
1278     return LinkageInfo::none();
1279 
1280   LinkageInfo LV;
1281   if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1282     if (!BD->getBlockManglingNumber())
1283       return LinkageInfo::none();
1284 
1285     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1286                          BD->getBlockManglingContextDecl(), computation);
1287   } else {
1288     const auto *FD = cast<FunctionDecl>(OuterD);
1289     if (!FD->isInlined() &&
1290         !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1291       return LinkageInfo::none();
1292 
1293     // If a function is hidden by -fvisibility-inlines-hidden option and
1294     // is not explicitly attributed as a hidden function,
1295     // we should not make static local variables in the function hidden.
1296     LV = getLVForDecl(FD, computation);
1297     if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1298         !LV.isVisibilityExplicit()) {
1299       assert(cast<VarDecl>(D)->isStaticLocal());
1300       // If this was an implicitly hidden inline method, check again for
1301       // explicit visibility on the parent class, and use that for static locals
1302       // if present.
1303       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1304         LV = getLVForDecl(MD->getParent(), computation);
1305       if (!LV.isVisibilityExplicit()) {
1306         Visibility globalVisibility =
1307             computation.isValueVisibility()
1308                 ? Context.getLangOpts().getValueVisibilityMode()
1309                 : Context.getLangOpts().getTypeVisibilityMode();
1310         return LinkageInfo(VisibleNoLinkage, globalVisibility,
1311                            /*visibilityExplicit=*/false);
1312       }
1313     }
1314   }
1315   if (!isExternallyVisible(LV.getLinkage()))
1316     return LinkageInfo::none();
1317   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1318                      LV.isVisibilityExplicit());
1319 }
1320 
1321 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1322                                               LVComputationKind computation,
1323                                               bool IgnoreVarTypeLinkage) {
1324   // Internal_linkage attribute overrides other considerations.
1325   if (D->hasAttr<InternalLinkageAttr>())
1326     return getInternalLinkageFor(D);
1327 
1328   // Objective-C: treat all Objective-C declarations as having external
1329   // linkage.
1330   switch (D->getKind()) {
1331     default:
1332       break;
1333 
1334     // Per C++ [basic.link]p2, only the names of objects, references,
1335     // functions, types, templates, namespaces, and values ever have linkage.
1336     //
1337     // Note that the name of a typedef, namespace alias, using declaration,
1338     // and so on are not the name of the corresponding type, namespace, or
1339     // declaration, so they do *not* have linkage.
1340     case Decl::ImplicitParam:
1341     case Decl::Label:
1342     case Decl::NamespaceAlias:
1343     case Decl::ParmVar:
1344     case Decl::Using:
1345     case Decl::UsingShadow:
1346     case Decl::UsingDirective:
1347       return LinkageInfo::none();
1348 
1349     case Decl::EnumConstant:
1350       // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1351       if (D->getASTContext().getLangOpts().CPlusPlus)
1352         return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1353       return LinkageInfo::visible_none();
1354 
1355     case Decl::Typedef:
1356     case Decl::TypeAlias:
1357       // A typedef declaration has linkage if it gives a type a name for
1358       // linkage purposes.
1359       if (!cast<TypedefNameDecl>(D)
1360                ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1361         return LinkageInfo::none();
1362       break;
1363 
1364     case Decl::TemplateTemplateParm: // count these as external
1365     case Decl::NonTypeTemplateParm:
1366     case Decl::ObjCAtDefsField:
1367     case Decl::ObjCCategory:
1368     case Decl::ObjCCategoryImpl:
1369     case Decl::ObjCCompatibleAlias:
1370     case Decl::ObjCImplementation:
1371     case Decl::ObjCMethod:
1372     case Decl::ObjCProperty:
1373     case Decl::ObjCPropertyImpl:
1374     case Decl::ObjCProtocol:
1375       return getExternalLinkageFor(D);
1376 
1377     case Decl::CXXRecord: {
1378       const auto *Record = cast<CXXRecordDecl>(D);
1379       if (Record->isLambda()) {
1380         if (Record->hasKnownLambdaInternalLinkage() ||
1381             !Record->getLambdaManglingNumber()) {
1382           // This lambda has no mangling number, so it's internal.
1383           return getInternalLinkageFor(D);
1384         }
1385 
1386         return getLVForClosure(
1387                   Record->getDeclContext()->getRedeclContext(),
1388                   Record->getLambdaContextDecl(), computation);
1389       }
1390 
1391       break;
1392     }
1393   }
1394 
1395   // Handle linkage for namespace-scope names.
1396   if (D->getDeclContext()->getRedeclContext()->isFileContext())
1397     return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1398 
1399   // C++ [basic.link]p5:
1400   //   In addition, a member function, static data member, a named
1401   //   class or enumeration of class scope, or an unnamed class or
1402   //   enumeration defined in a class-scope typedef declaration such
1403   //   that the class or enumeration has the typedef name for linkage
1404   //   purposes (7.1.3), has external linkage if the name of the class
1405   //   has external linkage.
1406   if (D->getDeclContext()->isRecord())
1407     return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1408 
1409   // C++ [basic.link]p6:
1410   //   The name of a function declared in block scope and the name of
1411   //   an object declared by a block scope extern declaration have
1412   //   linkage. If there is a visible declaration of an entity with
1413   //   linkage having the same name and type, ignoring entities
1414   //   declared outside the innermost enclosing namespace scope, the
1415   //   block scope declaration declares that same entity and receives
1416   //   the linkage of the previous declaration. If there is more than
1417   //   one such matching entity, the program is ill-formed. Otherwise,
1418   //   if no matching entity is found, the block scope entity receives
1419   //   external linkage.
1420   if (D->getDeclContext()->isFunctionOrMethod())
1421     return getLVForLocalDecl(D, computation);
1422 
1423   // C++ [basic.link]p6:
1424   //   Names not covered by these rules have no linkage.
1425   return LinkageInfo::none();
1426 }
1427 
1428 /// getLVForDecl - Get the linkage and visibility for the given declaration.
1429 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1430                                           LVComputationKind computation) {
1431   // Internal_linkage attribute overrides other considerations.
1432   if (D->hasAttr<InternalLinkageAttr>())
1433     return getInternalLinkageFor(D);
1434 
1435   if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1436     return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1437 
1438   if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1439     return *LI;
1440 
1441   LinkageInfo LV = computeLVForDecl(D, computation);
1442   if (D->hasCachedLinkage())
1443     assert(D->getCachedLinkage() == LV.getLinkage());
1444 
1445   D->setCachedLinkage(LV.getLinkage());
1446   cache(D, computation, LV);
1447 
1448 #ifndef NDEBUG
1449   // In C (because of gnu inline) and in c++ with microsoft extensions an
1450   // static can follow an extern, so we can have two decls with different
1451   // linkages.
1452   const LangOptions &Opts = D->getASTContext().getLangOpts();
1453   if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1454     return LV;
1455 
1456   // We have just computed the linkage for this decl. By induction we know
1457   // that all other computed linkages match, check that the one we just
1458   // computed also does.
1459   NamedDecl *Old = nullptr;
1460   for (auto I : D->redecls()) {
1461     auto *T = cast<NamedDecl>(I);
1462     if (T == D)
1463       continue;
1464     if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1465       Old = T;
1466       break;
1467     }
1468   }
1469   assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1470 #endif
1471 
1472   return LV;
1473 }
1474 
1475 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1476   return getLVForDecl(D,
1477                       LVComputationKind(usesTypeVisibility(D)
1478                                             ? NamedDecl::VisibilityForType
1479                                             : NamedDecl::VisibilityForValue));
1480 }
1481 
1482 Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1483   Module *M = getOwningModule();
1484   if (!M)
1485     return nullptr;
1486 
1487   switch (M->Kind) {
1488   case Module::ModuleMapModule:
1489     // Module map modules have no special linkage semantics.
1490     return nullptr;
1491 
1492   case Module::ModuleInterfaceUnit:
1493     return M;
1494 
1495   case Module::GlobalModuleFragment: {
1496     // External linkage declarations in the global module have no owning module
1497     // for linkage purposes. But internal linkage declarations in the global
1498     // module fragment of a particular module are owned by that module for
1499     // linkage purposes.
1500     if (IgnoreLinkage)
1501       return nullptr;
1502     bool InternalLinkage;
1503     if (auto *ND = dyn_cast<NamedDecl>(this))
1504       InternalLinkage = !ND->hasExternalFormalLinkage();
1505     else {
1506       auto *NSD = dyn_cast<NamespaceDecl>(this);
1507       InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1508                         isInAnonymousNamespace();
1509     }
1510     return InternalLinkage ? M->Parent : nullptr;
1511   }
1512 
1513   case Module::PrivateModuleFragment:
1514     // The private module fragment is part of its containing module for linkage
1515     // purposes.
1516     return M->Parent;
1517   }
1518 
1519   llvm_unreachable("unknown module kind");
1520 }
1521 
1522 void NamedDecl::printName(raw_ostream &os) const {
1523   os << Name;
1524 }
1525 
1526 std::string NamedDecl::getQualifiedNameAsString() const {
1527   std::string QualName;
1528   llvm::raw_string_ostream OS(QualName);
1529   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1530   return OS.str();
1531 }
1532 
1533 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1534   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1535 }
1536 
1537 void NamedDecl::printQualifiedName(raw_ostream &OS,
1538                                    const PrintingPolicy &P) const {
1539   if (getDeclContext()->isFunctionOrMethod()) {
1540     // We do not print '(anonymous)' for function parameters without name.
1541     printName(OS);
1542     return;
1543   }
1544   printNestedNameSpecifier(OS, P);
1545   if (getDeclName() || isa<DecompositionDecl>(this))
1546     OS << *this;
1547   else
1548     OS << "(anonymous)";
1549 }
1550 
1551 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1552   printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1553 }
1554 
1555 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1556                                          const PrintingPolicy &P) const {
1557   const DeclContext *Ctx = getDeclContext();
1558 
1559   // For ObjC methods and properties, look through categories and use the
1560   // interface as context.
1561   if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1562     if (auto *ID = MD->getClassInterface())
1563       Ctx = ID;
1564   if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1565     if (auto *MD = PD->getGetterMethodDecl())
1566       if (auto *ID = MD->getClassInterface())
1567         Ctx = ID;
1568   }
1569 
1570   if (Ctx->isFunctionOrMethod())
1571     return;
1572 
1573   using ContextsTy = SmallVector<const DeclContext *, 8>;
1574   ContextsTy Contexts;
1575 
1576   // Collect named contexts.
1577   while (Ctx) {
1578     if (isa<NamedDecl>(Ctx))
1579       Contexts.push_back(Ctx);
1580     Ctx = Ctx->getParent();
1581   }
1582 
1583   for (const DeclContext *DC : llvm::reverse(Contexts)) {
1584     if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1585       OS << Spec->getName();
1586       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1587       printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
1588     } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1589       if (P.SuppressUnwrittenScope &&
1590           (ND->isAnonymousNamespace() || ND->isInline()))
1591         continue;
1592       if (ND->isAnonymousNamespace()) {
1593         OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1594                                 : "(anonymous namespace)");
1595       }
1596       else
1597         OS << *ND;
1598     } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1599       if (!RD->getIdentifier())
1600         OS << "(anonymous " << RD->getKindName() << ')';
1601       else
1602         OS << *RD;
1603     } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1604       const FunctionProtoType *FT = nullptr;
1605       if (FD->hasWrittenPrototype())
1606         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1607 
1608       OS << *FD << '(';
1609       if (FT) {
1610         unsigned NumParams = FD->getNumParams();
1611         for (unsigned i = 0; i < NumParams; ++i) {
1612           if (i)
1613             OS << ", ";
1614           OS << FD->getParamDecl(i)->getType().stream(P);
1615         }
1616 
1617         if (FT->isVariadic()) {
1618           if (NumParams > 0)
1619             OS << ", ";
1620           OS << "...";
1621         }
1622       }
1623       OS << ')';
1624     } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1625       // C++ [dcl.enum]p10: Each enum-name and each unscoped
1626       // enumerator is declared in the scope that immediately contains
1627       // the enum-specifier. Each scoped enumerator is declared in the
1628       // scope of the enumeration.
1629       // For the case of unscoped enumerator, do not include in the qualified
1630       // name any information about its enum enclosing scope, as its visibility
1631       // is global.
1632       if (ED->isScoped())
1633         OS << *ED;
1634       else
1635         continue;
1636     } else {
1637       OS << *cast<NamedDecl>(DC);
1638     }
1639     OS << "::";
1640   }
1641 }
1642 
1643 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1644                                      const PrintingPolicy &Policy,
1645                                      bool Qualified) const {
1646   if (Qualified)
1647     printQualifiedName(OS, Policy);
1648   else
1649     printName(OS);
1650 }
1651 
1652 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1653   return true;
1654 }
1655 static bool isRedeclarableImpl(...) { return false; }
1656 static bool isRedeclarable(Decl::Kind K) {
1657   switch (K) {
1658 #define DECL(Type, Base) \
1659   case Decl::Type: \
1660     return isRedeclarableImpl((Type##Decl *)nullptr);
1661 #define ABSTRACT_DECL(DECL)
1662 #include "clang/AST/DeclNodes.inc"
1663   }
1664   llvm_unreachable("unknown decl kind");
1665 }
1666 
1667 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1668   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1669 
1670   // Never replace one imported declaration with another; we need both results
1671   // when re-exporting.
1672   if (OldD->isFromASTFile() && isFromASTFile())
1673     return false;
1674 
1675   // A kind mismatch implies that the declaration is not replaced.
1676   if (OldD->getKind() != getKind())
1677     return false;
1678 
1679   // For method declarations, we never replace. (Why?)
1680   if (isa<ObjCMethodDecl>(this))
1681     return false;
1682 
1683   // For parameters, pick the newer one. This is either an error or (in
1684   // Objective-C) permitted as an extension.
1685   if (isa<ParmVarDecl>(this))
1686     return true;
1687 
1688   // Inline namespaces can give us two declarations with the same
1689   // name and kind in the same scope but different contexts; we should
1690   // keep both declarations in this case.
1691   if (!this->getDeclContext()->getRedeclContext()->Equals(
1692           OldD->getDeclContext()->getRedeclContext()))
1693     return false;
1694 
1695   // Using declarations can be replaced if they import the same name from the
1696   // same context.
1697   if (auto *UD = dyn_cast<UsingDecl>(this)) {
1698     ASTContext &Context = getASTContext();
1699     return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1700            Context.getCanonicalNestedNameSpecifier(
1701                cast<UsingDecl>(OldD)->getQualifier());
1702   }
1703   if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1704     ASTContext &Context = getASTContext();
1705     return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1706            Context.getCanonicalNestedNameSpecifier(
1707                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1708   }
1709 
1710   if (isRedeclarable(getKind())) {
1711     if (getCanonicalDecl() != OldD->getCanonicalDecl())
1712       return false;
1713 
1714     if (IsKnownNewer)
1715       return true;
1716 
1717     // Check whether this is actually newer than OldD. We want to keep the
1718     // newer declaration. This loop will usually only iterate once, because
1719     // OldD is usually the previous declaration.
1720     for (auto D : redecls()) {
1721       if (D == OldD)
1722         break;
1723 
1724       // If we reach the canonical declaration, then OldD is not actually older
1725       // than this one.
1726       //
1727       // FIXME: In this case, we should not add this decl to the lookup table.
1728       if (D->isCanonicalDecl())
1729         return false;
1730     }
1731 
1732     // It's a newer declaration of the same kind of declaration in the same
1733     // scope: we want this decl instead of the existing one.
1734     return true;
1735   }
1736 
1737   // In all other cases, we need to keep both declarations in case they have
1738   // different visibility. Any attempt to use the name will result in an
1739   // ambiguity if more than one is visible.
1740   return false;
1741 }
1742 
1743 bool NamedDecl::hasLinkage() const {
1744   return getFormalLinkage() != NoLinkage;
1745 }
1746 
1747 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1748   NamedDecl *ND = this;
1749   while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1750     ND = UD->getTargetDecl();
1751 
1752   if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1753     return AD->getClassInterface();
1754 
1755   if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1756     return AD->getNamespace();
1757 
1758   return ND;
1759 }
1760 
1761 bool NamedDecl::isCXXInstanceMember() const {
1762   if (!isCXXClassMember())
1763     return false;
1764 
1765   const NamedDecl *D = this;
1766   if (isa<UsingShadowDecl>(D))
1767     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1768 
1769   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1770     return true;
1771   if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1772     return MD->isInstance();
1773   return false;
1774 }
1775 
1776 //===----------------------------------------------------------------------===//
1777 // DeclaratorDecl Implementation
1778 //===----------------------------------------------------------------------===//
1779 
1780 template <typename DeclT>
1781 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1782   if (decl->getNumTemplateParameterLists() > 0)
1783     return decl->getTemplateParameterList(0)->getTemplateLoc();
1784   else
1785     return decl->getInnerLocStart();
1786 }
1787 
1788 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1789   TypeSourceInfo *TSI = getTypeSourceInfo();
1790   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1791   return SourceLocation();
1792 }
1793 
1794 SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1795   TypeSourceInfo *TSI = getTypeSourceInfo();
1796   if (TSI) return TSI->getTypeLoc().getEndLoc();
1797   return SourceLocation();
1798 }
1799 
1800 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1801   if (QualifierLoc) {
1802     // Make sure the extended decl info is allocated.
1803     if (!hasExtInfo()) {
1804       // Save (non-extended) type source info pointer.
1805       auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1806       // Allocate external info struct.
1807       DeclInfo = new (getASTContext()) ExtInfo;
1808       // Restore savedTInfo into (extended) decl info.
1809       getExtInfo()->TInfo = savedTInfo;
1810     }
1811     // Set qualifier info.
1812     getExtInfo()->QualifierLoc = QualifierLoc;
1813   } else if (hasExtInfo()) {
1814     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1815     getExtInfo()->QualifierLoc = QualifierLoc;
1816   }
1817 }
1818 
1819 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1820   assert(TrailingRequiresClause);
1821   // Make sure the extended decl info is allocated.
1822   if (!hasExtInfo()) {
1823     // Save (non-extended) type source info pointer.
1824     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1825     // Allocate external info struct.
1826     DeclInfo = new (getASTContext()) ExtInfo;
1827     // Restore savedTInfo into (extended) decl info.
1828     getExtInfo()->TInfo = savedTInfo;
1829   }
1830   // Set requires clause info.
1831   getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1832 }
1833 
1834 void DeclaratorDecl::setTemplateParameterListsInfo(
1835     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1836   assert(!TPLists.empty());
1837   // Make sure the extended decl info is allocated.
1838   if (!hasExtInfo()) {
1839     // Save (non-extended) type source info pointer.
1840     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1841     // Allocate external info struct.
1842     DeclInfo = new (getASTContext()) ExtInfo;
1843     // Restore savedTInfo into (extended) decl info.
1844     getExtInfo()->TInfo = savedTInfo;
1845   }
1846   // Set the template parameter lists info.
1847   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1848 }
1849 
1850 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1851   return getTemplateOrInnerLocStart(this);
1852 }
1853 
1854 // Helper function: returns true if QT is or contains a type
1855 // having a postfix component.
1856 static bool typeIsPostfix(QualType QT) {
1857   while (true) {
1858     const Type* T = QT.getTypePtr();
1859     switch (T->getTypeClass()) {
1860     default:
1861       return false;
1862     case Type::Pointer:
1863       QT = cast<PointerType>(T)->getPointeeType();
1864       break;
1865     case Type::BlockPointer:
1866       QT = cast<BlockPointerType>(T)->getPointeeType();
1867       break;
1868     case Type::MemberPointer:
1869       QT = cast<MemberPointerType>(T)->getPointeeType();
1870       break;
1871     case Type::LValueReference:
1872     case Type::RValueReference:
1873       QT = cast<ReferenceType>(T)->getPointeeType();
1874       break;
1875     case Type::PackExpansion:
1876       QT = cast<PackExpansionType>(T)->getPattern();
1877       break;
1878     case Type::Paren:
1879     case Type::ConstantArray:
1880     case Type::DependentSizedArray:
1881     case Type::IncompleteArray:
1882     case Type::VariableArray:
1883     case Type::FunctionProto:
1884     case Type::FunctionNoProto:
1885       return true;
1886     }
1887   }
1888 }
1889 
1890 SourceRange DeclaratorDecl::getSourceRange() const {
1891   SourceLocation RangeEnd = getLocation();
1892   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1893     // If the declaration has no name or the type extends past the name take the
1894     // end location of the type.
1895     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1896       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1897   }
1898   return SourceRange(getOuterLocStart(), RangeEnd);
1899 }
1900 
1901 void QualifierInfo::setTemplateParameterListsInfo(
1902     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1903   // Free previous template parameters (if any).
1904   if (NumTemplParamLists > 0) {
1905     Context.Deallocate(TemplParamLists);
1906     TemplParamLists = nullptr;
1907     NumTemplParamLists = 0;
1908   }
1909   // Set info on matched template parameter lists (if any).
1910   if (!TPLists.empty()) {
1911     TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1912     NumTemplParamLists = TPLists.size();
1913     std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
1914   }
1915 }
1916 
1917 //===----------------------------------------------------------------------===//
1918 // VarDecl Implementation
1919 //===----------------------------------------------------------------------===//
1920 
1921 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1922   switch (SC) {
1923   case SC_None:                 break;
1924   case SC_Auto:                 return "auto";
1925   case SC_Extern:               return "extern";
1926   case SC_PrivateExtern:        return "__private_extern__";
1927   case SC_Register:             return "register";
1928   case SC_Static:               return "static";
1929   }
1930 
1931   llvm_unreachable("Invalid storage class");
1932 }
1933 
1934 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1935                  SourceLocation StartLoc, SourceLocation IdLoc,
1936                  IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1937                  StorageClass SC)
1938     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1939       redeclarable_base(C) {
1940   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1941                 "VarDeclBitfields too large!");
1942   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1943                 "ParmVarDeclBitfields too large!");
1944   static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1945                 "NonParmVarDeclBitfields too large!");
1946   AllBits = 0;
1947   VarDeclBits.SClass = SC;
1948   // Everything else is implicitly initialized to false.
1949 }
1950 
1951 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1952                          SourceLocation StartL, SourceLocation IdL,
1953                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1954                          StorageClass S) {
1955   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1956 }
1957 
1958 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1959   return new (C, ID)
1960       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1961               QualType(), nullptr, SC_None);
1962 }
1963 
1964 void VarDecl::setStorageClass(StorageClass SC) {
1965   assert(isLegalForVariable(SC));
1966   VarDeclBits.SClass = SC;
1967 }
1968 
1969 VarDecl::TLSKind VarDecl::getTLSKind() const {
1970   switch (VarDeclBits.TSCSpec) {
1971   case TSCS_unspecified:
1972     if (!hasAttr<ThreadAttr>() &&
1973         !(getASTContext().getLangOpts().OpenMPUseTLS &&
1974           getASTContext().getTargetInfo().isTLSSupported() &&
1975           hasAttr<OMPThreadPrivateDeclAttr>()))
1976       return TLS_None;
1977     return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1978                 LangOptions::MSVC2015)) ||
1979             hasAttr<OMPThreadPrivateDeclAttr>())
1980                ? TLS_Dynamic
1981                : TLS_Static;
1982   case TSCS___thread: // Fall through.
1983   case TSCS__Thread_local:
1984     return TLS_Static;
1985   case TSCS_thread_local:
1986     return TLS_Dynamic;
1987   }
1988   llvm_unreachable("Unknown thread storage class specifier!");
1989 }
1990 
1991 SourceRange VarDecl::getSourceRange() const {
1992   if (const Expr *Init = getInit()) {
1993     SourceLocation InitEnd = Init->getEndLoc();
1994     // If Init is implicit, ignore its source range and fallback on
1995     // DeclaratorDecl::getSourceRange() to handle postfix elements.
1996     if (InitEnd.isValid() && InitEnd != getLocation())
1997       return SourceRange(getOuterLocStart(), InitEnd);
1998   }
1999   return DeclaratorDecl::getSourceRange();
2000 }
2001 
2002 template<typename T>
2003 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2004   // C++ [dcl.link]p1: All function types, function names with external linkage,
2005   // and variable names with external linkage have a language linkage.
2006   if (!D.hasExternalFormalLinkage())
2007     return NoLanguageLinkage;
2008 
2009   // Language linkage is a C++ concept, but saying that everything else in C has
2010   // C language linkage fits the implementation nicely.
2011   ASTContext &Context = D.getASTContext();
2012   if (!Context.getLangOpts().CPlusPlus)
2013     return CLanguageLinkage;
2014 
2015   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2016   // language linkage of the names of class members and the function type of
2017   // class member functions.
2018   const DeclContext *DC = D.getDeclContext();
2019   if (DC->isRecord())
2020     return CXXLanguageLinkage;
2021 
2022   // If the first decl is in an extern "C" context, any other redeclaration
2023   // will have C language linkage. If the first one is not in an extern "C"
2024   // context, we would have reported an error for any other decl being in one.
2025   if (isFirstInExternCContext(&D))
2026     return CLanguageLinkage;
2027   return CXXLanguageLinkage;
2028 }
2029 
2030 template<typename T>
2031 static bool isDeclExternC(const T &D) {
2032   // Since the context is ignored for class members, they can only have C++
2033   // language linkage or no language linkage.
2034   const DeclContext *DC = D.getDeclContext();
2035   if (DC->isRecord()) {
2036     assert(D.getASTContext().getLangOpts().CPlusPlus);
2037     return false;
2038   }
2039 
2040   return D.getLanguageLinkage() == CLanguageLinkage;
2041 }
2042 
2043 LanguageLinkage VarDecl::getLanguageLinkage() const {
2044   return getDeclLanguageLinkage(*this);
2045 }
2046 
2047 bool VarDecl::isExternC() const {
2048   return isDeclExternC(*this);
2049 }
2050 
2051 bool VarDecl::isInExternCContext() const {
2052   return getLexicalDeclContext()->isExternCContext();
2053 }
2054 
2055 bool VarDecl::isInExternCXXContext() const {
2056   return getLexicalDeclContext()->isExternCXXContext();
2057 }
2058 
2059 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2060 
2061 VarDecl::DefinitionKind
2062 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
2063   if (isThisDeclarationADemotedDefinition())
2064     return DeclarationOnly;
2065 
2066   // C++ [basic.def]p2:
2067   //   A declaration is a definition unless [...] it contains the 'extern'
2068   //   specifier or a linkage-specification and neither an initializer [...],
2069   //   it declares a non-inline static data member in a class declaration [...],
2070   //   it declares a static data member outside a class definition and the variable
2071   //   was defined within the class with the constexpr specifier [...],
2072   // C++1y [temp.expl.spec]p15:
2073   //   An explicit specialization of a static data member or an explicit
2074   //   specialization of a static data member template is a definition if the
2075   //   declaration includes an initializer; otherwise, it is a declaration.
2076   //
2077   // FIXME: How do you declare (but not define) a partial specialization of
2078   // a static data member template outside the containing class?
2079   if (isStaticDataMember()) {
2080     if (isOutOfLine() &&
2081         !(getCanonicalDecl()->isInline() &&
2082           getCanonicalDecl()->isConstexpr()) &&
2083         (hasInit() ||
2084          // If the first declaration is out-of-line, this may be an
2085          // instantiation of an out-of-line partial specialization of a variable
2086          // template for which we have not yet instantiated the initializer.
2087          (getFirstDecl()->isOutOfLine()
2088               ? getTemplateSpecializationKind() == TSK_Undeclared
2089               : getTemplateSpecializationKind() !=
2090                     TSK_ExplicitSpecialization) ||
2091          isa<VarTemplatePartialSpecializationDecl>(this)))
2092       return Definition;
2093     else if (!isOutOfLine() && isInline())
2094       return Definition;
2095     else
2096       return DeclarationOnly;
2097   }
2098   // C99 6.7p5:
2099   //   A definition of an identifier is a declaration for that identifier that
2100   //   [...] causes storage to be reserved for that object.
2101   // Note: that applies for all non-file-scope objects.
2102   // C99 6.9.2p1:
2103   //   If the declaration of an identifier for an object has file scope and an
2104   //   initializer, the declaration is an external definition for the identifier
2105   if (hasInit())
2106     return Definition;
2107 
2108   if (hasDefiningAttr())
2109     return Definition;
2110 
2111   if (const auto *SAA = getAttr<SelectAnyAttr>())
2112     if (!SAA->isInherited())
2113       return Definition;
2114 
2115   // A variable template specialization (other than a static data member
2116   // template or an explicit specialization) is a declaration until we
2117   // instantiate its initializer.
2118   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2119     if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2120         !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2121         !VTSD->IsCompleteDefinition)
2122       return DeclarationOnly;
2123   }
2124 
2125   if (hasExternalStorage())
2126     return DeclarationOnly;
2127 
2128   // [dcl.link] p7:
2129   //   A declaration directly contained in a linkage-specification is treated
2130   //   as if it contains the extern specifier for the purpose of determining
2131   //   the linkage of the declared name and whether it is a definition.
2132   if (isSingleLineLanguageLinkage(*this))
2133     return DeclarationOnly;
2134 
2135   // C99 6.9.2p2:
2136   //   A declaration of an object that has file scope without an initializer,
2137   //   and without a storage class specifier or the scs 'static', constitutes
2138   //   a tentative definition.
2139   // No such thing in C++.
2140   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2141     return TentativeDefinition;
2142 
2143   // What's left is (in C, block-scope) declarations without initializers or
2144   // external storage. These are definitions.
2145   return Definition;
2146 }
2147 
2148 VarDecl *VarDecl::getActingDefinition() {
2149   DefinitionKind Kind = isThisDeclarationADefinition();
2150   if (Kind != TentativeDefinition)
2151     return nullptr;
2152 
2153   VarDecl *LastTentative = nullptr;
2154   VarDecl *First = getFirstDecl();
2155   for (auto I : First->redecls()) {
2156     Kind = I->isThisDeclarationADefinition();
2157     if (Kind == Definition)
2158       return nullptr;
2159     else if (Kind == TentativeDefinition)
2160       LastTentative = I;
2161   }
2162   return LastTentative;
2163 }
2164 
2165 VarDecl *VarDecl::getDefinition(ASTContext &C) {
2166   VarDecl *First = getFirstDecl();
2167   for (auto I : First->redecls()) {
2168     if (I->isThisDeclarationADefinition(C) == Definition)
2169       return I;
2170   }
2171   return nullptr;
2172 }
2173 
2174 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2175   DefinitionKind Kind = DeclarationOnly;
2176 
2177   const VarDecl *First = getFirstDecl();
2178   for (auto I : First->redecls()) {
2179     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2180     if (Kind == Definition)
2181       break;
2182   }
2183 
2184   return Kind;
2185 }
2186 
2187 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2188   for (auto I : redecls()) {
2189     if (auto Expr = I->getInit()) {
2190       D = I;
2191       return Expr;
2192     }
2193   }
2194   return nullptr;
2195 }
2196 
2197 bool VarDecl::hasInit() const {
2198   if (auto *P = dyn_cast<ParmVarDecl>(this))
2199     if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2200       return false;
2201 
2202   return !Init.isNull();
2203 }
2204 
2205 Expr *VarDecl::getInit() {
2206   if (!hasInit())
2207     return nullptr;
2208 
2209   if (auto *S = Init.dyn_cast<Stmt *>())
2210     return cast<Expr>(S);
2211 
2212   return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2213 }
2214 
2215 Stmt **VarDecl::getInitAddress() {
2216   if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2217     return &ES->Value;
2218 
2219   return Init.getAddrOfPtr1();
2220 }
2221 
2222 VarDecl *VarDecl::getInitializingDeclaration() {
2223   VarDecl *Def = nullptr;
2224   for (auto I : redecls()) {
2225     if (I->hasInit())
2226       return I;
2227 
2228     if (I->isThisDeclarationADefinition()) {
2229       if (isStaticDataMember())
2230         return I;
2231       else
2232         Def = I;
2233     }
2234   }
2235   return Def;
2236 }
2237 
2238 bool VarDecl::isOutOfLine() const {
2239   if (Decl::isOutOfLine())
2240     return true;
2241 
2242   if (!isStaticDataMember())
2243     return false;
2244 
2245   // If this static data member was instantiated from a static data member of
2246   // a class template, check whether that static data member was defined
2247   // out-of-line.
2248   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2249     return VD->isOutOfLine();
2250 
2251   return false;
2252 }
2253 
2254 void VarDecl::setInit(Expr *I) {
2255   if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2256     Eval->~EvaluatedStmt();
2257     getASTContext().Deallocate(Eval);
2258   }
2259 
2260   Init = I;
2261 }
2262 
2263 bool VarDecl::mightBeUsableInConstantExpressions(ASTContext &C) const {
2264   const LangOptions &Lang = C.getLangOpts();
2265 
2266   if (!Lang.CPlusPlus)
2267     return false;
2268 
2269   // Function parameters are never usable in constant expressions.
2270   if (isa<ParmVarDecl>(this))
2271     return false;
2272 
2273   // In C++11, any variable of reference type can be used in a constant
2274   // expression if it is initialized by a constant expression.
2275   if (Lang.CPlusPlus11 && getType()->isReferenceType())
2276     return true;
2277 
2278   // Only const objects can be used in constant expressions in C++. C++98 does
2279   // not require the variable to be non-volatile, but we consider this to be a
2280   // defect.
2281   if (!getType().isConstQualified() || getType().isVolatileQualified())
2282     return false;
2283 
2284   // In C++, const, non-volatile variables of integral or enumeration types
2285   // can be used in constant expressions.
2286   if (getType()->isIntegralOrEnumerationType())
2287     return true;
2288 
2289   // Additionally, in C++11, non-volatile constexpr variables can be used in
2290   // constant expressions.
2291   return Lang.CPlusPlus11 && isConstexpr();
2292 }
2293 
2294 bool VarDecl::isUsableInConstantExpressions(ASTContext &Context) const {
2295   // C++2a [expr.const]p3:
2296   //   A variable is usable in constant expressions after its initializing
2297   //   declaration is encountered...
2298   const VarDecl *DefVD = nullptr;
2299   const Expr *Init = getAnyInitializer(DefVD);
2300   if (!Init || Init->isValueDependent() || getType()->isDependentType())
2301     return false;
2302   //   ... if it is a constexpr variable, or it is of reference type or of
2303   //   const-qualified integral or enumeration type, ...
2304   if (!DefVD->mightBeUsableInConstantExpressions(Context))
2305     return false;
2306   //   ... and its initializer is a constant initializer.
2307   return DefVD->checkInitIsICE();
2308 }
2309 
2310 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2311 /// form, which contains extra information on the evaluated value of the
2312 /// initializer.
2313 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2314   auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2315   if (!Eval) {
2316     // Note: EvaluatedStmt contains an APValue, which usually holds
2317     // resources not allocated from the ASTContext.  We need to do some
2318     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2319     // where we can detect whether there's anything to clean up or not.
2320     Eval = new (getASTContext()) EvaluatedStmt;
2321     Eval->Value = Init.get<Stmt *>();
2322     Init = Eval;
2323   }
2324   return Eval;
2325 }
2326 
2327 APValue *VarDecl::evaluateValue() const {
2328   SmallVector<PartialDiagnosticAt, 8> Notes;
2329   return evaluateValue(Notes);
2330 }
2331 
2332 APValue *VarDecl::evaluateValue(
2333     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2334   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2335 
2336   // We only produce notes indicating why an initializer is non-constant the
2337   // first time it is evaluated. FIXME: The notes won't always be emitted the
2338   // first time we try evaluation, so might not be produced at all.
2339   if (Eval->WasEvaluated)
2340     return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2341 
2342   const auto *Init = cast<Expr>(Eval->Value);
2343   assert(!Init->isValueDependent());
2344 
2345   if (Eval->IsEvaluating) {
2346     // FIXME: Produce a diagnostic for self-initialization.
2347     Eval->CheckedICE = true;
2348     Eval->IsICE = false;
2349     return nullptr;
2350   }
2351 
2352   Eval->IsEvaluating = true;
2353 
2354   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2355                                             this, Notes);
2356 
2357   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2358   // or that it's empty (so that there's nothing to clean up) if evaluation
2359   // failed.
2360   if (!Result)
2361     Eval->Evaluated = APValue();
2362   else if (Eval->Evaluated.needsCleanup())
2363     getASTContext().addDestruction(&Eval->Evaluated);
2364 
2365   Eval->IsEvaluating = false;
2366   Eval->WasEvaluated = true;
2367 
2368   // In C++11, we have determined whether the initializer was a constant
2369   // expression as a side-effect.
2370   if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
2371     Eval->CheckedICE = true;
2372     Eval->IsICE = Result && Notes.empty();
2373   }
2374 
2375   return Result ? &Eval->Evaluated : nullptr;
2376 }
2377 
2378 APValue *VarDecl::getEvaluatedValue() const {
2379   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2380     if (Eval->WasEvaluated)
2381       return &Eval->Evaluated;
2382 
2383   return nullptr;
2384 }
2385 
2386 bool VarDecl::isInitKnownICE() const {
2387   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2388     return Eval->CheckedICE;
2389 
2390   return false;
2391 }
2392 
2393 bool VarDecl::isInitICE() const {
2394   assert(isInitKnownICE() &&
2395          "Check whether we already know that the initializer is an ICE");
2396   return Init.get<EvaluatedStmt *>()->IsICE;
2397 }
2398 
2399 bool VarDecl::checkInitIsICE() const {
2400   // Initializers of weak variables are never ICEs.
2401   if (isWeak())
2402     return false;
2403 
2404   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2405   if (Eval->CheckedICE)
2406     // We have already checked whether this subexpression is an
2407     // integral constant expression.
2408     return Eval->IsICE;
2409 
2410   const auto *Init = cast<Expr>(Eval->Value);
2411   assert(!Init->isValueDependent());
2412 
2413   // In C++11, evaluate the initializer to check whether it's a constant
2414   // expression.
2415   if (getASTContext().getLangOpts().CPlusPlus11) {
2416     SmallVector<PartialDiagnosticAt, 8> Notes;
2417     evaluateValue(Notes);
2418     return Eval->IsICE;
2419   }
2420 
2421   // It's an ICE whether or not the definition we found is
2422   // out-of-line.  See DR 721 and the discussion in Clang PR
2423   // 6206 for details.
2424 
2425   if (Eval->CheckingICE)
2426     return false;
2427   Eval->CheckingICE = true;
2428 
2429   Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2430   Eval->CheckingICE = false;
2431   Eval->CheckedICE = true;
2432   return Eval->IsICE;
2433 }
2434 
2435 bool VarDecl::isParameterPack() const {
2436   return isa<PackExpansionType>(getType());
2437 }
2438 
2439 template<typename DeclT>
2440 static DeclT *getDefinitionOrSelf(DeclT *D) {
2441   assert(D);
2442   if (auto *Def = D->getDefinition())
2443     return Def;
2444   return D;
2445 }
2446 
2447 bool VarDecl::isEscapingByref() const {
2448   return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2449 }
2450 
2451 bool VarDecl::isNonEscapingByref() const {
2452   return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2453 }
2454 
2455 VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2456   const VarDecl *VD = this;
2457 
2458   // If this is an instantiated member, walk back to the template from which
2459   // it was instantiated.
2460   if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2461     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2462       VD = VD->getInstantiatedFromStaticDataMember();
2463       while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2464         VD = NewVD;
2465     }
2466   }
2467 
2468   // If it's an instantiated variable template specialization, find the
2469   // template or partial specialization from which it was instantiated.
2470   if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2471     if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2472       auto From = VDTemplSpec->getInstantiatedFrom();
2473       if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2474         while (!VTD->isMemberSpecialization()) {
2475           auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2476           if (!NewVTD)
2477             break;
2478           VTD = NewVTD;
2479         }
2480         return getDefinitionOrSelf(VTD->getTemplatedDecl());
2481       }
2482       if (auto *VTPSD =
2483               From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2484         while (!VTPSD->isMemberSpecialization()) {
2485           auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2486           if (!NewVTPSD)
2487             break;
2488           VTPSD = NewVTPSD;
2489         }
2490         return getDefinitionOrSelf<VarDecl>(VTPSD);
2491       }
2492     }
2493   }
2494 
2495   // If this is the pattern of a variable template, find where it was
2496   // instantiated from. FIXME: Is this necessary?
2497   if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2498     while (!VarTemplate->isMemberSpecialization()) {
2499       auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2500       if (!NewVT)
2501         break;
2502       VarTemplate = NewVT;
2503     }
2504 
2505     return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2506   }
2507 
2508   if (VD == this)
2509     return nullptr;
2510   return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2511 }
2512 
2513 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2514   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2515     return cast<VarDecl>(MSI->getInstantiatedFrom());
2516 
2517   return nullptr;
2518 }
2519 
2520 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2521   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2522     return Spec->getSpecializationKind();
2523 
2524   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2525     return MSI->getTemplateSpecializationKind();
2526 
2527   return TSK_Undeclared;
2528 }
2529 
2530 TemplateSpecializationKind
2531 VarDecl::getTemplateSpecializationKindForInstantiation() const {
2532   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2533     return MSI->getTemplateSpecializationKind();
2534 
2535   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2536     return Spec->getSpecializationKind();
2537 
2538   return TSK_Undeclared;
2539 }
2540 
2541 SourceLocation VarDecl::getPointOfInstantiation() const {
2542   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2543     return Spec->getPointOfInstantiation();
2544 
2545   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2546     return MSI->getPointOfInstantiation();
2547 
2548   return SourceLocation();
2549 }
2550 
2551 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2552   return getASTContext().getTemplateOrSpecializationInfo(this)
2553       .dyn_cast<VarTemplateDecl *>();
2554 }
2555 
2556 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2557   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2558 }
2559 
2560 bool VarDecl::isKnownToBeDefined() const {
2561   const auto &LangOpts = getASTContext().getLangOpts();
2562   // In CUDA mode without relocatable device code, variables of form 'extern
2563   // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2564   // memory pool.  These are never undefined variables, even if they appear
2565   // inside of an anon namespace or static function.
2566   //
2567   // With CUDA relocatable device code enabled, these variables don't get
2568   // special handling; they're treated like regular extern variables.
2569   if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2570       hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2571       isa<IncompleteArrayType>(getType()))
2572     return true;
2573 
2574   return hasDefinition();
2575 }
2576 
2577 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2578   return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2579                                 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2580                                  !hasAttr<AlwaysDestroyAttr>()));
2581 }
2582 
2583 QualType::DestructionKind
2584 VarDecl::needsDestruction(const ASTContext &Ctx) const {
2585   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2586     if (Eval->HasConstantDestruction)
2587       return QualType::DK_none;
2588 
2589   if (isNoDestroy(Ctx))
2590     return QualType::DK_none;
2591 
2592   return getType().isDestructedType();
2593 }
2594 
2595 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2596   if (isStaticDataMember())
2597     // FIXME: Remove ?
2598     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2599     return getASTContext().getTemplateOrSpecializationInfo(this)
2600         .dyn_cast<MemberSpecializationInfo *>();
2601   return nullptr;
2602 }
2603 
2604 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2605                                          SourceLocation PointOfInstantiation) {
2606   assert((isa<VarTemplateSpecializationDecl>(this) ||
2607           getMemberSpecializationInfo()) &&
2608          "not a variable or static data member template specialization");
2609 
2610   if (VarTemplateSpecializationDecl *Spec =
2611           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2612     Spec->setSpecializationKind(TSK);
2613     if (TSK != TSK_ExplicitSpecialization &&
2614         PointOfInstantiation.isValid() &&
2615         Spec->getPointOfInstantiation().isInvalid()) {
2616       Spec->setPointOfInstantiation(PointOfInstantiation);
2617       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2618         L->InstantiationRequested(this);
2619     }
2620   } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2621     MSI->setTemplateSpecializationKind(TSK);
2622     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2623         MSI->getPointOfInstantiation().isInvalid()) {
2624       MSI->setPointOfInstantiation(PointOfInstantiation);
2625       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2626         L->InstantiationRequested(this);
2627     }
2628   }
2629 }
2630 
2631 void
2632 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2633                                             TemplateSpecializationKind TSK) {
2634   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2635          "Previous template or instantiation?");
2636   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2637 }
2638 
2639 //===----------------------------------------------------------------------===//
2640 // ParmVarDecl Implementation
2641 //===----------------------------------------------------------------------===//
2642 
2643 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2644                                  SourceLocation StartLoc,
2645                                  SourceLocation IdLoc, IdentifierInfo *Id,
2646                                  QualType T, TypeSourceInfo *TInfo,
2647                                  StorageClass S, Expr *DefArg) {
2648   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2649                                  S, DefArg);
2650 }
2651 
2652 QualType ParmVarDecl::getOriginalType() const {
2653   TypeSourceInfo *TSI = getTypeSourceInfo();
2654   QualType T = TSI ? TSI->getType() : getType();
2655   if (const auto *DT = dyn_cast<DecayedType>(T))
2656     return DT->getOriginalType();
2657   return T;
2658 }
2659 
2660 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2661   return new (C, ID)
2662       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2663                   nullptr, QualType(), nullptr, SC_None, nullptr);
2664 }
2665 
2666 SourceRange ParmVarDecl::getSourceRange() const {
2667   if (!hasInheritedDefaultArg()) {
2668     SourceRange ArgRange = getDefaultArgRange();
2669     if (ArgRange.isValid())
2670       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2671   }
2672 
2673   // DeclaratorDecl considers the range of postfix types as overlapping with the
2674   // declaration name, but this is not the case with parameters in ObjC methods.
2675   if (isa<ObjCMethodDecl>(getDeclContext()))
2676     return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2677 
2678   return DeclaratorDecl::getSourceRange();
2679 }
2680 
2681 Expr *ParmVarDecl::getDefaultArg() {
2682   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2683   assert(!hasUninstantiatedDefaultArg() &&
2684          "Default argument is not yet instantiated!");
2685 
2686   Expr *Arg = getInit();
2687   if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
2688     return E->getSubExpr();
2689 
2690   return Arg;
2691 }
2692 
2693 void ParmVarDecl::setDefaultArg(Expr *defarg) {
2694   ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2695   Init = defarg;
2696 }
2697 
2698 SourceRange ParmVarDecl::getDefaultArgRange() const {
2699   switch (ParmVarDeclBits.DefaultArgKind) {
2700   case DAK_None:
2701   case DAK_Unparsed:
2702     // Nothing we can do here.
2703     return SourceRange();
2704 
2705   case DAK_Uninstantiated:
2706     return getUninstantiatedDefaultArg()->getSourceRange();
2707 
2708   case DAK_Normal:
2709     if (const Expr *E = getInit())
2710       return E->getSourceRange();
2711 
2712     // Missing an actual expression, may be invalid.
2713     return SourceRange();
2714   }
2715   llvm_unreachable("Invalid default argument kind.");
2716 }
2717 
2718 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2719   ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2720   Init = arg;
2721 }
2722 
2723 Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2724   assert(hasUninstantiatedDefaultArg() &&
2725          "Wrong kind of initialization expression!");
2726   return cast_or_null<Expr>(Init.get<Stmt *>());
2727 }
2728 
2729 bool ParmVarDecl::hasDefaultArg() const {
2730   // FIXME: We should just return false for DAK_None here once callers are
2731   // prepared for the case that we encountered an invalid default argument and
2732   // were unable to even build an invalid expression.
2733   return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2734          !Init.isNull();
2735 }
2736 
2737 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2738   getASTContext().setParameterIndex(this, parameterIndex);
2739   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2740 }
2741 
2742 unsigned ParmVarDecl::getParameterIndexLarge() const {
2743   return getASTContext().getParameterIndex(this);
2744 }
2745 
2746 //===----------------------------------------------------------------------===//
2747 // FunctionDecl Implementation
2748 //===----------------------------------------------------------------------===//
2749 
2750 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2751                            SourceLocation StartLoc,
2752                            const DeclarationNameInfo &NameInfo, QualType T,
2753                            TypeSourceInfo *TInfo, StorageClass S,
2754                            bool isInlineSpecified,
2755                            ConstexprSpecKind ConstexprKind,
2756                            Expr *TrailingRequiresClause)
2757     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2758                      StartLoc),
2759       DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
2760       EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
2761   assert(T.isNull() || T->isFunctionType());
2762   FunctionDeclBits.SClass = S;
2763   FunctionDeclBits.IsInline = isInlineSpecified;
2764   FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2765   FunctionDeclBits.IsVirtualAsWritten = false;
2766   FunctionDeclBits.IsPure = false;
2767   FunctionDeclBits.HasInheritedPrototype = false;
2768   FunctionDeclBits.HasWrittenPrototype = true;
2769   FunctionDeclBits.IsDeleted = false;
2770   FunctionDeclBits.IsTrivial = false;
2771   FunctionDeclBits.IsTrivialForCall = false;
2772   FunctionDeclBits.IsDefaulted = false;
2773   FunctionDeclBits.IsExplicitlyDefaulted = false;
2774   FunctionDeclBits.HasDefaultedFunctionInfo = false;
2775   FunctionDeclBits.HasImplicitReturnZero = false;
2776   FunctionDeclBits.IsLateTemplateParsed = false;
2777   FunctionDeclBits.ConstexprKind = ConstexprKind;
2778   FunctionDeclBits.InstantiationIsPending = false;
2779   FunctionDeclBits.UsesSEHTry = false;
2780   FunctionDeclBits.UsesFPIntrin = false;
2781   FunctionDeclBits.HasSkippedBody = false;
2782   FunctionDeclBits.WillHaveBody = false;
2783   FunctionDeclBits.IsMultiVersion = false;
2784   FunctionDeclBits.IsCopyDeductionCandidate = false;
2785   FunctionDeclBits.HasODRHash = false;
2786   if (TrailingRequiresClause)
2787     setTrailingRequiresClause(TrailingRequiresClause);
2788 }
2789 
2790 void FunctionDecl::getNameForDiagnostic(
2791     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2792   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2793   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2794   if (TemplateArgs)
2795     printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
2796 }
2797 
2798 bool FunctionDecl::isVariadic() const {
2799   if (const auto *FT = getType()->getAs<FunctionProtoType>())
2800     return FT->isVariadic();
2801   return false;
2802 }
2803 
2804 FunctionDecl::DefaultedFunctionInfo *
2805 FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2806                                             ArrayRef<DeclAccessPair> Lookups) {
2807   DefaultedFunctionInfo *Info = new (Context.Allocate(
2808       totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2809       std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2810       DefaultedFunctionInfo;
2811   Info->NumLookups = Lookups.size();
2812   std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2813                           Info->getTrailingObjects<DeclAccessPair>());
2814   return Info;
2815 }
2816 
2817 void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
2818   assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
2819   assert(!Body && "can't replace function body with defaulted function info");
2820 
2821   FunctionDeclBits.HasDefaultedFunctionInfo = true;
2822   DefaultedInfo = Info;
2823 }
2824 
2825 FunctionDecl::DefaultedFunctionInfo *
2826 FunctionDecl::getDefaultedFunctionInfo() const {
2827   return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
2828 }
2829 
2830 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2831   for (auto I : redecls()) {
2832     if (I->doesThisDeclarationHaveABody()) {
2833       Definition = I;
2834       return true;
2835     }
2836   }
2837 
2838   return false;
2839 }
2840 
2841 bool FunctionDecl::hasTrivialBody() const {
2842   Stmt *S = getBody();
2843   if (!S) {
2844     // Since we don't have a body for this function, we don't know if it's
2845     // trivial or not.
2846     return false;
2847   }
2848 
2849   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2850     return true;
2851   return false;
2852 }
2853 
2854 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2855   for (auto I : redecls()) {
2856     if (I->isThisDeclarationADefinition()) {
2857       Definition = I;
2858       return true;
2859     }
2860   }
2861 
2862   return false;
2863 }
2864 
2865 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2866   if (!hasBody(Definition))
2867     return nullptr;
2868 
2869   assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
2870          "definition should not have a body");
2871   if (Definition->Body)
2872     return Definition->Body.get(getASTContext().getExternalSource());
2873 
2874   return nullptr;
2875 }
2876 
2877 void FunctionDecl::setBody(Stmt *B) {
2878   FunctionDeclBits.HasDefaultedFunctionInfo = false;
2879   Body = LazyDeclStmtPtr(B);
2880   if (B)
2881     EndRangeLoc = B->getEndLoc();
2882 }
2883 
2884 void FunctionDecl::setPure(bool P) {
2885   FunctionDeclBits.IsPure = P;
2886   if (P)
2887     if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2888       Parent->markedVirtualFunctionPure();
2889 }
2890 
2891 template<std::size_t Len>
2892 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2893   IdentifierInfo *II = ND->getIdentifier();
2894   return II && II->isStr(Str);
2895 }
2896 
2897 bool FunctionDecl::isMain() const {
2898   const TranslationUnitDecl *tunit =
2899     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2900   return tunit &&
2901          !tunit->getASTContext().getLangOpts().Freestanding &&
2902          isNamed(this, "main");
2903 }
2904 
2905 bool FunctionDecl::isMSVCRTEntryPoint() const {
2906   const TranslationUnitDecl *TUnit =
2907       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2908   if (!TUnit)
2909     return false;
2910 
2911   // Even though we aren't really targeting MSVCRT if we are freestanding,
2912   // semantic analysis for these functions remains the same.
2913 
2914   // MSVCRT entry points only exist on MSVCRT targets.
2915   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2916     return false;
2917 
2918   // Nameless functions like constructors cannot be entry points.
2919   if (!getIdentifier())
2920     return false;
2921 
2922   return llvm::StringSwitch<bool>(getName())
2923       .Cases("main",     // an ANSI console app
2924              "wmain",    // a Unicode console App
2925              "WinMain",  // an ANSI GUI app
2926              "wWinMain", // a Unicode GUI app
2927              "DllMain",  // a DLL
2928              true)
2929       .Default(false);
2930 }
2931 
2932 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2933   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2934   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2935          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2936          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2937          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2938 
2939   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2940     return false;
2941 
2942   const auto *proto = getType()->castAs<FunctionProtoType>();
2943   if (proto->getNumParams() != 2 || proto->isVariadic())
2944     return false;
2945 
2946   ASTContext &Context =
2947     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2948       ->getASTContext();
2949 
2950   // The result type and first argument type are constant across all
2951   // these operators.  The second argument must be exactly void*.
2952   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2953 }
2954 
2955 bool FunctionDecl::isReplaceableGlobalAllocationFunction(
2956     Optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
2957   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2958     return false;
2959   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2960       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2961       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2962       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2963     return false;
2964 
2965   if (isa<CXXRecordDecl>(getDeclContext()))
2966     return false;
2967 
2968   // This can only fail for an invalid 'operator new' declaration.
2969   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2970     return false;
2971 
2972   const auto *FPT = getType()->castAs<FunctionProtoType>();
2973   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
2974     return false;
2975 
2976   // If this is a single-parameter function, it must be a replaceable global
2977   // allocation or deallocation function.
2978   if (FPT->getNumParams() == 1)
2979     return true;
2980 
2981   unsigned Params = 1;
2982   QualType Ty = FPT->getParamType(Params);
2983   ASTContext &Ctx = getASTContext();
2984 
2985   auto Consume = [&] {
2986     ++Params;
2987     Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2988   };
2989 
2990   // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2991   bool IsSizedDelete = false;
2992   if (Ctx.getLangOpts().SizedDeallocation &&
2993       (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2994        getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2995       Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2996     IsSizedDelete = true;
2997     Consume();
2998   }
2999 
3000   // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3001   // new/delete.
3002   if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3003     Consume();
3004     if (AlignmentParam)
3005       *AlignmentParam = Params;
3006   }
3007 
3008   // Finally, if this is not a sized delete, the final parameter can
3009   // be a 'const std::nothrow_t&'.
3010   if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3011     Ty = Ty->getPointeeType();
3012     if (Ty.getCVRQualifiers() != Qualifiers::Const)
3013       return false;
3014     if (Ty->isNothrowT()) {
3015       if (IsNothrow)
3016         *IsNothrow = true;
3017       Consume();
3018     }
3019   }
3020 
3021   return Params == FPT->getNumParams();
3022 }
3023 
3024 bool FunctionDecl::isInlineBuiltinDeclaration() const {
3025   if (!getBuiltinID())
3026     return false;
3027 
3028   const FunctionDecl *Definition;
3029   return hasBody(Definition) && Definition->isInlineSpecified();
3030 }
3031 
3032 bool FunctionDecl::isDestroyingOperatorDelete() const {
3033   // C++ P0722:
3034   //   Within a class C, a single object deallocation function with signature
3035   //     (T, std::destroying_delete_t, <more params>)
3036   //   is a destroying operator delete.
3037   if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3038       getNumParams() < 2)
3039     return false;
3040 
3041   auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3042   return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3043          RD->getIdentifier()->isStr("destroying_delete_t");
3044 }
3045 
3046 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3047   return getDeclLanguageLinkage(*this);
3048 }
3049 
3050 bool FunctionDecl::isExternC() const {
3051   return isDeclExternC(*this);
3052 }
3053 
3054 bool FunctionDecl::isInExternCContext() const {
3055   if (hasAttr<OpenCLKernelAttr>())
3056     return true;
3057   return getLexicalDeclContext()->isExternCContext();
3058 }
3059 
3060 bool FunctionDecl::isInExternCXXContext() const {
3061   return getLexicalDeclContext()->isExternCXXContext();
3062 }
3063 
3064 bool FunctionDecl::isGlobal() const {
3065   if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3066     return Method->isStatic();
3067 
3068   if (getCanonicalDecl()->getStorageClass() == SC_Static)
3069     return false;
3070 
3071   for (const DeclContext *DC = getDeclContext();
3072        DC->isNamespace();
3073        DC = DC->getParent()) {
3074     if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3075       if (!Namespace->getDeclName())
3076         return false;
3077       break;
3078     }
3079   }
3080 
3081   return true;
3082 }
3083 
3084 bool FunctionDecl::isNoReturn() const {
3085   if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3086       hasAttr<C11NoReturnAttr>())
3087     return true;
3088 
3089   if (auto *FnTy = getType()->getAs<FunctionType>())
3090     return FnTy->getNoReturnAttr();
3091 
3092   return false;
3093 }
3094 
3095 
3096 MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3097   if (hasAttr<TargetAttr>())
3098     return MultiVersionKind::Target;
3099   if (hasAttr<CPUDispatchAttr>())
3100     return MultiVersionKind::CPUDispatch;
3101   if (hasAttr<CPUSpecificAttr>())
3102     return MultiVersionKind::CPUSpecific;
3103   return MultiVersionKind::None;
3104 }
3105 
3106 bool FunctionDecl::isCPUDispatchMultiVersion() const {
3107   return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3108 }
3109 
3110 bool FunctionDecl::isCPUSpecificMultiVersion() const {
3111   return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3112 }
3113 
3114 bool FunctionDecl::isTargetMultiVersion() const {
3115   return isMultiVersion() && hasAttr<TargetAttr>();
3116 }
3117 
3118 void
3119 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3120   redeclarable_base::setPreviousDecl(PrevDecl);
3121 
3122   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3123     FunctionTemplateDecl *PrevFunTmpl
3124       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3125     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3126     FunTmpl->setPreviousDecl(PrevFunTmpl);
3127   }
3128 
3129   if (PrevDecl && PrevDecl->isInlined())
3130     setImplicitlyInline(true);
3131 }
3132 
3133 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3134 
3135 /// Returns a value indicating whether this function corresponds to a builtin
3136 /// function.
3137 ///
3138 /// The function corresponds to a built-in function if it is declared at
3139 /// translation scope or within an extern "C" block and its name matches with
3140 /// the name of a builtin. The returned value will be 0 for functions that do
3141 /// not correspond to a builtin, a value of type \c Builtin::ID if in the
3142 /// target-independent range \c [1,Builtin::First), or a target-specific builtin
3143 /// value.
3144 ///
3145 /// \param ConsiderWrapperFunctions If true, we should consider wrapper
3146 /// functions as their wrapped builtins. This shouldn't be done in general, but
3147 /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3148 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3149   unsigned BuiltinID;
3150 
3151   if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3152     BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3153   } else {
3154     if (!getIdentifier())
3155       return 0;
3156 
3157     BuiltinID = getIdentifier()->getBuiltinID();
3158   }
3159 
3160   if (!BuiltinID)
3161     return 0;
3162 
3163   ASTContext &Context = getASTContext();
3164   if (Context.getLangOpts().CPlusPlus) {
3165     const auto *LinkageDecl =
3166         dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
3167     // In C++, the first declaration of a builtin is always inside an implicit
3168     // extern "C".
3169     // FIXME: A recognised library function may not be directly in an extern "C"
3170     // declaration, for instance "extern "C" { namespace std { decl } }".
3171     if (!LinkageDecl) {
3172       if (BuiltinID == Builtin::BI__GetExceptionInfo &&
3173           Context.getTargetInfo().getCXXABI().isMicrosoft())
3174         return Builtin::BI__GetExceptionInfo;
3175       return 0;
3176     }
3177     if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
3178       return 0;
3179   }
3180 
3181   // If the function is marked "overloadable", it has a different mangled name
3182   // and is not the C library function.
3183   if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3184       !hasAttr<ArmBuiltinAliasAttr>())
3185     return 0;
3186 
3187   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3188     return BuiltinID;
3189 
3190   // This function has the name of a known C library
3191   // function. Determine whether it actually refers to the C library
3192   // function or whether it just has the same name.
3193 
3194   // If this is a static function, it's not a builtin.
3195   if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3196     return 0;
3197 
3198   // OpenCL v1.2 s6.9.f - The library functions defined in
3199   // the C99 standard headers are not available.
3200   if (Context.getLangOpts().OpenCL &&
3201       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3202     return 0;
3203 
3204   // CUDA does not have device-side standard library. printf and malloc are the
3205   // only special cases that are supported by device-side runtime.
3206   if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3207       !hasAttr<CUDAHostAttr>() &&
3208       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3209     return 0;
3210 
3211   return BuiltinID;
3212 }
3213 
3214 /// getNumParams - Return the number of parameters this function must have
3215 /// based on its FunctionType.  This is the length of the ParamInfo array
3216 /// after it has been created.
3217 unsigned FunctionDecl::getNumParams() const {
3218   const auto *FPT = getType()->getAs<FunctionProtoType>();
3219   return FPT ? FPT->getNumParams() : 0;
3220 }
3221 
3222 void FunctionDecl::setParams(ASTContext &C,
3223                              ArrayRef<ParmVarDecl *> NewParamInfo) {
3224   assert(!ParamInfo && "Already has param info!");
3225   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3226 
3227   // Zero params -> null pointer.
3228   if (!NewParamInfo.empty()) {
3229     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3230     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3231   }
3232 }
3233 
3234 /// getMinRequiredArguments - Returns the minimum number of arguments
3235 /// needed to call this function. This may be fewer than the number of
3236 /// function parameters, if some of the parameters have default
3237 /// arguments (in C++) or are parameter packs (C++11).
3238 unsigned FunctionDecl::getMinRequiredArguments() const {
3239   if (!getASTContext().getLangOpts().CPlusPlus)
3240     return getNumParams();
3241 
3242   unsigned NumRequiredArgs = 0;
3243   for (auto *Param : parameters())
3244     if (!Param->isParameterPack() && !Param->hasDefaultArg())
3245       ++NumRequiredArgs;
3246   return NumRequiredArgs;
3247 }
3248 
3249 /// The combination of the extern and inline keywords under MSVC forces
3250 /// the function to be required.
3251 ///
3252 /// Note: This function assumes that we will only get called when isInlined()
3253 /// would return true for this FunctionDecl.
3254 bool FunctionDecl::isMSExternInline() const {
3255   assert(isInlined() && "expected to get called on an inlined function!");
3256 
3257   const ASTContext &Context = getASTContext();
3258   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3259       !hasAttr<DLLExportAttr>())
3260     return false;
3261 
3262   for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3263        FD = FD->getPreviousDecl())
3264     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3265       return true;
3266 
3267   return false;
3268 }
3269 
3270 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3271   if (Redecl->getStorageClass() != SC_Extern)
3272     return false;
3273 
3274   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3275        FD = FD->getPreviousDecl())
3276     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3277       return false;
3278 
3279   return true;
3280 }
3281 
3282 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3283   // Only consider file-scope declarations in this test.
3284   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3285     return false;
3286 
3287   // Only consider explicit declarations; the presence of a builtin for a
3288   // libcall shouldn't affect whether a definition is externally visible.
3289   if (Redecl->isImplicit())
3290     return false;
3291 
3292   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3293     return true; // Not an inline definition
3294 
3295   return false;
3296 }
3297 
3298 /// For a function declaration in C or C++, determine whether this
3299 /// declaration causes the definition to be externally visible.
3300 ///
3301 /// For instance, this determines if adding the current declaration to the set
3302 /// of redeclarations of the given functions causes
3303 /// isInlineDefinitionExternallyVisible to change from false to true.
3304 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3305   assert(!doesThisDeclarationHaveABody() &&
3306          "Must have a declaration without a body.");
3307 
3308   ASTContext &Context = getASTContext();
3309 
3310   if (Context.getLangOpts().MSVCCompat) {
3311     const FunctionDecl *Definition;
3312     if (hasBody(Definition) && Definition->isInlined() &&
3313         redeclForcesDefMSVC(this))
3314       return true;
3315   }
3316 
3317   if (Context.getLangOpts().CPlusPlus)
3318     return false;
3319 
3320   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3321     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3322     // an externally visible definition.
3323     //
3324     // FIXME: What happens if gnu_inline gets added on after the first
3325     // declaration?
3326     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3327       return false;
3328 
3329     const FunctionDecl *Prev = this;
3330     bool FoundBody = false;
3331     while ((Prev = Prev->getPreviousDecl())) {
3332       FoundBody |= Prev->doesThisDeclarationHaveABody();
3333 
3334       if (Prev->doesThisDeclarationHaveABody()) {
3335         // If it's not the case that both 'inline' and 'extern' are
3336         // specified on the definition, then it is always externally visible.
3337         if (!Prev->isInlineSpecified() ||
3338             Prev->getStorageClass() != SC_Extern)
3339           return false;
3340       } else if (Prev->isInlineSpecified() &&
3341                  Prev->getStorageClass() != SC_Extern) {
3342         return false;
3343       }
3344     }
3345     return FoundBody;
3346   }
3347 
3348   // C99 6.7.4p6:
3349   //   [...] If all of the file scope declarations for a function in a
3350   //   translation unit include the inline function specifier without extern,
3351   //   then the definition in that translation unit is an inline definition.
3352   if (isInlineSpecified() && getStorageClass() != SC_Extern)
3353     return false;
3354   const FunctionDecl *Prev = this;
3355   bool FoundBody = false;
3356   while ((Prev = Prev->getPreviousDecl())) {
3357     FoundBody |= Prev->doesThisDeclarationHaveABody();
3358     if (RedeclForcesDefC99(Prev))
3359       return false;
3360   }
3361   return FoundBody;
3362 }
3363 
3364 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
3365   const TypeSourceInfo *TSI = getTypeSourceInfo();
3366   return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3367              : FunctionTypeLoc();
3368 }
3369 
3370 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3371   FunctionTypeLoc FTL = getFunctionTypeLoc();
3372   if (!FTL)
3373     return SourceRange();
3374 
3375   // Skip self-referential return types.
3376   const SourceManager &SM = getASTContext().getSourceManager();
3377   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3378   SourceLocation Boundary = getNameInfo().getBeginLoc();
3379   if (RTRange.isInvalid() || Boundary.isInvalid() ||
3380       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3381     return SourceRange();
3382 
3383   return RTRange;
3384 }
3385 
3386 SourceRange FunctionDecl::getParametersSourceRange() const {
3387   unsigned NP = getNumParams();
3388   SourceLocation EllipsisLoc = getEllipsisLoc();
3389 
3390   if (NP == 0 && EllipsisLoc.isInvalid())
3391     return SourceRange();
3392 
3393   SourceLocation Begin =
3394       NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3395   SourceLocation End = EllipsisLoc.isValid()
3396                            ? EllipsisLoc
3397                            : ParamInfo[NP - 1]->getSourceRange().getEnd();
3398 
3399   return SourceRange(Begin, End);
3400 }
3401 
3402 SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3403   FunctionTypeLoc FTL = getFunctionTypeLoc();
3404   return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3405 }
3406 
3407 /// For an inline function definition in C, or for a gnu_inline function
3408 /// in C++, determine whether the definition will be externally visible.
3409 ///
3410 /// Inline function definitions are always available for inlining optimizations.
3411 /// However, depending on the language dialect, declaration specifiers, and
3412 /// attributes, the definition of an inline function may or may not be
3413 /// "externally" visible to other translation units in the program.
3414 ///
3415 /// In C99, inline definitions are not externally visible by default. However,
3416 /// if even one of the global-scope declarations is marked "extern inline", the
3417 /// inline definition becomes externally visible (C99 6.7.4p6).
3418 ///
3419 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3420 /// definition, we use the GNU semantics for inline, which are nearly the
3421 /// opposite of C99 semantics. In particular, "inline" by itself will create
3422 /// an externally visible symbol, but "extern inline" will not create an
3423 /// externally visible symbol.
3424 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3425   assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3426           hasAttr<AliasAttr>()) &&
3427          "Must be a function definition");
3428   assert(isInlined() && "Function must be inline");
3429   ASTContext &Context = getASTContext();
3430 
3431   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3432     // Note: If you change the logic here, please change
3433     // doesDeclarationForceExternallyVisibleDefinition as well.
3434     //
3435     // If it's not the case that both 'inline' and 'extern' are
3436     // specified on the definition, then this inline definition is
3437     // externally visible.
3438     if (Context.getLangOpts().CPlusPlus)
3439       return false;
3440     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3441       return true;
3442 
3443     // If any declaration is 'inline' but not 'extern', then this definition
3444     // is externally visible.
3445     for (auto Redecl : redecls()) {
3446       if (Redecl->isInlineSpecified() &&
3447           Redecl->getStorageClass() != SC_Extern)
3448         return true;
3449     }
3450 
3451     return false;
3452   }
3453 
3454   // The rest of this function is C-only.
3455   assert(!Context.getLangOpts().CPlusPlus &&
3456          "should not use C inline rules in C++");
3457 
3458   // C99 6.7.4p6:
3459   //   [...] If all of the file scope declarations for a function in a
3460   //   translation unit include the inline function specifier without extern,
3461   //   then the definition in that translation unit is an inline definition.
3462   for (auto Redecl : redecls()) {
3463     if (RedeclForcesDefC99(Redecl))
3464       return true;
3465   }
3466 
3467   // C99 6.7.4p6:
3468   //   An inline definition does not provide an external definition for the
3469   //   function, and does not forbid an external definition in another
3470   //   translation unit.
3471   return false;
3472 }
3473 
3474 /// getOverloadedOperator - Which C++ overloaded operator this
3475 /// function represents, if any.
3476 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3477   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3478     return getDeclName().getCXXOverloadedOperator();
3479   else
3480     return OO_None;
3481 }
3482 
3483 /// getLiteralIdentifier - The literal suffix identifier this function
3484 /// represents, if any.
3485 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3486   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3487     return getDeclName().getCXXLiteralIdentifier();
3488   else
3489     return nullptr;
3490 }
3491 
3492 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3493   if (TemplateOrSpecialization.isNull())
3494     return TK_NonTemplate;
3495   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3496     return TK_FunctionTemplate;
3497   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3498     return TK_MemberSpecialization;
3499   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3500     return TK_FunctionTemplateSpecialization;
3501   if (TemplateOrSpecialization.is
3502                                <DependentFunctionTemplateSpecializationInfo*>())
3503     return TK_DependentFunctionTemplateSpecialization;
3504 
3505   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3506 }
3507 
3508 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3509   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3510     return cast<FunctionDecl>(Info->getInstantiatedFrom());
3511 
3512   return nullptr;
3513 }
3514 
3515 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3516   if (auto *MSI =
3517           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3518     return MSI;
3519   if (auto *FTSI = TemplateOrSpecialization
3520                        .dyn_cast<FunctionTemplateSpecializationInfo *>())
3521     return FTSI->getMemberSpecializationInfo();
3522   return nullptr;
3523 }
3524 
3525 void
3526 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3527                                                FunctionDecl *FD,
3528                                                TemplateSpecializationKind TSK) {
3529   assert(TemplateOrSpecialization.isNull() &&
3530          "Member function is already a specialization");
3531   MemberSpecializationInfo *Info
3532     = new (C) MemberSpecializationInfo(FD, TSK);
3533   TemplateOrSpecialization = Info;
3534 }
3535 
3536 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3537   return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3538 }
3539 
3540 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3541   assert(TemplateOrSpecialization.isNull() &&
3542          "Member function is already a specialization");
3543   TemplateOrSpecialization = Template;
3544 }
3545 
3546 bool FunctionDecl::isImplicitlyInstantiable() const {
3547   // If the function is invalid, it can't be implicitly instantiated.
3548   if (isInvalidDecl())
3549     return false;
3550 
3551   switch (getTemplateSpecializationKindForInstantiation()) {
3552   case TSK_Undeclared:
3553   case TSK_ExplicitInstantiationDefinition:
3554   case TSK_ExplicitSpecialization:
3555     return false;
3556 
3557   case TSK_ImplicitInstantiation:
3558     return true;
3559 
3560   case TSK_ExplicitInstantiationDeclaration:
3561     // Handled below.
3562     break;
3563   }
3564 
3565   // Find the actual template from which we will instantiate.
3566   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3567   bool HasPattern = false;
3568   if (PatternDecl)
3569     HasPattern = PatternDecl->hasBody(PatternDecl);
3570 
3571   // C++0x [temp.explicit]p9:
3572   //   Except for inline functions, other explicit instantiation declarations
3573   //   have the effect of suppressing the implicit instantiation of the entity
3574   //   to which they refer.
3575   if (!HasPattern || !PatternDecl)
3576     return true;
3577 
3578   return PatternDecl->isInlined();
3579 }
3580 
3581 bool FunctionDecl::isTemplateInstantiation() const {
3582   // FIXME: Remove this, it's not clear what it means. (Which template
3583   // specialization kind?)
3584   return clang::isTemplateInstantiation(getTemplateSpecializationKind());
3585 }
3586 
3587 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
3588   // If this is a generic lambda call operator specialization, its
3589   // instantiation pattern is always its primary template's pattern
3590   // even if its primary template was instantiated from another
3591   // member template (which happens with nested generic lambdas).
3592   // Since a lambda's call operator's body is transformed eagerly,
3593   // we don't have to go hunting for a prototype definition template
3594   // (i.e. instantiated-from-member-template) to use as an instantiation
3595   // pattern.
3596 
3597   if (isGenericLambdaCallOperatorSpecialization(
3598           dyn_cast<CXXMethodDecl>(this))) {
3599     assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3600     return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3601   }
3602 
3603   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) {
3604     if (!clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
3605       return nullptr;
3606     return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3607   }
3608 
3609   if (!clang::isTemplateInstantiation(getTemplateSpecializationKind()))
3610     return nullptr;
3611 
3612   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3613     // If we hit a point where the user provided a specialization of this
3614     // template, we're done looking.
3615     while (!Primary->isMemberSpecialization()) {
3616       auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3617       if (!NewPrimary)
3618         break;
3619       Primary = NewPrimary;
3620     }
3621 
3622     return getDefinitionOrSelf(Primary->getTemplatedDecl());
3623   }
3624 
3625   return nullptr;
3626 }
3627 
3628 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3629   if (FunctionTemplateSpecializationInfo *Info
3630         = TemplateOrSpecialization
3631             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3632     return Info->getTemplate();
3633   }
3634   return nullptr;
3635 }
3636 
3637 FunctionTemplateSpecializationInfo *
3638 FunctionDecl::getTemplateSpecializationInfo() const {
3639   return TemplateOrSpecialization
3640       .dyn_cast<FunctionTemplateSpecializationInfo *>();
3641 }
3642 
3643 const TemplateArgumentList *
3644 FunctionDecl::getTemplateSpecializationArgs() const {
3645   if (FunctionTemplateSpecializationInfo *Info
3646         = TemplateOrSpecialization
3647             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3648     return Info->TemplateArguments;
3649   }
3650   return nullptr;
3651 }
3652 
3653 const ASTTemplateArgumentListInfo *
3654 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3655   if (FunctionTemplateSpecializationInfo *Info
3656         = TemplateOrSpecialization
3657             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3658     return Info->TemplateArgumentsAsWritten;
3659   }
3660   return nullptr;
3661 }
3662 
3663 void
3664 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3665                                                 FunctionTemplateDecl *Template,
3666                                      const TemplateArgumentList *TemplateArgs,
3667                                                 void *InsertPos,
3668                                                 TemplateSpecializationKind TSK,
3669                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
3670                                           SourceLocation PointOfInstantiation) {
3671   assert((TemplateOrSpecialization.isNull() ||
3672           TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
3673          "Member function is already a specialization");
3674   assert(TSK != TSK_Undeclared &&
3675          "Must specify the type of function template specialization");
3676   assert((TemplateOrSpecialization.isNull() ||
3677           TSK == TSK_ExplicitSpecialization) &&
3678          "Member specialization must be an explicit specialization");
3679   FunctionTemplateSpecializationInfo *Info =
3680       FunctionTemplateSpecializationInfo::Create(
3681           C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3682           PointOfInstantiation,
3683           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
3684   TemplateOrSpecialization = Info;
3685   Template->addSpecialization(Info, InsertPos);
3686 }
3687 
3688 void
3689 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3690                                     const UnresolvedSetImpl &Templates,
3691                              const TemplateArgumentListInfo &TemplateArgs) {
3692   assert(TemplateOrSpecialization.isNull());
3693   DependentFunctionTemplateSpecializationInfo *Info =
3694       DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3695                                                           TemplateArgs);
3696   TemplateOrSpecialization = Info;
3697 }
3698 
3699 DependentFunctionTemplateSpecializationInfo *
3700 FunctionDecl::getDependentSpecializationInfo() const {
3701   return TemplateOrSpecialization
3702       .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3703 }
3704 
3705 DependentFunctionTemplateSpecializationInfo *
3706 DependentFunctionTemplateSpecializationInfo::Create(
3707     ASTContext &Context, const UnresolvedSetImpl &Ts,
3708     const TemplateArgumentListInfo &TArgs) {
3709   void *Buffer = Context.Allocate(
3710       totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3711           TArgs.size(), Ts.size()));
3712   return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3713 }
3714 
3715 DependentFunctionTemplateSpecializationInfo::
3716 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3717                                       const TemplateArgumentListInfo &TArgs)
3718   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3719   NumTemplates = Ts.size();
3720   NumArgs = TArgs.size();
3721 
3722   FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3723   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3724     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3725 
3726   TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
3727   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3728     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3729 }
3730 
3731 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3732   // For a function template specialization, query the specialization
3733   // information object.
3734   if (FunctionTemplateSpecializationInfo *FTSInfo =
3735           TemplateOrSpecialization
3736               .dyn_cast<FunctionTemplateSpecializationInfo *>())
3737     return FTSInfo->getTemplateSpecializationKind();
3738 
3739   if (MemberSpecializationInfo *MSInfo =
3740           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3741     return MSInfo->getTemplateSpecializationKind();
3742 
3743   return TSK_Undeclared;
3744 }
3745 
3746 TemplateSpecializationKind
3747 FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
3748   // This is the same as getTemplateSpecializationKind(), except that for a
3749   // function that is both a function template specialization and a member
3750   // specialization, we prefer the member specialization information. Eg:
3751   //
3752   // template<typename T> struct A {
3753   //   template<typename U> void f() {}
3754   //   template<> void f<int>() {}
3755   // };
3756   //
3757   // For A<int>::f<int>():
3758   // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
3759   // * getTemplateSpecializationKindForInstantiation() will return
3760   //       TSK_ImplicitInstantiation
3761   //
3762   // This reflects the facts that A<int>::f<int> is an explicit specialization
3763   // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
3764   // from A::f<int> if a definition is needed.
3765   if (FunctionTemplateSpecializationInfo *FTSInfo =
3766           TemplateOrSpecialization
3767               .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
3768     if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
3769       return MSInfo->getTemplateSpecializationKind();
3770     return FTSInfo->getTemplateSpecializationKind();
3771   }
3772 
3773   if (MemberSpecializationInfo *MSInfo =
3774           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3775     return MSInfo->getTemplateSpecializationKind();
3776 
3777   return TSK_Undeclared;
3778 }
3779 
3780 void
3781 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3782                                           SourceLocation PointOfInstantiation) {
3783   if (FunctionTemplateSpecializationInfo *FTSInfo
3784         = TemplateOrSpecialization.dyn_cast<
3785                                     FunctionTemplateSpecializationInfo*>()) {
3786     FTSInfo->setTemplateSpecializationKind(TSK);
3787     if (TSK != TSK_ExplicitSpecialization &&
3788         PointOfInstantiation.isValid() &&
3789         FTSInfo->getPointOfInstantiation().isInvalid()) {
3790       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3791       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3792         L->InstantiationRequested(this);
3793     }
3794   } else if (MemberSpecializationInfo *MSInfo
3795              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3796     MSInfo->setTemplateSpecializationKind(TSK);
3797     if (TSK != TSK_ExplicitSpecialization &&
3798         PointOfInstantiation.isValid() &&
3799         MSInfo->getPointOfInstantiation().isInvalid()) {
3800       MSInfo->setPointOfInstantiation(PointOfInstantiation);
3801       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3802         L->InstantiationRequested(this);
3803     }
3804   } else
3805     llvm_unreachable("Function cannot have a template specialization kind");
3806 }
3807 
3808 SourceLocation FunctionDecl::getPointOfInstantiation() const {
3809   if (FunctionTemplateSpecializationInfo *FTSInfo
3810         = TemplateOrSpecialization.dyn_cast<
3811                                         FunctionTemplateSpecializationInfo*>())
3812     return FTSInfo->getPointOfInstantiation();
3813   else if (MemberSpecializationInfo *MSInfo
3814              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3815     return MSInfo->getPointOfInstantiation();
3816 
3817   return SourceLocation();
3818 }
3819 
3820 bool FunctionDecl::isOutOfLine() const {
3821   if (Decl::isOutOfLine())
3822     return true;
3823 
3824   // If this function was instantiated from a member function of a
3825   // class template, check whether that member function was defined out-of-line.
3826   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3827     const FunctionDecl *Definition;
3828     if (FD->hasBody(Definition))
3829       return Definition->isOutOfLine();
3830   }
3831 
3832   // If this function was instantiated from a function template,
3833   // check whether that function template was defined out-of-line.
3834   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3835     const FunctionDecl *Definition;
3836     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3837       return Definition->isOutOfLine();
3838   }
3839 
3840   return false;
3841 }
3842 
3843 SourceRange FunctionDecl::getSourceRange() const {
3844   return SourceRange(getOuterLocStart(), EndRangeLoc);
3845 }
3846 
3847 unsigned FunctionDecl::getMemoryFunctionKind() const {
3848   IdentifierInfo *FnInfo = getIdentifier();
3849 
3850   if (!FnInfo)
3851     return 0;
3852 
3853   // Builtin handling.
3854   switch (getBuiltinID()) {
3855   case Builtin::BI__builtin_memset:
3856   case Builtin::BI__builtin___memset_chk:
3857   case Builtin::BImemset:
3858     return Builtin::BImemset;
3859 
3860   case Builtin::BI__builtin_memcpy:
3861   case Builtin::BI__builtin___memcpy_chk:
3862   case Builtin::BImemcpy:
3863     return Builtin::BImemcpy;
3864 
3865   case Builtin::BI__builtin_mempcpy:
3866   case Builtin::BI__builtin___mempcpy_chk:
3867   case Builtin::BImempcpy:
3868     return Builtin::BImempcpy;
3869 
3870   case Builtin::BI__builtin_memmove:
3871   case Builtin::BI__builtin___memmove_chk:
3872   case Builtin::BImemmove:
3873     return Builtin::BImemmove;
3874 
3875   case Builtin::BIstrlcpy:
3876   case Builtin::BI__builtin___strlcpy_chk:
3877     return Builtin::BIstrlcpy;
3878 
3879   case Builtin::BIstrlcat:
3880   case Builtin::BI__builtin___strlcat_chk:
3881     return Builtin::BIstrlcat;
3882 
3883   case Builtin::BI__builtin_memcmp:
3884   case Builtin::BImemcmp:
3885     return Builtin::BImemcmp;
3886 
3887   case Builtin::BI__builtin_bcmp:
3888   case Builtin::BIbcmp:
3889     return Builtin::BIbcmp;
3890 
3891   case Builtin::BI__builtin_strncpy:
3892   case Builtin::BI__builtin___strncpy_chk:
3893   case Builtin::BIstrncpy:
3894     return Builtin::BIstrncpy;
3895 
3896   case Builtin::BI__builtin_strncmp:
3897   case Builtin::BIstrncmp:
3898     return Builtin::BIstrncmp;
3899 
3900   case Builtin::BI__builtin_strncasecmp:
3901   case Builtin::BIstrncasecmp:
3902     return Builtin::BIstrncasecmp;
3903 
3904   case Builtin::BI__builtin_strncat:
3905   case Builtin::BI__builtin___strncat_chk:
3906   case Builtin::BIstrncat:
3907     return Builtin::BIstrncat;
3908 
3909   case Builtin::BI__builtin_strndup:
3910   case Builtin::BIstrndup:
3911     return Builtin::BIstrndup;
3912 
3913   case Builtin::BI__builtin_strlen:
3914   case Builtin::BIstrlen:
3915     return Builtin::BIstrlen;
3916 
3917   case Builtin::BI__builtin_bzero:
3918   case Builtin::BIbzero:
3919     return Builtin::BIbzero;
3920 
3921   default:
3922     if (isExternC()) {
3923       if (FnInfo->isStr("memset"))
3924         return Builtin::BImemset;
3925       else if (FnInfo->isStr("memcpy"))
3926         return Builtin::BImemcpy;
3927       else if (FnInfo->isStr("mempcpy"))
3928         return Builtin::BImempcpy;
3929       else if (FnInfo->isStr("memmove"))
3930         return Builtin::BImemmove;
3931       else if (FnInfo->isStr("memcmp"))
3932         return Builtin::BImemcmp;
3933       else if (FnInfo->isStr("bcmp"))
3934         return Builtin::BIbcmp;
3935       else if (FnInfo->isStr("strncpy"))
3936         return Builtin::BIstrncpy;
3937       else if (FnInfo->isStr("strncmp"))
3938         return Builtin::BIstrncmp;
3939       else if (FnInfo->isStr("strncasecmp"))
3940         return Builtin::BIstrncasecmp;
3941       else if (FnInfo->isStr("strncat"))
3942         return Builtin::BIstrncat;
3943       else if (FnInfo->isStr("strndup"))
3944         return Builtin::BIstrndup;
3945       else if (FnInfo->isStr("strlen"))
3946         return Builtin::BIstrlen;
3947       else if (FnInfo->isStr("bzero"))
3948         return Builtin::BIbzero;
3949     }
3950     break;
3951   }
3952   return 0;
3953 }
3954 
3955 unsigned FunctionDecl::getODRHash() const {
3956   assert(hasODRHash());
3957   return ODRHash;
3958 }
3959 
3960 unsigned FunctionDecl::getODRHash() {
3961   if (hasODRHash())
3962     return ODRHash;
3963 
3964   if (auto *FT = getInstantiatedFromMemberFunction()) {
3965     setHasODRHash(true);
3966     ODRHash = FT->getODRHash();
3967     return ODRHash;
3968   }
3969 
3970   class ODRHash Hash;
3971   Hash.AddFunctionDecl(this);
3972   setHasODRHash(true);
3973   ODRHash = Hash.CalculateHash();
3974   return ODRHash;
3975 }
3976 
3977 //===----------------------------------------------------------------------===//
3978 // FieldDecl Implementation
3979 //===----------------------------------------------------------------------===//
3980 
3981 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3982                              SourceLocation StartLoc, SourceLocation IdLoc,
3983                              IdentifierInfo *Id, QualType T,
3984                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3985                              InClassInitStyle InitStyle) {
3986   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3987                                BW, Mutable, InitStyle);
3988 }
3989 
3990 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3991   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3992                                SourceLocation(), nullptr, QualType(), nullptr,
3993                                nullptr, false, ICIS_NoInit);
3994 }
3995 
3996 bool FieldDecl::isAnonymousStructOrUnion() const {
3997   if (!isImplicit() || getDeclName())
3998     return false;
3999 
4000   if (const auto *Record = getType()->getAs<RecordType>())
4001     return Record->getDecl()->isAnonymousStructOrUnion();
4002 
4003   return false;
4004 }
4005 
4006 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4007   assert(isBitField() && "not a bitfield");
4008   return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4009 }
4010 
4011 bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4012   return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
4013          getBitWidthValue(Ctx) == 0;
4014 }
4015 
4016 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4017   if (isZeroLengthBitField(Ctx))
4018     return true;
4019 
4020   // C++2a [intro.object]p7:
4021   //   An object has nonzero size if it
4022   //     -- is not a potentially-overlapping subobject, or
4023   if (!hasAttr<NoUniqueAddressAttr>())
4024     return false;
4025 
4026   //     -- is not of class type, or
4027   const auto *RT = getType()->getAs<RecordType>();
4028   if (!RT)
4029     return false;
4030   const RecordDecl *RD = RT->getDecl()->getDefinition();
4031   if (!RD) {
4032     assert(isInvalidDecl() && "valid field has incomplete type");
4033     return false;
4034   }
4035 
4036   //     -- [has] virtual member functions or virtual base classes, or
4037   //     -- has subobjects of nonzero size or bit-fields of nonzero length
4038   const auto *CXXRD = cast<CXXRecordDecl>(RD);
4039   if (!CXXRD->isEmpty())
4040     return false;
4041 
4042   // Otherwise, [...] the circumstances under which the object has zero size
4043   // are implementation-defined.
4044   // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4045   // ABI will do.
4046   return true;
4047 }
4048 
4049 unsigned FieldDecl::getFieldIndex() const {
4050   const FieldDecl *Canonical = getCanonicalDecl();
4051   if (Canonical != this)
4052     return Canonical->getFieldIndex();
4053 
4054   if (CachedFieldIndex) return CachedFieldIndex - 1;
4055 
4056   unsigned Index = 0;
4057   const RecordDecl *RD = getParent()->getDefinition();
4058   assert(RD && "requested index for field of struct with no definition");
4059 
4060   for (auto *Field : RD->fields()) {
4061     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4062     ++Index;
4063   }
4064 
4065   assert(CachedFieldIndex && "failed to find field in parent");
4066   return CachedFieldIndex - 1;
4067 }
4068 
4069 SourceRange FieldDecl::getSourceRange() const {
4070   const Expr *FinalExpr = getInClassInitializer();
4071   if (!FinalExpr)
4072     FinalExpr = getBitWidth();
4073   if (FinalExpr)
4074     return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4075   return DeclaratorDecl::getSourceRange();
4076 }
4077 
4078 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4079   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4080          "capturing type in non-lambda or captured record.");
4081   assert(InitStorage.getInt() == ISK_NoInit &&
4082          InitStorage.getPointer() == nullptr &&
4083          "bit width, initializer or captured type already set");
4084   InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4085                                ISK_CapturedVLAType);
4086 }
4087 
4088 //===----------------------------------------------------------------------===//
4089 // TagDecl Implementation
4090 //===----------------------------------------------------------------------===//
4091 
4092 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4093                  SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4094                  SourceLocation StartL)
4095     : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4096       TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4097   assert((DK != Enum || TK == TTK_Enum) &&
4098          "EnumDecl not matched with TTK_Enum");
4099   setPreviousDecl(PrevDecl);
4100   setTagKind(TK);
4101   setCompleteDefinition(false);
4102   setBeingDefined(false);
4103   setEmbeddedInDeclarator(false);
4104   setFreeStanding(false);
4105   setCompleteDefinitionRequired(false);
4106 }
4107 
4108 SourceLocation TagDecl::getOuterLocStart() const {
4109   return getTemplateOrInnerLocStart(this);
4110 }
4111 
4112 SourceRange TagDecl::getSourceRange() const {
4113   SourceLocation RBraceLoc = BraceRange.getEnd();
4114   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4115   return SourceRange(getOuterLocStart(), E);
4116 }
4117 
4118 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4119 
4120 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4121   TypedefNameDeclOrQualifier = TDD;
4122   if (const Type *T = getTypeForDecl()) {
4123     (void)T;
4124     assert(T->isLinkageValid());
4125   }
4126   assert(isLinkageValid());
4127 }
4128 
4129 void TagDecl::startDefinition() {
4130   setBeingDefined(true);
4131 
4132   if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4133     struct CXXRecordDecl::DefinitionData *Data =
4134       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4135     for (auto I : redecls())
4136       cast<CXXRecordDecl>(I)->DefinitionData = Data;
4137   }
4138 }
4139 
4140 void TagDecl::completeDefinition() {
4141   assert((!isa<CXXRecordDecl>(this) ||
4142           cast<CXXRecordDecl>(this)->hasDefinition()) &&
4143          "definition completed but not started");
4144 
4145   setCompleteDefinition(true);
4146   setBeingDefined(false);
4147 
4148   if (ASTMutationListener *L = getASTMutationListener())
4149     L->CompletedTagDefinition(this);
4150 }
4151 
4152 TagDecl *TagDecl::getDefinition() const {
4153   if (isCompleteDefinition())
4154     return const_cast<TagDecl *>(this);
4155 
4156   // If it's possible for us to have an out-of-date definition, check now.
4157   if (mayHaveOutOfDateDef()) {
4158     if (IdentifierInfo *II = getIdentifier()) {
4159       if (II->isOutOfDate()) {
4160         updateOutOfDate(*II);
4161       }
4162     }
4163   }
4164 
4165   if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4166     return CXXRD->getDefinition();
4167 
4168   for (auto R : redecls())
4169     if (R->isCompleteDefinition())
4170       return R;
4171 
4172   return nullptr;
4173 }
4174 
4175 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4176   if (QualifierLoc) {
4177     // Make sure the extended qualifier info is allocated.
4178     if (!hasExtInfo())
4179       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4180     // Set qualifier info.
4181     getExtInfo()->QualifierLoc = QualifierLoc;
4182   } else {
4183     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4184     if (hasExtInfo()) {
4185       if (getExtInfo()->NumTemplParamLists == 0) {
4186         getASTContext().Deallocate(getExtInfo());
4187         TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4188       }
4189       else
4190         getExtInfo()->QualifierLoc = QualifierLoc;
4191     }
4192   }
4193 }
4194 
4195 void TagDecl::setTemplateParameterListsInfo(
4196     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4197   assert(!TPLists.empty());
4198   // Make sure the extended decl info is allocated.
4199   if (!hasExtInfo())
4200     // Allocate external info struct.
4201     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4202   // Set the template parameter lists info.
4203   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4204 }
4205 
4206 //===----------------------------------------------------------------------===//
4207 // EnumDecl Implementation
4208 //===----------------------------------------------------------------------===//
4209 
4210 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4211                    SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4212                    bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4213     : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4214   assert(Scoped || !ScopedUsingClassTag);
4215   IntegerType = nullptr;
4216   setNumPositiveBits(0);
4217   setNumNegativeBits(0);
4218   setScoped(Scoped);
4219   setScopedUsingClassTag(ScopedUsingClassTag);
4220   setFixed(Fixed);
4221   setHasODRHash(false);
4222   ODRHash = 0;
4223 }
4224 
4225 void EnumDecl::anchor() {}
4226 
4227 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4228                            SourceLocation StartLoc, SourceLocation IdLoc,
4229                            IdentifierInfo *Id,
4230                            EnumDecl *PrevDecl, bool IsScoped,
4231                            bool IsScopedUsingClassTag, bool IsFixed) {
4232   auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4233                                     IsScoped, IsScopedUsingClassTag, IsFixed);
4234   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4235   C.getTypeDeclType(Enum, PrevDecl);
4236   return Enum;
4237 }
4238 
4239 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4240   EnumDecl *Enum =
4241       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4242                            nullptr, nullptr, false, false, false);
4243   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4244   return Enum;
4245 }
4246 
4247 SourceRange EnumDecl::getIntegerTypeRange() const {
4248   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4249     return TI->getTypeLoc().getSourceRange();
4250   return SourceRange();
4251 }
4252 
4253 void EnumDecl::completeDefinition(QualType NewType,
4254                                   QualType NewPromotionType,
4255                                   unsigned NumPositiveBits,
4256                                   unsigned NumNegativeBits) {
4257   assert(!isCompleteDefinition() && "Cannot redefine enums!");
4258   if (!IntegerType)
4259     IntegerType = NewType.getTypePtr();
4260   PromotionType = NewPromotionType;
4261   setNumPositiveBits(NumPositiveBits);
4262   setNumNegativeBits(NumNegativeBits);
4263   TagDecl::completeDefinition();
4264 }
4265 
4266 bool EnumDecl::isClosed() const {
4267   if (const auto *A = getAttr<EnumExtensibilityAttr>())
4268     return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4269   return true;
4270 }
4271 
4272 bool EnumDecl::isClosedFlag() const {
4273   return isClosed() && hasAttr<FlagEnumAttr>();
4274 }
4275 
4276 bool EnumDecl::isClosedNonFlag() const {
4277   return isClosed() && !hasAttr<FlagEnumAttr>();
4278 }
4279 
4280 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4281   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4282     return MSI->getTemplateSpecializationKind();
4283 
4284   return TSK_Undeclared;
4285 }
4286 
4287 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4288                                          SourceLocation PointOfInstantiation) {
4289   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4290   assert(MSI && "Not an instantiated member enumeration?");
4291   MSI->setTemplateSpecializationKind(TSK);
4292   if (TSK != TSK_ExplicitSpecialization &&
4293       PointOfInstantiation.isValid() &&
4294       MSI->getPointOfInstantiation().isInvalid())
4295     MSI->setPointOfInstantiation(PointOfInstantiation);
4296 }
4297 
4298 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4299   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4300     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4301       EnumDecl *ED = getInstantiatedFromMemberEnum();
4302       while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4303         ED = NewED;
4304       return getDefinitionOrSelf(ED);
4305     }
4306   }
4307 
4308   assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4309          "couldn't find pattern for enum instantiation");
4310   return nullptr;
4311 }
4312 
4313 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4314   if (SpecializationInfo)
4315     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4316 
4317   return nullptr;
4318 }
4319 
4320 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4321                                             TemplateSpecializationKind TSK) {
4322   assert(!SpecializationInfo && "Member enum is already a specialization");
4323   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4324 }
4325 
4326 unsigned EnumDecl::getODRHash() {
4327   if (hasODRHash())
4328     return ODRHash;
4329 
4330   class ODRHash Hash;
4331   Hash.AddEnumDecl(this);
4332   setHasODRHash(true);
4333   ODRHash = Hash.CalculateHash();
4334   return ODRHash;
4335 }
4336 
4337 //===----------------------------------------------------------------------===//
4338 // RecordDecl Implementation
4339 //===----------------------------------------------------------------------===//
4340 
4341 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4342                        DeclContext *DC, SourceLocation StartLoc,
4343                        SourceLocation IdLoc, IdentifierInfo *Id,
4344                        RecordDecl *PrevDecl)
4345     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4346   assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4347   setHasFlexibleArrayMember(false);
4348   setAnonymousStructOrUnion(false);
4349   setHasObjectMember(false);
4350   setHasVolatileMember(false);
4351   setHasLoadedFieldsFromExternalStorage(false);
4352   setNonTrivialToPrimitiveDefaultInitialize(false);
4353   setNonTrivialToPrimitiveCopy(false);
4354   setNonTrivialToPrimitiveDestroy(false);
4355   setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4356   setHasNonTrivialToPrimitiveDestructCUnion(false);
4357   setHasNonTrivialToPrimitiveCopyCUnion(false);
4358   setParamDestroyedInCallee(false);
4359   setArgPassingRestrictions(APK_CanPassInRegs);
4360 }
4361 
4362 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
4363                                SourceLocation StartLoc, SourceLocation IdLoc,
4364                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
4365   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4366                                          StartLoc, IdLoc, Id, PrevDecl);
4367   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4368 
4369   C.getTypeDeclType(R, PrevDecl);
4370   return R;
4371 }
4372 
4373 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
4374   RecordDecl *R =
4375       new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4376                              SourceLocation(), nullptr, nullptr);
4377   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4378   return R;
4379 }
4380 
4381 bool RecordDecl::isInjectedClassName() const {
4382   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
4383     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4384 }
4385 
4386 bool RecordDecl::isLambda() const {
4387   if (auto RD = dyn_cast<CXXRecordDecl>(this))
4388     return RD->isLambda();
4389   return false;
4390 }
4391 
4392 bool RecordDecl::isCapturedRecord() const {
4393   return hasAttr<CapturedRecordAttr>();
4394 }
4395 
4396 void RecordDecl::setCapturedRecord() {
4397   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4398 }
4399 
4400 RecordDecl::field_iterator RecordDecl::field_begin() const {
4401   if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
4402     LoadFieldsFromExternalStorage();
4403 
4404   return field_iterator(decl_iterator(FirstDecl));
4405 }
4406 
4407 /// completeDefinition - Notes that the definition of this type is now
4408 /// complete.
4409 void RecordDecl::completeDefinition() {
4410   assert(!isCompleteDefinition() && "Cannot redefine record!");
4411   TagDecl::completeDefinition();
4412 }
4413 
4414 /// isMsStruct - Get whether or not this record uses ms_struct layout.
4415 /// This which can be turned on with an attribute, pragma, or the
4416 /// -mms-bitfields command-line option.
4417 bool RecordDecl::isMsStruct(const ASTContext &C) const {
4418   return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
4419 }
4420 
4421 void RecordDecl::LoadFieldsFromExternalStorage() const {
4422   ExternalASTSource *Source = getASTContext().getExternalSource();
4423   assert(hasExternalLexicalStorage() && Source && "No external storage?");
4424 
4425   // Notify that we have a RecordDecl doing some initialization.
4426   ExternalASTSource::Deserializing TheFields(Source);
4427 
4428   SmallVector<Decl*, 64> Decls;
4429   setHasLoadedFieldsFromExternalStorage(true);
4430   Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4431     return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4432   }, Decls);
4433 
4434 #ifndef NDEBUG
4435   // Check that all decls we got were FieldDecls.
4436   for (unsigned i=0, e=Decls.size(); i != e; ++i)
4437     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
4438 #endif
4439 
4440   if (Decls.empty())
4441     return;
4442 
4443   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
4444                                                  /*FieldsAlreadyLoaded=*/false);
4445 }
4446 
4447 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4448   ASTContext &Context = getASTContext();
4449   const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4450       (SanitizerKind::Address | SanitizerKind::KernelAddress);
4451   if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
4452     return false;
4453   const auto &Blacklist = Context.getSanitizerBlacklist();
4454   const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4455   // We may be able to relax some of these requirements.
4456   int ReasonToReject = -1;
4457   if (!CXXRD || CXXRD->isExternCContext())
4458     ReasonToReject = 0;  // is not C++.
4459   else if (CXXRD->hasAttr<PackedAttr>())
4460     ReasonToReject = 1;  // is packed.
4461   else if (CXXRD->isUnion())
4462     ReasonToReject = 2;  // is a union.
4463   else if (CXXRD->isTriviallyCopyable())
4464     ReasonToReject = 3;  // is trivially copyable.
4465   else if (CXXRD->hasTrivialDestructor())
4466     ReasonToReject = 4;  // has trivial destructor.
4467   else if (CXXRD->isStandardLayout())
4468     ReasonToReject = 5;  // is standard layout.
4469   else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4470                                            "field-padding"))
4471     ReasonToReject = 6;  // is in a blacklisted file.
4472   else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4473                                        getQualifiedNameAsString(),
4474                                        "field-padding"))
4475     ReasonToReject = 7;  // is blacklisted.
4476 
4477   if (EmitRemark) {
4478     if (ReasonToReject >= 0)
4479       Context.getDiagnostics().Report(
4480           getLocation(),
4481           diag::remark_sanitize_address_insert_extra_padding_rejected)
4482           << getQualifiedNameAsString() << ReasonToReject;
4483     else
4484       Context.getDiagnostics().Report(
4485           getLocation(),
4486           diag::remark_sanitize_address_insert_extra_padding_accepted)
4487           << getQualifiedNameAsString();
4488   }
4489   return ReasonToReject < 0;
4490 }
4491 
4492 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4493   for (const auto *I : fields()) {
4494     if (I->getIdentifier())
4495       return I;
4496 
4497     if (const auto *RT = I->getType()->getAs<RecordType>())
4498       if (const FieldDecl *NamedDataMember =
4499               RT->getDecl()->findFirstNamedDataMember())
4500         return NamedDataMember;
4501   }
4502 
4503   // We didn't find a named data member.
4504   return nullptr;
4505 }
4506 
4507 //===----------------------------------------------------------------------===//
4508 // BlockDecl Implementation
4509 //===----------------------------------------------------------------------===//
4510 
4511 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4512     : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4513   setIsVariadic(false);
4514   setCapturesCXXThis(false);
4515   setBlockMissingReturnType(true);
4516   setIsConversionFromLambda(false);
4517   setDoesNotEscape(false);
4518   setCanAvoidCopyToHeap(false);
4519 }
4520 
4521 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
4522   assert(!ParamInfo && "Already has param info!");
4523 
4524   // Zero params -> null pointer.
4525   if (!NewParamInfo.empty()) {
4526     NumParams = NewParamInfo.size();
4527     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4528     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
4529   }
4530 }
4531 
4532 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4533                             bool CapturesCXXThis) {
4534   this->setCapturesCXXThis(CapturesCXXThis);
4535   this->NumCaptures = Captures.size();
4536 
4537   if (Captures.empty()) {
4538     this->Captures = nullptr;
4539     return;
4540   }
4541 
4542   this->Captures = Captures.copy(Context).data();
4543 }
4544 
4545 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
4546   for (const auto &I : captures())
4547     // Only auto vars can be captured, so no redeclaration worries.
4548     if (I.getVariable() == variable)
4549       return true;
4550 
4551   return false;
4552 }
4553 
4554 SourceRange BlockDecl::getSourceRange() const {
4555   return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
4556 }
4557 
4558 //===----------------------------------------------------------------------===//
4559 // Other Decl Allocation/Deallocation Method Implementations
4560 //===----------------------------------------------------------------------===//
4561 
4562 void TranslationUnitDecl::anchor() {}
4563 
4564 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
4565   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
4566 }
4567 
4568 void PragmaCommentDecl::anchor() {}
4569 
4570 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4571                                              TranslationUnitDecl *DC,
4572                                              SourceLocation CommentLoc,
4573                                              PragmaMSCommentKind CommentKind,
4574                                              StringRef Arg) {
4575   PragmaCommentDecl *PCD =
4576       new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4577           PragmaCommentDecl(DC, CommentLoc, CommentKind);
4578   memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4579   PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4580   return PCD;
4581 }
4582 
4583 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4584                                                          unsigned ID,
4585                                                          unsigned ArgSize) {
4586   return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4587       PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4588 }
4589 
4590 void PragmaDetectMismatchDecl::anchor() {}
4591 
4592 PragmaDetectMismatchDecl *
4593 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4594                                  SourceLocation Loc, StringRef Name,
4595                                  StringRef Value) {
4596   size_t ValueStart = Name.size() + 1;
4597   PragmaDetectMismatchDecl *PDMD =
4598       new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4599           PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4600   memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4601   PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4602   memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4603          Value.size());
4604   PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4605   return PDMD;
4606 }
4607 
4608 PragmaDetectMismatchDecl *
4609 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4610                                              unsigned NameValueSize) {
4611   return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4612       PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4613 }
4614 
4615 void ExternCContextDecl::anchor() {}
4616 
4617 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4618                                                TranslationUnitDecl *DC) {
4619   return new (C, DC) ExternCContextDecl(DC);
4620 }
4621 
4622 void LabelDecl::anchor() {}
4623 
4624 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4625                              SourceLocation IdentL, IdentifierInfo *II) {
4626   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
4627 }
4628 
4629 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4630                              SourceLocation IdentL, IdentifierInfo *II,
4631                              SourceLocation GnuLabelL) {
4632   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
4633   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
4634 }
4635 
4636 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4637   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4638                                SourceLocation());
4639 }
4640 
4641 void LabelDecl::setMSAsmLabel(StringRef Name) {
4642 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4643   memcpy(Buffer, Name.data(), Name.size());
4644   Buffer[Name.size()] = '\0';
4645   MSAsmName = Buffer;
4646 }
4647 
4648 void ValueDecl::anchor() {}
4649 
4650 bool ValueDecl::isWeak() const {
4651   for (const auto *I : attrs())
4652     if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
4653       return true;
4654 
4655   return isWeakImported();
4656 }
4657 
4658 void ImplicitParamDecl::anchor() {}
4659 
4660 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
4661                                              SourceLocation IdLoc,
4662                                              IdentifierInfo *Id, QualType Type,
4663                                              ImplicitParamKind ParamKind) {
4664   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4665 }
4666 
4667 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4668                                              ImplicitParamKind ParamKind) {
4669   return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
4670 }
4671 
4672 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
4673                                                          unsigned ID) {
4674   return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
4675 }
4676 
4677 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
4678                                    SourceLocation StartLoc,
4679                                    const DeclarationNameInfo &NameInfo,
4680                                    QualType T, TypeSourceInfo *TInfo,
4681                                    StorageClass SC, bool isInlineSpecified,
4682                                    bool hasWrittenPrototype,
4683                                    ConstexprSpecKind ConstexprKind,
4684                                    Expr *TrailingRequiresClause) {
4685   FunctionDecl *New =
4686       new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4687                                SC, isInlineSpecified, ConstexprKind,
4688                                TrailingRequiresClause);
4689   New->setHasWrittenPrototype(hasWrittenPrototype);
4690   return New;
4691 }
4692 
4693 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4694   return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
4695                                   DeclarationNameInfo(), QualType(), nullptr,
4696                                   SC_None, false, CSK_unspecified, nullptr);
4697 }
4698 
4699 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4700   return new (C, DC) BlockDecl(DC, L);
4701 }
4702 
4703 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4704   return new (C, ID) BlockDecl(nullptr, SourceLocation());
4705 }
4706 
4707 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4708     : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4709       NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4710 
4711 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4712                                    unsigned NumParams) {
4713   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4714       CapturedDecl(DC, NumParams);
4715 }
4716 
4717 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4718                                                unsigned NumParams) {
4719   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4720       CapturedDecl(nullptr, NumParams);
4721 }
4722 
4723 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4724 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4725 
4726 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4727 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4728 
4729 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4730                                            SourceLocation L,
4731                                            IdentifierInfo *Id, QualType T,
4732                                            Expr *E, const llvm::APSInt &V) {
4733   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
4734 }
4735 
4736 EnumConstantDecl *
4737 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4738   return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4739                                       QualType(), nullptr, llvm::APSInt());
4740 }
4741 
4742 void IndirectFieldDecl::anchor() {}
4743 
4744 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4745                                      SourceLocation L, DeclarationName N,
4746                                      QualType T,
4747                                      MutableArrayRef<NamedDecl *> CH)
4748     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4749       ChainingSize(CH.size()) {
4750   // In C++, indirect field declarations conflict with tag declarations in the
4751   // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4752   if (C.getLangOpts().CPlusPlus)
4753     IdentifierNamespace |= IDNS_Tag;
4754 }
4755 
4756 IndirectFieldDecl *
4757 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
4758                           IdentifierInfo *Id, QualType T,
4759                           llvm::MutableArrayRef<NamedDecl *> CH) {
4760   return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
4761 }
4762 
4763 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4764                                                          unsigned ID) {
4765   return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
4766                                        DeclarationName(), QualType(), None);
4767 }
4768 
4769 SourceRange EnumConstantDecl::getSourceRange() const {
4770   SourceLocation End = getLocation();
4771   if (Init)
4772     End = Init->getEndLoc();
4773   return SourceRange(getLocation(), End);
4774 }
4775 
4776 void TypeDecl::anchor() {}
4777 
4778 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
4779                                  SourceLocation StartLoc, SourceLocation IdLoc,
4780                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
4781   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4782 }
4783 
4784 void TypedefNameDecl::anchor() {}
4785 
4786 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4787   if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4788     auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4789     auto *ThisTypedef = this;
4790     if (AnyRedecl && OwningTypedef) {
4791       OwningTypedef = OwningTypedef->getCanonicalDecl();
4792       ThisTypedef = ThisTypedef->getCanonicalDecl();
4793     }
4794     if (OwningTypedef == ThisTypedef)
4795       return TT->getDecl();
4796   }
4797 
4798   return nullptr;
4799 }
4800 
4801 bool TypedefNameDecl::isTransparentTagSlow() const {
4802   auto determineIsTransparent = [&]() {
4803     if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4804       if (auto *TD = TT->getDecl()) {
4805         if (TD->getName() != getName())
4806           return false;
4807         SourceLocation TTLoc = getLocation();
4808         SourceLocation TDLoc = TD->getLocation();
4809         if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4810           return false;
4811         SourceManager &SM = getASTContext().getSourceManager();
4812         return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4813       }
4814     }
4815     return false;
4816   };
4817 
4818   bool isTransparent = determineIsTransparent();
4819   MaybeModedTInfo.setInt((isTransparent << 1) | 1);
4820   return isTransparent;
4821 }
4822 
4823 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4824   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
4825                                  nullptr, nullptr);
4826 }
4827 
4828 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4829                                      SourceLocation StartLoc,
4830                                      SourceLocation IdLoc, IdentifierInfo *Id,
4831                                      TypeSourceInfo *TInfo) {
4832   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4833 }
4834 
4835 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4836   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4837                                    SourceLocation(), nullptr, nullptr);
4838 }
4839 
4840 SourceRange TypedefDecl::getSourceRange() const {
4841   SourceLocation RangeEnd = getLocation();
4842   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4843     if (typeIsPostfix(TInfo->getType()))
4844       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4845   }
4846   return SourceRange(getBeginLoc(), RangeEnd);
4847 }
4848 
4849 SourceRange TypeAliasDecl::getSourceRange() const {
4850   SourceLocation RangeEnd = getBeginLoc();
4851   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4852     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4853   return SourceRange(getBeginLoc(), RangeEnd);
4854 }
4855 
4856 void FileScopeAsmDecl::anchor() {}
4857 
4858 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
4859                                            StringLiteral *Str,
4860                                            SourceLocation AsmLoc,
4861                                            SourceLocation RParenLoc) {
4862   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
4863 }
4864 
4865 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
4866                                                        unsigned ID) {
4867   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4868                                       SourceLocation());
4869 }
4870 
4871 void EmptyDecl::anchor() {}
4872 
4873 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4874   return new (C, DC) EmptyDecl(DC, L);
4875 }
4876 
4877 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4878   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
4879 }
4880 
4881 //===----------------------------------------------------------------------===//
4882 // ImportDecl Implementation
4883 //===----------------------------------------------------------------------===//
4884 
4885 /// Retrieve the number of module identifiers needed to name the given
4886 /// module.
4887 static unsigned getNumModuleIdentifiers(Module *Mod) {
4888   unsigned Result = 1;
4889   while (Mod->Parent) {
4890     Mod = Mod->Parent;
4891     ++Result;
4892   }
4893   return Result;
4894 }
4895 
4896 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4897                        Module *Imported,
4898                        ArrayRef<SourceLocation> IdentifierLocs)
4899     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
4900       NextLocalImportAndComplete(nullptr, true) {
4901   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
4902   auto *StoredLocs = getTrailingObjects<SourceLocation>();
4903   std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4904                           StoredLocs);
4905 }
4906 
4907 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4908                        Module *Imported, SourceLocation EndLoc)
4909     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
4910       NextLocalImportAndComplete(nullptr, false) {
4911   *getTrailingObjects<SourceLocation>() = EndLoc;
4912 }
4913 
4914 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
4915                                SourceLocation StartLoc, Module *Imported,
4916                                ArrayRef<SourceLocation> IdentifierLocs) {
4917   return new (C, DC,
4918               additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
4919       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
4920 }
4921 
4922 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
4923                                        SourceLocation StartLoc,
4924                                        Module *Imported,
4925                                        SourceLocation EndLoc) {
4926   ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4927       ImportDecl(DC, StartLoc, Imported, EndLoc);
4928   Import->setImplicit();
4929   return Import;
4930 }
4931 
4932 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4933                                            unsigned NumLocations) {
4934   return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
4935       ImportDecl(EmptyShell());
4936 }
4937 
4938 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4939   if (!isImportComplete())
4940     return None;
4941 
4942   const auto *StoredLocs = getTrailingObjects<SourceLocation>();
4943   return llvm::makeArrayRef(StoredLocs,
4944                             getNumModuleIdentifiers(getImportedModule()));
4945 }
4946 
4947 SourceRange ImportDecl::getSourceRange() const {
4948   if (!isImportComplete())
4949     return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4950 
4951   return SourceRange(getLocation(), getIdentifierLocs().back());
4952 }
4953 
4954 //===----------------------------------------------------------------------===//
4955 // ExportDecl Implementation
4956 //===----------------------------------------------------------------------===//
4957 
4958 void ExportDecl::anchor() {}
4959 
4960 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4961                                SourceLocation ExportLoc) {
4962   return new (C, DC) ExportDecl(DC, ExportLoc);
4963 }
4964 
4965 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4966   return new (C, ID) ExportDecl(nullptr, SourceLocation());
4967 }
4968