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