xref: /freebsd/contrib/llvm-project/clang/lib/AST/Decl.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
10b57cec5SDimitry Andric //===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the Decl subclasses.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "clang/AST/Decl.h"
140b57cec5SDimitry Andric #include "Linkage.h"
150b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
160b57cec5SDimitry Andric #include "clang/AST/ASTDiagnostic.h"
170b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h"
180b57cec5SDimitry Andric #include "clang/AST/ASTMutationListener.h"
19480093f4SDimitry Andric #include "clang/AST/Attr.h"
200b57cec5SDimitry Andric #include "clang/AST/CanonicalType.h"
210b57cec5SDimitry Andric #include "clang/AST/DeclBase.h"
220b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
230b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
240b57cec5SDimitry Andric #include "clang/AST/DeclOpenMP.h"
250b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
260b57cec5SDimitry Andric #include "clang/AST/DeclarationName.h"
270b57cec5SDimitry Andric #include "clang/AST/Expr.h"
280b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
290b57cec5SDimitry Andric #include "clang/AST/ExternalASTSource.h"
300b57cec5SDimitry Andric #include "clang/AST/ODRHash.h"
310b57cec5SDimitry Andric #include "clang/AST/PrettyDeclStackTrace.h"
320b57cec5SDimitry Andric #include "clang/AST/PrettyPrinter.h"
330b57cec5SDimitry Andric #include "clang/AST/Redeclarable.h"
340b57cec5SDimitry Andric #include "clang/AST/Stmt.h"
350b57cec5SDimitry Andric #include "clang/AST/TemplateBase.h"
360b57cec5SDimitry Andric #include "clang/AST/Type.h"
370b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
380b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
390b57cec5SDimitry Andric #include "clang/Basic/IdentifierTable.h"
400b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
410b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
420b57cec5SDimitry Andric #include "clang/Basic/Linkage.h"
430b57cec5SDimitry Andric #include "clang/Basic/Module.h"
44fe6060f1SDimitry Andric #include "clang/Basic/NoSanitizeList.h"
450b57cec5SDimitry Andric #include "clang/Basic/PartialDiagnostic.h"
460b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.h"
470b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
480b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
490b57cec5SDimitry Andric #include "clang/Basic/Specifiers.h"
500b57cec5SDimitry Andric #include "clang/Basic/TargetCXXABI.h"
510b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
520b57cec5SDimitry Andric #include "clang/Basic/Visibility.h"
530b57cec5SDimitry Andric #include "llvm/ADT/APSInt.h"
540b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
550b57cec5SDimitry Andric #include "llvm/ADT/None.h"
560b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
570b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
580b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
590b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
60480093f4SDimitry Andric #include "llvm/ADT/StringSwitch.h"
610b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
620b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
630b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
640b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
650b57cec5SDimitry Andric #include <algorithm>
660b57cec5SDimitry Andric #include <cassert>
670b57cec5SDimitry Andric #include <cstddef>
680b57cec5SDimitry Andric #include <cstring>
690b57cec5SDimitry Andric #include <memory>
700b57cec5SDimitry Andric #include <string>
710b57cec5SDimitry Andric #include <tuple>
720b57cec5SDimitry Andric #include <type_traits>
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric using namespace clang;
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric Decl *clang::getPrimaryMergedDecl(Decl *D) {
770b57cec5SDimitry Andric   return D->getASTContext().getPrimaryMergedDecl(D);
780b57cec5SDimitry Andric }
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
810b57cec5SDimitry Andric   SourceLocation Loc = this->Loc;
820b57cec5SDimitry Andric   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
830b57cec5SDimitry Andric   if (Loc.isValid()) {
840b57cec5SDimitry Andric     Loc.print(OS, Context.getSourceManager());
850b57cec5SDimitry Andric     OS << ": ";
860b57cec5SDimitry Andric   }
870b57cec5SDimitry Andric   OS << Message;
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric   if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
900b57cec5SDimitry Andric     OS << " '";
910b57cec5SDimitry Andric     ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
920b57cec5SDimitry Andric     OS << "'";
930b57cec5SDimitry Andric   }
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric   OS << '\n';
960b57cec5SDimitry Andric }
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric // Defined here so that it can be inlined into its direct callers.
990b57cec5SDimitry Andric bool Decl::isOutOfLine() const {
1000b57cec5SDimitry Andric   return !getLexicalDeclContext()->Equals(getDeclContext());
1010b57cec5SDimitry Andric }
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
1040b57cec5SDimitry Andric     : Decl(TranslationUnit, nullptr, SourceLocation()),
105fe6060f1SDimitry Andric       DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {}
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1080b57cec5SDimitry Andric // NamedDecl Implementation
1090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric // Visibility rules aren't rigorously externally specified, but here
1120b57cec5SDimitry Andric // are the basic principles behind what we implement:
1130b57cec5SDimitry Andric //
1140b57cec5SDimitry Andric // 1. An explicit visibility attribute is generally a direct expression
1150b57cec5SDimitry Andric // of the user's intent and should be honored.  Only the innermost
1160b57cec5SDimitry Andric // visibility attribute applies.  If no visibility attribute applies,
1170b57cec5SDimitry Andric // global visibility settings are considered.
1180b57cec5SDimitry Andric //
1190b57cec5SDimitry Andric // 2. There is one caveat to the above: on or in a template pattern,
1200b57cec5SDimitry Andric // an explicit visibility attribute is just a default rule, and
1210b57cec5SDimitry Andric // visibility can be decreased by the visibility of template
1220b57cec5SDimitry Andric // arguments.  But this, too, has an exception: an attribute on an
1230b57cec5SDimitry Andric // explicit specialization or instantiation causes all the visibility
1240b57cec5SDimitry Andric // restrictions of the template arguments to be ignored.
1250b57cec5SDimitry Andric //
1260b57cec5SDimitry Andric // 3. A variable that does not otherwise have explicit visibility can
1270b57cec5SDimitry Andric // be restricted by the visibility of its type.
1280b57cec5SDimitry Andric //
1290b57cec5SDimitry Andric // 4. A visibility restriction is explicit if it comes from an
1300b57cec5SDimitry Andric // attribute (or something like it), not a global visibility setting.
1310b57cec5SDimitry Andric // When emitting a reference to an external symbol, visibility
1320b57cec5SDimitry Andric // restrictions are ignored unless they are explicit.
1330b57cec5SDimitry Andric //
1340b57cec5SDimitry Andric // 5. When computing the visibility of a non-type, including a
1350b57cec5SDimitry Andric // non-type member of a class, only non-type visibility restrictions
1360b57cec5SDimitry Andric // are considered: the 'visibility' attribute, global value-visibility
1370b57cec5SDimitry Andric // settings, and a few special cases like __private_extern.
1380b57cec5SDimitry Andric //
1390b57cec5SDimitry Andric // 6. When computing the visibility of a type, including a type member
1400b57cec5SDimitry Andric // of a class, only type visibility restrictions are considered:
1410b57cec5SDimitry Andric // the 'type_visibility' attribute and global type-visibility settings.
1420b57cec5SDimitry Andric // However, a 'visibility' attribute counts as a 'type_visibility'
1430b57cec5SDimitry Andric // attribute on any declaration that only has the former.
1440b57cec5SDimitry Andric //
1450b57cec5SDimitry Andric // The visibility of a "secondary" entity, like a template argument,
1460b57cec5SDimitry Andric // is computed using the kind of that entity, not the kind of the
1470b57cec5SDimitry Andric // primary entity for which we are computing visibility.  For example,
1480b57cec5SDimitry Andric // the visibility of a specialization of either of these templates:
1490b57cec5SDimitry Andric //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
1500b57cec5SDimitry Andric //   template <class T, bool (&compare)(T, X)> class matcher;
1510b57cec5SDimitry Andric // is restricted according to the type visibility of the argument 'T',
1520b57cec5SDimitry Andric // the type visibility of 'bool(&)(T,X)', and the value visibility of
1530b57cec5SDimitry Andric // the argument function 'compare'.  That 'has_match' is a value
1540b57cec5SDimitry Andric // and 'matcher' is a type only matters when looking for attributes
1550b57cec5SDimitry Andric // and settings from the immediate context.
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric /// Does this computation kind permit us to consider additional
1580b57cec5SDimitry Andric /// visibility settings from attributes and the like?
1590b57cec5SDimitry Andric static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
1600b57cec5SDimitry Andric   return computation.IgnoreExplicitVisibility;
1610b57cec5SDimitry Andric }
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric /// Given an LVComputationKind, return one of the same type/value sort
1640b57cec5SDimitry Andric /// that records that it already has explicit visibility.
1650b57cec5SDimitry Andric static LVComputationKind
1660b57cec5SDimitry Andric withExplicitVisibilityAlready(LVComputationKind Kind) {
1670b57cec5SDimitry Andric   Kind.IgnoreExplicitVisibility = true;
1680b57cec5SDimitry Andric   return Kind;
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
1720b57cec5SDimitry Andric                                                   LVComputationKind kind) {
1730b57cec5SDimitry Andric   assert(!kind.IgnoreExplicitVisibility &&
1740b57cec5SDimitry Andric          "asking for explicit visibility when we shouldn't be");
1750b57cec5SDimitry Andric   return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric /// Is the given declaration a "type" or a "value" for the purposes of
1790b57cec5SDimitry Andric /// visibility computation?
1800b57cec5SDimitry Andric static bool usesTypeVisibility(const NamedDecl *D) {
1810b57cec5SDimitry Andric   return isa<TypeDecl>(D) ||
1820b57cec5SDimitry Andric          isa<ClassTemplateDecl>(D) ||
1830b57cec5SDimitry Andric          isa<ObjCInterfaceDecl>(D);
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric /// Does the given declaration have member specialization information,
1870b57cec5SDimitry Andric /// and if so, is it an explicit specialization?
1880b57cec5SDimitry Andric template <class T> static typename
1890b57cec5SDimitry Andric std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
1900b57cec5SDimitry Andric isExplicitMemberSpecialization(const T *D) {
1910b57cec5SDimitry Andric   if (const MemberSpecializationInfo *member =
1920b57cec5SDimitry Andric         D->getMemberSpecializationInfo()) {
1930b57cec5SDimitry Andric     return member->isExplicitSpecialization();
1940b57cec5SDimitry Andric   }
1950b57cec5SDimitry Andric   return false;
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric /// For templates, this question is easier: a member template can't be
1990b57cec5SDimitry Andric /// explicitly instantiated, so there's a single bit indicating whether
2000b57cec5SDimitry Andric /// or not this is an explicit member specialization.
2010b57cec5SDimitry Andric static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
2020b57cec5SDimitry Andric   return D->isMemberSpecialization();
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric /// Given a visibility attribute, return the explicit visibility
2060b57cec5SDimitry Andric /// associated with it.
2070b57cec5SDimitry Andric template <class T>
2080b57cec5SDimitry Andric static Visibility getVisibilityFromAttr(const T *attr) {
2090b57cec5SDimitry Andric   switch (attr->getVisibility()) {
2100b57cec5SDimitry Andric   case T::Default:
2110b57cec5SDimitry Andric     return DefaultVisibility;
2120b57cec5SDimitry Andric   case T::Hidden:
2130b57cec5SDimitry Andric     return HiddenVisibility;
2140b57cec5SDimitry Andric   case T::Protected:
2150b57cec5SDimitry Andric     return ProtectedVisibility;
2160b57cec5SDimitry Andric   }
2170b57cec5SDimitry Andric   llvm_unreachable("bad visibility kind");
2180b57cec5SDimitry Andric }
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric /// Return the explicit visibility of the given declaration.
2210b57cec5SDimitry Andric static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
2220b57cec5SDimitry Andric                                     NamedDecl::ExplicitVisibilityKind kind) {
2230b57cec5SDimitry Andric   // If we're ultimately computing the visibility of a type, look for
2240b57cec5SDimitry Andric   // a 'type_visibility' attribute before looking for 'visibility'.
2250b57cec5SDimitry Andric   if (kind == NamedDecl::VisibilityForType) {
2260b57cec5SDimitry Andric     if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
2270b57cec5SDimitry Andric       return getVisibilityFromAttr(A);
2280b57cec5SDimitry Andric     }
2290b57cec5SDimitry Andric   }
2300b57cec5SDimitry Andric 
2310b57cec5SDimitry Andric   // If this declaration has an explicit visibility attribute, use it.
2320b57cec5SDimitry Andric   if (const auto *A = D->getAttr<VisibilityAttr>()) {
2330b57cec5SDimitry Andric     return getVisibilityFromAttr(A);
2340b57cec5SDimitry Andric   }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   return None;
2370b57cec5SDimitry Andric }
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric LinkageInfo LinkageComputer::getLVForType(const Type &T,
2400b57cec5SDimitry Andric                                           LVComputationKind computation) {
2410b57cec5SDimitry Andric   if (computation.IgnoreAllVisibility)
2420b57cec5SDimitry Andric     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
2430b57cec5SDimitry Andric   return getTypeLinkageAndVisibility(&T);
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric /// Get the most restrictive linkage for the types in the given
2470b57cec5SDimitry Andric /// template parameter list.  For visibility purposes, template
2480b57cec5SDimitry Andric /// parameters are part of the signature of a template.
2490b57cec5SDimitry Andric LinkageInfo LinkageComputer::getLVForTemplateParameterList(
2500b57cec5SDimitry Andric     const TemplateParameterList *Params, LVComputationKind computation) {
2510b57cec5SDimitry Andric   LinkageInfo LV;
2520b57cec5SDimitry Andric   for (const NamedDecl *P : *Params) {
2530b57cec5SDimitry Andric     // Template type parameters are the most common and never
2540b57cec5SDimitry Andric     // contribute to visibility, pack or not.
2550b57cec5SDimitry Andric     if (isa<TemplateTypeParmDecl>(P))
2560b57cec5SDimitry Andric       continue;
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric     // Non-type template parameters can be restricted by the value type, e.g.
2590b57cec5SDimitry Andric     //   template <enum X> class A { ... };
2600b57cec5SDimitry Andric     // We have to be careful here, though, because we can be dealing with
2610b57cec5SDimitry Andric     // dependent types.
2620b57cec5SDimitry Andric     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2630b57cec5SDimitry Andric       // Handle the non-pack case first.
2640b57cec5SDimitry Andric       if (!NTTP->isExpandedParameterPack()) {
2650b57cec5SDimitry Andric         if (!NTTP->getType()->isDependentType()) {
2660b57cec5SDimitry Andric           LV.merge(getLVForType(*NTTP->getType(), computation));
2670b57cec5SDimitry Andric         }
2680b57cec5SDimitry Andric         continue;
2690b57cec5SDimitry Andric       }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric       // Look at all the types in an expanded pack.
2720b57cec5SDimitry Andric       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
2730b57cec5SDimitry Andric         QualType type = NTTP->getExpansionType(i);
2740b57cec5SDimitry Andric         if (!type->isDependentType())
2750b57cec5SDimitry Andric           LV.merge(getTypeLinkageAndVisibility(type));
2760b57cec5SDimitry Andric       }
2770b57cec5SDimitry Andric       continue;
2780b57cec5SDimitry Andric     }
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric     // Template template parameters can be restricted by their
2810b57cec5SDimitry Andric     // template parameters, recursively.
2820b57cec5SDimitry Andric     const auto *TTP = cast<TemplateTemplateParmDecl>(P);
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric     // Handle the non-pack case first.
2850b57cec5SDimitry Andric     if (!TTP->isExpandedParameterPack()) {
2860b57cec5SDimitry Andric       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
2870b57cec5SDimitry Andric                                              computation));
2880b57cec5SDimitry Andric       continue;
2890b57cec5SDimitry Andric     }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric     // Look at all expansions in an expanded pack.
2920b57cec5SDimitry Andric     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
2930b57cec5SDimitry Andric            i != n; ++i) {
2940b57cec5SDimitry Andric       LV.merge(getLVForTemplateParameterList(
2950b57cec5SDimitry Andric           TTP->getExpansionTemplateParameters(i), computation));
2960b57cec5SDimitry Andric     }
2970b57cec5SDimitry Andric   }
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   return LV;
3000b57cec5SDimitry Andric }
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
3030b57cec5SDimitry Andric   const Decl *Ret = nullptr;
3040b57cec5SDimitry Andric   const DeclContext *DC = D->getDeclContext();
3050b57cec5SDimitry Andric   while (DC->getDeclKind() != Decl::TranslationUnit) {
3060b57cec5SDimitry Andric     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
3070b57cec5SDimitry Andric       Ret = cast<Decl>(DC);
3080b57cec5SDimitry Andric     DC = DC->getParent();
3090b57cec5SDimitry Andric   }
3100b57cec5SDimitry Andric   return Ret;
3110b57cec5SDimitry Andric }
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric /// Get the most restrictive linkage for the types and
3140b57cec5SDimitry Andric /// declarations in the given template argument list.
3150b57cec5SDimitry Andric ///
3160b57cec5SDimitry Andric /// Note that we don't take an LVComputationKind because we always
3170b57cec5SDimitry Andric /// want to honor the visibility of template arguments in the same way.
3180b57cec5SDimitry Andric LinkageInfo
3190b57cec5SDimitry Andric LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
3200b57cec5SDimitry Andric                                               LVComputationKind computation) {
3210b57cec5SDimitry Andric   LinkageInfo LV;
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric   for (const TemplateArgument &Arg : Args) {
3240b57cec5SDimitry Andric     switch (Arg.getKind()) {
3250b57cec5SDimitry Andric     case TemplateArgument::Null:
3260b57cec5SDimitry Andric     case TemplateArgument::Integral:
3270b57cec5SDimitry Andric     case TemplateArgument::Expression:
3280b57cec5SDimitry Andric       continue;
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric     case TemplateArgument::Type:
3310b57cec5SDimitry Andric       LV.merge(getLVForType(*Arg.getAsType(), computation));
3320b57cec5SDimitry Andric       continue;
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric     case TemplateArgument::Declaration: {
3350b57cec5SDimitry Andric       const NamedDecl *ND = Arg.getAsDecl();
3360b57cec5SDimitry Andric       assert(!usesTypeVisibility(ND));
3370b57cec5SDimitry Andric       LV.merge(getLVForDecl(ND, computation));
3380b57cec5SDimitry Andric       continue;
3390b57cec5SDimitry Andric     }
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric     case TemplateArgument::NullPtr:
3420b57cec5SDimitry Andric       LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
3430b57cec5SDimitry Andric       continue;
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric     case TemplateArgument::Template:
3460b57cec5SDimitry Andric     case TemplateArgument::TemplateExpansion:
3470b57cec5SDimitry Andric       if (TemplateDecl *Template =
3480b57cec5SDimitry Andric               Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
3490b57cec5SDimitry Andric         LV.merge(getLVForDecl(Template, computation));
3500b57cec5SDimitry Andric       continue;
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric     case TemplateArgument::Pack:
3530b57cec5SDimitry Andric       LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
3540b57cec5SDimitry Andric       continue;
3550b57cec5SDimitry Andric     }
3560b57cec5SDimitry Andric     llvm_unreachable("bad template argument kind");
3570b57cec5SDimitry Andric   }
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric   return LV;
3600b57cec5SDimitry Andric }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric LinkageInfo
3630b57cec5SDimitry Andric LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
3640b57cec5SDimitry Andric                                               LVComputationKind computation) {
3650b57cec5SDimitry Andric   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
3660b57cec5SDimitry Andric }
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
3690b57cec5SDimitry Andric                         const FunctionTemplateSpecializationInfo *specInfo) {
3700b57cec5SDimitry Andric   // Include visibility from the template parameters and arguments
3710b57cec5SDimitry Andric   // only if this is not an explicit instantiation or specialization
3720b57cec5SDimitry Andric   // with direct explicit visibility.  (Implicit instantiations won't
3730b57cec5SDimitry Andric   // have a direct attribute.)
3740b57cec5SDimitry Andric   if (!specInfo->isExplicitInstantiationOrSpecialization())
3750b57cec5SDimitry Andric     return true;
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   return !fn->hasAttr<VisibilityAttr>();
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric /// Merge in template-related linkage and visibility for the given
3810b57cec5SDimitry Andric /// function template specialization.
3820b57cec5SDimitry Andric ///
3830b57cec5SDimitry Andric /// We don't need a computation kind here because we can assume
3840b57cec5SDimitry Andric /// LVForValue.
3850b57cec5SDimitry Andric ///
3860b57cec5SDimitry Andric /// \param[out] LV the computation to use for the parent
3870b57cec5SDimitry Andric void LinkageComputer::mergeTemplateLV(
3880b57cec5SDimitry Andric     LinkageInfo &LV, const FunctionDecl *fn,
3890b57cec5SDimitry Andric     const FunctionTemplateSpecializationInfo *specInfo,
3900b57cec5SDimitry Andric     LVComputationKind computation) {
3910b57cec5SDimitry Andric   bool considerVisibility =
3920b57cec5SDimitry Andric     shouldConsiderTemplateVisibility(fn, specInfo);
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   // Merge information from the template parameters.
3950b57cec5SDimitry Andric   FunctionTemplateDecl *temp = specInfo->getTemplate();
3960b57cec5SDimitry Andric   LinkageInfo tempLV =
3970b57cec5SDimitry Andric     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
3980b57cec5SDimitry Andric   LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric   // Merge information from the template arguments.
4010b57cec5SDimitry Andric   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
4020b57cec5SDimitry Andric   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
4030b57cec5SDimitry Andric   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric /// Does the given declaration have a direct visibility attribute
4070b57cec5SDimitry Andric /// that would match the given rules?
4080b57cec5SDimitry Andric static bool hasDirectVisibilityAttribute(const NamedDecl *D,
4090b57cec5SDimitry Andric                                          LVComputationKind computation) {
4100b57cec5SDimitry Andric   if (computation.IgnoreAllVisibility)
4110b57cec5SDimitry Andric     return false;
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
4140b57cec5SDimitry Andric          D->hasAttr<VisibilityAttr>();
4150b57cec5SDimitry Andric }
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric /// Should we consider visibility associated with the template
4180b57cec5SDimitry Andric /// arguments and parameters of the given class template specialization?
4190b57cec5SDimitry Andric static bool shouldConsiderTemplateVisibility(
4200b57cec5SDimitry Andric                                  const ClassTemplateSpecializationDecl *spec,
4210b57cec5SDimitry Andric                                  LVComputationKind computation) {
4220b57cec5SDimitry Andric   // Include visibility from the template parameters and arguments
4230b57cec5SDimitry Andric   // only if this is not an explicit instantiation or specialization
4240b57cec5SDimitry Andric   // with direct explicit visibility (and note that implicit
4250b57cec5SDimitry Andric   // instantiations won't have a direct attribute).
4260b57cec5SDimitry Andric   //
4270b57cec5SDimitry Andric   // Furthermore, we want to ignore template parameters and arguments
4280b57cec5SDimitry Andric   // for an explicit specialization when computing the visibility of a
4290b57cec5SDimitry Andric   // member thereof with explicit visibility.
4300b57cec5SDimitry Andric   //
4310b57cec5SDimitry Andric   // This is a bit complex; let's unpack it.
4320b57cec5SDimitry Andric   //
4330b57cec5SDimitry Andric   // An explicit class specialization is an independent, top-level
4340b57cec5SDimitry Andric   // declaration.  As such, if it or any of its members has an
4350b57cec5SDimitry Andric   // explicit visibility attribute, that must directly express the
4360b57cec5SDimitry Andric   // user's intent, and we should honor it.  The same logic applies to
4370b57cec5SDimitry Andric   // an explicit instantiation of a member of such a thing.
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric   // Fast path: if this is not an explicit instantiation or
4400b57cec5SDimitry Andric   // specialization, we always want to consider template-related
4410b57cec5SDimitry Andric   // visibility restrictions.
4420b57cec5SDimitry Andric   if (!spec->isExplicitInstantiationOrSpecialization())
4430b57cec5SDimitry Andric     return true;
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric   // This is the 'member thereof' check.
4460b57cec5SDimitry Andric   if (spec->isExplicitSpecialization() &&
4470b57cec5SDimitry Andric       hasExplicitVisibilityAlready(computation))
4480b57cec5SDimitry Andric     return false;
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   return !hasDirectVisibilityAttribute(spec, computation);
4510b57cec5SDimitry Andric }
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric /// Merge in template-related linkage and visibility for the given
4540b57cec5SDimitry Andric /// class template specialization.
4550b57cec5SDimitry Andric void LinkageComputer::mergeTemplateLV(
4560b57cec5SDimitry Andric     LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
4570b57cec5SDimitry Andric     LVComputationKind computation) {
4580b57cec5SDimitry Andric   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   // Merge information from the template parameters, but ignore
4610b57cec5SDimitry Andric   // visibility if we're only considering template arguments.
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
4640b57cec5SDimitry Andric   LinkageInfo tempLV =
4650b57cec5SDimitry Andric     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
4660b57cec5SDimitry Andric   LV.mergeMaybeWithVisibility(tempLV,
4670b57cec5SDimitry Andric            considerVisibility && !hasExplicitVisibilityAlready(computation));
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   // Merge information from the template arguments.  We ignore
4700b57cec5SDimitry Andric   // template-argument visibility if we've got an explicit
4710b57cec5SDimitry Andric   // instantiation with a visibility attribute.
4720b57cec5SDimitry Andric   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
4730b57cec5SDimitry Andric   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
4740b57cec5SDimitry Andric   if (considerVisibility)
4750b57cec5SDimitry Andric     LV.mergeVisibility(argsLV);
4760b57cec5SDimitry Andric   LV.mergeExternalVisibility(argsLV);
4770b57cec5SDimitry Andric }
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric /// Should we consider visibility associated with the template
4800b57cec5SDimitry Andric /// arguments and parameters of the given variable template
4810b57cec5SDimitry Andric /// specialization? As usual, follow class template specialization
4820b57cec5SDimitry Andric /// logic up to initialization.
4830b57cec5SDimitry Andric static bool shouldConsiderTemplateVisibility(
4840b57cec5SDimitry Andric                                  const VarTemplateSpecializationDecl *spec,
4850b57cec5SDimitry Andric                                  LVComputationKind computation) {
4860b57cec5SDimitry Andric   // Include visibility from the template parameters and arguments
4870b57cec5SDimitry Andric   // only if this is not an explicit instantiation or specialization
4880b57cec5SDimitry Andric   // with direct explicit visibility (and note that implicit
4890b57cec5SDimitry Andric   // instantiations won't have a direct attribute).
4900b57cec5SDimitry Andric   if (!spec->isExplicitInstantiationOrSpecialization())
4910b57cec5SDimitry Andric     return true;
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   // An explicit variable specialization is an independent, top-level
4940b57cec5SDimitry Andric   // declaration.  As such, if it has an explicit visibility attribute,
4950b57cec5SDimitry Andric   // that must directly express the user's intent, and we should honor
4960b57cec5SDimitry Andric   // it.
4970b57cec5SDimitry Andric   if (spec->isExplicitSpecialization() &&
4980b57cec5SDimitry Andric       hasExplicitVisibilityAlready(computation))
4990b57cec5SDimitry Andric     return false;
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric   return !hasDirectVisibilityAttribute(spec, computation);
5020b57cec5SDimitry Andric }
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric /// Merge in template-related linkage and visibility for the given
5050b57cec5SDimitry Andric /// variable template specialization. As usual, follow class template
5060b57cec5SDimitry Andric /// specialization logic up to initialization.
5070b57cec5SDimitry Andric void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
5080b57cec5SDimitry Andric                                       const VarTemplateSpecializationDecl *spec,
5090b57cec5SDimitry Andric                                       LVComputationKind computation) {
5100b57cec5SDimitry Andric   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   // Merge information from the template parameters, but ignore
5130b57cec5SDimitry Andric   // visibility if we're only considering template arguments.
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   VarTemplateDecl *temp = spec->getSpecializedTemplate();
5160b57cec5SDimitry Andric   LinkageInfo tempLV =
5170b57cec5SDimitry Andric     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
5180b57cec5SDimitry Andric   LV.mergeMaybeWithVisibility(tempLV,
5190b57cec5SDimitry Andric            considerVisibility && !hasExplicitVisibilityAlready(computation));
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric   // Merge information from the template arguments.  We ignore
5220b57cec5SDimitry Andric   // template-argument visibility if we've got an explicit
5230b57cec5SDimitry Andric   // instantiation with a visibility attribute.
5240b57cec5SDimitry Andric   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
5250b57cec5SDimitry Andric   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
5260b57cec5SDimitry Andric   if (considerVisibility)
5270b57cec5SDimitry Andric     LV.mergeVisibility(argsLV);
5280b57cec5SDimitry Andric   LV.mergeExternalVisibility(argsLV);
5290b57cec5SDimitry Andric }
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric static bool useInlineVisibilityHidden(const NamedDecl *D) {
5320b57cec5SDimitry Andric   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
5330b57cec5SDimitry Andric   const LangOptions &Opts = D->getASTContext().getLangOpts();
5340b57cec5SDimitry Andric   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
5350b57cec5SDimitry Andric     return false;
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric   const auto *FD = dyn_cast<FunctionDecl>(D);
5380b57cec5SDimitry Andric   if (!FD)
5390b57cec5SDimitry Andric     return false;
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric   TemplateSpecializationKind TSK = TSK_Undeclared;
5420b57cec5SDimitry Andric   if (FunctionTemplateSpecializationInfo *spec
5430b57cec5SDimitry Andric       = FD->getTemplateSpecializationInfo()) {
5440b57cec5SDimitry Andric     TSK = spec->getTemplateSpecializationKind();
5450b57cec5SDimitry Andric   } else if (MemberSpecializationInfo *MSI =
5460b57cec5SDimitry Andric              FD->getMemberSpecializationInfo()) {
5470b57cec5SDimitry Andric     TSK = MSI->getTemplateSpecializationKind();
5480b57cec5SDimitry Andric   }
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   const FunctionDecl *Def = nullptr;
5510b57cec5SDimitry Andric   // InlineVisibilityHidden only applies to definitions, and
5520b57cec5SDimitry Andric   // isInlined() only gives meaningful answers on definitions
5530b57cec5SDimitry Andric   // anyway.
5540b57cec5SDimitry Andric   return TSK != TSK_ExplicitInstantiationDeclaration &&
5550b57cec5SDimitry Andric     TSK != TSK_ExplicitInstantiationDefinition &&
5560b57cec5SDimitry Andric     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
5570b57cec5SDimitry Andric }
5580b57cec5SDimitry Andric 
5590b57cec5SDimitry Andric template <typename T> static bool isFirstInExternCContext(T *D) {
5600b57cec5SDimitry Andric   const T *First = D->getFirstDecl();
5610b57cec5SDimitry Andric   return First->isInExternCContext();
5620b57cec5SDimitry Andric }
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric static bool isSingleLineLanguageLinkage(const Decl &D) {
5650b57cec5SDimitry Andric   if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
5660b57cec5SDimitry Andric     if (!SD->hasBraces())
5670b57cec5SDimitry Andric       return true;
5680b57cec5SDimitry Andric   return false;
5690b57cec5SDimitry Andric }
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric /// Determine whether D is declared in the purview of a named module.
5720b57cec5SDimitry Andric static bool isInModulePurview(const NamedDecl *D) {
5730b57cec5SDimitry Andric   if (auto *M = D->getOwningModule())
5740b57cec5SDimitry Andric     return M->isModulePurview();
5750b57cec5SDimitry Andric   return false;
5760b57cec5SDimitry Andric }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
5790b57cec5SDimitry Andric   // FIXME: Handle isModulePrivate.
5800b57cec5SDimitry Andric   switch (D->getModuleOwnershipKind()) {
5810b57cec5SDimitry Andric   case Decl::ModuleOwnershipKind::Unowned:
5820b57cec5SDimitry Andric   case Decl::ModuleOwnershipKind::ModulePrivate:
5830b57cec5SDimitry Andric     return false;
5840b57cec5SDimitry Andric   case Decl::ModuleOwnershipKind::Visible:
5850b57cec5SDimitry Andric   case Decl::ModuleOwnershipKind::VisibleWhenImported:
5860b57cec5SDimitry Andric     return isInModulePurview(D);
5870b57cec5SDimitry Andric   }
5880b57cec5SDimitry Andric   llvm_unreachable("unexpected module ownership kind");
5890b57cec5SDimitry Andric }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
5920b57cec5SDimitry Andric   // Internal linkage declarations within a module interface unit are modeled
5930b57cec5SDimitry Andric   // as "module-internal linkage", which means that they have internal linkage
5940b57cec5SDimitry Andric   // formally but can be indirectly accessed from outside the module via inline
5950b57cec5SDimitry Andric   // functions and templates defined within the module.
5960b57cec5SDimitry Andric   if (isInModulePurview(D))
5970b57cec5SDimitry Andric     return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
5980b57cec5SDimitry Andric 
5990b57cec5SDimitry Andric   return LinkageInfo::internal();
6000b57cec5SDimitry Andric }
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
6030b57cec5SDimitry Andric   // C++ Modules TS [basic.link]/6.8:
6040b57cec5SDimitry Andric   //   - A name declared at namespace scope that does not have internal linkage
6050b57cec5SDimitry Andric   //     by the previous rules and that is introduced by a non-exported
6060b57cec5SDimitry Andric   //     declaration has module linkage.
6070b57cec5SDimitry Andric   if (isInModulePurview(D) && !isExportedFromModuleInterfaceUnit(
6080b57cec5SDimitry Andric                                   cast<NamedDecl>(D->getCanonicalDecl())))
6090b57cec5SDimitry Andric     return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric   return LinkageInfo::external();
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric static StorageClass getStorageClass(const Decl *D) {
6150b57cec5SDimitry Andric   if (auto *TD = dyn_cast<TemplateDecl>(D))
6160b57cec5SDimitry Andric     D = TD->getTemplatedDecl();
6170b57cec5SDimitry Andric   if (D) {
6180b57cec5SDimitry Andric     if (auto *VD = dyn_cast<VarDecl>(D))
6190b57cec5SDimitry Andric       return VD->getStorageClass();
6200b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
6210b57cec5SDimitry Andric       return FD->getStorageClass();
6220b57cec5SDimitry Andric   }
6230b57cec5SDimitry Andric   return SC_None;
6240b57cec5SDimitry Andric }
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric LinkageInfo
6270b57cec5SDimitry Andric LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
6280b57cec5SDimitry Andric                                             LVComputationKind computation,
6290b57cec5SDimitry Andric                                             bool IgnoreVarTypeLinkage) {
6300b57cec5SDimitry Andric   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
6310b57cec5SDimitry Andric          "Not a name having namespace scope");
6320b57cec5SDimitry Andric   ASTContext &Context = D->getASTContext();
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric   // C++ [basic.link]p3:
6350b57cec5SDimitry Andric   //   A name having namespace scope (3.3.6) has internal linkage if it
6360b57cec5SDimitry Andric   //   is the name of
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
6390b57cec5SDimitry Andric     // - a variable, variable template, function, or function template
6400b57cec5SDimitry Andric     //   that is explicitly declared static; or
6410b57cec5SDimitry Andric     // (This bullet corresponds to C99 6.2.2p3.)
6420b57cec5SDimitry Andric     return getInternalLinkageFor(D);
6430b57cec5SDimitry Andric   }
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   if (const auto *Var = dyn_cast<VarDecl>(D)) {
6460b57cec5SDimitry Andric     // - a non-template variable of non-volatile const-qualified type, unless
6470b57cec5SDimitry Andric     //   - it is explicitly declared extern, or
6480b57cec5SDimitry Andric     //   - it is inline or exported, or
6490b57cec5SDimitry Andric     //   - it was previously declared and the prior declaration did not have
6500b57cec5SDimitry Andric     //     internal linkage
6510b57cec5SDimitry Andric     // (There is no equivalent in C99.)
6520b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus &&
6530b57cec5SDimitry Andric         Var->getType().isConstQualified() &&
6540b57cec5SDimitry Andric         !Var->getType().isVolatileQualified() &&
6550b57cec5SDimitry Andric         !Var->isInline() &&
6560b57cec5SDimitry Andric         !isExportedFromModuleInterfaceUnit(Var) &&
6570b57cec5SDimitry Andric         !isa<VarTemplateSpecializationDecl>(Var) &&
6580b57cec5SDimitry Andric         !Var->getDescribedVarTemplate()) {
6590b57cec5SDimitry Andric       const VarDecl *PrevVar = Var->getPreviousDecl();
6600b57cec5SDimitry Andric       if (PrevVar)
6610b57cec5SDimitry Andric         return getLVForDecl(PrevVar, computation);
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric       if (Var->getStorageClass() != SC_Extern &&
6640b57cec5SDimitry Andric           Var->getStorageClass() != SC_PrivateExtern &&
6650b57cec5SDimitry Andric           !isSingleLineLanguageLinkage(*Var))
6660b57cec5SDimitry Andric         return getInternalLinkageFor(Var);
6670b57cec5SDimitry Andric     }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
6700b57cec5SDimitry Andric          PrevVar = PrevVar->getPreviousDecl()) {
6710b57cec5SDimitry Andric       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
6720b57cec5SDimitry Andric           Var->getStorageClass() == SC_None)
6730b57cec5SDimitry Andric         return getDeclLinkageAndVisibility(PrevVar);
6740b57cec5SDimitry Andric       // Explicitly declared static.
6750b57cec5SDimitry Andric       if (PrevVar->getStorageClass() == SC_Static)
6760b57cec5SDimitry Andric         return getInternalLinkageFor(Var);
6770b57cec5SDimitry Andric     }
6780b57cec5SDimitry Andric   } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
6790b57cec5SDimitry Andric     //   - a data member of an anonymous union.
6800b57cec5SDimitry Andric     const VarDecl *VD = IFD->getVarDecl();
6810b57cec5SDimitry Andric     assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
6820b57cec5SDimitry Andric     return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
6830b57cec5SDimitry Andric   }
6840b57cec5SDimitry Andric   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   // FIXME: This gives internal linkage to names that should have no linkage
6870b57cec5SDimitry Andric   // (those not covered by [basic.link]p6).
6880b57cec5SDimitry Andric   if (D->isInAnonymousNamespace()) {
6890b57cec5SDimitry Andric     const auto *Var = dyn_cast<VarDecl>(D);
6900b57cec5SDimitry Andric     const auto *Func = dyn_cast<FunctionDecl>(D);
6910b57cec5SDimitry Andric     // FIXME: The check for extern "C" here is not justified by the standard
6920b57cec5SDimitry Andric     // wording, but we retain it from the pre-DR1113 model to avoid breaking
6930b57cec5SDimitry Andric     // code.
6940b57cec5SDimitry Andric     //
6950b57cec5SDimitry Andric     // C++11 [basic.link]p4:
6960b57cec5SDimitry Andric     //   An unnamed namespace or a namespace declared directly or indirectly
6970b57cec5SDimitry Andric     //   within an unnamed namespace has internal linkage.
6980b57cec5SDimitry Andric     if ((!Var || !isFirstInExternCContext(Var)) &&
6990b57cec5SDimitry Andric         (!Func || !isFirstInExternCContext(Func)))
7000b57cec5SDimitry Andric       return getInternalLinkageFor(D);
7010b57cec5SDimitry Andric   }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   // Set up the defaults.
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   // C99 6.2.2p5:
7060b57cec5SDimitry Andric   //   If the declaration of an identifier for an object has file
7070b57cec5SDimitry Andric   //   scope and no storage-class specifier, its linkage is
7080b57cec5SDimitry Andric   //   external.
7090b57cec5SDimitry Andric   LinkageInfo LV = getExternalLinkageFor(D);
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric   if (!hasExplicitVisibilityAlready(computation)) {
7120b57cec5SDimitry Andric     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
7130b57cec5SDimitry Andric       LV.mergeVisibility(*Vis, true);
7140b57cec5SDimitry Andric     } else {
7150b57cec5SDimitry Andric       // If we're declared in a namespace with a visibility attribute,
7160b57cec5SDimitry Andric       // use that namespace's visibility, and it still counts as explicit.
7170b57cec5SDimitry Andric       for (const DeclContext *DC = D->getDeclContext();
7180b57cec5SDimitry Andric            !isa<TranslationUnitDecl>(DC);
7190b57cec5SDimitry Andric            DC = DC->getParent()) {
7200b57cec5SDimitry Andric         const auto *ND = dyn_cast<NamespaceDecl>(DC);
7210b57cec5SDimitry Andric         if (!ND) continue;
7220b57cec5SDimitry Andric         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
7230b57cec5SDimitry Andric           LV.mergeVisibility(*Vis, true);
7240b57cec5SDimitry Andric           break;
7250b57cec5SDimitry Andric         }
7260b57cec5SDimitry Andric       }
7270b57cec5SDimitry Andric     }
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric     // Add in global settings if the above didn't give us direct visibility.
7300b57cec5SDimitry Andric     if (!LV.isVisibilityExplicit()) {
7310b57cec5SDimitry Andric       // Use global type/value visibility as appropriate.
7320b57cec5SDimitry Andric       Visibility globalVisibility =
7330b57cec5SDimitry Andric           computation.isValueVisibility()
7340b57cec5SDimitry Andric               ? Context.getLangOpts().getValueVisibilityMode()
7350b57cec5SDimitry Andric               : Context.getLangOpts().getTypeVisibilityMode();
7360b57cec5SDimitry Andric       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric       // If we're paying attention to global visibility, apply
7390b57cec5SDimitry Andric       // -finline-visibility-hidden if this is an inline method.
7400b57cec5SDimitry Andric       if (useInlineVisibilityHidden(D))
7410b57cec5SDimitry Andric         LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
7420b57cec5SDimitry Andric     }
7430b57cec5SDimitry Andric   }
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   // C++ [basic.link]p4:
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric   //   A name having namespace scope that has not been given internal linkage
7480b57cec5SDimitry Andric   //   above and that is the name of
7490b57cec5SDimitry Andric   //   [...bullets...]
7500b57cec5SDimitry Andric   //   has its linkage determined as follows:
7510b57cec5SDimitry Andric   //     - if the enclosing namespace has internal linkage, the name has
7520b57cec5SDimitry Andric   //       internal linkage; [handled above]
7530b57cec5SDimitry Andric   //     - otherwise, if the declaration of the name is attached to a named
7540b57cec5SDimitry Andric   //       module and is not exported, the name has module linkage;
7550b57cec5SDimitry Andric   //     - otherwise, the name has external linkage.
7560b57cec5SDimitry Andric   // LV is currently set up to handle the last two bullets.
7570b57cec5SDimitry Andric   //
7580b57cec5SDimitry Andric   //   The bullets are:
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   //     - a variable; or
7610b57cec5SDimitry Andric   if (const auto *Var = dyn_cast<VarDecl>(D)) {
7620b57cec5SDimitry Andric     // GCC applies the following optimization to variables and static
7630b57cec5SDimitry Andric     // data members, but not to functions:
7640b57cec5SDimitry Andric     //
7650b57cec5SDimitry Andric     // Modify the variable's LV by the LV of its type unless this is
7660b57cec5SDimitry Andric     // C or extern "C".  This follows from [basic.link]p9:
7670b57cec5SDimitry Andric     //   A type without linkage shall not be used as the type of a
7680b57cec5SDimitry Andric     //   variable or function with external linkage unless
7690b57cec5SDimitry Andric     //    - the entity has C language linkage, or
7700b57cec5SDimitry Andric     //    - the entity is declared within an unnamed namespace, or
7710b57cec5SDimitry Andric     //    - the entity is not used or is defined in the same
7720b57cec5SDimitry Andric     //      translation unit.
7730b57cec5SDimitry Andric     // and [basic.link]p10:
7740b57cec5SDimitry Andric     //   ...the types specified by all declarations referring to a
7750b57cec5SDimitry Andric     //   given variable or function shall be identical...
7760b57cec5SDimitry Andric     // C does not have an equivalent rule.
7770b57cec5SDimitry Andric     //
7780b57cec5SDimitry Andric     // Ignore this if we've got an explicit attribute;  the user
7790b57cec5SDimitry Andric     // probably knows what they're doing.
7800b57cec5SDimitry Andric     //
7810b57cec5SDimitry Andric     // Note that we don't want to make the variable non-external
7820b57cec5SDimitry Andric     // because of this, but unique-external linkage suits us.
7830b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
7840b57cec5SDimitry Andric         !IgnoreVarTypeLinkage) {
7850b57cec5SDimitry Andric       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
7860b57cec5SDimitry Andric       if (!isExternallyVisible(TypeLV.getLinkage()))
7870b57cec5SDimitry Andric         return LinkageInfo::uniqueExternal();
7880b57cec5SDimitry Andric       if (!LV.isVisibilityExplicit())
7890b57cec5SDimitry Andric         LV.mergeVisibility(TypeLV);
7900b57cec5SDimitry Andric     }
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric     if (Var->getStorageClass() == SC_PrivateExtern)
7930b57cec5SDimitry Andric       LV.mergeVisibility(HiddenVisibility, true);
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric     // Note that Sema::MergeVarDecl already takes care of implementing
7960b57cec5SDimitry Andric     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
7970b57cec5SDimitry Andric     // to do it here.
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric     // As per function and class template specializations (below),
8000b57cec5SDimitry Andric     // consider LV for the template and template arguments.  We're at file
8010b57cec5SDimitry Andric     // scope, so we do not need to worry about nested specializations.
8020b57cec5SDimitry Andric     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
8030b57cec5SDimitry Andric       mergeTemplateLV(LV, spec, computation);
8040b57cec5SDimitry Andric     }
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   //     - a function; or
8070b57cec5SDimitry Andric   } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
8080b57cec5SDimitry Andric     // In theory, we can modify the function's LV by the LV of its
8090b57cec5SDimitry Andric     // type unless it has C linkage (see comment above about variables
8100b57cec5SDimitry Andric     // for justification).  In practice, GCC doesn't do this, so it's
8110b57cec5SDimitry Andric     // just too painful to make work.
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric     if (Function->getStorageClass() == SC_PrivateExtern)
8140b57cec5SDimitry Andric       LV.mergeVisibility(HiddenVisibility, true);
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
8170b57cec5SDimitry Andric     // merging storage classes and visibility attributes, so we don't have to
8180b57cec5SDimitry Andric     // look at previous decls in here.
8190b57cec5SDimitry Andric 
8200b57cec5SDimitry Andric     // In C++, then if the type of the function uses a type with
8210b57cec5SDimitry Andric     // unique-external linkage, it's not legally usable from outside
8220b57cec5SDimitry Andric     // this translation unit.  However, we should use the C linkage
8230b57cec5SDimitry Andric     // rules instead for extern "C" declarations.
8240b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
8250b57cec5SDimitry Andric       // Only look at the type-as-written. Otherwise, deducing the return type
8260b57cec5SDimitry Andric       // of a function could change its linkage.
8270b57cec5SDimitry Andric       QualType TypeAsWritten = Function->getType();
8280b57cec5SDimitry Andric       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
8290b57cec5SDimitry Andric         TypeAsWritten = TSI->getType();
8300b57cec5SDimitry Andric       if (!isExternallyVisible(TypeAsWritten->getLinkage()))
8310b57cec5SDimitry Andric         return LinkageInfo::uniqueExternal();
8320b57cec5SDimitry Andric     }
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric     // Consider LV from the template and the template arguments.
8350b57cec5SDimitry Andric     // We're at file scope, so we do not need to worry about nested
8360b57cec5SDimitry Andric     // specializations.
8370b57cec5SDimitry Andric     if (FunctionTemplateSpecializationInfo *specInfo
8380b57cec5SDimitry Andric                                = Function->getTemplateSpecializationInfo()) {
8390b57cec5SDimitry Andric       mergeTemplateLV(LV, Function, specInfo, computation);
8400b57cec5SDimitry Andric     }
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric   //     - a named class (Clause 9), or an unnamed class defined in a
8430b57cec5SDimitry Andric   //       typedef declaration in which the class has the typedef name
8440b57cec5SDimitry Andric   //       for linkage purposes (7.1.3); or
8450b57cec5SDimitry Andric   //     - a named enumeration (7.2), or an unnamed enumeration
8460b57cec5SDimitry Andric   //       defined in a typedef declaration in which the enumeration
8470b57cec5SDimitry Andric   //       has the typedef name for linkage purposes (7.1.3); or
8480b57cec5SDimitry Andric   } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
8490b57cec5SDimitry Andric     // Unnamed tags have no linkage.
8500b57cec5SDimitry Andric     if (!Tag->hasNameForLinkage())
8510b57cec5SDimitry Andric       return LinkageInfo::none();
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric     // If this is a class template specialization, consider the
8540b57cec5SDimitry Andric     // linkage of the template and template arguments.  We're at file
8550b57cec5SDimitry Andric     // scope, so we do not need to worry about nested specializations.
8560b57cec5SDimitry Andric     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
8570b57cec5SDimitry Andric       mergeTemplateLV(LV, spec, computation);
8580b57cec5SDimitry Andric     }
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   // FIXME: This is not part of the C++ standard any more.
8610b57cec5SDimitry Andric   //     - an enumerator belonging to an enumeration with external linkage; or
8620b57cec5SDimitry Andric   } else if (isa<EnumConstantDecl>(D)) {
8630b57cec5SDimitry Andric     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
8640b57cec5SDimitry Andric                                       computation);
8650b57cec5SDimitry Andric     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
8660b57cec5SDimitry Andric       return LinkageInfo::none();
8670b57cec5SDimitry Andric     LV.merge(EnumLV);
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric   //     - a template
8700b57cec5SDimitry Andric   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
8710b57cec5SDimitry Andric     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
8720b57cec5SDimitry Andric     LinkageInfo tempLV =
8730b57cec5SDimitry Andric       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
8740b57cec5SDimitry Andric     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   //     An unnamed namespace or a namespace declared directly or indirectly
8770b57cec5SDimitry Andric   //     within an unnamed namespace has internal linkage. All other namespaces
8780b57cec5SDimitry Andric   //     have external linkage.
8790b57cec5SDimitry Andric   //
8800b57cec5SDimitry Andric   // We handled names in anonymous namespaces above.
8810b57cec5SDimitry Andric   } else if (isa<NamespaceDecl>(D)) {
8820b57cec5SDimitry Andric     return LV;
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   // By extension, we assign external linkage to Objective-C
8850b57cec5SDimitry Andric   // interfaces.
8860b57cec5SDimitry Andric   } else if (isa<ObjCInterfaceDecl>(D)) {
8870b57cec5SDimitry Andric     // fallout
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
8900b57cec5SDimitry Andric     // A typedef declaration has linkage if it gives a type a name for
8910b57cec5SDimitry Andric     // linkage purposes.
8920b57cec5SDimitry Andric     if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
8930b57cec5SDimitry Andric       return LinkageInfo::none();
8940b57cec5SDimitry Andric 
8955ffd83dbSDimitry Andric   } else if (isa<MSGuidDecl>(D)) {
8965ffd83dbSDimitry Andric     // A GUID behaves like an inline variable with external linkage. Fall
8975ffd83dbSDimitry Andric     // through.
8985ffd83dbSDimitry Andric 
8990b57cec5SDimitry Andric   // Everything not covered here has no linkage.
9000b57cec5SDimitry Andric   } else {
9010b57cec5SDimitry Andric     return LinkageInfo::none();
9020b57cec5SDimitry Andric   }
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric   // If we ended up with non-externally-visible linkage, visibility should
9050b57cec5SDimitry Andric   // always be default.
9060b57cec5SDimitry Andric   if (!isExternallyVisible(LV.getLinkage()))
9070b57cec5SDimitry Andric     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
9080b57cec5SDimitry Andric 
909480093f4SDimitry Andric   // Mark the symbols as hidden when compiling for the device.
910480093f4SDimitry Andric   if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice)
911480093f4SDimitry Andric     LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
912480093f4SDimitry Andric 
9130b57cec5SDimitry Andric   return LV;
9140b57cec5SDimitry Andric }
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric LinkageInfo
9170b57cec5SDimitry Andric LinkageComputer::getLVForClassMember(const NamedDecl *D,
9180b57cec5SDimitry Andric                                      LVComputationKind computation,
9190b57cec5SDimitry Andric                                      bool IgnoreVarTypeLinkage) {
9200b57cec5SDimitry Andric   // Only certain class members have linkage.  Note that fields don't
9210b57cec5SDimitry Andric   // really have linkage, but it's convenient to say they do for the
9220b57cec5SDimitry Andric   // purposes of calculating linkage of pointer-to-data-member
9230b57cec5SDimitry Andric   // template arguments.
9240b57cec5SDimitry Andric   //
9250b57cec5SDimitry Andric   // Templates also don't officially have linkage, but since we ignore
9260b57cec5SDimitry Andric   // the C++ standard and look at template arguments when determining
9270b57cec5SDimitry Andric   // linkage and visibility of a template specialization, we might hit
9280b57cec5SDimitry Andric   // a template template argument that way. If we do, we need to
9290b57cec5SDimitry Andric   // consider its linkage.
9300b57cec5SDimitry Andric   if (!(isa<CXXMethodDecl>(D) ||
9310b57cec5SDimitry Andric         isa<VarDecl>(D) ||
9320b57cec5SDimitry Andric         isa<FieldDecl>(D) ||
9330b57cec5SDimitry Andric         isa<IndirectFieldDecl>(D) ||
9340b57cec5SDimitry Andric         isa<TagDecl>(D) ||
9350b57cec5SDimitry Andric         isa<TemplateDecl>(D)))
9360b57cec5SDimitry Andric     return LinkageInfo::none();
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   LinkageInfo LV;
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   // If we have an explicit visibility attribute, merge that in.
9410b57cec5SDimitry Andric   if (!hasExplicitVisibilityAlready(computation)) {
9420b57cec5SDimitry Andric     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
9430b57cec5SDimitry Andric       LV.mergeVisibility(*Vis, true);
9440b57cec5SDimitry Andric     // If we're paying attention to global visibility, apply
9450b57cec5SDimitry Andric     // -finline-visibility-hidden if this is an inline method.
9460b57cec5SDimitry Andric     //
9470b57cec5SDimitry Andric     // Note that we do this before merging information about
9480b57cec5SDimitry Andric     // the class visibility.
9490b57cec5SDimitry Andric     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
9500b57cec5SDimitry Andric       LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
9510b57cec5SDimitry Andric   }
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric   // If this class member has an explicit visibility attribute, the only
9540b57cec5SDimitry Andric   // thing that can change its visibility is the template arguments, so
9550b57cec5SDimitry Andric   // only look for them when processing the class.
9560b57cec5SDimitry Andric   LVComputationKind classComputation = computation;
9570b57cec5SDimitry Andric   if (LV.isVisibilityExplicit())
9580b57cec5SDimitry Andric     classComputation = withExplicitVisibilityAlready(computation);
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   LinkageInfo classLV =
9610b57cec5SDimitry Andric     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
9620b57cec5SDimitry Andric   // The member has the same linkage as the class. If that's not externally
9630b57cec5SDimitry Andric   // visible, we don't need to compute anything about the linkage.
9640b57cec5SDimitry Andric   // FIXME: If we're only computing linkage, can we bail out here?
9650b57cec5SDimitry Andric   if (!isExternallyVisible(classLV.getLinkage()))
9660b57cec5SDimitry Andric     return classLV;
9670b57cec5SDimitry Andric 
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric   // Otherwise, don't merge in classLV yet, because in certain cases
9700b57cec5SDimitry Andric   // we need to completely ignore the visibility from it.
9710b57cec5SDimitry Andric 
9720b57cec5SDimitry Andric   // Specifically, if this decl exists and has an explicit attribute.
9730b57cec5SDimitry Andric   const NamedDecl *explicitSpecSuppressor = nullptr;
9740b57cec5SDimitry Andric 
9750b57cec5SDimitry Andric   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
9760b57cec5SDimitry Andric     // Only look at the type-as-written. Otherwise, deducing the return type
9770b57cec5SDimitry Andric     // of a function could change its linkage.
9780b57cec5SDimitry Andric     QualType TypeAsWritten = MD->getType();
9790b57cec5SDimitry Andric     if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
9800b57cec5SDimitry Andric       TypeAsWritten = TSI->getType();
9810b57cec5SDimitry Andric     if (!isExternallyVisible(TypeAsWritten->getLinkage()))
9820b57cec5SDimitry Andric       return LinkageInfo::uniqueExternal();
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric     // If this is a method template specialization, use the linkage for
9850b57cec5SDimitry Andric     // the template parameters and arguments.
9860b57cec5SDimitry Andric     if (FunctionTemplateSpecializationInfo *spec
9870b57cec5SDimitry Andric            = MD->getTemplateSpecializationInfo()) {
9880b57cec5SDimitry Andric       mergeTemplateLV(LV, MD, spec, computation);
9890b57cec5SDimitry Andric       if (spec->isExplicitSpecialization()) {
9900b57cec5SDimitry Andric         explicitSpecSuppressor = MD;
9910b57cec5SDimitry Andric       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
9920b57cec5SDimitry Andric         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
9930b57cec5SDimitry Andric       }
9940b57cec5SDimitry Andric     } else if (isExplicitMemberSpecialization(MD)) {
9950b57cec5SDimitry Andric       explicitSpecSuppressor = MD;
9960b57cec5SDimitry Andric     }
9970b57cec5SDimitry Andric 
9980b57cec5SDimitry Andric   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9990b57cec5SDimitry Andric     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
10000b57cec5SDimitry Andric       mergeTemplateLV(LV, spec, computation);
10010b57cec5SDimitry Andric       if (spec->isExplicitSpecialization()) {
10020b57cec5SDimitry Andric         explicitSpecSuppressor = spec;
10030b57cec5SDimitry Andric       } else {
10040b57cec5SDimitry Andric         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
10050b57cec5SDimitry Andric         if (isExplicitMemberSpecialization(temp)) {
10060b57cec5SDimitry Andric           explicitSpecSuppressor = temp->getTemplatedDecl();
10070b57cec5SDimitry Andric         }
10080b57cec5SDimitry Andric       }
10090b57cec5SDimitry Andric     } else if (isExplicitMemberSpecialization(RD)) {
10100b57cec5SDimitry Andric       explicitSpecSuppressor = RD;
10110b57cec5SDimitry Andric     }
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric   // Static data members.
10140b57cec5SDimitry Andric   } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
10150b57cec5SDimitry Andric     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
10160b57cec5SDimitry Andric       mergeTemplateLV(LV, spec, computation);
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric     // Modify the variable's linkage by its type, but ignore the
10190b57cec5SDimitry Andric     // type's visibility unless it's a definition.
10200b57cec5SDimitry Andric     if (!IgnoreVarTypeLinkage) {
10210b57cec5SDimitry Andric       LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
10220b57cec5SDimitry Andric       // FIXME: If the type's linkage is not externally visible, we can
10230b57cec5SDimitry Andric       // give this static data member UniqueExternalLinkage.
10240b57cec5SDimitry Andric       if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
10250b57cec5SDimitry Andric         LV.mergeVisibility(typeLV);
10260b57cec5SDimitry Andric       LV.mergeExternalVisibility(typeLV);
10270b57cec5SDimitry Andric     }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric     if (isExplicitMemberSpecialization(VD)) {
10300b57cec5SDimitry Andric       explicitSpecSuppressor = VD;
10310b57cec5SDimitry Andric     }
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric   // Template members.
10340b57cec5SDimitry Andric   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
10350b57cec5SDimitry Andric     bool considerVisibility =
10360b57cec5SDimitry Andric       (!LV.isVisibilityExplicit() &&
10370b57cec5SDimitry Andric        !classLV.isVisibilityExplicit() &&
10380b57cec5SDimitry Andric        !hasExplicitVisibilityAlready(computation));
10390b57cec5SDimitry Andric     LinkageInfo tempLV =
10400b57cec5SDimitry Andric       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
10410b57cec5SDimitry Andric     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric     if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
10440b57cec5SDimitry Andric       if (isExplicitMemberSpecialization(redeclTemp)) {
10450b57cec5SDimitry Andric         explicitSpecSuppressor = temp->getTemplatedDecl();
10460b57cec5SDimitry Andric       }
10470b57cec5SDimitry Andric     }
10480b57cec5SDimitry Andric   }
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric   // We should never be looking for an attribute directly on a template.
10510b57cec5SDimitry Andric   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric   // If this member is an explicit member specialization, and it has
10540b57cec5SDimitry Andric   // an explicit attribute, ignore visibility from the parent.
10550b57cec5SDimitry Andric   bool considerClassVisibility = true;
10560b57cec5SDimitry Andric   if (explicitSpecSuppressor &&
10570b57cec5SDimitry Andric       // optimization: hasDVA() is true only with explicit visibility.
10580b57cec5SDimitry Andric       LV.isVisibilityExplicit() &&
10590b57cec5SDimitry Andric       classLV.getVisibility() != DefaultVisibility &&
10600b57cec5SDimitry Andric       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
10610b57cec5SDimitry Andric     considerClassVisibility = false;
10620b57cec5SDimitry Andric   }
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   // Finally, merge in information from the class.
10650b57cec5SDimitry Andric   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
10660b57cec5SDimitry Andric   return LV;
10670b57cec5SDimitry Andric }
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric void NamedDecl::anchor() {}
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric bool NamedDecl::isLinkageValid() const {
10720b57cec5SDimitry Andric   if (!hasCachedLinkage())
10730b57cec5SDimitry Andric     return true;
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric   Linkage L = LinkageComputer{}
10760b57cec5SDimitry Andric                   .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
10770b57cec5SDimitry Andric                   .getLinkage();
10780b57cec5SDimitry Andric   return L == getCachedLinkage();
10790b57cec5SDimitry Andric }
10800b57cec5SDimitry Andric 
1081fe6060f1SDimitry Andric ReservedIdentifierStatus
1082fe6060f1SDimitry Andric NamedDecl::isReserved(const LangOptions &LangOpts) const {
1083fe6060f1SDimitry Andric   const IdentifierInfo *II = getIdentifier();
1084fe6060f1SDimitry Andric 
1085fe6060f1SDimitry Andric   // This triggers at least for CXXLiteralIdentifiers, which we already checked
1086fe6060f1SDimitry Andric   // at lexing time.
1087fe6060f1SDimitry Andric   if (!II)
1088fe6060f1SDimitry Andric     return ReservedIdentifierStatus::NotReserved;
1089fe6060f1SDimitry Andric 
1090fe6060f1SDimitry Andric   ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1091*349cc55cSDimitry Andric   if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {
1092*349cc55cSDimitry Andric     // This name is only reserved at global scope. Check if this declaration
1093*349cc55cSDimitry Andric     // conflicts with a global scope declaration.
1094fe6060f1SDimitry Andric     if (isa<ParmVarDecl>(this) || isTemplateParameter())
1095fe6060f1SDimitry Andric       return ReservedIdentifierStatus::NotReserved;
1096*349cc55cSDimitry Andric 
1097*349cc55cSDimitry Andric     // C++ [dcl.link]/7:
1098*349cc55cSDimitry Andric     //   Two declarations [conflict] if [...] one declares a function or
1099*349cc55cSDimitry Andric     //   variable with C language linkage, and the other declares [...] a
1100*349cc55cSDimitry Andric     //   variable that belongs to the global scope.
1101*349cc55cSDimitry Andric     //
1102*349cc55cSDimitry Andric     // Therefore names that are reserved at global scope are also reserved as
1103*349cc55cSDimitry Andric     // names of variables and functions with C language linkage.
1104fe6060f1SDimitry Andric     const DeclContext *DC = getDeclContext()->getRedeclContext();
1105*349cc55cSDimitry Andric     if (DC->isTranslationUnit())
1106*349cc55cSDimitry Andric       return Status;
1107*349cc55cSDimitry Andric     if (auto *VD = dyn_cast<VarDecl>(this))
1108*349cc55cSDimitry Andric       if (VD->isExternC())
1109*349cc55cSDimitry Andric         return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1110*349cc55cSDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(this))
1111*349cc55cSDimitry Andric       if (FD->isExternC())
1112*349cc55cSDimitry Andric         return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1113fe6060f1SDimitry Andric     return ReservedIdentifierStatus::NotReserved;
1114fe6060f1SDimitry Andric   }
1115fe6060f1SDimitry Andric 
1116fe6060f1SDimitry Andric   return Status;
1117fe6060f1SDimitry Andric }
1118fe6060f1SDimitry Andric 
11190b57cec5SDimitry Andric ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
11200b57cec5SDimitry Andric   StringRef name = getName();
11210b57cec5SDimitry Andric   if (name.empty()) return SFF_None;
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric   if (name.front() == 'C')
11240b57cec5SDimitry Andric     if (name == "CFStringCreateWithFormat" ||
11250b57cec5SDimitry Andric         name == "CFStringCreateWithFormatAndArguments" ||
11260b57cec5SDimitry Andric         name == "CFStringAppendFormat" ||
11270b57cec5SDimitry Andric         name == "CFStringAppendFormatAndArguments")
11280b57cec5SDimitry Andric       return SFF_CFString;
11290b57cec5SDimitry Andric   return SFF_None;
11300b57cec5SDimitry Andric }
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric Linkage NamedDecl::getLinkageInternal() const {
11330b57cec5SDimitry Andric   // We don't care about visibility here, so ask for the cheapest
11340b57cec5SDimitry Andric   // possible visibility analysis.
11350b57cec5SDimitry Andric   return LinkageComputer{}
11360b57cec5SDimitry Andric       .getLVForDecl(this, LVComputationKind::forLinkageOnly())
11370b57cec5SDimitry Andric       .getLinkage();
11380b57cec5SDimitry Andric }
11390b57cec5SDimitry Andric 
11400b57cec5SDimitry Andric LinkageInfo NamedDecl::getLinkageAndVisibility() const {
11410b57cec5SDimitry Andric   return LinkageComputer{}.getDeclLinkageAndVisibility(this);
11420b57cec5SDimitry Andric }
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric static Optional<Visibility>
11450b57cec5SDimitry Andric getExplicitVisibilityAux(const NamedDecl *ND,
11460b57cec5SDimitry Andric                          NamedDecl::ExplicitVisibilityKind kind,
11470b57cec5SDimitry Andric                          bool IsMostRecent) {
11480b57cec5SDimitry Andric   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric   // Check the declaration itself first.
11510b57cec5SDimitry Andric   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
11520b57cec5SDimitry Andric     return V;
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric   // If this is a member class of a specialization of a class template
11550b57cec5SDimitry Andric   // and the corresponding decl has explicit visibility, use that.
11560b57cec5SDimitry Andric   if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
11570b57cec5SDimitry Andric     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
11580b57cec5SDimitry Andric     if (InstantiatedFrom)
11590b57cec5SDimitry Andric       return getVisibilityOf(InstantiatedFrom, kind);
11600b57cec5SDimitry Andric   }
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric   // If there wasn't explicit visibility there, and this is a
11630b57cec5SDimitry Andric   // specialization of a class template, check for visibility
11640b57cec5SDimitry Andric   // on the pattern.
11650b57cec5SDimitry Andric   if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
11660b57cec5SDimitry Andric     // Walk all the template decl till this point to see if there are
11670b57cec5SDimitry Andric     // explicit visibility attributes.
11680b57cec5SDimitry Andric     const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
11690b57cec5SDimitry Andric     while (TD != nullptr) {
11700b57cec5SDimitry Andric       auto Vis = getVisibilityOf(TD, kind);
11710b57cec5SDimitry Andric       if (Vis != None)
11720b57cec5SDimitry Andric         return Vis;
11730b57cec5SDimitry Andric       TD = TD->getPreviousDecl();
11740b57cec5SDimitry Andric     }
11750b57cec5SDimitry Andric     return None;
11760b57cec5SDimitry Andric   }
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric   // Use the most recent declaration.
11790b57cec5SDimitry Andric   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
11800b57cec5SDimitry Andric     const NamedDecl *MostRecent = ND->getMostRecentDecl();
11810b57cec5SDimitry Andric     if (MostRecent != ND)
11820b57cec5SDimitry Andric       return getExplicitVisibilityAux(MostRecent, kind, true);
11830b57cec5SDimitry Andric   }
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric   if (const auto *Var = dyn_cast<VarDecl>(ND)) {
11860b57cec5SDimitry Andric     if (Var->isStaticDataMember()) {
11870b57cec5SDimitry Andric       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
11880b57cec5SDimitry Andric       if (InstantiatedFrom)
11890b57cec5SDimitry Andric         return getVisibilityOf(InstantiatedFrom, kind);
11900b57cec5SDimitry Andric     }
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric     if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
11930b57cec5SDimitry Andric       return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
11940b57cec5SDimitry Andric                              kind);
11950b57cec5SDimitry Andric 
11960b57cec5SDimitry Andric     return None;
11970b57cec5SDimitry Andric   }
11980b57cec5SDimitry Andric   // Also handle function template specializations.
11990b57cec5SDimitry Andric   if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
12000b57cec5SDimitry Andric     // If the function is a specialization of a template with an
12010b57cec5SDimitry Andric     // explicit visibility attribute, use that.
12020b57cec5SDimitry Andric     if (FunctionTemplateSpecializationInfo *templateInfo
12030b57cec5SDimitry Andric           = fn->getTemplateSpecializationInfo())
12040b57cec5SDimitry Andric       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
12050b57cec5SDimitry Andric                              kind);
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric     // If the function is a member of a specialization of a class template
12080b57cec5SDimitry Andric     // and the corresponding decl has explicit visibility, use that.
12090b57cec5SDimitry Andric     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
12100b57cec5SDimitry Andric     if (InstantiatedFrom)
12110b57cec5SDimitry Andric       return getVisibilityOf(InstantiatedFrom, kind);
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric     return None;
12140b57cec5SDimitry Andric   }
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric   // The visibility of a template is stored in the templated decl.
12170b57cec5SDimitry Andric   if (const auto *TD = dyn_cast<TemplateDecl>(ND))
12180b57cec5SDimitry Andric     return getVisibilityOf(TD->getTemplatedDecl(), kind);
12190b57cec5SDimitry Andric 
12200b57cec5SDimitry Andric   return None;
12210b57cec5SDimitry Andric }
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric Optional<Visibility>
12240b57cec5SDimitry Andric NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
12250b57cec5SDimitry Andric   return getExplicitVisibilityAux(this, kind, false);
12260b57cec5SDimitry Andric }
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
12290b57cec5SDimitry Andric                                              Decl *ContextDecl,
12300b57cec5SDimitry Andric                                              LVComputationKind computation) {
12310b57cec5SDimitry Andric   // This lambda has its linkage/visibility determined by its owner.
12320b57cec5SDimitry Andric   const NamedDecl *Owner;
12330b57cec5SDimitry Andric   if (!ContextDecl)
12340b57cec5SDimitry Andric     Owner = dyn_cast<NamedDecl>(DC);
12350b57cec5SDimitry Andric   else if (isa<ParmVarDecl>(ContextDecl))
12360b57cec5SDimitry Andric     Owner =
12370b57cec5SDimitry Andric         dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
12380b57cec5SDimitry Andric   else
12390b57cec5SDimitry Andric     Owner = cast<NamedDecl>(ContextDecl);
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric   if (!Owner)
12420b57cec5SDimitry Andric     return LinkageInfo::none();
12430b57cec5SDimitry Andric 
12440b57cec5SDimitry Andric   // If the owner has a deduced type, we need to skip querying the linkage and
12450b57cec5SDimitry Andric   // visibility of that type, because it might involve this closure type.  The
12460b57cec5SDimitry Andric   // only effect of this is that we might give a lambda VisibleNoLinkage rather
12470b57cec5SDimitry Andric   // than NoLinkage when we don't strictly need to, which is benign.
12480b57cec5SDimitry Andric   auto *VD = dyn_cast<VarDecl>(Owner);
12490b57cec5SDimitry Andric   LinkageInfo OwnerLV =
12500b57cec5SDimitry Andric       VD && VD->getType()->getContainedDeducedType()
12510b57cec5SDimitry Andric           ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
12520b57cec5SDimitry Andric           : getLVForDecl(Owner, computation);
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric   // A lambda never formally has linkage. But if the owner is externally
12550b57cec5SDimitry Andric   // visible, then the lambda is too. We apply the same rules to blocks.
12560b57cec5SDimitry Andric   if (!isExternallyVisible(OwnerLV.getLinkage()))
12570b57cec5SDimitry Andric     return LinkageInfo::none();
12580b57cec5SDimitry Andric   return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
12590b57cec5SDimitry Andric                      OwnerLV.isVisibilityExplicit());
12600b57cec5SDimitry Andric }
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
12630b57cec5SDimitry Andric                                                LVComputationKind computation) {
12640b57cec5SDimitry Andric   if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
12650b57cec5SDimitry Andric     if (Function->isInAnonymousNamespace() &&
12660b57cec5SDimitry Andric         !isFirstInExternCContext(Function))
12670b57cec5SDimitry Andric       return getInternalLinkageFor(Function);
12680b57cec5SDimitry Andric 
12690b57cec5SDimitry Andric     // This is a "void f();" which got merged with a file static.
12700b57cec5SDimitry Andric     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
12710b57cec5SDimitry Andric       return getInternalLinkageFor(Function);
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric     LinkageInfo LV;
12740b57cec5SDimitry Andric     if (!hasExplicitVisibilityAlready(computation)) {
12750b57cec5SDimitry Andric       if (Optional<Visibility> Vis =
12760b57cec5SDimitry Andric               getExplicitVisibility(Function, computation))
12770b57cec5SDimitry Andric         LV.mergeVisibility(*Vis, true);
12780b57cec5SDimitry Andric     }
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
12810b57cec5SDimitry Andric     // merging storage classes and visibility attributes, so we don't have to
12820b57cec5SDimitry Andric     // look at previous decls in here.
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric     return LV;
12850b57cec5SDimitry Andric   }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric   if (const auto *Var = dyn_cast<VarDecl>(D)) {
12880b57cec5SDimitry Andric     if (Var->hasExternalStorage()) {
12890b57cec5SDimitry Andric       if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
12900b57cec5SDimitry Andric         return getInternalLinkageFor(Var);
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric       LinkageInfo LV;
12930b57cec5SDimitry Andric       if (Var->getStorageClass() == SC_PrivateExtern)
12940b57cec5SDimitry Andric         LV.mergeVisibility(HiddenVisibility, true);
12950b57cec5SDimitry Andric       else if (!hasExplicitVisibilityAlready(computation)) {
12960b57cec5SDimitry Andric         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
12970b57cec5SDimitry Andric           LV.mergeVisibility(*Vis, true);
12980b57cec5SDimitry Andric       }
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric       if (const VarDecl *Prev = Var->getPreviousDecl()) {
13010b57cec5SDimitry Andric         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
13020b57cec5SDimitry Andric         if (PrevLV.getLinkage())
13030b57cec5SDimitry Andric           LV.setLinkage(PrevLV.getLinkage());
13040b57cec5SDimitry Andric         LV.mergeVisibility(PrevLV);
13050b57cec5SDimitry Andric       }
13060b57cec5SDimitry Andric 
13070b57cec5SDimitry Andric       return LV;
13080b57cec5SDimitry Andric     }
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric     if (!Var->isStaticLocal())
13110b57cec5SDimitry Andric       return LinkageInfo::none();
13120b57cec5SDimitry Andric   }
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric   ASTContext &Context = D->getASTContext();
13150b57cec5SDimitry Andric   if (!Context.getLangOpts().CPlusPlus)
13160b57cec5SDimitry Andric     return LinkageInfo::none();
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
13190b57cec5SDimitry Andric   if (!OuterD || OuterD->isInvalidDecl())
13200b57cec5SDimitry Andric     return LinkageInfo::none();
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric   LinkageInfo LV;
13230b57cec5SDimitry Andric   if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
13240b57cec5SDimitry Andric     if (!BD->getBlockManglingNumber())
13250b57cec5SDimitry Andric       return LinkageInfo::none();
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
13280b57cec5SDimitry Andric                          BD->getBlockManglingContextDecl(), computation);
13290b57cec5SDimitry Andric   } else {
13300b57cec5SDimitry Andric     const auto *FD = cast<FunctionDecl>(OuterD);
13310b57cec5SDimitry Andric     if (!FD->isInlined() &&
13320b57cec5SDimitry Andric         !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
13330b57cec5SDimitry Andric       return LinkageInfo::none();
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric     // If a function is hidden by -fvisibility-inlines-hidden option and
13360b57cec5SDimitry Andric     // is not explicitly attributed as a hidden function,
13370b57cec5SDimitry Andric     // we should not make static local variables in the function hidden.
13380b57cec5SDimitry Andric     LV = getLVForDecl(FD, computation);
13390b57cec5SDimitry Andric     if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1340e8d8bef9SDimitry Andric         !LV.isVisibilityExplicit() &&
1341e8d8bef9SDimitry Andric         !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
13420b57cec5SDimitry Andric       assert(cast<VarDecl>(D)->isStaticLocal());
13430b57cec5SDimitry Andric       // If this was an implicitly hidden inline method, check again for
13440b57cec5SDimitry Andric       // explicit visibility on the parent class, and use that for static locals
13450b57cec5SDimitry Andric       // if present.
13460b57cec5SDimitry Andric       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
13470b57cec5SDimitry Andric         LV = getLVForDecl(MD->getParent(), computation);
13480b57cec5SDimitry Andric       if (!LV.isVisibilityExplicit()) {
13490b57cec5SDimitry Andric         Visibility globalVisibility =
13500b57cec5SDimitry Andric             computation.isValueVisibility()
13510b57cec5SDimitry Andric                 ? Context.getLangOpts().getValueVisibilityMode()
13520b57cec5SDimitry Andric                 : Context.getLangOpts().getTypeVisibilityMode();
13530b57cec5SDimitry Andric         return LinkageInfo(VisibleNoLinkage, globalVisibility,
13540b57cec5SDimitry Andric                            /*visibilityExplicit=*/false);
13550b57cec5SDimitry Andric       }
13560b57cec5SDimitry Andric     }
13570b57cec5SDimitry Andric   }
13580b57cec5SDimitry Andric   if (!isExternallyVisible(LV.getLinkage()))
13590b57cec5SDimitry Andric     return LinkageInfo::none();
13600b57cec5SDimitry Andric   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
13610b57cec5SDimitry Andric                      LV.isVisibilityExplicit());
13620b57cec5SDimitry Andric }
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
13650b57cec5SDimitry Andric                                               LVComputationKind computation,
13660b57cec5SDimitry Andric                                               bool IgnoreVarTypeLinkage) {
13670b57cec5SDimitry Andric   // Internal_linkage attribute overrides other considerations.
13680b57cec5SDimitry Andric   if (D->hasAttr<InternalLinkageAttr>())
13690b57cec5SDimitry Andric     return getInternalLinkageFor(D);
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric   // Objective-C: treat all Objective-C declarations as having external
13720b57cec5SDimitry Andric   // linkage.
13730b57cec5SDimitry Andric   switch (D->getKind()) {
13740b57cec5SDimitry Andric     default:
13750b57cec5SDimitry Andric       break;
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric     // Per C++ [basic.link]p2, only the names of objects, references,
13780b57cec5SDimitry Andric     // functions, types, templates, namespaces, and values ever have linkage.
13790b57cec5SDimitry Andric     //
13800b57cec5SDimitry Andric     // Note that the name of a typedef, namespace alias, using declaration,
13810b57cec5SDimitry Andric     // and so on are not the name of the corresponding type, namespace, or
13820b57cec5SDimitry Andric     // declaration, so they do *not* have linkage.
13830b57cec5SDimitry Andric     case Decl::ImplicitParam:
13840b57cec5SDimitry Andric     case Decl::Label:
13850b57cec5SDimitry Andric     case Decl::NamespaceAlias:
13860b57cec5SDimitry Andric     case Decl::ParmVar:
13870b57cec5SDimitry Andric     case Decl::Using:
1388fe6060f1SDimitry Andric     case Decl::UsingEnum:
13890b57cec5SDimitry Andric     case Decl::UsingShadow:
13900b57cec5SDimitry Andric     case Decl::UsingDirective:
13910b57cec5SDimitry Andric       return LinkageInfo::none();
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric     case Decl::EnumConstant:
13940b57cec5SDimitry Andric       // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
13950b57cec5SDimitry Andric       if (D->getASTContext().getLangOpts().CPlusPlus)
13960b57cec5SDimitry Andric         return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
13970b57cec5SDimitry Andric       return LinkageInfo::visible_none();
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric     case Decl::Typedef:
14000b57cec5SDimitry Andric     case Decl::TypeAlias:
14010b57cec5SDimitry Andric       // A typedef declaration has linkage if it gives a type a name for
14020b57cec5SDimitry Andric       // linkage purposes.
14030b57cec5SDimitry Andric       if (!cast<TypedefNameDecl>(D)
14040b57cec5SDimitry Andric                ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
14050b57cec5SDimitry Andric         return LinkageInfo::none();
14060b57cec5SDimitry Andric       break;
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric     case Decl::TemplateTemplateParm: // count these as external
14090b57cec5SDimitry Andric     case Decl::NonTypeTemplateParm:
14100b57cec5SDimitry Andric     case Decl::ObjCAtDefsField:
14110b57cec5SDimitry Andric     case Decl::ObjCCategory:
14120b57cec5SDimitry Andric     case Decl::ObjCCategoryImpl:
14130b57cec5SDimitry Andric     case Decl::ObjCCompatibleAlias:
14140b57cec5SDimitry Andric     case Decl::ObjCImplementation:
14150b57cec5SDimitry Andric     case Decl::ObjCMethod:
14160b57cec5SDimitry Andric     case Decl::ObjCProperty:
14170b57cec5SDimitry Andric     case Decl::ObjCPropertyImpl:
14180b57cec5SDimitry Andric     case Decl::ObjCProtocol:
14190b57cec5SDimitry Andric       return getExternalLinkageFor(D);
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric     case Decl::CXXRecord: {
14220b57cec5SDimitry Andric       const auto *Record = cast<CXXRecordDecl>(D);
14230b57cec5SDimitry Andric       if (Record->isLambda()) {
1424a7dea167SDimitry Andric         if (Record->hasKnownLambdaInternalLinkage() ||
1425a7dea167SDimitry Andric             !Record->getLambdaManglingNumber()) {
14260b57cec5SDimitry Andric           // This lambda has no mangling number, so it's internal.
14270b57cec5SDimitry Andric           return getInternalLinkageFor(D);
14280b57cec5SDimitry Andric         }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric         return getLVForClosure(
14315ffd83dbSDimitry Andric                   Record->getDeclContext()->getRedeclContext(),
14325ffd83dbSDimitry Andric                   Record->getLambdaContextDecl(), computation);
14330b57cec5SDimitry Andric       }
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric       break;
14360b57cec5SDimitry Andric     }
1437e8d8bef9SDimitry Andric 
1438e8d8bef9SDimitry Andric     case Decl::TemplateParamObject: {
1439e8d8bef9SDimitry Andric       // The template parameter object can be referenced from anywhere its type
1440e8d8bef9SDimitry Andric       // and value can be referenced.
1441e8d8bef9SDimitry Andric       auto *TPO = cast<TemplateParamObjectDecl>(D);
1442e8d8bef9SDimitry Andric       LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1443e8d8bef9SDimitry Andric       LV.merge(getLVForValue(TPO->getValue(), computation));
1444e8d8bef9SDimitry Andric       return LV;
1445e8d8bef9SDimitry Andric     }
14460b57cec5SDimitry Andric   }
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric   // Handle linkage for namespace-scope names.
14490b57cec5SDimitry Andric   if (D->getDeclContext()->getRedeclContext()->isFileContext())
14500b57cec5SDimitry Andric     return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric   // C++ [basic.link]p5:
14530b57cec5SDimitry Andric   //   In addition, a member function, static data member, a named
14540b57cec5SDimitry Andric   //   class or enumeration of class scope, or an unnamed class or
14550b57cec5SDimitry Andric   //   enumeration defined in a class-scope typedef declaration such
14560b57cec5SDimitry Andric   //   that the class or enumeration has the typedef name for linkage
14570b57cec5SDimitry Andric   //   purposes (7.1.3), has external linkage if the name of the class
14580b57cec5SDimitry Andric   //   has external linkage.
14590b57cec5SDimitry Andric   if (D->getDeclContext()->isRecord())
14600b57cec5SDimitry Andric     return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
14610b57cec5SDimitry Andric 
14620b57cec5SDimitry Andric   // C++ [basic.link]p6:
14630b57cec5SDimitry Andric   //   The name of a function declared in block scope and the name of
14640b57cec5SDimitry Andric   //   an object declared by a block scope extern declaration have
14650b57cec5SDimitry Andric   //   linkage. If there is a visible declaration of an entity with
14660b57cec5SDimitry Andric   //   linkage having the same name and type, ignoring entities
14670b57cec5SDimitry Andric   //   declared outside the innermost enclosing namespace scope, the
14680b57cec5SDimitry Andric   //   block scope declaration declares that same entity and receives
14690b57cec5SDimitry Andric   //   the linkage of the previous declaration. If there is more than
14700b57cec5SDimitry Andric   //   one such matching entity, the program is ill-formed. Otherwise,
14710b57cec5SDimitry Andric   //   if no matching entity is found, the block scope entity receives
14720b57cec5SDimitry Andric   //   external linkage.
14730b57cec5SDimitry Andric   if (D->getDeclContext()->isFunctionOrMethod())
14740b57cec5SDimitry Andric     return getLVForLocalDecl(D, computation);
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric   // C++ [basic.link]p6:
14770b57cec5SDimitry Andric   //   Names not covered by these rules have no linkage.
14780b57cec5SDimitry Andric   return LinkageInfo::none();
14790b57cec5SDimitry Andric }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric /// getLVForDecl - Get the linkage and visibility for the given declaration.
14820b57cec5SDimitry Andric LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
14830b57cec5SDimitry Andric                                           LVComputationKind computation) {
14840b57cec5SDimitry Andric   // Internal_linkage attribute overrides other considerations.
14850b57cec5SDimitry Andric   if (D->hasAttr<InternalLinkageAttr>())
14860b57cec5SDimitry Andric     return getInternalLinkageFor(D);
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric   if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
14890b57cec5SDimitry Andric     return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
14900b57cec5SDimitry Andric 
14910b57cec5SDimitry Andric   if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
14920b57cec5SDimitry Andric     return *LI;
14930b57cec5SDimitry Andric 
14940b57cec5SDimitry Andric   LinkageInfo LV = computeLVForDecl(D, computation);
14950b57cec5SDimitry Andric   if (D->hasCachedLinkage())
14960b57cec5SDimitry Andric     assert(D->getCachedLinkage() == LV.getLinkage());
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric   D->setCachedLinkage(LV.getLinkage());
14990b57cec5SDimitry Andric   cache(D, computation, LV);
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric #ifndef NDEBUG
15020b57cec5SDimitry Andric   // In C (because of gnu inline) and in c++ with microsoft extensions an
15030b57cec5SDimitry Andric   // static can follow an extern, so we can have two decls with different
15040b57cec5SDimitry Andric   // linkages.
15050b57cec5SDimitry Andric   const LangOptions &Opts = D->getASTContext().getLangOpts();
15060b57cec5SDimitry Andric   if (!Opts.CPlusPlus || Opts.MicrosoftExt)
15070b57cec5SDimitry Andric     return LV;
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric   // We have just computed the linkage for this decl. By induction we know
15100b57cec5SDimitry Andric   // that all other computed linkages match, check that the one we just
15110b57cec5SDimitry Andric   // computed also does.
15120b57cec5SDimitry Andric   NamedDecl *Old = nullptr;
15130b57cec5SDimitry Andric   for (auto I : D->redecls()) {
15140b57cec5SDimitry Andric     auto *T = cast<NamedDecl>(I);
15150b57cec5SDimitry Andric     if (T == D)
15160b57cec5SDimitry Andric       continue;
15170b57cec5SDimitry Andric     if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
15180b57cec5SDimitry Andric       Old = T;
15190b57cec5SDimitry Andric       break;
15200b57cec5SDimitry Andric     }
15210b57cec5SDimitry Andric   }
15220b57cec5SDimitry Andric   assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
15230b57cec5SDimitry Andric #endif
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric   return LV;
15260b57cec5SDimitry Andric }
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1529fe6060f1SDimitry Andric   NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)
15300b57cec5SDimitry Andric                                              ? NamedDecl::VisibilityForType
1531fe6060f1SDimitry Andric                                              : NamedDecl::VisibilityForValue;
1532fe6060f1SDimitry Andric   LVComputationKind CK(EK);
1533fe6060f1SDimitry Andric   return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1534fe6060f1SDimitry Andric                              ? CK.forLinkageOnly()
1535fe6060f1SDimitry Andric                              : CK);
15360b57cec5SDimitry Andric }
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
15390b57cec5SDimitry Andric   Module *M = getOwningModule();
15400b57cec5SDimitry Andric   if (!M)
15410b57cec5SDimitry Andric     return nullptr;
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric   switch (M->Kind) {
15440b57cec5SDimitry Andric   case Module::ModuleMapModule:
15450b57cec5SDimitry Andric     // Module map modules have no special linkage semantics.
15460b57cec5SDimitry Andric     return nullptr;
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric   case Module::ModuleInterfaceUnit:
15490b57cec5SDimitry Andric     return M;
15500b57cec5SDimitry Andric 
15510b57cec5SDimitry Andric   case Module::GlobalModuleFragment: {
15520b57cec5SDimitry Andric     // External linkage declarations in the global module have no owning module
15530b57cec5SDimitry Andric     // for linkage purposes. But internal linkage declarations in the global
15540b57cec5SDimitry Andric     // module fragment of a particular module are owned by that module for
15550b57cec5SDimitry Andric     // linkage purposes.
15560b57cec5SDimitry Andric     if (IgnoreLinkage)
15570b57cec5SDimitry Andric       return nullptr;
15580b57cec5SDimitry Andric     bool InternalLinkage;
15590b57cec5SDimitry Andric     if (auto *ND = dyn_cast<NamedDecl>(this))
15600b57cec5SDimitry Andric       InternalLinkage = !ND->hasExternalFormalLinkage();
15610b57cec5SDimitry Andric     else {
15620b57cec5SDimitry Andric       auto *NSD = dyn_cast<NamespaceDecl>(this);
15630b57cec5SDimitry Andric       InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
15640b57cec5SDimitry Andric                         isInAnonymousNamespace();
15650b57cec5SDimitry Andric     }
15660b57cec5SDimitry Andric     return InternalLinkage ? M->Parent : nullptr;
15670b57cec5SDimitry Andric   }
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric   case Module::PrivateModuleFragment:
15700b57cec5SDimitry Andric     // The private module fragment is part of its containing module for linkage
15710b57cec5SDimitry Andric     // purposes.
15720b57cec5SDimitry Andric     return M->Parent;
15730b57cec5SDimitry Andric   }
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   llvm_unreachable("unknown module kind");
15760b57cec5SDimitry Andric }
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric void NamedDecl::printName(raw_ostream &os) const {
15790b57cec5SDimitry Andric   os << Name;
15800b57cec5SDimitry Andric }
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric std::string NamedDecl::getQualifiedNameAsString() const {
15830b57cec5SDimitry Andric   std::string QualName;
15840b57cec5SDimitry Andric   llvm::raw_string_ostream OS(QualName);
15850b57cec5SDimitry Andric   printQualifiedName(OS, getASTContext().getPrintingPolicy());
15860b57cec5SDimitry Andric   return OS.str();
15870b57cec5SDimitry Andric }
15880b57cec5SDimitry Andric 
15890b57cec5SDimitry Andric void NamedDecl::printQualifiedName(raw_ostream &OS) const {
15900b57cec5SDimitry Andric   printQualifiedName(OS, getASTContext().getPrintingPolicy());
15910b57cec5SDimitry Andric }
15920b57cec5SDimitry Andric 
15930b57cec5SDimitry Andric void NamedDecl::printQualifiedName(raw_ostream &OS,
15940b57cec5SDimitry Andric                                    const PrintingPolicy &P) const {
1595a7dea167SDimitry Andric   if (getDeclContext()->isFunctionOrMethod()) {
1596a7dea167SDimitry Andric     // We do not print '(anonymous)' for function parameters without name.
1597a7dea167SDimitry Andric     printName(OS);
1598a7dea167SDimitry Andric     return;
1599a7dea167SDimitry Andric   }
1600a7dea167SDimitry Andric   printNestedNameSpecifier(OS, P);
16015ffd83dbSDimitry Andric   if (getDeclName())
1602a7dea167SDimitry Andric     OS << *this;
16035ffd83dbSDimitry Andric   else {
16045ffd83dbSDimitry Andric     // Give the printName override a chance to pick a different name before we
16055ffd83dbSDimitry Andric     // fall back to "(anonymous)".
16065ffd83dbSDimitry Andric     SmallString<64> NameBuffer;
16075ffd83dbSDimitry Andric     llvm::raw_svector_ostream NameOS(NameBuffer);
16085ffd83dbSDimitry Andric     printName(NameOS);
16095ffd83dbSDimitry Andric     if (NameBuffer.empty())
1610a7dea167SDimitry Andric       OS << "(anonymous)";
16115ffd83dbSDimitry Andric     else
16125ffd83dbSDimitry Andric       OS << NameBuffer;
16135ffd83dbSDimitry Andric   }
1614a7dea167SDimitry Andric }
1615a7dea167SDimitry Andric 
1616a7dea167SDimitry Andric void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1617a7dea167SDimitry Andric   printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1618a7dea167SDimitry Andric }
1619a7dea167SDimitry Andric 
1620a7dea167SDimitry Andric void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1621a7dea167SDimitry Andric                                          const PrintingPolicy &P) const {
16220b57cec5SDimitry Andric   const DeclContext *Ctx = getDeclContext();
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric   // For ObjC methods and properties, look through categories and use the
16250b57cec5SDimitry Andric   // interface as context.
16265ffd83dbSDimitry Andric   if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
16270b57cec5SDimitry Andric     if (auto *ID = MD->getClassInterface())
16280b57cec5SDimitry Andric       Ctx = ID;
16295ffd83dbSDimitry Andric   } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
16300b57cec5SDimitry Andric     if (auto *MD = PD->getGetterMethodDecl())
16310b57cec5SDimitry Andric       if (auto *ID = MD->getClassInterface())
16320b57cec5SDimitry Andric         Ctx = ID;
16335ffd83dbSDimitry Andric   } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
16345ffd83dbSDimitry Andric     if (auto *CI = ID->getContainingInterface())
16355ffd83dbSDimitry Andric       Ctx = CI;
16360b57cec5SDimitry Andric   }
16370b57cec5SDimitry Andric 
1638a7dea167SDimitry Andric   if (Ctx->isFunctionOrMethod())
16390b57cec5SDimitry Andric     return;
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric   using ContextsTy = SmallVector<const DeclContext *, 8>;
16420b57cec5SDimitry Andric   ContextsTy Contexts;
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric   // Collect named contexts.
1645e8d8bef9SDimitry Andric   DeclarationName NameInScope = getDeclName();
1646e8d8bef9SDimitry Andric   for (; Ctx; Ctx = Ctx->getParent()) {
1647e8d8bef9SDimitry Andric     // Suppress anonymous namespace if requested.
1648e8d8bef9SDimitry Andric     if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1649e8d8bef9SDimitry Andric         cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1650e8d8bef9SDimitry Andric       continue;
1651e8d8bef9SDimitry Andric 
1652e8d8bef9SDimitry Andric     // Suppress inline namespace if it doesn't make the result ambiguous.
1653e8d8bef9SDimitry Andric     if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1654fe6060f1SDimitry Andric         cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))
1655e8d8bef9SDimitry Andric       continue;
1656e8d8bef9SDimitry Andric 
1657e8d8bef9SDimitry Andric     // Skip non-named contexts such as linkage specifications and ExportDecls.
1658e8d8bef9SDimitry Andric     const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1659e8d8bef9SDimitry Andric     if (!ND)
1660e8d8bef9SDimitry Andric       continue;
1661e8d8bef9SDimitry Andric 
16620b57cec5SDimitry Andric     Contexts.push_back(Ctx);
1663e8d8bef9SDimitry Andric     NameInScope = ND->getDeclName();
16640b57cec5SDimitry Andric   }
16650b57cec5SDimitry Andric 
1666*349cc55cSDimitry Andric   for (const DeclContext *DC : llvm::reverse(Contexts)) {
16670b57cec5SDimitry Andric     if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
16680b57cec5SDimitry Andric       OS << Spec->getName();
16690b57cec5SDimitry Andric       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1670e8d8bef9SDimitry Andric       printTemplateArgumentList(
1671e8d8bef9SDimitry Andric           OS, TemplateArgs.asArray(), P,
1672e8d8bef9SDimitry Andric           Spec->getSpecializedTemplate()->getTemplateParameters());
16730b57cec5SDimitry Andric     } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
16740b57cec5SDimitry Andric       if (ND->isAnonymousNamespace()) {
16750b57cec5SDimitry Andric         OS << (P.MSVCFormatting ? "`anonymous namespace\'"
16760b57cec5SDimitry Andric                                 : "(anonymous namespace)");
16770b57cec5SDimitry Andric       }
16780b57cec5SDimitry Andric       else
16790b57cec5SDimitry Andric         OS << *ND;
16800b57cec5SDimitry Andric     } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
16810b57cec5SDimitry Andric       if (!RD->getIdentifier())
16820b57cec5SDimitry Andric         OS << "(anonymous " << RD->getKindName() << ')';
16830b57cec5SDimitry Andric       else
16840b57cec5SDimitry Andric         OS << *RD;
16850b57cec5SDimitry Andric     } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
16860b57cec5SDimitry Andric       const FunctionProtoType *FT = nullptr;
16870b57cec5SDimitry Andric       if (FD->hasWrittenPrototype())
16880b57cec5SDimitry Andric         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric       OS << *FD << '(';
16910b57cec5SDimitry Andric       if (FT) {
16920b57cec5SDimitry Andric         unsigned NumParams = FD->getNumParams();
16930b57cec5SDimitry Andric         for (unsigned i = 0; i < NumParams; ++i) {
16940b57cec5SDimitry Andric           if (i)
16950b57cec5SDimitry Andric             OS << ", ";
16960b57cec5SDimitry Andric           OS << FD->getParamDecl(i)->getType().stream(P);
16970b57cec5SDimitry Andric         }
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric         if (FT->isVariadic()) {
17000b57cec5SDimitry Andric           if (NumParams > 0)
17010b57cec5SDimitry Andric             OS << ", ";
17020b57cec5SDimitry Andric           OS << "...";
17030b57cec5SDimitry Andric         }
17040b57cec5SDimitry Andric       }
17050b57cec5SDimitry Andric       OS << ')';
17060b57cec5SDimitry Andric     } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
17070b57cec5SDimitry Andric       // C++ [dcl.enum]p10: Each enum-name and each unscoped
17080b57cec5SDimitry Andric       // enumerator is declared in the scope that immediately contains
17090b57cec5SDimitry Andric       // the enum-specifier. Each scoped enumerator is declared in the
17100b57cec5SDimitry Andric       // scope of the enumeration.
17110b57cec5SDimitry Andric       // For the case of unscoped enumerator, do not include in the qualified
17120b57cec5SDimitry Andric       // name any information about its enum enclosing scope, as its visibility
17130b57cec5SDimitry Andric       // is global.
17140b57cec5SDimitry Andric       if (ED->isScoped())
17150b57cec5SDimitry Andric         OS << *ED;
17160b57cec5SDimitry Andric       else
17170b57cec5SDimitry Andric         continue;
17180b57cec5SDimitry Andric     } else {
17190b57cec5SDimitry Andric       OS << *cast<NamedDecl>(DC);
17200b57cec5SDimitry Andric     }
17210b57cec5SDimitry Andric     OS << "::";
17220b57cec5SDimitry Andric   }
17230b57cec5SDimitry Andric }
17240b57cec5SDimitry Andric 
17250b57cec5SDimitry Andric void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
17260b57cec5SDimitry Andric                                      const PrintingPolicy &Policy,
17270b57cec5SDimitry Andric                                      bool Qualified) const {
17280b57cec5SDimitry Andric   if (Qualified)
17290b57cec5SDimitry Andric     printQualifiedName(OS, Policy);
17300b57cec5SDimitry Andric   else
17310b57cec5SDimitry Andric     printName(OS);
17320b57cec5SDimitry Andric }
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
17350b57cec5SDimitry Andric   return true;
17360b57cec5SDimitry Andric }
17370b57cec5SDimitry Andric static bool isRedeclarableImpl(...) { return false; }
17380b57cec5SDimitry Andric static bool isRedeclarable(Decl::Kind K) {
17390b57cec5SDimitry Andric   switch (K) {
17400b57cec5SDimitry Andric #define DECL(Type, Base) \
17410b57cec5SDimitry Andric   case Decl::Type: \
17420b57cec5SDimitry Andric     return isRedeclarableImpl((Type##Decl *)nullptr);
17430b57cec5SDimitry Andric #define ABSTRACT_DECL(DECL)
17440b57cec5SDimitry Andric #include "clang/AST/DeclNodes.inc"
17450b57cec5SDimitry Andric   }
17460b57cec5SDimitry Andric   llvm_unreachable("unknown decl kind");
17470b57cec5SDimitry Andric }
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
17500b57cec5SDimitry Andric   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
17510b57cec5SDimitry Andric 
17520b57cec5SDimitry Andric   // Never replace one imported declaration with another; we need both results
17530b57cec5SDimitry Andric   // when re-exporting.
17540b57cec5SDimitry Andric   if (OldD->isFromASTFile() && isFromASTFile())
17550b57cec5SDimitry Andric     return false;
17560b57cec5SDimitry Andric 
17570b57cec5SDimitry Andric   // A kind mismatch implies that the declaration is not replaced.
17580b57cec5SDimitry Andric   if (OldD->getKind() != getKind())
17590b57cec5SDimitry Andric     return false;
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   // For method declarations, we never replace. (Why?)
17620b57cec5SDimitry Andric   if (isa<ObjCMethodDecl>(this))
17630b57cec5SDimitry Andric     return false;
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric   // For parameters, pick the newer one. This is either an error or (in
17660b57cec5SDimitry Andric   // Objective-C) permitted as an extension.
17670b57cec5SDimitry Andric   if (isa<ParmVarDecl>(this))
17680b57cec5SDimitry Andric     return true;
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric   // Inline namespaces can give us two declarations with the same
17710b57cec5SDimitry Andric   // name and kind in the same scope but different contexts; we should
17720b57cec5SDimitry Andric   // keep both declarations in this case.
17730b57cec5SDimitry Andric   if (!this->getDeclContext()->getRedeclContext()->Equals(
17740b57cec5SDimitry Andric           OldD->getDeclContext()->getRedeclContext()))
17750b57cec5SDimitry Andric     return false;
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric   // Using declarations can be replaced if they import the same name from the
17780b57cec5SDimitry Andric   // same context.
17790b57cec5SDimitry Andric   if (auto *UD = dyn_cast<UsingDecl>(this)) {
17800b57cec5SDimitry Andric     ASTContext &Context = getASTContext();
17810b57cec5SDimitry Andric     return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
17820b57cec5SDimitry Andric            Context.getCanonicalNestedNameSpecifier(
17830b57cec5SDimitry Andric                cast<UsingDecl>(OldD)->getQualifier());
17840b57cec5SDimitry Andric   }
17850b57cec5SDimitry Andric   if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
17860b57cec5SDimitry Andric     ASTContext &Context = getASTContext();
17870b57cec5SDimitry Andric     return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
17880b57cec5SDimitry Andric            Context.getCanonicalNestedNameSpecifier(
17890b57cec5SDimitry Andric                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
17900b57cec5SDimitry Andric   }
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   if (isRedeclarable(getKind())) {
17930b57cec5SDimitry Andric     if (getCanonicalDecl() != OldD->getCanonicalDecl())
17940b57cec5SDimitry Andric       return false;
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric     if (IsKnownNewer)
17970b57cec5SDimitry Andric       return true;
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric     // Check whether this is actually newer than OldD. We want to keep the
18000b57cec5SDimitry Andric     // newer declaration. This loop will usually only iterate once, because
18010b57cec5SDimitry Andric     // OldD is usually the previous declaration.
18020b57cec5SDimitry Andric     for (auto D : redecls()) {
18030b57cec5SDimitry Andric       if (D == OldD)
18040b57cec5SDimitry Andric         break;
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric       // If we reach the canonical declaration, then OldD is not actually older
18070b57cec5SDimitry Andric       // than this one.
18080b57cec5SDimitry Andric       //
18090b57cec5SDimitry Andric       // FIXME: In this case, we should not add this decl to the lookup table.
18100b57cec5SDimitry Andric       if (D->isCanonicalDecl())
18110b57cec5SDimitry Andric         return false;
18120b57cec5SDimitry Andric     }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric     // It's a newer declaration of the same kind of declaration in the same
18150b57cec5SDimitry Andric     // scope: we want this decl instead of the existing one.
18160b57cec5SDimitry Andric     return true;
18170b57cec5SDimitry Andric   }
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   // In all other cases, we need to keep both declarations in case they have
18200b57cec5SDimitry Andric   // different visibility. Any attempt to use the name will result in an
18210b57cec5SDimitry Andric   // ambiguity if more than one is visible.
18220b57cec5SDimitry Andric   return false;
18230b57cec5SDimitry Andric }
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric bool NamedDecl::hasLinkage() const {
18260b57cec5SDimitry Andric   return getFormalLinkage() != NoLinkage;
18270b57cec5SDimitry Andric }
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
18300b57cec5SDimitry Andric   NamedDecl *ND = this;
18310b57cec5SDimitry Andric   while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
18320b57cec5SDimitry Andric     ND = UD->getTargetDecl();
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric   if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
18350b57cec5SDimitry Andric     return AD->getClassInterface();
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric   if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
18380b57cec5SDimitry Andric     return AD->getNamespace();
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric   return ND;
18410b57cec5SDimitry Andric }
18420b57cec5SDimitry Andric 
18430b57cec5SDimitry Andric bool NamedDecl::isCXXInstanceMember() const {
18440b57cec5SDimitry Andric   if (!isCXXClassMember())
18450b57cec5SDimitry Andric     return false;
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric   const NamedDecl *D = this;
18480b57cec5SDimitry Andric   if (isa<UsingShadowDecl>(D))
18490b57cec5SDimitry Andric     D = cast<UsingShadowDecl>(D)->getTargetDecl();
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
18520b57cec5SDimitry Andric     return true;
18530b57cec5SDimitry Andric   if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
18540b57cec5SDimitry Andric     return MD->isInstance();
18550b57cec5SDimitry Andric   return false;
18560b57cec5SDimitry Andric }
18570b57cec5SDimitry Andric 
18580b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
18590b57cec5SDimitry Andric // DeclaratorDecl Implementation
18600b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
18610b57cec5SDimitry Andric 
18620b57cec5SDimitry Andric template <typename DeclT>
18630b57cec5SDimitry Andric static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
18640b57cec5SDimitry Andric   if (decl->getNumTemplateParameterLists() > 0)
18650b57cec5SDimitry Andric     return decl->getTemplateParameterList(0)->getTemplateLoc();
18660b57cec5SDimitry Andric   return decl->getInnerLocStart();
18670b57cec5SDimitry Andric }
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
18700b57cec5SDimitry Andric   TypeSourceInfo *TSI = getTypeSourceInfo();
18710b57cec5SDimitry Andric   if (TSI) return TSI->getTypeLoc().getBeginLoc();
18720b57cec5SDimitry Andric   return SourceLocation();
18730b57cec5SDimitry Andric }
18740b57cec5SDimitry Andric 
1875480093f4SDimitry Andric SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1876480093f4SDimitry Andric   TypeSourceInfo *TSI = getTypeSourceInfo();
1877480093f4SDimitry Andric   if (TSI) return TSI->getTypeLoc().getEndLoc();
1878480093f4SDimitry Andric   return SourceLocation();
1879480093f4SDimitry Andric }
1880480093f4SDimitry Andric 
18810b57cec5SDimitry Andric void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
18820b57cec5SDimitry Andric   if (QualifierLoc) {
18830b57cec5SDimitry Andric     // Make sure the extended decl info is allocated.
18840b57cec5SDimitry Andric     if (!hasExtInfo()) {
18850b57cec5SDimitry Andric       // Save (non-extended) type source info pointer.
18860b57cec5SDimitry Andric       auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
18870b57cec5SDimitry Andric       // Allocate external info struct.
18880b57cec5SDimitry Andric       DeclInfo = new (getASTContext()) ExtInfo;
18890b57cec5SDimitry Andric       // Restore savedTInfo into (extended) decl info.
18900b57cec5SDimitry Andric       getExtInfo()->TInfo = savedTInfo;
18910b57cec5SDimitry Andric     }
18920b57cec5SDimitry Andric     // Set qualifier info.
18930b57cec5SDimitry Andric     getExtInfo()->QualifierLoc = QualifierLoc;
1894480093f4SDimitry Andric   } else if (hasExtInfo()) {
18950b57cec5SDimitry Andric     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
18960b57cec5SDimitry Andric     getExtInfo()->QualifierLoc = QualifierLoc;
18970b57cec5SDimitry Andric   }
18980b57cec5SDimitry Andric }
1899480093f4SDimitry Andric 
1900480093f4SDimitry Andric void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1901480093f4SDimitry Andric   assert(TrailingRequiresClause);
1902480093f4SDimitry Andric   // Make sure the extended decl info is allocated.
1903480093f4SDimitry Andric   if (!hasExtInfo()) {
1904480093f4SDimitry Andric     // Save (non-extended) type source info pointer.
1905480093f4SDimitry Andric     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1906480093f4SDimitry Andric     // Allocate external info struct.
1907480093f4SDimitry Andric     DeclInfo = new (getASTContext()) ExtInfo;
1908480093f4SDimitry Andric     // Restore savedTInfo into (extended) decl info.
1909480093f4SDimitry Andric     getExtInfo()->TInfo = savedTInfo;
1910480093f4SDimitry Andric   }
1911480093f4SDimitry Andric   // Set requires clause info.
1912480093f4SDimitry Andric   getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
19130b57cec5SDimitry Andric }
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric void DeclaratorDecl::setTemplateParameterListsInfo(
19160b57cec5SDimitry Andric     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
19170b57cec5SDimitry Andric   assert(!TPLists.empty());
19180b57cec5SDimitry Andric   // Make sure the extended decl info is allocated.
19190b57cec5SDimitry Andric   if (!hasExtInfo()) {
19200b57cec5SDimitry Andric     // Save (non-extended) type source info pointer.
19210b57cec5SDimitry Andric     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
19220b57cec5SDimitry Andric     // Allocate external info struct.
19230b57cec5SDimitry Andric     DeclInfo = new (getASTContext()) ExtInfo;
19240b57cec5SDimitry Andric     // Restore savedTInfo into (extended) decl info.
19250b57cec5SDimitry Andric     getExtInfo()->TInfo = savedTInfo;
19260b57cec5SDimitry Andric   }
19270b57cec5SDimitry Andric   // Set the template parameter lists info.
19280b57cec5SDimitry Andric   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
19290b57cec5SDimitry Andric }
19300b57cec5SDimitry Andric 
19310b57cec5SDimitry Andric SourceLocation DeclaratorDecl::getOuterLocStart() const {
19320b57cec5SDimitry Andric   return getTemplateOrInnerLocStart(this);
19330b57cec5SDimitry Andric }
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric // Helper function: returns true if QT is or contains a type
19360b57cec5SDimitry Andric // having a postfix component.
19370b57cec5SDimitry Andric static bool typeIsPostfix(QualType QT) {
19380b57cec5SDimitry Andric   while (true) {
19390b57cec5SDimitry Andric     const Type* T = QT.getTypePtr();
19400b57cec5SDimitry Andric     switch (T->getTypeClass()) {
19410b57cec5SDimitry Andric     default:
19420b57cec5SDimitry Andric       return false;
19430b57cec5SDimitry Andric     case Type::Pointer:
19440b57cec5SDimitry Andric       QT = cast<PointerType>(T)->getPointeeType();
19450b57cec5SDimitry Andric       break;
19460b57cec5SDimitry Andric     case Type::BlockPointer:
19470b57cec5SDimitry Andric       QT = cast<BlockPointerType>(T)->getPointeeType();
19480b57cec5SDimitry Andric       break;
19490b57cec5SDimitry Andric     case Type::MemberPointer:
19500b57cec5SDimitry Andric       QT = cast<MemberPointerType>(T)->getPointeeType();
19510b57cec5SDimitry Andric       break;
19520b57cec5SDimitry Andric     case Type::LValueReference:
19530b57cec5SDimitry Andric     case Type::RValueReference:
19540b57cec5SDimitry Andric       QT = cast<ReferenceType>(T)->getPointeeType();
19550b57cec5SDimitry Andric       break;
19560b57cec5SDimitry Andric     case Type::PackExpansion:
19570b57cec5SDimitry Andric       QT = cast<PackExpansionType>(T)->getPattern();
19580b57cec5SDimitry Andric       break;
19590b57cec5SDimitry Andric     case Type::Paren:
19600b57cec5SDimitry Andric     case Type::ConstantArray:
19610b57cec5SDimitry Andric     case Type::DependentSizedArray:
19620b57cec5SDimitry Andric     case Type::IncompleteArray:
19630b57cec5SDimitry Andric     case Type::VariableArray:
19640b57cec5SDimitry Andric     case Type::FunctionProto:
19650b57cec5SDimitry Andric     case Type::FunctionNoProto:
19660b57cec5SDimitry Andric       return true;
19670b57cec5SDimitry Andric     }
19680b57cec5SDimitry Andric   }
19690b57cec5SDimitry Andric }
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric SourceRange DeclaratorDecl::getSourceRange() const {
19720b57cec5SDimitry Andric   SourceLocation RangeEnd = getLocation();
19730b57cec5SDimitry Andric   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
19740b57cec5SDimitry Andric     // If the declaration has no name or the type extends past the name take the
19750b57cec5SDimitry Andric     // end location of the type.
19760b57cec5SDimitry Andric     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
19770b57cec5SDimitry Andric       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
19780b57cec5SDimitry Andric   }
19790b57cec5SDimitry Andric   return SourceRange(getOuterLocStart(), RangeEnd);
19800b57cec5SDimitry Andric }
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric void QualifierInfo::setTemplateParameterListsInfo(
19830b57cec5SDimitry Andric     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
19840b57cec5SDimitry Andric   // Free previous template parameters (if any).
19850b57cec5SDimitry Andric   if (NumTemplParamLists > 0) {
19860b57cec5SDimitry Andric     Context.Deallocate(TemplParamLists);
19870b57cec5SDimitry Andric     TemplParamLists = nullptr;
19880b57cec5SDimitry Andric     NumTemplParamLists = 0;
19890b57cec5SDimitry Andric   }
19900b57cec5SDimitry Andric   // Set info on matched template parameter lists (if any).
19910b57cec5SDimitry Andric   if (!TPLists.empty()) {
19920b57cec5SDimitry Andric     TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
19930b57cec5SDimitry Andric     NumTemplParamLists = TPLists.size();
19940b57cec5SDimitry Andric     std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
19950b57cec5SDimitry Andric   }
19960b57cec5SDimitry Andric }
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
19990b57cec5SDimitry Andric // VarDecl Implementation
20000b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
20030b57cec5SDimitry Andric   switch (SC) {
20040b57cec5SDimitry Andric   case SC_None:                 break;
20050b57cec5SDimitry Andric   case SC_Auto:                 return "auto";
20060b57cec5SDimitry Andric   case SC_Extern:               return "extern";
20070b57cec5SDimitry Andric   case SC_PrivateExtern:        return "__private_extern__";
20080b57cec5SDimitry Andric   case SC_Register:             return "register";
20090b57cec5SDimitry Andric   case SC_Static:               return "static";
20100b57cec5SDimitry Andric   }
20110b57cec5SDimitry Andric 
20120b57cec5SDimitry Andric   llvm_unreachable("Invalid storage class");
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
20160b57cec5SDimitry Andric                  SourceLocation StartLoc, SourceLocation IdLoc,
20170b57cec5SDimitry Andric                  IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
20180b57cec5SDimitry Andric                  StorageClass SC)
20190b57cec5SDimitry Andric     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
20200b57cec5SDimitry Andric       redeclarable_base(C) {
20210b57cec5SDimitry Andric   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
20220b57cec5SDimitry Andric                 "VarDeclBitfields too large!");
20230b57cec5SDimitry Andric   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
20240b57cec5SDimitry Andric                 "ParmVarDeclBitfields too large!");
20250b57cec5SDimitry Andric   static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
20260b57cec5SDimitry Andric                 "NonParmVarDeclBitfields too large!");
20270b57cec5SDimitry Andric   AllBits = 0;
20280b57cec5SDimitry Andric   VarDeclBits.SClass = SC;
20290b57cec5SDimitry Andric   // Everything else is implicitly initialized to false.
20300b57cec5SDimitry Andric }
20310b57cec5SDimitry Andric 
20320b57cec5SDimitry Andric VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
20330b57cec5SDimitry Andric                          SourceLocation StartL, SourceLocation IdL,
20340b57cec5SDimitry Andric                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
20350b57cec5SDimitry Andric                          StorageClass S) {
20360b57cec5SDimitry Andric   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
20370b57cec5SDimitry Andric }
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
20400b57cec5SDimitry Andric   return new (C, ID)
20410b57cec5SDimitry Andric       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
20420b57cec5SDimitry Andric               QualType(), nullptr, SC_None);
20430b57cec5SDimitry Andric }
20440b57cec5SDimitry Andric 
20450b57cec5SDimitry Andric void VarDecl::setStorageClass(StorageClass SC) {
20460b57cec5SDimitry Andric   assert(isLegalForVariable(SC));
20470b57cec5SDimitry Andric   VarDeclBits.SClass = SC;
20480b57cec5SDimitry Andric }
20490b57cec5SDimitry Andric 
20500b57cec5SDimitry Andric VarDecl::TLSKind VarDecl::getTLSKind() const {
20510b57cec5SDimitry Andric   switch (VarDeclBits.TSCSpec) {
20520b57cec5SDimitry Andric   case TSCS_unspecified:
20530b57cec5SDimitry Andric     if (!hasAttr<ThreadAttr>() &&
20540b57cec5SDimitry Andric         !(getASTContext().getLangOpts().OpenMPUseTLS &&
20550b57cec5SDimitry Andric           getASTContext().getTargetInfo().isTLSSupported() &&
20560b57cec5SDimitry Andric           hasAttr<OMPThreadPrivateDeclAttr>()))
20570b57cec5SDimitry Andric       return TLS_None;
20580b57cec5SDimitry Andric     return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
20590b57cec5SDimitry Andric                 LangOptions::MSVC2015)) ||
20600b57cec5SDimitry Andric             hasAttr<OMPThreadPrivateDeclAttr>())
20610b57cec5SDimitry Andric                ? TLS_Dynamic
20620b57cec5SDimitry Andric                : TLS_Static;
20630b57cec5SDimitry Andric   case TSCS___thread: // Fall through.
20640b57cec5SDimitry Andric   case TSCS__Thread_local:
20650b57cec5SDimitry Andric     return TLS_Static;
20660b57cec5SDimitry Andric   case TSCS_thread_local:
20670b57cec5SDimitry Andric     return TLS_Dynamic;
20680b57cec5SDimitry Andric   }
20690b57cec5SDimitry Andric   llvm_unreachable("Unknown thread storage class specifier!");
20700b57cec5SDimitry Andric }
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric SourceRange VarDecl::getSourceRange() const {
20730b57cec5SDimitry Andric   if (const Expr *Init = getInit()) {
20740b57cec5SDimitry Andric     SourceLocation InitEnd = Init->getEndLoc();
20750b57cec5SDimitry Andric     // If Init is implicit, ignore its source range and fallback on
20760b57cec5SDimitry Andric     // DeclaratorDecl::getSourceRange() to handle postfix elements.
20770b57cec5SDimitry Andric     if (InitEnd.isValid() && InitEnd != getLocation())
20780b57cec5SDimitry Andric       return SourceRange(getOuterLocStart(), InitEnd);
20790b57cec5SDimitry Andric   }
20800b57cec5SDimitry Andric   return DeclaratorDecl::getSourceRange();
20810b57cec5SDimitry Andric }
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric template<typename T>
20840b57cec5SDimitry Andric static LanguageLinkage getDeclLanguageLinkage(const T &D) {
20850b57cec5SDimitry Andric   // C++ [dcl.link]p1: All function types, function names with external linkage,
20860b57cec5SDimitry Andric   // and variable names with external linkage have a language linkage.
20870b57cec5SDimitry Andric   if (!D.hasExternalFormalLinkage())
20880b57cec5SDimitry Andric     return NoLanguageLinkage;
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric   // Language linkage is a C++ concept, but saying that everything else in C has
20910b57cec5SDimitry Andric   // C language linkage fits the implementation nicely.
20920b57cec5SDimitry Andric   ASTContext &Context = D.getASTContext();
20930b57cec5SDimitry Andric   if (!Context.getLangOpts().CPlusPlus)
20940b57cec5SDimitry Andric     return CLanguageLinkage;
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
20970b57cec5SDimitry Andric   // language linkage of the names of class members and the function type of
20980b57cec5SDimitry Andric   // class member functions.
20990b57cec5SDimitry Andric   const DeclContext *DC = D.getDeclContext();
21000b57cec5SDimitry Andric   if (DC->isRecord())
21010b57cec5SDimitry Andric     return CXXLanguageLinkage;
21020b57cec5SDimitry Andric 
21030b57cec5SDimitry Andric   // If the first decl is in an extern "C" context, any other redeclaration
21040b57cec5SDimitry Andric   // will have C language linkage. If the first one is not in an extern "C"
21050b57cec5SDimitry Andric   // context, we would have reported an error for any other decl being in one.
21060b57cec5SDimitry Andric   if (isFirstInExternCContext(&D))
21070b57cec5SDimitry Andric     return CLanguageLinkage;
21080b57cec5SDimitry Andric   return CXXLanguageLinkage;
21090b57cec5SDimitry Andric }
21100b57cec5SDimitry Andric 
21110b57cec5SDimitry Andric template<typename T>
21120b57cec5SDimitry Andric static bool isDeclExternC(const T &D) {
21130b57cec5SDimitry Andric   // Since the context is ignored for class members, they can only have C++
21140b57cec5SDimitry Andric   // language linkage or no language linkage.
21150b57cec5SDimitry Andric   const DeclContext *DC = D.getDeclContext();
21160b57cec5SDimitry Andric   if (DC->isRecord()) {
21170b57cec5SDimitry Andric     assert(D.getASTContext().getLangOpts().CPlusPlus);
21180b57cec5SDimitry Andric     return false;
21190b57cec5SDimitry Andric   }
21200b57cec5SDimitry Andric 
21210b57cec5SDimitry Andric   return D.getLanguageLinkage() == CLanguageLinkage;
21220b57cec5SDimitry Andric }
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric LanguageLinkage VarDecl::getLanguageLinkage() const {
21250b57cec5SDimitry Andric   return getDeclLanguageLinkage(*this);
21260b57cec5SDimitry Andric }
21270b57cec5SDimitry Andric 
21280b57cec5SDimitry Andric bool VarDecl::isExternC() const {
21290b57cec5SDimitry Andric   return isDeclExternC(*this);
21300b57cec5SDimitry Andric }
21310b57cec5SDimitry Andric 
21320b57cec5SDimitry Andric bool VarDecl::isInExternCContext() const {
21330b57cec5SDimitry Andric   return getLexicalDeclContext()->isExternCContext();
21340b57cec5SDimitry Andric }
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric bool VarDecl::isInExternCXXContext() const {
21370b57cec5SDimitry Andric   return getLexicalDeclContext()->isExternCXXContext();
21380b57cec5SDimitry Andric }
21390b57cec5SDimitry Andric 
21400b57cec5SDimitry Andric VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
21410b57cec5SDimitry Andric 
21420b57cec5SDimitry Andric VarDecl::DefinitionKind
21430b57cec5SDimitry Andric VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
21440b57cec5SDimitry Andric   if (isThisDeclarationADemotedDefinition())
21450b57cec5SDimitry Andric     return DeclarationOnly;
21460b57cec5SDimitry Andric 
21470b57cec5SDimitry Andric   // C++ [basic.def]p2:
21480b57cec5SDimitry Andric   //   A declaration is a definition unless [...] it contains the 'extern'
21490b57cec5SDimitry Andric   //   specifier or a linkage-specification and neither an initializer [...],
21500b57cec5SDimitry Andric   //   it declares a non-inline static data member in a class declaration [...],
21510b57cec5SDimitry Andric   //   it declares a static data member outside a class definition and the variable
21520b57cec5SDimitry Andric   //   was defined within the class with the constexpr specifier [...],
21530b57cec5SDimitry Andric   // C++1y [temp.expl.spec]p15:
21540b57cec5SDimitry Andric   //   An explicit specialization of a static data member or an explicit
21550b57cec5SDimitry Andric   //   specialization of a static data member template is a definition if the
21560b57cec5SDimitry Andric   //   declaration includes an initializer; otherwise, it is a declaration.
21570b57cec5SDimitry Andric   //
21580b57cec5SDimitry Andric   // FIXME: How do you declare (but not define) a partial specialization of
21590b57cec5SDimitry Andric   // a static data member template outside the containing class?
21600b57cec5SDimitry Andric   if (isStaticDataMember()) {
21610b57cec5SDimitry Andric     if (isOutOfLine() &&
21620b57cec5SDimitry Andric         !(getCanonicalDecl()->isInline() &&
21630b57cec5SDimitry Andric           getCanonicalDecl()->isConstexpr()) &&
21640b57cec5SDimitry Andric         (hasInit() ||
21650b57cec5SDimitry Andric          // If the first declaration is out-of-line, this may be an
21660b57cec5SDimitry Andric          // instantiation of an out-of-line partial specialization of a variable
21670b57cec5SDimitry Andric          // template for which we have not yet instantiated the initializer.
21680b57cec5SDimitry Andric          (getFirstDecl()->isOutOfLine()
21690b57cec5SDimitry Andric               ? getTemplateSpecializationKind() == TSK_Undeclared
21700b57cec5SDimitry Andric               : getTemplateSpecializationKind() !=
21710b57cec5SDimitry Andric                     TSK_ExplicitSpecialization) ||
21720b57cec5SDimitry Andric          isa<VarTemplatePartialSpecializationDecl>(this)))
21730b57cec5SDimitry Andric       return Definition;
2174e8d8bef9SDimitry Andric     if (!isOutOfLine() && isInline())
21750b57cec5SDimitry Andric       return Definition;
21760b57cec5SDimitry Andric     return DeclarationOnly;
21770b57cec5SDimitry Andric   }
21780b57cec5SDimitry Andric   // C99 6.7p5:
21790b57cec5SDimitry Andric   //   A definition of an identifier is a declaration for that identifier that
21800b57cec5SDimitry Andric   //   [...] causes storage to be reserved for that object.
21810b57cec5SDimitry Andric   // Note: that applies for all non-file-scope objects.
21820b57cec5SDimitry Andric   // C99 6.9.2p1:
21830b57cec5SDimitry Andric   //   If the declaration of an identifier for an object has file scope and an
21840b57cec5SDimitry Andric   //   initializer, the declaration is an external definition for the identifier
21850b57cec5SDimitry Andric   if (hasInit())
21860b57cec5SDimitry Andric     return Definition;
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric   if (hasDefiningAttr())
21890b57cec5SDimitry Andric     return Definition;
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric   if (const auto *SAA = getAttr<SelectAnyAttr>())
21920b57cec5SDimitry Andric     if (!SAA->isInherited())
21930b57cec5SDimitry Andric       return Definition;
21940b57cec5SDimitry Andric 
21950b57cec5SDimitry Andric   // A variable template specialization (other than a static data member
21960b57cec5SDimitry Andric   // template or an explicit specialization) is a declaration until we
21970b57cec5SDimitry Andric   // instantiate its initializer.
21980b57cec5SDimitry Andric   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
21990b57cec5SDimitry Andric     if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
22000b57cec5SDimitry Andric         !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
22010b57cec5SDimitry Andric         !VTSD->IsCompleteDefinition)
22020b57cec5SDimitry Andric       return DeclarationOnly;
22030b57cec5SDimitry Andric   }
22040b57cec5SDimitry Andric 
22050b57cec5SDimitry Andric   if (hasExternalStorage())
22060b57cec5SDimitry Andric     return DeclarationOnly;
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric   // [dcl.link] p7:
22090b57cec5SDimitry Andric   //   A declaration directly contained in a linkage-specification is treated
22100b57cec5SDimitry Andric   //   as if it contains the extern specifier for the purpose of determining
22110b57cec5SDimitry Andric   //   the linkage of the declared name and whether it is a definition.
22120b57cec5SDimitry Andric   if (isSingleLineLanguageLinkage(*this))
22130b57cec5SDimitry Andric     return DeclarationOnly;
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric   // C99 6.9.2p2:
22160b57cec5SDimitry Andric   //   A declaration of an object that has file scope without an initializer,
22170b57cec5SDimitry Andric   //   and without a storage class specifier or the scs 'static', constitutes
22180b57cec5SDimitry Andric   //   a tentative definition.
22190b57cec5SDimitry Andric   // No such thing in C++.
22200b57cec5SDimitry Andric   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
22210b57cec5SDimitry Andric     return TentativeDefinition;
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric   // What's left is (in C, block-scope) declarations without initializers or
22240b57cec5SDimitry Andric   // external storage. These are definitions.
22250b57cec5SDimitry Andric   return Definition;
22260b57cec5SDimitry Andric }
22270b57cec5SDimitry Andric 
22280b57cec5SDimitry Andric VarDecl *VarDecl::getActingDefinition() {
22290b57cec5SDimitry Andric   DefinitionKind Kind = isThisDeclarationADefinition();
22300b57cec5SDimitry Andric   if (Kind != TentativeDefinition)
22310b57cec5SDimitry Andric     return nullptr;
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric   VarDecl *LastTentative = nullptr;
2234*349cc55cSDimitry Andric 
2235*349cc55cSDimitry Andric   // Loop through the declaration chain, starting with the most recent.
2236*349cc55cSDimitry Andric   for (VarDecl *Decl = getMostRecentDecl(); Decl;
2237*349cc55cSDimitry Andric        Decl = Decl->getPreviousDecl()) {
2238*349cc55cSDimitry Andric     Kind = Decl->isThisDeclarationADefinition();
22390b57cec5SDimitry Andric     if (Kind == Definition)
22400b57cec5SDimitry Andric       return nullptr;
2241*349cc55cSDimitry Andric     // Record the first (most recent) TentativeDefinition that is encountered.
2242*349cc55cSDimitry Andric     if (Kind == TentativeDefinition && !LastTentative)
2243*349cc55cSDimitry Andric       LastTentative = Decl;
22440b57cec5SDimitry Andric   }
2245*349cc55cSDimitry Andric 
22460b57cec5SDimitry Andric   return LastTentative;
22470b57cec5SDimitry Andric }
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric VarDecl *VarDecl::getDefinition(ASTContext &C) {
22500b57cec5SDimitry Andric   VarDecl *First = getFirstDecl();
22510b57cec5SDimitry Andric   for (auto I : First->redecls()) {
22520b57cec5SDimitry Andric     if (I->isThisDeclarationADefinition(C) == Definition)
22530b57cec5SDimitry Andric       return I;
22540b57cec5SDimitry Andric   }
22550b57cec5SDimitry Andric   return nullptr;
22560b57cec5SDimitry Andric }
22570b57cec5SDimitry Andric 
22580b57cec5SDimitry Andric VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
22590b57cec5SDimitry Andric   DefinitionKind Kind = DeclarationOnly;
22600b57cec5SDimitry Andric 
22610b57cec5SDimitry Andric   const VarDecl *First = getFirstDecl();
22620b57cec5SDimitry Andric   for (auto I : First->redecls()) {
22630b57cec5SDimitry Andric     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
22640b57cec5SDimitry Andric     if (Kind == Definition)
22650b57cec5SDimitry Andric       break;
22660b57cec5SDimitry Andric   }
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric   return Kind;
22690b57cec5SDimitry Andric }
22700b57cec5SDimitry Andric 
22710b57cec5SDimitry Andric const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
22720b57cec5SDimitry Andric   for (auto I : redecls()) {
22730b57cec5SDimitry Andric     if (auto Expr = I->getInit()) {
22740b57cec5SDimitry Andric       D = I;
22750b57cec5SDimitry Andric       return Expr;
22760b57cec5SDimitry Andric     }
22770b57cec5SDimitry Andric   }
22780b57cec5SDimitry Andric   return nullptr;
22790b57cec5SDimitry Andric }
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric bool VarDecl::hasInit() const {
22820b57cec5SDimitry Andric   if (auto *P = dyn_cast<ParmVarDecl>(this))
22830b57cec5SDimitry Andric     if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
22840b57cec5SDimitry Andric       return false;
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric   return !Init.isNull();
22870b57cec5SDimitry Andric }
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric Expr *VarDecl::getInit() {
22900b57cec5SDimitry Andric   if (!hasInit())
22910b57cec5SDimitry Andric     return nullptr;
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric   if (auto *S = Init.dyn_cast<Stmt *>())
22940b57cec5SDimitry Andric     return cast<Expr>(S);
22950b57cec5SDimitry Andric 
22960b57cec5SDimitry Andric   return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
22970b57cec5SDimitry Andric }
22980b57cec5SDimitry Andric 
22990b57cec5SDimitry Andric Stmt **VarDecl::getInitAddress() {
23000b57cec5SDimitry Andric   if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
23010b57cec5SDimitry Andric     return &ES->Value;
23020b57cec5SDimitry Andric 
23030b57cec5SDimitry Andric   return Init.getAddrOfPtr1();
23040b57cec5SDimitry Andric }
23050b57cec5SDimitry Andric 
2306a7dea167SDimitry Andric VarDecl *VarDecl::getInitializingDeclaration() {
2307a7dea167SDimitry Andric   VarDecl *Def = nullptr;
2308a7dea167SDimitry Andric   for (auto I : redecls()) {
2309a7dea167SDimitry Andric     if (I->hasInit())
2310a7dea167SDimitry Andric       return I;
2311a7dea167SDimitry Andric 
2312a7dea167SDimitry Andric     if (I->isThisDeclarationADefinition()) {
2313a7dea167SDimitry Andric       if (isStaticDataMember())
2314a7dea167SDimitry Andric         return I;
2315a7dea167SDimitry Andric       Def = I;
2316a7dea167SDimitry Andric     }
2317a7dea167SDimitry Andric   }
2318a7dea167SDimitry Andric   return Def;
2319a7dea167SDimitry Andric }
2320a7dea167SDimitry Andric 
23210b57cec5SDimitry Andric bool VarDecl::isOutOfLine() const {
23220b57cec5SDimitry Andric   if (Decl::isOutOfLine())
23230b57cec5SDimitry Andric     return true;
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric   if (!isStaticDataMember())
23260b57cec5SDimitry Andric     return false;
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric   // If this static data member was instantiated from a static data member of
23290b57cec5SDimitry Andric   // a class template, check whether that static data member was defined
23300b57cec5SDimitry Andric   // out-of-line.
23310b57cec5SDimitry Andric   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
23320b57cec5SDimitry Andric     return VD->isOutOfLine();
23330b57cec5SDimitry Andric 
23340b57cec5SDimitry Andric   return false;
23350b57cec5SDimitry Andric }
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric void VarDecl::setInit(Expr *I) {
23380b57cec5SDimitry Andric   if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
23390b57cec5SDimitry Andric     Eval->~EvaluatedStmt();
23400b57cec5SDimitry Andric     getASTContext().Deallocate(Eval);
23410b57cec5SDimitry Andric   }
23420b57cec5SDimitry Andric 
23430b57cec5SDimitry Andric   Init = I;
23440b57cec5SDimitry Andric }
23450b57cec5SDimitry Andric 
2346e8d8bef9SDimitry Andric bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
23470b57cec5SDimitry Andric   const LangOptions &Lang = C.getLangOpts();
23480b57cec5SDimitry Andric 
2349e8d8bef9SDimitry Andric   // OpenCL permits const integral variables to be used in constant
2350e8d8bef9SDimitry Andric   // expressions, like in C++98.
2351e8d8bef9SDimitry Andric   if (!Lang.CPlusPlus && !Lang.OpenCL)
23520b57cec5SDimitry Andric     return false;
23530b57cec5SDimitry Andric 
23540b57cec5SDimitry Andric   // Function parameters are never usable in constant expressions.
23550b57cec5SDimitry Andric   if (isa<ParmVarDecl>(this))
23560b57cec5SDimitry Andric     return false;
23570b57cec5SDimitry Andric 
2358e8d8bef9SDimitry Andric   // The values of weak variables are never usable in constant expressions.
2359e8d8bef9SDimitry Andric   if (isWeak())
2360e8d8bef9SDimitry Andric     return false;
2361e8d8bef9SDimitry Andric 
23620b57cec5SDimitry Andric   // In C++11, any variable of reference type can be used in a constant
23630b57cec5SDimitry Andric   // expression if it is initialized by a constant expression.
23640b57cec5SDimitry Andric   if (Lang.CPlusPlus11 && getType()->isReferenceType())
23650b57cec5SDimitry Andric     return true;
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric   // Only const objects can be used in constant expressions in C++. C++98 does
23680b57cec5SDimitry Andric   // not require the variable to be non-volatile, but we consider this to be a
23690b57cec5SDimitry Andric   // defect.
2370e8d8bef9SDimitry Andric   if (!getType().isConstant(C) || getType().isVolatileQualified())
23710b57cec5SDimitry Andric     return false;
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric   // In C++, const, non-volatile variables of integral or enumeration types
23740b57cec5SDimitry Andric   // can be used in constant expressions.
23750b57cec5SDimitry Andric   if (getType()->isIntegralOrEnumerationType())
23760b57cec5SDimitry Andric     return true;
23770b57cec5SDimitry Andric 
23780b57cec5SDimitry Andric   // Additionally, in C++11, non-volatile constexpr variables can be used in
23790b57cec5SDimitry Andric   // constant expressions.
23800b57cec5SDimitry Andric   return Lang.CPlusPlus11 && isConstexpr();
23810b57cec5SDimitry Andric }
23820b57cec5SDimitry Andric 
2383e8d8bef9SDimitry Andric bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
23840b57cec5SDimitry Andric   // C++2a [expr.const]p3:
23850b57cec5SDimitry Andric   //   A variable is usable in constant expressions after its initializing
23860b57cec5SDimitry Andric   //   declaration is encountered...
23870b57cec5SDimitry Andric   const VarDecl *DefVD = nullptr;
23880b57cec5SDimitry Andric   const Expr *Init = getAnyInitializer(DefVD);
23890b57cec5SDimitry Andric   if (!Init || Init->isValueDependent() || getType()->isDependentType())
23900b57cec5SDimitry Andric     return false;
23910b57cec5SDimitry Andric   //   ... if it is a constexpr variable, or it is of reference type or of
23920b57cec5SDimitry Andric   //   const-qualified integral or enumeration type, ...
23930b57cec5SDimitry Andric   if (!DefVD->mightBeUsableInConstantExpressions(Context))
23940b57cec5SDimitry Andric     return false;
23950b57cec5SDimitry Andric   //   ... and its initializer is a constant initializer.
2396e8d8bef9SDimitry Andric   if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2397e8d8bef9SDimitry Andric     return false;
2398e8d8bef9SDimitry Andric   // C++98 [expr.const]p1:
2399e8d8bef9SDimitry Andric   //   An integral constant-expression can involve only [...] const variables
2400e8d8bef9SDimitry Andric   //   or static data members of integral or enumeration types initialized with
2401e8d8bef9SDimitry Andric   //   [integer] constant expressions (dcl.init)
2402e8d8bef9SDimitry Andric   if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2403e8d8bef9SDimitry Andric       !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2404e8d8bef9SDimitry Andric     return false;
2405e8d8bef9SDimitry Andric   return true;
24060b57cec5SDimitry Andric }
24070b57cec5SDimitry Andric 
24080b57cec5SDimitry Andric /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
24090b57cec5SDimitry Andric /// form, which contains extra information on the evaluated value of the
24100b57cec5SDimitry Andric /// initializer.
24110b57cec5SDimitry Andric EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
24120b57cec5SDimitry Andric   auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
24130b57cec5SDimitry Andric   if (!Eval) {
24140b57cec5SDimitry Andric     // Note: EvaluatedStmt contains an APValue, which usually holds
24150b57cec5SDimitry Andric     // resources not allocated from the ASTContext.  We need to do some
24160b57cec5SDimitry Andric     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
24170b57cec5SDimitry Andric     // where we can detect whether there's anything to clean up or not.
24180b57cec5SDimitry Andric     Eval = new (getASTContext()) EvaluatedStmt;
24190b57cec5SDimitry Andric     Eval->Value = Init.get<Stmt *>();
24200b57cec5SDimitry Andric     Init = Eval;
24210b57cec5SDimitry Andric   }
24220b57cec5SDimitry Andric   return Eval;
24230b57cec5SDimitry Andric }
24240b57cec5SDimitry Andric 
2425e8d8bef9SDimitry Andric EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2426e8d8bef9SDimitry Andric   return Init.dyn_cast<EvaluatedStmt *>();
24270b57cec5SDimitry Andric }
24280b57cec5SDimitry Andric 
2429e8d8bef9SDimitry Andric APValue *VarDecl::evaluateValue() const {
2430e8d8bef9SDimitry Andric   SmallVector<PartialDiagnosticAt, 8> Notes;
2431d409305fSDimitry Andric   return evaluateValue(Notes);
2432e8d8bef9SDimitry Andric }
2433e8d8bef9SDimitry Andric 
2434d409305fSDimitry Andric APValue *VarDecl::evaluateValue(
2435d409305fSDimitry Andric     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
24360b57cec5SDimitry Andric   EvaluatedStmt *Eval = ensureEvaluatedStmt();
24370b57cec5SDimitry Andric 
2438e8d8bef9SDimitry Andric   const auto *Init = cast<Expr>(Eval->Value);
2439e8d8bef9SDimitry Andric   assert(!Init->isValueDependent());
2440e8d8bef9SDimitry Andric 
24410b57cec5SDimitry Andric   // We only produce notes indicating why an initializer is non-constant the
24420b57cec5SDimitry Andric   // first time it is evaluated. FIXME: The notes won't always be emitted the
24430b57cec5SDimitry Andric   // first time we try evaluation, so might not be produced at all.
24440b57cec5SDimitry Andric   if (Eval->WasEvaluated)
24450b57cec5SDimitry Andric     return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
24460b57cec5SDimitry Andric 
24470b57cec5SDimitry Andric   if (Eval->IsEvaluating) {
24480b57cec5SDimitry Andric     // FIXME: Produce a diagnostic for self-initialization.
24490b57cec5SDimitry Andric     return nullptr;
24500b57cec5SDimitry Andric   }
24510b57cec5SDimitry Andric 
24520b57cec5SDimitry Andric   Eval->IsEvaluating = true;
24530b57cec5SDimitry Andric 
2454d409305fSDimitry Andric   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2455d409305fSDimitry Andric                                             this, Notes);
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
24580b57cec5SDimitry Andric   // or that it's empty (so that there's nothing to clean up) if evaluation
24590b57cec5SDimitry Andric   // failed.
24600b57cec5SDimitry Andric   if (!Result)
24610b57cec5SDimitry Andric     Eval->Evaluated = APValue();
24620b57cec5SDimitry Andric   else if (Eval->Evaluated.needsCleanup())
2463d409305fSDimitry Andric     getASTContext().addDestruction(&Eval->Evaluated);
24640b57cec5SDimitry Andric 
24650b57cec5SDimitry Andric   Eval->IsEvaluating = false;
24660b57cec5SDimitry Andric   Eval->WasEvaluated = true;
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric   return Result ? &Eval->Evaluated : nullptr;
24690b57cec5SDimitry Andric }
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric APValue *VarDecl::getEvaluatedValue() const {
2472e8d8bef9SDimitry Andric   if (EvaluatedStmt *Eval = getEvaluatedStmt())
24730b57cec5SDimitry Andric     if (Eval->WasEvaluated)
24740b57cec5SDimitry Andric       return &Eval->Evaluated;
24750b57cec5SDimitry Andric 
24760b57cec5SDimitry Andric   return nullptr;
24770b57cec5SDimitry Andric }
24780b57cec5SDimitry Andric 
2479e8d8bef9SDimitry Andric bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2480e8d8bef9SDimitry Andric   const Expr *Init = getInit();
2481e8d8bef9SDimitry Andric   assert(Init && "no initializer");
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2484e8d8bef9SDimitry Andric   if (!Eval->CheckedForICEInit) {
2485e8d8bef9SDimitry Andric     Eval->CheckedForICEInit = true;
2486e8d8bef9SDimitry Andric     Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2487e8d8bef9SDimitry Andric   }
2488e8d8bef9SDimitry Andric   return Eval->HasICEInit;
24890b57cec5SDimitry Andric }
24900b57cec5SDimitry Andric 
2491e8d8bef9SDimitry Andric bool VarDecl::hasConstantInitialization() const {
2492e8d8bef9SDimitry Andric   // In C, all globals (and only globals) have constant initialization.
2493e8d8bef9SDimitry Andric   if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus)
2494e8d8bef9SDimitry Andric     return true;
24950b57cec5SDimitry Andric 
2496e8d8bef9SDimitry Andric   // In C++, it depends on whether the evaluation at the point of definition
2497e8d8bef9SDimitry Andric   // was evaluatable as a constant initializer.
2498e8d8bef9SDimitry Andric   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2499e8d8bef9SDimitry Andric     return Eval->HasConstantInitialization;
2500e8d8bef9SDimitry Andric 
25010b57cec5SDimitry Andric   return false;
2502e8d8bef9SDimitry Andric }
25030b57cec5SDimitry Andric 
2504e8d8bef9SDimitry Andric bool VarDecl::checkForConstantInitialization(
2505e8d8bef9SDimitry Andric     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2506e8d8bef9SDimitry Andric   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2507e8d8bef9SDimitry Andric   // If we ask for the value before we know whether we have a constant
2508e8d8bef9SDimitry Andric   // initializer, we can compute the wrong value (for example, due to
2509e8d8bef9SDimitry Andric   // std::is_constant_evaluated()).
2510e8d8bef9SDimitry Andric   assert(!Eval->WasEvaluated &&
2511e8d8bef9SDimitry Andric          "already evaluated var value before checking for constant init");
2512e8d8bef9SDimitry Andric   assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++");
2513e8d8bef9SDimitry Andric 
2514e8d8bef9SDimitry Andric   assert(!cast<Expr>(Eval->Value)->isValueDependent());
2515e8d8bef9SDimitry Andric 
2516e8d8bef9SDimitry Andric   // Evaluate the initializer to check whether it's a constant expression.
2517d409305fSDimitry Andric   Eval->HasConstantInitialization = evaluateValue(Notes) && Notes.empty();
2518e8d8bef9SDimitry Andric   return Eval->HasConstantInitialization;
25190b57cec5SDimitry Andric }
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric bool VarDecl::isParameterPack() const {
25220b57cec5SDimitry Andric   return isa<PackExpansionType>(getType());
25230b57cec5SDimitry Andric }
25240b57cec5SDimitry Andric 
25250b57cec5SDimitry Andric template<typename DeclT>
25260b57cec5SDimitry Andric static DeclT *getDefinitionOrSelf(DeclT *D) {
25270b57cec5SDimitry Andric   assert(D);
25280b57cec5SDimitry Andric   if (auto *Def = D->getDefinition())
25290b57cec5SDimitry Andric     return Def;
25300b57cec5SDimitry Andric   return D;
25310b57cec5SDimitry Andric }
25320b57cec5SDimitry Andric 
25330b57cec5SDimitry Andric bool VarDecl::isEscapingByref() const {
25340b57cec5SDimitry Andric   return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
25350b57cec5SDimitry Andric }
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric bool VarDecl::isNonEscapingByref() const {
25380b57cec5SDimitry Andric   return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
25390b57cec5SDimitry Andric }
25400b57cec5SDimitry Andric 
2541fe6060f1SDimitry Andric bool VarDecl::hasDependentAlignment() const {
2542fe6060f1SDimitry Andric   QualType T = getType();
2543fe6060f1SDimitry Andric   return T->isDependentType() || T->isUndeducedAutoType() ||
2544fe6060f1SDimitry Andric          llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {
2545fe6060f1SDimitry Andric            return AA->isAlignmentDependent();
2546fe6060f1SDimitry Andric          });
2547fe6060f1SDimitry Andric }
2548fe6060f1SDimitry Andric 
25490b57cec5SDimitry Andric VarDecl *VarDecl::getTemplateInstantiationPattern() const {
25500b57cec5SDimitry Andric   const VarDecl *VD = this;
25510b57cec5SDimitry Andric 
25520b57cec5SDimitry Andric   // If this is an instantiated member, walk back to the template from which
25530b57cec5SDimitry Andric   // it was instantiated.
25540b57cec5SDimitry Andric   if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
25550b57cec5SDimitry Andric     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
25560b57cec5SDimitry Andric       VD = VD->getInstantiatedFromStaticDataMember();
25570b57cec5SDimitry Andric       while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
25580b57cec5SDimitry Andric         VD = NewVD;
25590b57cec5SDimitry Andric     }
25600b57cec5SDimitry Andric   }
25610b57cec5SDimitry Andric 
25620b57cec5SDimitry Andric   // If it's an instantiated variable template specialization, find the
25630b57cec5SDimitry Andric   // template or partial specialization from which it was instantiated.
25640b57cec5SDimitry Andric   if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
25650b57cec5SDimitry Andric     if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
25660b57cec5SDimitry Andric       auto From = VDTemplSpec->getInstantiatedFrom();
25670b57cec5SDimitry Andric       if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
25680b57cec5SDimitry Andric         while (!VTD->isMemberSpecialization()) {
25690b57cec5SDimitry Andric           auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
25700b57cec5SDimitry Andric           if (!NewVTD)
25710b57cec5SDimitry Andric             break;
25720b57cec5SDimitry Andric           VTD = NewVTD;
25730b57cec5SDimitry Andric         }
25740b57cec5SDimitry Andric         return getDefinitionOrSelf(VTD->getTemplatedDecl());
25750b57cec5SDimitry Andric       }
25760b57cec5SDimitry Andric       if (auto *VTPSD =
25770b57cec5SDimitry Andric               From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
25780b57cec5SDimitry Andric         while (!VTPSD->isMemberSpecialization()) {
25790b57cec5SDimitry Andric           auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
25800b57cec5SDimitry Andric           if (!NewVTPSD)
25810b57cec5SDimitry Andric             break;
25820b57cec5SDimitry Andric           VTPSD = NewVTPSD;
25830b57cec5SDimitry Andric         }
25840b57cec5SDimitry Andric         return getDefinitionOrSelf<VarDecl>(VTPSD);
25850b57cec5SDimitry Andric       }
25860b57cec5SDimitry Andric     }
25870b57cec5SDimitry Andric   }
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric   // If this is the pattern of a variable template, find where it was
25900b57cec5SDimitry Andric   // instantiated from. FIXME: Is this necessary?
25910b57cec5SDimitry Andric   if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
25920b57cec5SDimitry Andric     while (!VarTemplate->isMemberSpecialization()) {
25930b57cec5SDimitry Andric       auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
25940b57cec5SDimitry Andric       if (!NewVT)
25950b57cec5SDimitry Andric         break;
25960b57cec5SDimitry Andric       VarTemplate = NewVT;
25970b57cec5SDimitry Andric     }
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric     return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
26000b57cec5SDimitry Andric   }
26010b57cec5SDimitry Andric 
26020b57cec5SDimitry Andric   if (VD == this)
26030b57cec5SDimitry Andric     return nullptr;
26040b57cec5SDimitry Andric   return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
26050b57cec5SDimitry Andric }
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
26080b57cec5SDimitry Andric   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
26090b57cec5SDimitry Andric     return cast<VarDecl>(MSI->getInstantiatedFrom());
26100b57cec5SDimitry Andric 
26110b57cec5SDimitry Andric   return nullptr;
26120b57cec5SDimitry Andric }
26130b57cec5SDimitry Andric 
26140b57cec5SDimitry Andric TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
26150b57cec5SDimitry Andric   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
26160b57cec5SDimitry Andric     return Spec->getSpecializationKind();
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
26190b57cec5SDimitry Andric     return MSI->getTemplateSpecializationKind();
26200b57cec5SDimitry Andric 
26210b57cec5SDimitry Andric   return TSK_Undeclared;
26220b57cec5SDimitry Andric }
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric TemplateSpecializationKind
26250b57cec5SDimitry Andric VarDecl::getTemplateSpecializationKindForInstantiation() const {
26260b57cec5SDimitry Andric   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
26270b57cec5SDimitry Andric     return MSI->getTemplateSpecializationKind();
26280b57cec5SDimitry Andric 
26290b57cec5SDimitry Andric   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
26300b57cec5SDimitry Andric     return Spec->getSpecializationKind();
26310b57cec5SDimitry Andric 
26320b57cec5SDimitry Andric   return TSK_Undeclared;
26330b57cec5SDimitry Andric }
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric SourceLocation VarDecl::getPointOfInstantiation() const {
26360b57cec5SDimitry Andric   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
26370b57cec5SDimitry Andric     return Spec->getPointOfInstantiation();
26380b57cec5SDimitry Andric 
26390b57cec5SDimitry Andric   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
26400b57cec5SDimitry Andric     return MSI->getPointOfInstantiation();
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric   return SourceLocation();
26430b57cec5SDimitry Andric }
26440b57cec5SDimitry Andric 
26450b57cec5SDimitry Andric VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
26460b57cec5SDimitry Andric   return getASTContext().getTemplateOrSpecializationInfo(this)
26470b57cec5SDimitry Andric       .dyn_cast<VarTemplateDecl *>();
26480b57cec5SDimitry Andric }
26490b57cec5SDimitry Andric 
26500b57cec5SDimitry Andric void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
26510b57cec5SDimitry Andric   getASTContext().setTemplateOrSpecializationInfo(this, Template);
26520b57cec5SDimitry Andric }
26530b57cec5SDimitry Andric 
26540b57cec5SDimitry Andric bool VarDecl::isKnownToBeDefined() const {
26550b57cec5SDimitry Andric   const auto &LangOpts = getASTContext().getLangOpts();
26560b57cec5SDimitry Andric   // In CUDA mode without relocatable device code, variables of form 'extern
26570b57cec5SDimitry Andric   // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
26580b57cec5SDimitry Andric   // memory pool.  These are never undefined variables, even if they appear
26590b57cec5SDimitry Andric   // inside of an anon namespace or static function.
26600b57cec5SDimitry Andric   //
26610b57cec5SDimitry Andric   // With CUDA relocatable device code enabled, these variables don't get
26620b57cec5SDimitry Andric   // special handling; they're treated like regular extern variables.
26630b57cec5SDimitry Andric   if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
26640b57cec5SDimitry Andric       hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
26650b57cec5SDimitry Andric       isa<IncompleteArrayType>(getType()))
26660b57cec5SDimitry Andric     return true;
26670b57cec5SDimitry Andric 
26680b57cec5SDimitry Andric   return hasDefinition();
26690b57cec5SDimitry Andric }
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
26720b57cec5SDimitry Andric   return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
26730b57cec5SDimitry Andric                                 (!Ctx.getLangOpts().RegisterStaticDestructors &&
26740b57cec5SDimitry Andric                                  !hasAttr<AlwaysDestroyAttr>()));
26750b57cec5SDimitry Andric }
26760b57cec5SDimitry Andric 
2677a7dea167SDimitry Andric QualType::DestructionKind
2678a7dea167SDimitry Andric VarDecl::needsDestruction(const ASTContext &Ctx) const {
2679e8d8bef9SDimitry Andric   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2680a7dea167SDimitry Andric     if (Eval->HasConstantDestruction)
2681a7dea167SDimitry Andric       return QualType::DK_none;
2682a7dea167SDimitry Andric 
2683a7dea167SDimitry Andric   if (isNoDestroy(Ctx))
2684a7dea167SDimitry Andric     return QualType::DK_none;
2685a7dea167SDimitry Andric 
2686a7dea167SDimitry Andric   return getType().isDestructedType();
2687a7dea167SDimitry Andric }
2688a7dea167SDimitry Andric 
26890b57cec5SDimitry Andric MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
26900b57cec5SDimitry Andric   if (isStaticDataMember())
26910b57cec5SDimitry Andric     // FIXME: Remove ?
26920b57cec5SDimitry Andric     // return getASTContext().getInstantiatedFromStaticDataMember(this);
26930b57cec5SDimitry Andric     return getASTContext().getTemplateOrSpecializationInfo(this)
26940b57cec5SDimitry Andric         .dyn_cast<MemberSpecializationInfo *>();
26950b57cec5SDimitry Andric   return nullptr;
26960b57cec5SDimitry Andric }
26970b57cec5SDimitry Andric 
26980b57cec5SDimitry Andric void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
26990b57cec5SDimitry Andric                                          SourceLocation PointOfInstantiation) {
27000b57cec5SDimitry Andric   assert((isa<VarTemplateSpecializationDecl>(this) ||
27010b57cec5SDimitry Andric           getMemberSpecializationInfo()) &&
27020b57cec5SDimitry Andric          "not a variable or static data member template specialization");
27030b57cec5SDimitry Andric 
27040b57cec5SDimitry Andric   if (VarTemplateSpecializationDecl *Spec =
27050b57cec5SDimitry Andric           dyn_cast<VarTemplateSpecializationDecl>(this)) {
27060b57cec5SDimitry Andric     Spec->setSpecializationKind(TSK);
27070b57cec5SDimitry Andric     if (TSK != TSK_ExplicitSpecialization &&
27080b57cec5SDimitry Andric         PointOfInstantiation.isValid() &&
27090b57cec5SDimitry Andric         Spec->getPointOfInstantiation().isInvalid()) {
27100b57cec5SDimitry Andric       Spec->setPointOfInstantiation(PointOfInstantiation);
27110b57cec5SDimitry Andric       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
27120b57cec5SDimitry Andric         L->InstantiationRequested(this);
27130b57cec5SDimitry Andric     }
27140b57cec5SDimitry Andric   } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
27150b57cec5SDimitry Andric     MSI->setTemplateSpecializationKind(TSK);
27160b57cec5SDimitry Andric     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
27170b57cec5SDimitry Andric         MSI->getPointOfInstantiation().isInvalid()) {
27180b57cec5SDimitry Andric       MSI->setPointOfInstantiation(PointOfInstantiation);
27190b57cec5SDimitry Andric       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
27200b57cec5SDimitry Andric         L->InstantiationRequested(this);
27210b57cec5SDimitry Andric     }
27220b57cec5SDimitry Andric   }
27230b57cec5SDimitry Andric }
27240b57cec5SDimitry Andric 
27250b57cec5SDimitry Andric void
27260b57cec5SDimitry Andric VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
27270b57cec5SDimitry Andric                                             TemplateSpecializationKind TSK) {
27280b57cec5SDimitry Andric   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
27290b57cec5SDimitry Andric          "Previous template or instantiation?");
27300b57cec5SDimitry Andric   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
27310b57cec5SDimitry Andric }
27320b57cec5SDimitry Andric 
27330b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
27340b57cec5SDimitry Andric // ParmVarDecl Implementation
27350b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
27360b57cec5SDimitry Andric 
27370b57cec5SDimitry Andric ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
27380b57cec5SDimitry Andric                                  SourceLocation StartLoc,
27390b57cec5SDimitry Andric                                  SourceLocation IdLoc, IdentifierInfo *Id,
27400b57cec5SDimitry Andric                                  QualType T, TypeSourceInfo *TInfo,
27410b57cec5SDimitry Andric                                  StorageClass S, Expr *DefArg) {
27420b57cec5SDimitry Andric   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
27430b57cec5SDimitry Andric                                  S, DefArg);
27440b57cec5SDimitry Andric }
27450b57cec5SDimitry Andric 
27460b57cec5SDimitry Andric QualType ParmVarDecl::getOriginalType() const {
27470b57cec5SDimitry Andric   TypeSourceInfo *TSI = getTypeSourceInfo();
27480b57cec5SDimitry Andric   QualType T = TSI ? TSI->getType() : getType();
27490b57cec5SDimitry Andric   if (const auto *DT = dyn_cast<DecayedType>(T))
27500b57cec5SDimitry Andric     return DT->getOriginalType();
27510b57cec5SDimitry Andric   return T;
27520b57cec5SDimitry Andric }
27530b57cec5SDimitry Andric 
27540b57cec5SDimitry Andric ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
27550b57cec5SDimitry Andric   return new (C, ID)
27560b57cec5SDimitry Andric       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
27570b57cec5SDimitry Andric                   nullptr, QualType(), nullptr, SC_None, nullptr);
27580b57cec5SDimitry Andric }
27590b57cec5SDimitry Andric 
27600b57cec5SDimitry Andric SourceRange ParmVarDecl::getSourceRange() const {
27610b57cec5SDimitry Andric   if (!hasInheritedDefaultArg()) {
27620b57cec5SDimitry Andric     SourceRange ArgRange = getDefaultArgRange();
27630b57cec5SDimitry Andric     if (ArgRange.isValid())
27640b57cec5SDimitry Andric       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
27650b57cec5SDimitry Andric   }
27660b57cec5SDimitry Andric 
27670b57cec5SDimitry Andric   // DeclaratorDecl considers the range of postfix types as overlapping with the
27680b57cec5SDimitry Andric   // declaration name, but this is not the case with parameters in ObjC methods.
27690b57cec5SDimitry Andric   if (isa<ObjCMethodDecl>(getDeclContext()))
27700b57cec5SDimitry Andric     return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
27710b57cec5SDimitry Andric 
27720b57cec5SDimitry Andric   return DeclaratorDecl::getSourceRange();
27730b57cec5SDimitry Andric }
27740b57cec5SDimitry Andric 
2775e8d8bef9SDimitry Andric bool ParmVarDecl::isDestroyedInCallee() const {
2776*349cc55cSDimitry Andric   // ns_consumed only affects code generation in ARC
2777e8d8bef9SDimitry Andric   if (hasAttr<NSConsumedAttr>())
2778*349cc55cSDimitry Andric     return getASTContext().getLangOpts().ObjCAutoRefCount;
2779e8d8bef9SDimitry Andric 
2780*349cc55cSDimitry Andric   // FIXME: isParamDestroyedInCallee() should probably imply
2781*349cc55cSDimitry Andric   // isDestructedType()
2782e8d8bef9SDimitry Andric   auto *RT = getType()->getAs<RecordType>();
2783*349cc55cSDimitry Andric   if (RT && RT->getDecl()->isParamDestroyedInCallee() &&
2784*349cc55cSDimitry Andric       getType().isDestructedType())
2785e8d8bef9SDimitry Andric     return true;
2786e8d8bef9SDimitry Andric 
2787e8d8bef9SDimitry Andric   return false;
2788e8d8bef9SDimitry Andric }
2789e8d8bef9SDimitry Andric 
27900b57cec5SDimitry Andric Expr *ParmVarDecl::getDefaultArg() {
27910b57cec5SDimitry Andric   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
27920b57cec5SDimitry Andric   assert(!hasUninstantiatedDefaultArg() &&
27930b57cec5SDimitry Andric          "Default argument is not yet instantiated!");
27940b57cec5SDimitry Andric 
27950b57cec5SDimitry Andric   Expr *Arg = getInit();
27960b57cec5SDimitry Andric   if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
27970b57cec5SDimitry Andric     return E->getSubExpr();
27980b57cec5SDimitry Andric 
27990b57cec5SDimitry Andric   return Arg;
28000b57cec5SDimitry Andric }
28010b57cec5SDimitry Andric 
28020b57cec5SDimitry Andric void ParmVarDecl::setDefaultArg(Expr *defarg) {
28030b57cec5SDimitry Andric   ParmVarDeclBits.DefaultArgKind = DAK_Normal;
28040b57cec5SDimitry Andric   Init = defarg;
28050b57cec5SDimitry Andric }
28060b57cec5SDimitry Andric 
28070b57cec5SDimitry Andric SourceRange ParmVarDecl::getDefaultArgRange() const {
28080b57cec5SDimitry Andric   switch (ParmVarDeclBits.DefaultArgKind) {
28090b57cec5SDimitry Andric   case DAK_None:
28100b57cec5SDimitry Andric   case DAK_Unparsed:
28110b57cec5SDimitry Andric     // Nothing we can do here.
28120b57cec5SDimitry Andric     return SourceRange();
28130b57cec5SDimitry Andric 
28140b57cec5SDimitry Andric   case DAK_Uninstantiated:
28150b57cec5SDimitry Andric     return getUninstantiatedDefaultArg()->getSourceRange();
28160b57cec5SDimitry Andric 
28170b57cec5SDimitry Andric   case DAK_Normal:
28180b57cec5SDimitry Andric     if (const Expr *E = getInit())
28190b57cec5SDimitry Andric       return E->getSourceRange();
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric     // Missing an actual expression, may be invalid.
28220b57cec5SDimitry Andric     return SourceRange();
28230b57cec5SDimitry Andric   }
28240b57cec5SDimitry Andric   llvm_unreachable("Invalid default argument kind.");
28250b57cec5SDimitry Andric }
28260b57cec5SDimitry Andric 
28270b57cec5SDimitry Andric void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
28280b57cec5SDimitry Andric   ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
28290b57cec5SDimitry Andric   Init = arg;
28300b57cec5SDimitry Andric }
28310b57cec5SDimitry Andric 
28320b57cec5SDimitry Andric Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
28330b57cec5SDimitry Andric   assert(hasUninstantiatedDefaultArg() &&
28340b57cec5SDimitry Andric          "Wrong kind of initialization expression!");
28350b57cec5SDimitry Andric   return cast_or_null<Expr>(Init.get<Stmt *>());
28360b57cec5SDimitry Andric }
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric bool ParmVarDecl::hasDefaultArg() const {
28390b57cec5SDimitry Andric   // FIXME: We should just return false for DAK_None here once callers are
28400b57cec5SDimitry Andric   // prepared for the case that we encountered an invalid default argument and
28410b57cec5SDimitry Andric   // were unable to even build an invalid expression.
28420b57cec5SDimitry Andric   return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
28430b57cec5SDimitry Andric          !Init.isNull();
28440b57cec5SDimitry Andric }
28450b57cec5SDimitry Andric 
28460b57cec5SDimitry Andric void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
28470b57cec5SDimitry Andric   getASTContext().setParameterIndex(this, parameterIndex);
28480b57cec5SDimitry Andric   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
28490b57cec5SDimitry Andric }
28500b57cec5SDimitry Andric 
28510b57cec5SDimitry Andric unsigned ParmVarDecl::getParameterIndexLarge() const {
28520b57cec5SDimitry Andric   return getASTContext().getParameterIndex(this);
28530b57cec5SDimitry Andric }
28540b57cec5SDimitry Andric 
28550b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
28560b57cec5SDimitry Andric // FunctionDecl Implementation
28570b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
28580b57cec5SDimitry Andric 
28590b57cec5SDimitry Andric FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
28600b57cec5SDimitry Andric                            SourceLocation StartLoc,
28610b57cec5SDimitry Andric                            const DeclarationNameInfo &NameInfo, QualType T,
28620b57cec5SDimitry Andric                            TypeSourceInfo *TInfo, StorageClass S,
2863*349cc55cSDimitry Andric                            bool UsesFPIntrin, bool isInlineSpecified,
2864480093f4SDimitry Andric                            ConstexprSpecKind ConstexprKind,
2865480093f4SDimitry Andric                            Expr *TrailingRequiresClause)
28660b57cec5SDimitry Andric     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
28670b57cec5SDimitry Andric                      StartLoc),
2868480093f4SDimitry Andric       DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
28690b57cec5SDimitry Andric       EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
28700b57cec5SDimitry Andric   assert(T.isNull() || T->isFunctionType());
28710b57cec5SDimitry Andric   FunctionDeclBits.SClass = S;
28720b57cec5SDimitry Andric   FunctionDeclBits.IsInline = isInlineSpecified;
28730b57cec5SDimitry Andric   FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
28740b57cec5SDimitry Andric   FunctionDeclBits.IsVirtualAsWritten = false;
28750b57cec5SDimitry Andric   FunctionDeclBits.IsPure = false;
28760b57cec5SDimitry Andric   FunctionDeclBits.HasInheritedPrototype = false;
28770b57cec5SDimitry Andric   FunctionDeclBits.HasWrittenPrototype = true;
28780b57cec5SDimitry Andric   FunctionDeclBits.IsDeleted = false;
28790b57cec5SDimitry Andric   FunctionDeclBits.IsTrivial = false;
28800b57cec5SDimitry Andric   FunctionDeclBits.IsTrivialForCall = false;
28810b57cec5SDimitry Andric   FunctionDeclBits.IsDefaulted = false;
28820b57cec5SDimitry Andric   FunctionDeclBits.IsExplicitlyDefaulted = false;
2883480093f4SDimitry Andric   FunctionDeclBits.HasDefaultedFunctionInfo = false;
28840b57cec5SDimitry Andric   FunctionDeclBits.HasImplicitReturnZero = false;
28850b57cec5SDimitry Andric   FunctionDeclBits.IsLateTemplateParsed = false;
2886e8d8bef9SDimitry Andric   FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
28870b57cec5SDimitry Andric   FunctionDeclBits.InstantiationIsPending = false;
28880b57cec5SDimitry Andric   FunctionDeclBits.UsesSEHTry = false;
2889*349cc55cSDimitry Andric   FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
28900b57cec5SDimitry Andric   FunctionDeclBits.HasSkippedBody = false;
28910b57cec5SDimitry Andric   FunctionDeclBits.WillHaveBody = false;
28920b57cec5SDimitry Andric   FunctionDeclBits.IsMultiVersion = false;
28930b57cec5SDimitry Andric   FunctionDeclBits.IsCopyDeductionCandidate = false;
28940b57cec5SDimitry Andric   FunctionDeclBits.HasODRHash = false;
2895480093f4SDimitry Andric   if (TrailingRequiresClause)
2896480093f4SDimitry Andric     setTrailingRequiresClause(TrailingRequiresClause);
28970b57cec5SDimitry Andric }
28980b57cec5SDimitry Andric 
28990b57cec5SDimitry Andric void FunctionDecl::getNameForDiagnostic(
29000b57cec5SDimitry Andric     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
29010b57cec5SDimitry Andric   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
29020b57cec5SDimitry Andric   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
29030b57cec5SDimitry Andric   if (TemplateArgs)
29040b57cec5SDimitry Andric     printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
29050b57cec5SDimitry Andric }
29060b57cec5SDimitry Andric 
29070b57cec5SDimitry Andric bool FunctionDecl::isVariadic() const {
29080b57cec5SDimitry Andric   if (const auto *FT = getType()->getAs<FunctionProtoType>())
29090b57cec5SDimitry Andric     return FT->isVariadic();
29100b57cec5SDimitry Andric   return false;
29110b57cec5SDimitry Andric }
29120b57cec5SDimitry Andric 
2913480093f4SDimitry Andric FunctionDecl::DefaultedFunctionInfo *
2914480093f4SDimitry Andric FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2915480093f4SDimitry Andric                                             ArrayRef<DeclAccessPair> Lookups) {
2916480093f4SDimitry Andric   DefaultedFunctionInfo *Info = new (Context.Allocate(
2917480093f4SDimitry Andric       totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2918480093f4SDimitry Andric       std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2919480093f4SDimitry Andric       DefaultedFunctionInfo;
2920480093f4SDimitry Andric   Info->NumLookups = Lookups.size();
2921480093f4SDimitry Andric   std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2922480093f4SDimitry Andric                           Info->getTrailingObjects<DeclAccessPair>());
2923480093f4SDimitry Andric   return Info;
2924480093f4SDimitry Andric }
2925480093f4SDimitry Andric 
2926480093f4SDimitry Andric void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
2927480093f4SDimitry Andric   assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
2928480093f4SDimitry Andric   assert(!Body && "can't replace function body with defaulted function info");
2929480093f4SDimitry Andric 
2930480093f4SDimitry Andric   FunctionDeclBits.HasDefaultedFunctionInfo = true;
2931480093f4SDimitry Andric   DefaultedInfo = Info;
2932480093f4SDimitry Andric }
2933480093f4SDimitry Andric 
2934480093f4SDimitry Andric FunctionDecl::DefaultedFunctionInfo *
2935480093f4SDimitry Andric FunctionDecl::getDefaultedFunctionInfo() const {
2936480093f4SDimitry Andric   return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
2937480093f4SDimitry Andric }
2938480093f4SDimitry Andric 
29390b57cec5SDimitry Andric bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
29400b57cec5SDimitry Andric   for (auto I : redecls()) {
29410b57cec5SDimitry Andric     if (I->doesThisDeclarationHaveABody()) {
29420b57cec5SDimitry Andric       Definition = I;
29430b57cec5SDimitry Andric       return true;
29440b57cec5SDimitry Andric     }
29450b57cec5SDimitry Andric   }
29460b57cec5SDimitry Andric 
29470b57cec5SDimitry Andric   return false;
29480b57cec5SDimitry Andric }
29490b57cec5SDimitry Andric 
2950480093f4SDimitry Andric bool FunctionDecl::hasTrivialBody() const {
29510b57cec5SDimitry Andric   Stmt *S = getBody();
29520b57cec5SDimitry Andric   if (!S) {
29530b57cec5SDimitry Andric     // Since we don't have a body for this function, we don't know if it's
29540b57cec5SDimitry Andric     // trivial or not.
29550b57cec5SDimitry Andric     return false;
29560b57cec5SDimitry Andric   }
29570b57cec5SDimitry Andric 
29580b57cec5SDimitry Andric   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
29590b57cec5SDimitry Andric     return true;
29600b57cec5SDimitry Andric   return false;
29610b57cec5SDimitry Andric }
29620b57cec5SDimitry Andric 
2963e8d8bef9SDimitry Andric bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
2964e8d8bef9SDimitry Andric   if (!getFriendObjectKind())
2965e8d8bef9SDimitry Andric     return false;
2966e8d8bef9SDimitry Andric 
2967e8d8bef9SDimitry Andric   // Check for a friend function instantiated from a friend function
2968e8d8bef9SDimitry Andric   // definition in a templated class.
2969e8d8bef9SDimitry Andric   if (const FunctionDecl *InstantiatedFrom =
2970e8d8bef9SDimitry Andric           getInstantiatedFromMemberFunction())
2971e8d8bef9SDimitry Andric     return InstantiatedFrom->getFriendObjectKind() &&
2972e8d8bef9SDimitry Andric            InstantiatedFrom->isThisDeclarationADefinition();
2973e8d8bef9SDimitry Andric 
2974e8d8bef9SDimitry Andric   // Check for a friend function template instantiated from a friend
2975e8d8bef9SDimitry Andric   // function template definition in a templated class.
2976e8d8bef9SDimitry Andric   if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
2977e8d8bef9SDimitry Andric     if (const FunctionTemplateDecl *InstantiatedFrom =
2978e8d8bef9SDimitry Andric             Template->getInstantiatedFromMemberTemplate())
2979e8d8bef9SDimitry Andric       return InstantiatedFrom->getFriendObjectKind() &&
2980e8d8bef9SDimitry Andric              InstantiatedFrom->isThisDeclarationADefinition();
2981e8d8bef9SDimitry Andric   }
2982e8d8bef9SDimitry Andric 
2983e8d8bef9SDimitry Andric   return false;
2984e8d8bef9SDimitry Andric }
2985e8d8bef9SDimitry Andric 
2986e8d8bef9SDimitry Andric bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
2987e8d8bef9SDimitry Andric                              bool CheckForPendingFriendDefinition) const {
2988e8d8bef9SDimitry Andric   for (const FunctionDecl *FD : redecls()) {
2989e8d8bef9SDimitry Andric     if (FD->isThisDeclarationADefinition()) {
2990e8d8bef9SDimitry Andric       Definition = FD;
2991e8d8bef9SDimitry Andric       return true;
2992e8d8bef9SDimitry Andric     }
2993e8d8bef9SDimitry Andric 
2994e8d8bef9SDimitry Andric     // If this is a friend function defined in a class template, it does not
2995e8d8bef9SDimitry Andric     // have a body until it is used, nevertheless it is a definition, see
2996e8d8bef9SDimitry Andric     // [temp.inst]p2:
2997e8d8bef9SDimitry Andric     //
2998e8d8bef9SDimitry Andric     // ... for the purpose of determining whether an instantiated redeclaration
2999e8d8bef9SDimitry Andric     // is valid according to [basic.def.odr] and [class.mem], a declaration that
3000e8d8bef9SDimitry Andric     // corresponds to a definition in the template is considered to be a
3001e8d8bef9SDimitry Andric     // definition.
3002e8d8bef9SDimitry Andric     //
3003e8d8bef9SDimitry Andric     // The following code must produce redefinition error:
3004e8d8bef9SDimitry Andric     //
3005e8d8bef9SDimitry Andric     //     template<typename T> struct C20 { friend void func_20() {} };
3006e8d8bef9SDimitry Andric     //     C20<int> c20i;
3007e8d8bef9SDimitry Andric     //     void func_20() {}
3008e8d8bef9SDimitry Andric     //
3009e8d8bef9SDimitry Andric     if (CheckForPendingFriendDefinition &&
3010e8d8bef9SDimitry Andric         FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3011e8d8bef9SDimitry Andric       Definition = FD;
30120b57cec5SDimitry Andric       return true;
30130b57cec5SDimitry Andric     }
30140b57cec5SDimitry Andric   }
30150b57cec5SDimitry Andric 
30160b57cec5SDimitry Andric   return false;
30170b57cec5SDimitry Andric }
30180b57cec5SDimitry Andric 
30190b57cec5SDimitry Andric Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
30200b57cec5SDimitry Andric   if (!hasBody(Definition))
30210b57cec5SDimitry Andric     return nullptr;
30220b57cec5SDimitry Andric 
3023480093f4SDimitry Andric   assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
3024480093f4SDimitry Andric          "definition should not have a body");
30250b57cec5SDimitry Andric   if (Definition->Body)
30260b57cec5SDimitry Andric     return Definition->Body.get(getASTContext().getExternalSource());
30270b57cec5SDimitry Andric 
30280b57cec5SDimitry Andric   return nullptr;
30290b57cec5SDimitry Andric }
30300b57cec5SDimitry Andric 
30310b57cec5SDimitry Andric void FunctionDecl::setBody(Stmt *B) {
3032480093f4SDimitry Andric   FunctionDeclBits.HasDefaultedFunctionInfo = false;
3033480093f4SDimitry Andric   Body = LazyDeclStmtPtr(B);
30340b57cec5SDimitry Andric   if (B)
30350b57cec5SDimitry Andric     EndRangeLoc = B->getEndLoc();
30360b57cec5SDimitry Andric }
30370b57cec5SDimitry Andric 
30380b57cec5SDimitry Andric void FunctionDecl::setPure(bool P) {
30390b57cec5SDimitry Andric   FunctionDeclBits.IsPure = P;
30400b57cec5SDimitry Andric   if (P)
30410b57cec5SDimitry Andric     if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
30420b57cec5SDimitry Andric       Parent->markedVirtualFunctionPure();
30430b57cec5SDimitry Andric }
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric template<std::size_t Len>
30460b57cec5SDimitry Andric static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
30470b57cec5SDimitry Andric   IdentifierInfo *II = ND->getIdentifier();
30480b57cec5SDimitry Andric   return II && II->isStr(Str);
30490b57cec5SDimitry Andric }
30500b57cec5SDimitry Andric 
30510b57cec5SDimitry Andric bool FunctionDecl::isMain() const {
30520b57cec5SDimitry Andric   const TranslationUnitDecl *tunit =
30530b57cec5SDimitry Andric     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
30540b57cec5SDimitry Andric   return tunit &&
30550b57cec5SDimitry Andric          !tunit->getASTContext().getLangOpts().Freestanding &&
30560b57cec5SDimitry Andric          isNamed(this, "main");
30570b57cec5SDimitry Andric }
30580b57cec5SDimitry Andric 
30590b57cec5SDimitry Andric bool FunctionDecl::isMSVCRTEntryPoint() const {
30600b57cec5SDimitry Andric   const TranslationUnitDecl *TUnit =
30610b57cec5SDimitry Andric       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
30620b57cec5SDimitry Andric   if (!TUnit)
30630b57cec5SDimitry Andric     return false;
30640b57cec5SDimitry Andric 
30650b57cec5SDimitry Andric   // Even though we aren't really targeting MSVCRT if we are freestanding,
30660b57cec5SDimitry Andric   // semantic analysis for these functions remains the same.
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   // MSVCRT entry points only exist on MSVCRT targets.
30690b57cec5SDimitry Andric   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
30700b57cec5SDimitry Andric     return false;
30710b57cec5SDimitry Andric 
30720b57cec5SDimitry Andric   // Nameless functions like constructors cannot be entry points.
30730b57cec5SDimitry Andric   if (!getIdentifier())
30740b57cec5SDimitry Andric     return false;
30750b57cec5SDimitry Andric 
30760b57cec5SDimitry Andric   return llvm::StringSwitch<bool>(getName())
30770b57cec5SDimitry Andric       .Cases("main",     // an ANSI console app
30780b57cec5SDimitry Andric              "wmain",    // a Unicode console App
30790b57cec5SDimitry Andric              "WinMain",  // an ANSI GUI app
30800b57cec5SDimitry Andric              "wWinMain", // a Unicode GUI app
30810b57cec5SDimitry Andric              "DllMain",  // a DLL
30820b57cec5SDimitry Andric              true)
30830b57cec5SDimitry Andric       .Default(false);
30840b57cec5SDimitry Andric }
30850b57cec5SDimitry Andric 
30860b57cec5SDimitry Andric bool FunctionDecl::isReservedGlobalPlacementOperator() const {
30870b57cec5SDimitry Andric   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
30880b57cec5SDimitry Andric   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
30890b57cec5SDimitry Andric          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
30900b57cec5SDimitry Andric          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
30910b57cec5SDimitry Andric          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
30920b57cec5SDimitry Andric 
30930b57cec5SDimitry Andric   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
30940b57cec5SDimitry Andric     return false;
30950b57cec5SDimitry Andric 
30960b57cec5SDimitry Andric   const auto *proto = getType()->castAs<FunctionProtoType>();
30970b57cec5SDimitry Andric   if (proto->getNumParams() != 2 || proto->isVariadic())
30980b57cec5SDimitry Andric     return false;
30990b57cec5SDimitry Andric 
31000b57cec5SDimitry Andric   ASTContext &Context =
31010b57cec5SDimitry Andric     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
31020b57cec5SDimitry Andric       ->getASTContext();
31030b57cec5SDimitry Andric 
31040b57cec5SDimitry Andric   // The result type and first argument type are constant across all
31050b57cec5SDimitry Andric   // these operators.  The second argument must be exactly void*.
31060b57cec5SDimitry Andric   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
31070b57cec5SDimitry Andric }
31080b57cec5SDimitry Andric 
31095ffd83dbSDimitry Andric bool FunctionDecl::isReplaceableGlobalAllocationFunction(
31105ffd83dbSDimitry Andric     Optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
31110b57cec5SDimitry Andric   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
31120b57cec5SDimitry Andric     return false;
31130b57cec5SDimitry Andric   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
31140b57cec5SDimitry Andric       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
31150b57cec5SDimitry Andric       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
31160b57cec5SDimitry Andric       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
31170b57cec5SDimitry Andric     return false;
31180b57cec5SDimitry Andric 
31190b57cec5SDimitry Andric   if (isa<CXXRecordDecl>(getDeclContext()))
31200b57cec5SDimitry Andric     return false;
31210b57cec5SDimitry Andric 
31220b57cec5SDimitry Andric   // This can only fail for an invalid 'operator new' declaration.
31230b57cec5SDimitry Andric   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
31240b57cec5SDimitry Andric     return false;
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric   const auto *FPT = getType()->castAs<FunctionProtoType>();
31270b57cec5SDimitry Andric   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
31280b57cec5SDimitry Andric     return false;
31290b57cec5SDimitry Andric 
31300b57cec5SDimitry Andric   // If this is a single-parameter function, it must be a replaceable global
31310b57cec5SDimitry Andric   // allocation or deallocation function.
31320b57cec5SDimitry Andric   if (FPT->getNumParams() == 1)
31330b57cec5SDimitry Andric     return true;
31340b57cec5SDimitry Andric 
31350b57cec5SDimitry Andric   unsigned Params = 1;
31360b57cec5SDimitry Andric   QualType Ty = FPT->getParamType(Params);
31370b57cec5SDimitry Andric   ASTContext &Ctx = getASTContext();
31380b57cec5SDimitry Andric 
31390b57cec5SDimitry Andric   auto Consume = [&] {
31400b57cec5SDimitry Andric     ++Params;
31410b57cec5SDimitry Andric     Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
31420b57cec5SDimitry Andric   };
31430b57cec5SDimitry Andric 
31440b57cec5SDimitry Andric   // In C++14, the next parameter can be a 'std::size_t' for sized delete.
31450b57cec5SDimitry Andric   bool IsSizedDelete = false;
31460b57cec5SDimitry Andric   if (Ctx.getLangOpts().SizedDeallocation &&
31470b57cec5SDimitry Andric       (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
31480b57cec5SDimitry Andric        getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
31490b57cec5SDimitry Andric       Ctx.hasSameType(Ty, Ctx.getSizeType())) {
31500b57cec5SDimitry Andric     IsSizedDelete = true;
31510b57cec5SDimitry Andric     Consume();
31520b57cec5SDimitry Andric   }
31530b57cec5SDimitry Andric 
31540b57cec5SDimitry Andric   // In C++17, the next parameter can be a 'std::align_val_t' for aligned
31550b57cec5SDimitry Andric   // new/delete.
31560b57cec5SDimitry Andric   if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
31570b57cec5SDimitry Andric     Consume();
31585ffd83dbSDimitry Andric     if (AlignmentParam)
31595ffd83dbSDimitry Andric       *AlignmentParam = Params;
31600b57cec5SDimitry Andric   }
31610b57cec5SDimitry Andric 
31620b57cec5SDimitry Andric   // Finally, if this is not a sized delete, the final parameter can
31630b57cec5SDimitry Andric   // be a 'const std::nothrow_t&'.
31640b57cec5SDimitry Andric   if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
31650b57cec5SDimitry Andric     Ty = Ty->getPointeeType();
31660b57cec5SDimitry Andric     if (Ty.getCVRQualifiers() != Qualifiers::Const)
31670b57cec5SDimitry Andric       return false;
31685ffd83dbSDimitry Andric     if (Ty->isNothrowT()) {
31695ffd83dbSDimitry Andric       if (IsNothrow)
31705ffd83dbSDimitry Andric         *IsNothrow = true;
31710b57cec5SDimitry Andric       Consume();
31720b57cec5SDimitry Andric     }
31735ffd83dbSDimitry Andric   }
31740b57cec5SDimitry Andric 
31750b57cec5SDimitry Andric   return Params == FPT->getNumParams();
31760b57cec5SDimitry Andric }
31770b57cec5SDimitry Andric 
3178480093f4SDimitry Andric bool FunctionDecl::isInlineBuiltinDeclaration() const {
3179480093f4SDimitry Andric   if (!getBuiltinID())
3180480093f4SDimitry Andric     return false;
3181480093f4SDimitry Andric 
3182480093f4SDimitry Andric   const FunctionDecl *Definition;
3183*349cc55cSDimitry Andric   return hasBody(Definition) && Definition->isInlineSpecified() &&
3184*349cc55cSDimitry Andric          Definition->hasAttr<AlwaysInlineAttr>() &&
3185*349cc55cSDimitry Andric          Definition->hasAttr<GNUInlineAttr>();
3186480093f4SDimitry Andric }
3187480093f4SDimitry Andric 
31880b57cec5SDimitry Andric bool FunctionDecl::isDestroyingOperatorDelete() const {
31890b57cec5SDimitry Andric   // C++ P0722:
31900b57cec5SDimitry Andric   //   Within a class C, a single object deallocation function with signature
31910b57cec5SDimitry Andric   //     (T, std::destroying_delete_t, <more params>)
31920b57cec5SDimitry Andric   //   is a destroying operator delete.
31930b57cec5SDimitry Andric   if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
31940b57cec5SDimitry Andric       getNumParams() < 2)
31950b57cec5SDimitry Andric     return false;
31960b57cec5SDimitry Andric 
31970b57cec5SDimitry Andric   auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
31980b57cec5SDimitry Andric   return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
31990b57cec5SDimitry Andric          RD->getIdentifier()->isStr("destroying_delete_t");
32000b57cec5SDimitry Andric }
32010b57cec5SDimitry Andric 
32020b57cec5SDimitry Andric LanguageLinkage FunctionDecl::getLanguageLinkage() const {
32030b57cec5SDimitry Andric   return getDeclLanguageLinkage(*this);
32040b57cec5SDimitry Andric }
32050b57cec5SDimitry Andric 
32060b57cec5SDimitry Andric bool FunctionDecl::isExternC() const {
32070b57cec5SDimitry Andric   return isDeclExternC(*this);
32080b57cec5SDimitry Andric }
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric bool FunctionDecl::isInExternCContext() const {
32110b57cec5SDimitry Andric   if (hasAttr<OpenCLKernelAttr>())
32120b57cec5SDimitry Andric     return true;
32130b57cec5SDimitry Andric   return getLexicalDeclContext()->isExternCContext();
32140b57cec5SDimitry Andric }
32150b57cec5SDimitry Andric 
32160b57cec5SDimitry Andric bool FunctionDecl::isInExternCXXContext() const {
32170b57cec5SDimitry Andric   return getLexicalDeclContext()->isExternCXXContext();
32180b57cec5SDimitry Andric }
32190b57cec5SDimitry Andric 
32200b57cec5SDimitry Andric bool FunctionDecl::isGlobal() const {
32210b57cec5SDimitry Andric   if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
32220b57cec5SDimitry Andric     return Method->isStatic();
32230b57cec5SDimitry Andric 
32240b57cec5SDimitry Andric   if (getCanonicalDecl()->getStorageClass() == SC_Static)
32250b57cec5SDimitry Andric     return false;
32260b57cec5SDimitry Andric 
32270b57cec5SDimitry Andric   for (const DeclContext *DC = getDeclContext();
32280b57cec5SDimitry Andric        DC->isNamespace();
32290b57cec5SDimitry Andric        DC = DC->getParent()) {
32300b57cec5SDimitry Andric     if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
32310b57cec5SDimitry Andric       if (!Namespace->getDeclName())
32320b57cec5SDimitry Andric         return false;
32330b57cec5SDimitry Andric       break;
32340b57cec5SDimitry Andric     }
32350b57cec5SDimitry Andric   }
32360b57cec5SDimitry Andric 
32370b57cec5SDimitry Andric   return true;
32380b57cec5SDimitry Andric }
32390b57cec5SDimitry Andric 
32400b57cec5SDimitry Andric bool FunctionDecl::isNoReturn() const {
32410b57cec5SDimitry Andric   if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
32420b57cec5SDimitry Andric       hasAttr<C11NoReturnAttr>())
32430b57cec5SDimitry Andric     return true;
32440b57cec5SDimitry Andric 
32450b57cec5SDimitry Andric   if (auto *FnTy = getType()->getAs<FunctionType>())
32460b57cec5SDimitry Andric     return FnTy->getNoReturnAttr();
32470b57cec5SDimitry Andric 
32480b57cec5SDimitry Andric   return false;
32490b57cec5SDimitry Andric }
32500b57cec5SDimitry Andric 
32510b57cec5SDimitry Andric 
32520b57cec5SDimitry Andric MultiVersionKind FunctionDecl::getMultiVersionKind() const {
32530b57cec5SDimitry Andric   if (hasAttr<TargetAttr>())
32540b57cec5SDimitry Andric     return MultiVersionKind::Target;
32550b57cec5SDimitry Andric   if (hasAttr<CPUDispatchAttr>())
32560b57cec5SDimitry Andric     return MultiVersionKind::CPUDispatch;
32570b57cec5SDimitry Andric   if (hasAttr<CPUSpecificAttr>())
32580b57cec5SDimitry Andric     return MultiVersionKind::CPUSpecific;
32590b57cec5SDimitry Andric   return MultiVersionKind::None;
32600b57cec5SDimitry Andric }
32610b57cec5SDimitry Andric 
32620b57cec5SDimitry Andric bool FunctionDecl::isCPUDispatchMultiVersion() const {
32630b57cec5SDimitry Andric   return isMultiVersion() && hasAttr<CPUDispatchAttr>();
32640b57cec5SDimitry Andric }
32650b57cec5SDimitry Andric 
32660b57cec5SDimitry Andric bool FunctionDecl::isCPUSpecificMultiVersion() const {
32670b57cec5SDimitry Andric   return isMultiVersion() && hasAttr<CPUSpecificAttr>();
32680b57cec5SDimitry Andric }
32690b57cec5SDimitry Andric 
32700b57cec5SDimitry Andric bool FunctionDecl::isTargetMultiVersion() const {
32710b57cec5SDimitry Andric   return isMultiVersion() && hasAttr<TargetAttr>();
32720b57cec5SDimitry Andric }
32730b57cec5SDimitry Andric 
32740b57cec5SDimitry Andric void
32750b57cec5SDimitry Andric FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
32760b57cec5SDimitry Andric   redeclarable_base::setPreviousDecl(PrevDecl);
32770b57cec5SDimitry Andric 
32780b57cec5SDimitry Andric   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
32790b57cec5SDimitry Andric     FunctionTemplateDecl *PrevFunTmpl
32800b57cec5SDimitry Andric       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
32810b57cec5SDimitry Andric     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
32820b57cec5SDimitry Andric     FunTmpl->setPreviousDecl(PrevFunTmpl);
32830b57cec5SDimitry Andric   }
32840b57cec5SDimitry Andric 
32850b57cec5SDimitry Andric   if (PrevDecl && PrevDecl->isInlined())
32860b57cec5SDimitry Andric     setImplicitlyInline(true);
32870b57cec5SDimitry Andric }
32880b57cec5SDimitry Andric 
32890b57cec5SDimitry Andric FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
32900b57cec5SDimitry Andric 
32910b57cec5SDimitry Andric /// Returns a value indicating whether this function corresponds to a builtin
32920b57cec5SDimitry Andric /// function.
32930b57cec5SDimitry Andric ///
32940b57cec5SDimitry Andric /// The function corresponds to a built-in function if it is declared at
32950b57cec5SDimitry Andric /// translation scope or within an extern "C" block and its name matches with
32960b57cec5SDimitry Andric /// the name of a builtin. The returned value will be 0 for functions that do
32970b57cec5SDimitry Andric /// not correspond to a builtin, a value of type \c Builtin::ID if in the
32980b57cec5SDimitry Andric /// target-independent range \c [1,Builtin::First), or a target-specific builtin
32990b57cec5SDimitry Andric /// value.
33000b57cec5SDimitry Andric ///
33010b57cec5SDimitry Andric /// \param ConsiderWrapperFunctions If true, we should consider wrapper
33020b57cec5SDimitry Andric /// functions as their wrapped builtins. This shouldn't be done in general, but
33030b57cec5SDimitry Andric /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
33040b57cec5SDimitry Andric unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3305927c847dSDimitry Andric   unsigned BuiltinID = 0;
3306480093f4SDimitry Andric 
33075ffd83dbSDimitry Andric   if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
33085ffd83dbSDimitry Andric     BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3309fe6060f1SDimitry Andric   } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3310fe6060f1SDimitry Andric     BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3311927c847dSDimitry Andric   } else if (const auto *A = getAttr<BuiltinAttr>()) {
3312927c847dSDimitry Andric     BuiltinID = A->getID();
3313480093f4SDimitry Andric   }
3314480093f4SDimitry Andric 
33150b57cec5SDimitry Andric   if (!BuiltinID)
33160b57cec5SDimitry Andric     return 0;
33170b57cec5SDimitry Andric 
33180b57cec5SDimitry Andric   // If the function is marked "overloadable", it has a different mangled name
33190b57cec5SDimitry Andric   // and is not the C library function.
3320480093f4SDimitry Andric   if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3321fe6060f1SDimitry Andric       (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
33220b57cec5SDimitry Andric     return 0;
33230b57cec5SDimitry Andric 
3324927c847dSDimitry Andric   ASTContext &Context = getASTContext();
33250b57cec5SDimitry Andric   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
33260b57cec5SDimitry Andric     return BuiltinID;
33270b57cec5SDimitry Andric 
33280b57cec5SDimitry Andric   // This function has the name of a known C library
33290b57cec5SDimitry Andric   // function. Determine whether it actually refers to the C library
33300b57cec5SDimitry Andric   // function or whether it just has the same name.
33310b57cec5SDimitry Andric 
33320b57cec5SDimitry Andric   // If this is a static function, it's not a builtin.
33330b57cec5SDimitry Andric   if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
33340b57cec5SDimitry Andric     return 0;
33350b57cec5SDimitry Andric 
33360b57cec5SDimitry Andric   // OpenCL v1.2 s6.9.f - The library functions defined in
33370b57cec5SDimitry Andric   // the C99 standard headers are not available.
33380b57cec5SDimitry Andric   if (Context.getLangOpts().OpenCL &&
33390b57cec5SDimitry Andric       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
33400b57cec5SDimitry Andric     return 0;
33410b57cec5SDimitry Andric 
33420b57cec5SDimitry Andric   // CUDA does not have device-side standard library. printf and malloc are the
33430b57cec5SDimitry Andric   // only special cases that are supported by device-side runtime.
33440b57cec5SDimitry Andric   if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
33450b57cec5SDimitry Andric       !hasAttr<CUDAHostAttr>() &&
33460b57cec5SDimitry Andric       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
33470b57cec5SDimitry Andric     return 0;
33480b57cec5SDimitry Andric 
33495ffd83dbSDimitry Andric   // As AMDGCN implementation of OpenMP does not have a device-side standard
33505ffd83dbSDimitry Andric   // library, none of the predefined library functions except printf and malloc
33515ffd83dbSDimitry Andric   // should be treated as a builtin i.e. 0 should be returned for them.
33525ffd83dbSDimitry Andric   if (Context.getTargetInfo().getTriple().isAMDGCN() &&
33535ffd83dbSDimitry Andric       Context.getLangOpts().OpenMPIsDevice &&
33545ffd83dbSDimitry Andric       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
33555ffd83dbSDimitry Andric       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
33565ffd83dbSDimitry Andric     return 0;
33575ffd83dbSDimitry Andric 
33580b57cec5SDimitry Andric   return BuiltinID;
33590b57cec5SDimitry Andric }
33600b57cec5SDimitry Andric 
33610b57cec5SDimitry Andric /// getNumParams - Return the number of parameters this function must have
33620b57cec5SDimitry Andric /// based on its FunctionType.  This is the length of the ParamInfo array
33630b57cec5SDimitry Andric /// after it has been created.
33640b57cec5SDimitry Andric unsigned FunctionDecl::getNumParams() const {
33650b57cec5SDimitry Andric   const auto *FPT = getType()->getAs<FunctionProtoType>();
33660b57cec5SDimitry Andric   return FPT ? FPT->getNumParams() : 0;
33670b57cec5SDimitry Andric }
33680b57cec5SDimitry Andric 
33690b57cec5SDimitry Andric void FunctionDecl::setParams(ASTContext &C,
33700b57cec5SDimitry Andric                              ArrayRef<ParmVarDecl *> NewParamInfo) {
33710b57cec5SDimitry Andric   assert(!ParamInfo && "Already has param info!");
33720b57cec5SDimitry Andric   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
33730b57cec5SDimitry Andric 
33740b57cec5SDimitry Andric   // Zero params -> null pointer.
33750b57cec5SDimitry Andric   if (!NewParamInfo.empty()) {
33760b57cec5SDimitry Andric     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
33770b57cec5SDimitry Andric     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
33780b57cec5SDimitry Andric   }
33790b57cec5SDimitry Andric }
33800b57cec5SDimitry Andric 
33810b57cec5SDimitry Andric /// getMinRequiredArguments - Returns the minimum number of arguments
33820b57cec5SDimitry Andric /// needed to call this function. This may be fewer than the number of
33830b57cec5SDimitry Andric /// function parameters, if some of the parameters have default
33840b57cec5SDimitry Andric /// arguments (in C++) or are parameter packs (C++11).
33850b57cec5SDimitry Andric unsigned FunctionDecl::getMinRequiredArguments() const {
33860b57cec5SDimitry Andric   if (!getASTContext().getLangOpts().CPlusPlus)
33870b57cec5SDimitry Andric     return getNumParams();
33880b57cec5SDimitry Andric 
33895ffd83dbSDimitry Andric   // Note that it is possible for a parameter with no default argument to
33905ffd83dbSDimitry Andric   // follow a parameter with a default argument.
33910b57cec5SDimitry Andric   unsigned NumRequiredArgs = 0;
33925ffd83dbSDimitry Andric   unsigned MinParamsSoFar = 0;
33935ffd83dbSDimitry Andric   for (auto *Param : parameters()) {
33945ffd83dbSDimitry Andric     if (!Param->isParameterPack()) {
33955ffd83dbSDimitry Andric       ++MinParamsSoFar;
33965ffd83dbSDimitry Andric       if (!Param->hasDefaultArg())
33975ffd83dbSDimitry Andric         NumRequiredArgs = MinParamsSoFar;
33985ffd83dbSDimitry Andric     }
33995ffd83dbSDimitry Andric   }
34000b57cec5SDimitry Andric   return NumRequiredArgs;
34010b57cec5SDimitry Andric }
34020b57cec5SDimitry Andric 
34035ffd83dbSDimitry Andric bool FunctionDecl::hasOneParamOrDefaultArgs() const {
34045ffd83dbSDimitry Andric   return getNumParams() == 1 ||
34055ffd83dbSDimitry Andric          (getNumParams() > 1 &&
34065ffd83dbSDimitry Andric           std::all_of(param_begin() + 1, param_end(),
34075ffd83dbSDimitry Andric                       [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
34085ffd83dbSDimitry Andric }
34095ffd83dbSDimitry Andric 
34100b57cec5SDimitry Andric /// The combination of the extern and inline keywords under MSVC forces
34110b57cec5SDimitry Andric /// the function to be required.
34120b57cec5SDimitry Andric ///
34130b57cec5SDimitry Andric /// Note: This function assumes that we will only get called when isInlined()
34140b57cec5SDimitry Andric /// would return true for this FunctionDecl.
34150b57cec5SDimitry Andric bool FunctionDecl::isMSExternInline() const {
34160b57cec5SDimitry Andric   assert(isInlined() && "expected to get called on an inlined function!");
34170b57cec5SDimitry Andric 
34180b57cec5SDimitry Andric   const ASTContext &Context = getASTContext();
34190b57cec5SDimitry Andric   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
34200b57cec5SDimitry Andric       !hasAttr<DLLExportAttr>())
34210b57cec5SDimitry Andric     return false;
34220b57cec5SDimitry Andric 
34230b57cec5SDimitry Andric   for (const FunctionDecl *FD = getMostRecentDecl(); FD;
34240b57cec5SDimitry Andric        FD = FD->getPreviousDecl())
34250b57cec5SDimitry Andric     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
34260b57cec5SDimitry Andric       return true;
34270b57cec5SDimitry Andric 
34280b57cec5SDimitry Andric   return false;
34290b57cec5SDimitry Andric }
34300b57cec5SDimitry Andric 
34310b57cec5SDimitry Andric static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
34320b57cec5SDimitry Andric   if (Redecl->getStorageClass() != SC_Extern)
34330b57cec5SDimitry Andric     return false;
34340b57cec5SDimitry Andric 
34350b57cec5SDimitry Andric   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
34360b57cec5SDimitry Andric        FD = FD->getPreviousDecl())
34370b57cec5SDimitry Andric     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
34380b57cec5SDimitry Andric       return false;
34390b57cec5SDimitry Andric 
34400b57cec5SDimitry Andric   return true;
34410b57cec5SDimitry Andric }
34420b57cec5SDimitry Andric 
34430b57cec5SDimitry Andric static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
34440b57cec5SDimitry Andric   // Only consider file-scope declarations in this test.
34450b57cec5SDimitry Andric   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
34460b57cec5SDimitry Andric     return false;
34470b57cec5SDimitry Andric 
34480b57cec5SDimitry Andric   // Only consider explicit declarations; the presence of a builtin for a
34490b57cec5SDimitry Andric   // libcall shouldn't affect whether a definition is externally visible.
34500b57cec5SDimitry Andric   if (Redecl->isImplicit())
34510b57cec5SDimitry Andric     return false;
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
34540b57cec5SDimitry Andric     return true; // Not an inline definition
34550b57cec5SDimitry Andric 
34560b57cec5SDimitry Andric   return false;
34570b57cec5SDimitry Andric }
34580b57cec5SDimitry Andric 
34590b57cec5SDimitry Andric /// For a function declaration in C or C++, determine whether this
34600b57cec5SDimitry Andric /// declaration causes the definition to be externally visible.
34610b57cec5SDimitry Andric ///
34620b57cec5SDimitry Andric /// For instance, this determines if adding the current declaration to the set
34630b57cec5SDimitry Andric /// of redeclarations of the given functions causes
34640b57cec5SDimitry Andric /// isInlineDefinitionExternallyVisible to change from false to true.
34650b57cec5SDimitry Andric bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
34660b57cec5SDimitry Andric   assert(!doesThisDeclarationHaveABody() &&
34670b57cec5SDimitry Andric          "Must have a declaration without a body.");
34680b57cec5SDimitry Andric 
34690b57cec5SDimitry Andric   ASTContext &Context = getASTContext();
34700b57cec5SDimitry Andric 
34710b57cec5SDimitry Andric   if (Context.getLangOpts().MSVCCompat) {
34720b57cec5SDimitry Andric     const FunctionDecl *Definition;
34730b57cec5SDimitry Andric     if (hasBody(Definition) && Definition->isInlined() &&
34740b57cec5SDimitry Andric         redeclForcesDefMSVC(this))
34750b57cec5SDimitry Andric       return true;
34760b57cec5SDimitry Andric   }
34770b57cec5SDimitry Andric 
3478a7dea167SDimitry Andric   if (Context.getLangOpts().CPlusPlus)
3479a7dea167SDimitry Andric     return false;
3480a7dea167SDimitry Andric 
34810b57cec5SDimitry Andric   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
34820b57cec5SDimitry Andric     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
34830b57cec5SDimitry Andric     // an externally visible definition.
34840b57cec5SDimitry Andric     //
34850b57cec5SDimitry Andric     // FIXME: What happens if gnu_inline gets added on after the first
34860b57cec5SDimitry Andric     // declaration?
34870b57cec5SDimitry Andric     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
34880b57cec5SDimitry Andric       return false;
34890b57cec5SDimitry Andric 
34900b57cec5SDimitry Andric     const FunctionDecl *Prev = this;
34910b57cec5SDimitry Andric     bool FoundBody = false;
34920b57cec5SDimitry Andric     while ((Prev = Prev->getPreviousDecl())) {
3493480093f4SDimitry Andric       FoundBody |= Prev->doesThisDeclarationHaveABody();
34940b57cec5SDimitry Andric 
3495480093f4SDimitry Andric       if (Prev->doesThisDeclarationHaveABody()) {
34960b57cec5SDimitry Andric         // If it's not the case that both 'inline' and 'extern' are
34970b57cec5SDimitry Andric         // specified on the definition, then it is always externally visible.
34980b57cec5SDimitry Andric         if (!Prev->isInlineSpecified() ||
34990b57cec5SDimitry Andric             Prev->getStorageClass() != SC_Extern)
35000b57cec5SDimitry Andric           return false;
35010b57cec5SDimitry Andric       } else if (Prev->isInlineSpecified() &&
35020b57cec5SDimitry Andric                  Prev->getStorageClass() != SC_Extern) {
35030b57cec5SDimitry Andric         return false;
35040b57cec5SDimitry Andric       }
35050b57cec5SDimitry Andric     }
35060b57cec5SDimitry Andric     return FoundBody;
35070b57cec5SDimitry Andric   }
35080b57cec5SDimitry Andric 
35090b57cec5SDimitry Andric   // C99 6.7.4p6:
35100b57cec5SDimitry Andric   //   [...] If all of the file scope declarations for a function in a
35110b57cec5SDimitry Andric   //   translation unit include the inline function specifier without extern,
35120b57cec5SDimitry Andric   //   then the definition in that translation unit is an inline definition.
35130b57cec5SDimitry Andric   if (isInlineSpecified() && getStorageClass() != SC_Extern)
35140b57cec5SDimitry Andric     return false;
35150b57cec5SDimitry Andric   const FunctionDecl *Prev = this;
35160b57cec5SDimitry Andric   bool FoundBody = false;
35170b57cec5SDimitry Andric   while ((Prev = Prev->getPreviousDecl())) {
3518480093f4SDimitry Andric     FoundBody |= Prev->doesThisDeclarationHaveABody();
35190b57cec5SDimitry Andric     if (RedeclForcesDefC99(Prev))
35200b57cec5SDimitry Andric       return false;
35210b57cec5SDimitry Andric   }
35220b57cec5SDimitry Andric   return FoundBody;
35230b57cec5SDimitry Andric }
35240b57cec5SDimitry Andric 
3525480093f4SDimitry Andric FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
35260b57cec5SDimitry Andric   const TypeSourceInfo *TSI = getTypeSourceInfo();
3527480093f4SDimitry Andric   return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3528480093f4SDimitry Andric              : FunctionTypeLoc();
3529480093f4SDimitry Andric }
3530480093f4SDimitry Andric 
3531480093f4SDimitry Andric SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3532480093f4SDimitry Andric   FunctionTypeLoc FTL = getFunctionTypeLoc();
35330b57cec5SDimitry Andric   if (!FTL)
35340b57cec5SDimitry Andric     return SourceRange();
35350b57cec5SDimitry Andric 
35360b57cec5SDimitry Andric   // Skip self-referential return types.
35370b57cec5SDimitry Andric   const SourceManager &SM = getASTContext().getSourceManager();
35380b57cec5SDimitry Andric   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
35390b57cec5SDimitry Andric   SourceLocation Boundary = getNameInfo().getBeginLoc();
35400b57cec5SDimitry Andric   if (RTRange.isInvalid() || Boundary.isInvalid() ||
35410b57cec5SDimitry Andric       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
35420b57cec5SDimitry Andric     return SourceRange();
35430b57cec5SDimitry Andric 
35440b57cec5SDimitry Andric   return RTRange;
35450b57cec5SDimitry Andric }
35460b57cec5SDimitry Andric 
3547480093f4SDimitry Andric SourceRange FunctionDecl::getParametersSourceRange() const {
3548480093f4SDimitry Andric   unsigned NP = getNumParams();
3549480093f4SDimitry Andric   SourceLocation EllipsisLoc = getEllipsisLoc();
3550480093f4SDimitry Andric 
3551480093f4SDimitry Andric   if (NP == 0 && EllipsisLoc.isInvalid())
35520b57cec5SDimitry Andric     return SourceRange();
35530b57cec5SDimitry Andric 
3554480093f4SDimitry Andric   SourceLocation Begin =
3555480093f4SDimitry Andric       NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3556480093f4SDimitry Andric   SourceLocation End = EllipsisLoc.isValid()
3557480093f4SDimitry Andric                            ? EllipsisLoc
3558480093f4SDimitry Andric                            : ParamInfo[NP - 1]->getSourceRange().getEnd();
3559480093f4SDimitry Andric 
3560480093f4SDimitry Andric   return SourceRange(Begin, End);
3561480093f4SDimitry Andric }
3562480093f4SDimitry Andric 
3563480093f4SDimitry Andric SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3564480093f4SDimitry Andric   FunctionTypeLoc FTL = getFunctionTypeLoc();
3565480093f4SDimitry Andric   return FTL ? FTL.getExceptionSpecRange() : SourceRange();
35660b57cec5SDimitry Andric }
35670b57cec5SDimitry Andric 
35680b57cec5SDimitry Andric /// For an inline function definition in C, or for a gnu_inline function
35690b57cec5SDimitry Andric /// in C++, determine whether the definition will be externally visible.
35700b57cec5SDimitry Andric ///
35710b57cec5SDimitry Andric /// Inline function definitions are always available for inlining optimizations.
35720b57cec5SDimitry Andric /// However, depending on the language dialect, declaration specifiers, and
35730b57cec5SDimitry Andric /// attributes, the definition of an inline function may or may not be
35740b57cec5SDimitry Andric /// "externally" visible to other translation units in the program.
35750b57cec5SDimitry Andric ///
35760b57cec5SDimitry Andric /// In C99, inline definitions are not externally visible by default. However,
35770b57cec5SDimitry Andric /// if even one of the global-scope declarations is marked "extern inline", the
35780b57cec5SDimitry Andric /// inline definition becomes externally visible (C99 6.7.4p6).
35790b57cec5SDimitry Andric ///
35800b57cec5SDimitry Andric /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
35810b57cec5SDimitry Andric /// definition, we use the GNU semantics for inline, which are nearly the
35820b57cec5SDimitry Andric /// opposite of C99 semantics. In particular, "inline" by itself will create
35830b57cec5SDimitry Andric /// an externally visible symbol, but "extern inline" will not create an
35840b57cec5SDimitry Andric /// externally visible symbol.
35850b57cec5SDimitry Andric bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
35860b57cec5SDimitry Andric   assert((doesThisDeclarationHaveABody() || willHaveBody() ||
35870b57cec5SDimitry Andric           hasAttr<AliasAttr>()) &&
35880b57cec5SDimitry Andric          "Must be a function definition");
35890b57cec5SDimitry Andric   assert(isInlined() && "Function must be inline");
35900b57cec5SDimitry Andric   ASTContext &Context = getASTContext();
35910b57cec5SDimitry Andric 
35920b57cec5SDimitry Andric   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
35930b57cec5SDimitry Andric     // Note: If you change the logic here, please change
35940b57cec5SDimitry Andric     // doesDeclarationForceExternallyVisibleDefinition as well.
35950b57cec5SDimitry Andric     //
35960b57cec5SDimitry Andric     // If it's not the case that both 'inline' and 'extern' are
35970b57cec5SDimitry Andric     // specified on the definition, then this inline definition is
35980b57cec5SDimitry Andric     // externally visible.
3599a7dea167SDimitry Andric     if (Context.getLangOpts().CPlusPlus)
3600a7dea167SDimitry Andric       return false;
36010b57cec5SDimitry Andric     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
36020b57cec5SDimitry Andric       return true;
36030b57cec5SDimitry Andric 
36040b57cec5SDimitry Andric     // If any declaration is 'inline' but not 'extern', then this definition
36050b57cec5SDimitry Andric     // is externally visible.
36060b57cec5SDimitry Andric     for (auto Redecl : redecls()) {
36070b57cec5SDimitry Andric       if (Redecl->isInlineSpecified() &&
36080b57cec5SDimitry Andric           Redecl->getStorageClass() != SC_Extern)
36090b57cec5SDimitry Andric         return true;
36100b57cec5SDimitry Andric     }
36110b57cec5SDimitry Andric 
36120b57cec5SDimitry Andric     return false;
36130b57cec5SDimitry Andric   }
36140b57cec5SDimitry Andric 
36150b57cec5SDimitry Andric   // The rest of this function is C-only.
36160b57cec5SDimitry Andric   assert(!Context.getLangOpts().CPlusPlus &&
36170b57cec5SDimitry Andric          "should not use C inline rules in C++");
36180b57cec5SDimitry Andric 
36190b57cec5SDimitry Andric   // C99 6.7.4p6:
36200b57cec5SDimitry Andric   //   [...] If all of the file scope declarations for a function in a
36210b57cec5SDimitry Andric   //   translation unit include the inline function specifier without extern,
36220b57cec5SDimitry Andric   //   then the definition in that translation unit is an inline definition.
36230b57cec5SDimitry Andric   for (auto Redecl : redecls()) {
36240b57cec5SDimitry Andric     if (RedeclForcesDefC99(Redecl))
36250b57cec5SDimitry Andric       return true;
36260b57cec5SDimitry Andric   }
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric   // C99 6.7.4p6:
36290b57cec5SDimitry Andric   //   An inline definition does not provide an external definition for the
36300b57cec5SDimitry Andric   //   function, and does not forbid an external definition in another
36310b57cec5SDimitry Andric   //   translation unit.
36320b57cec5SDimitry Andric   return false;
36330b57cec5SDimitry Andric }
36340b57cec5SDimitry Andric 
36350b57cec5SDimitry Andric /// getOverloadedOperator - Which C++ overloaded operator this
36360b57cec5SDimitry Andric /// function represents, if any.
36370b57cec5SDimitry Andric OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
36380b57cec5SDimitry Andric   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
36390b57cec5SDimitry Andric     return getDeclName().getCXXOverloadedOperator();
36400b57cec5SDimitry Andric   return OO_None;
36410b57cec5SDimitry Andric }
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric /// getLiteralIdentifier - The literal suffix identifier this function
36440b57cec5SDimitry Andric /// represents, if any.
36450b57cec5SDimitry Andric const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
36460b57cec5SDimitry Andric   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
36470b57cec5SDimitry Andric     return getDeclName().getCXXLiteralIdentifier();
36480b57cec5SDimitry Andric   return nullptr;
36490b57cec5SDimitry Andric }
36500b57cec5SDimitry Andric 
36510b57cec5SDimitry Andric FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
36520b57cec5SDimitry Andric   if (TemplateOrSpecialization.isNull())
36530b57cec5SDimitry Andric     return TK_NonTemplate;
36540b57cec5SDimitry Andric   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
36550b57cec5SDimitry Andric     return TK_FunctionTemplate;
36560b57cec5SDimitry Andric   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
36570b57cec5SDimitry Andric     return TK_MemberSpecialization;
36580b57cec5SDimitry Andric   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
36590b57cec5SDimitry Andric     return TK_FunctionTemplateSpecialization;
36600b57cec5SDimitry Andric   if (TemplateOrSpecialization.is
36610b57cec5SDimitry Andric                                <DependentFunctionTemplateSpecializationInfo*>())
36620b57cec5SDimitry Andric     return TK_DependentFunctionTemplateSpecialization;
36630b57cec5SDimitry Andric 
36640b57cec5SDimitry Andric   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
36650b57cec5SDimitry Andric }
36660b57cec5SDimitry Andric 
36670b57cec5SDimitry Andric FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
36680b57cec5SDimitry Andric   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
36690b57cec5SDimitry Andric     return cast<FunctionDecl>(Info->getInstantiatedFrom());
36700b57cec5SDimitry Andric 
36710b57cec5SDimitry Andric   return nullptr;
36720b57cec5SDimitry Andric }
36730b57cec5SDimitry Andric 
36740b57cec5SDimitry Andric MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
36750b57cec5SDimitry Andric   if (auto *MSI =
36760b57cec5SDimitry Andric           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
36770b57cec5SDimitry Andric     return MSI;
36780b57cec5SDimitry Andric   if (auto *FTSI = TemplateOrSpecialization
36790b57cec5SDimitry Andric                        .dyn_cast<FunctionTemplateSpecializationInfo *>())
36800b57cec5SDimitry Andric     return FTSI->getMemberSpecializationInfo();
36810b57cec5SDimitry Andric   return nullptr;
36820b57cec5SDimitry Andric }
36830b57cec5SDimitry Andric 
36840b57cec5SDimitry Andric void
36850b57cec5SDimitry Andric FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
36860b57cec5SDimitry Andric                                                FunctionDecl *FD,
36870b57cec5SDimitry Andric                                                TemplateSpecializationKind TSK) {
36880b57cec5SDimitry Andric   assert(TemplateOrSpecialization.isNull() &&
36890b57cec5SDimitry Andric          "Member function is already a specialization");
36900b57cec5SDimitry Andric   MemberSpecializationInfo *Info
36910b57cec5SDimitry Andric     = new (C) MemberSpecializationInfo(FD, TSK);
36920b57cec5SDimitry Andric   TemplateOrSpecialization = Info;
36930b57cec5SDimitry Andric }
36940b57cec5SDimitry Andric 
36950b57cec5SDimitry Andric FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
36960b57cec5SDimitry Andric   return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
36970b57cec5SDimitry Andric }
36980b57cec5SDimitry Andric 
36990b57cec5SDimitry Andric void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
37000b57cec5SDimitry Andric   assert(TemplateOrSpecialization.isNull() &&
37010b57cec5SDimitry Andric          "Member function is already a specialization");
37020b57cec5SDimitry Andric   TemplateOrSpecialization = Template;
37030b57cec5SDimitry Andric }
37040b57cec5SDimitry Andric 
37050b57cec5SDimitry Andric bool FunctionDecl::isImplicitlyInstantiable() const {
37060b57cec5SDimitry Andric   // If the function is invalid, it can't be implicitly instantiated.
37070b57cec5SDimitry Andric   if (isInvalidDecl())
37080b57cec5SDimitry Andric     return false;
37090b57cec5SDimitry Andric 
37100b57cec5SDimitry Andric   switch (getTemplateSpecializationKindForInstantiation()) {
37110b57cec5SDimitry Andric   case TSK_Undeclared:
37120b57cec5SDimitry Andric   case TSK_ExplicitInstantiationDefinition:
37130b57cec5SDimitry Andric   case TSK_ExplicitSpecialization:
37140b57cec5SDimitry Andric     return false;
37150b57cec5SDimitry Andric 
37160b57cec5SDimitry Andric   case TSK_ImplicitInstantiation:
37170b57cec5SDimitry Andric     return true;
37180b57cec5SDimitry Andric 
37190b57cec5SDimitry Andric   case TSK_ExplicitInstantiationDeclaration:
37200b57cec5SDimitry Andric     // Handled below.
37210b57cec5SDimitry Andric     break;
37220b57cec5SDimitry Andric   }
37230b57cec5SDimitry Andric 
37240b57cec5SDimitry Andric   // Find the actual template from which we will instantiate.
37250b57cec5SDimitry Andric   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
37260b57cec5SDimitry Andric   bool HasPattern = false;
37270b57cec5SDimitry Andric   if (PatternDecl)
37280b57cec5SDimitry Andric     HasPattern = PatternDecl->hasBody(PatternDecl);
37290b57cec5SDimitry Andric 
37300b57cec5SDimitry Andric   // C++0x [temp.explicit]p9:
37310b57cec5SDimitry Andric   //   Except for inline functions, other explicit instantiation declarations
37320b57cec5SDimitry Andric   //   have the effect of suppressing the implicit instantiation of the entity
37330b57cec5SDimitry Andric   //   to which they refer.
37340b57cec5SDimitry Andric   if (!HasPattern || !PatternDecl)
37350b57cec5SDimitry Andric     return true;
37360b57cec5SDimitry Andric 
37370b57cec5SDimitry Andric   return PatternDecl->isInlined();
37380b57cec5SDimitry Andric }
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric bool FunctionDecl::isTemplateInstantiation() const {
37410b57cec5SDimitry Andric   // FIXME: Remove this, it's not clear what it means. (Which template
37420b57cec5SDimitry Andric   // specialization kind?)
37430b57cec5SDimitry Andric   return clang::isTemplateInstantiation(getTemplateSpecializationKind());
37440b57cec5SDimitry Andric }
37450b57cec5SDimitry Andric 
37465ffd83dbSDimitry Andric FunctionDecl *
37475ffd83dbSDimitry Andric FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
37480b57cec5SDimitry Andric   // If this is a generic lambda call operator specialization, its
37490b57cec5SDimitry Andric   // instantiation pattern is always its primary template's pattern
37500b57cec5SDimitry Andric   // even if its primary template was instantiated from another
37510b57cec5SDimitry Andric   // member template (which happens with nested generic lambdas).
37520b57cec5SDimitry Andric   // Since a lambda's call operator's body is transformed eagerly,
37530b57cec5SDimitry Andric   // we don't have to go hunting for a prototype definition template
37540b57cec5SDimitry Andric   // (i.e. instantiated-from-member-template) to use as an instantiation
37550b57cec5SDimitry Andric   // pattern.
37560b57cec5SDimitry Andric 
37570b57cec5SDimitry Andric   if (isGenericLambdaCallOperatorSpecialization(
37580b57cec5SDimitry Andric           dyn_cast<CXXMethodDecl>(this))) {
37590b57cec5SDimitry Andric     assert(getPrimaryTemplate() && "not a generic lambda call operator?");
37600b57cec5SDimitry Andric     return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
37610b57cec5SDimitry Andric   }
37620b57cec5SDimitry Andric 
3763e8d8bef9SDimitry Andric   // Check for a declaration of this function that was instantiated from a
3764e8d8bef9SDimitry Andric   // friend definition.
3765e8d8bef9SDimitry Andric   const FunctionDecl *FD = nullptr;
3766e8d8bef9SDimitry Andric   if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
3767e8d8bef9SDimitry Andric     FD = this;
3768e8d8bef9SDimitry Andric 
3769e8d8bef9SDimitry Andric   if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
37705ffd83dbSDimitry Andric     if (ForDefinition &&
37715ffd83dbSDimitry Andric         !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
37720b57cec5SDimitry Andric       return nullptr;
37730b57cec5SDimitry Andric     return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
37740b57cec5SDimitry Andric   }
37750b57cec5SDimitry Andric 
37765ffd83dbSDimitry Andric   if (ForDefinition &&
37775ffd83dbSDimitry Andric       !clang::isTemplateInstantiation(getTemplateSpecializationKind()))
37780b57cec5SDimitry Andric     return nullptr;
37790b57cec5SDimitry Andric 
37800b57cec5SDimitry Andric   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
37810b57cec5SDimitry Andric     // If we hit a point where the user provided a specialization of this
37820b57cec5SDimitry Andric     // template, we're done looking.
37835ffd83dbSDimitry Andric     while (!ForDefinition || !Primary->isMemberSpecialization()) {
37840b57cec5SDimitry Andric       auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
37850b57cec5SDimitry Andric       if (!NewPrimary)
37860b57cec5SDimitry Andric         break;
37870b57cec5SDimitry Andric       Primary = NewPrimary;
37880b57cec5SDimitry Andric     }
37890b57cec5SDimitry Andric 
37900b57cec5SDimitry Andric     return getDefinitionOrSelf(Primary->getTemplatedDecl());
37910b57cec5SDimitry Andric   }
37920b57cec5SDimitry Andric 
37930b57cec5SDimitry Andric   return nullptr;
37940b57cec5SDimitry Andric }
37950b57cec5SDimitry Andric 
37960b57cec5SDimitry Andric FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
37970b57cec5SDimitry Andric   if (FunctionTemplateSpecializationInfo *Info
37980b57cec5SDimitry Andric         = TemplateOrSpecialization
37990b57cec5SDimitry Andric             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
38000b57cec5SDimitry Andric     return Info->getTemplate();
38010b57cec5SDimitry Andric   }
38020b57cec5SDimitry Andric   return nullptr;
38030b57cec5SDimitry Andric }
38040b57cec5SDimitry Andric 
38050b57cec5SDimitry Andric FunctionTemplateSpecializationInfo *
38060b57cec5SDimitry Andric FunctionDecl::getTemplateSpecializationInfo() const {
38070b57cec5SDimitry Andric   return TemplateOrSpecialization
38080b57cec5SDimitry Andric       .dyn_cast<FunctionTemplateSpecializationInfo *>();
38090b57cec5SDimitry Andric }
38100b57cec5SDimitry Andric 
38110b57cec5SDimitry Andric const TemplateArgumentList *
38120b57cec5SDimitry Andric FunctionDecl::getTemplateSpecializationArgs() const {
38130b57cec5SDimitry Andric   if (FunctionTemplateSpecializationInfo *Info
38140b57cec5SDimitry Andric         = TemplateOrSpecialization
38150b57cec5SDimitry Andric             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
38160b57cec5SDimitry Andric     return Info->TemplateArguments;
38170b57cec5SDimitry Andric   }
38180b57cec5SDimitry Andric   return nullptr;
38190b57cec5SDimitry Andric }
38200b57cec5SDimitry Andric 
38210b57cec5SDimitry Andric const ASTTemplateArgumentListInfo *
38220b57cec5SDimitry Andric FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
38230b57cec5SDimitry Andric   if (FunctionTemplateSpecializationInfo *Info
38240b57cec5SDimitry Andric         = TemplateOrSpecialization
38250b57cec5SDimitry Andric             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
38260b57cec5SDimitry Andric     return Info->TemplateArgumentsAsWritten;
38270b57cec5SDimitry Andric   }
38280b57cec5SDimitry Andric   return nullptr;
38290b57cec5SDimitry Andric }
38300b57cec5SDimitry Andric 
38310b57cec5SDimitry Andric void
38320b57cec5SDimitry Andric FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
38330b57cec5SDimitry Andric                                                 FunctionTemplateDecl *Template,
38340b57cec5SDimitry Andric                                      const TemplateArgumentList *TemplateArgs,
38350b57cec5SDimitry Andric                                                 void *InsertPos,
38360b57cec5SDimitry Andric                                                 TemplateSpecializationKind TSK,
38370b57cec5SDimitry Andric                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
38380b57cec5SDimitry Andric                                           SourceLocation PointOfInstantiation) {
38390b57cec5SDimitry Andric   assert((TemplateOrSpecialization.isNull() ||
38400b57cec5SDimitry Andric           TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
38410b57cec5SDimitry Andric          "Member function is already a specialization");
38420b57cec5SDimitry Andric   assert(TSK != TSK_Undeclared &&
38430b57cec5SDimitry Andric          "Must specify the type of function template specialization");
38440b57cec5SDimitry Andric   assert((TemplateOrSpecialization.isNull() ||
38450b57cec5SDimitry Andric           TSK == TSK_ExplicitSpecialization) &&
38460b57cec5SDimitry Andric          "Member specialization must be an explicit specialization");
38470b57cec5SDimitry Andric   FunctionTemplateSpecializationInfo *Info =
38480b57cec5SDimitry Andric       FunctionTemplateSpecializationInfo::Create(
38490b57cec5SDimitry Andric           C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
38500b57cec5SDimitry Andric           PointOfInstantiation,
38510b57cec5SDimitry Andric           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
38520b57cec5SDimitry Andric   TemplateOrSpecialization = Info;
38530b57cec5SDimitry Andric   Template->addSpecialization(Info, InsertPos);
38540b57cec5SDimitry Andric }
38550b57cec5SDimitry Andric 
38560b57cec5SDimitry Andric void
38570b57cec5SDimitry Andric FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
38580b57cec5SDimitry Andric                                     const UnresolvedSetImpl &Templates,
38590b57cec5SDimitry Andric                              const TemplateArgumentListInfo &TemplateArgs) {
38600b57cec5SDimitry Andric   assert(TemplateOrSpecialization.isNull());
38610b57cec5SDimitry Andric   DependentFunctionTemplateSpecializationInfo *Info =
38620b57cec5SDimitry Andric       DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
38630b57cec5SDimitry Andric                                                           TemplateArgs);
38640b57cec5SDimitry Andric   TemplateOrSpecialization = Info;
38650b57cec5SDimitry Andric }
38660b57cec5SDimitry Andric 
38670b57cec5SDimitry Andric DependentFunctionTemplateSpecializationInfo *
38680b57cec5SDimitry Andric FunctionDecl::getDependentSpecializationInfo() const {
38690b57cec5SDimitry Andric   return TemplateOrSpecialization
38700b57cec5SDimitry Andric       .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
38710b57cec5SDimitry Andric }
38720b57cec5SDimitry Andric 
38730b57cec5SDimitry Andric DependentFunctionTemplateSpecializationInfo *
38740b57cec5SDimitry Andric DependentFunctionTemplateSpecializationInfo::Create(
38750b57cec5SDimitry Andric     ASTContext &Context, const UnresolvedSetImpl &Ts,
38760b57cec5SDimitry Andric     const TemplateArgumentListInfo &TArgs) {
38770b57cec5SDimitry Andric   void *Buffer = Context.Allocate(
38780b57cec5SDimitry Andric       totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
38790b57cec5SDimitry Andric           TArgs.size(), Ts.size()));
38800b57cec5SDimitry Andric   return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
38810b57cec5SDimitry Andric }
38820b57cec5SDimitry Andric 
38830b57cec5SDimitry Andric DependentFunctionTemplateSpecializationInfo::
38840b57cec5SDimitry Andric DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
38850b57cec5SDimitry Andric                                       const TemplateArgumentListInfo &TArgs)
38860b57cec5SDimitry Andric   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
38870b57cec5SDimitry Andric   NumTemplates = Ts.size();
38880b57cec5SDimitry Andric   NumArgs = TArgs.size();
38890b57cec5SDimitry Andric 
38900b57cec5SDimitry Andric   FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
38910b57cec5SDimitry Andric   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
38920b57cec5SDimitry Andric     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
38930b57cec5SDimitry Andric 
38940b57cec5SDimitry Andric   TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
38950b57cec5SDimitry Andric   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
38960b57cec5SDimitry Andric     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
38970b57cec5SDimitry Andric }
38980b57cec5SDimitry Andric 
38990b57cec5SDimitry Andric TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
39000b57cec5SDimitry Andric   // For a function template specialization, query the specialization
39010b57cec5SDimitry Andric   // information object.
39020b57cec5SDimitry Andric   if (FunctionTemplateSpecializationInfo *FTSInfo =
39030b57cec5SDimitry Andric           TemplateOrSpecialization
39040b57cec5SDimitry Andric               .dyn_cast<FunctionTemplateSpecializationInfo *>())
39050b57cec5SDimitry Andric     return FTSInfo->getTemplateSpecializationKind();
39060b57cec5SDimitry Andric 
39070b57cec5SDimitry Andric   if (MemberSpecializationInfo *MSInfo =
39080b57cec5SDimitry Andric           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
39090b57cec5SDimitry Andric     return MSInfo->getTemplateSpecializationKind();
39100b57cec5SDimitry Andric 
39110b57cec5SDimitry Andric   return TSK_Undeclared;
39120b57cec5SDimitry Andric }
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric TemplateSpecializationKind
39150b57cec5SDimitry Andric FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
39160b57cec5SDimitry Andric   // This is the same as getTemplateSpecializationKind(), except that for a
39170b57cec5SDimitry Andric   // function that is both a function template specialization and a member
39180b57cec5SDimitry Andric   // specialization, we prefer the member specialization information. Eg:
39190b57cec5SDimitry Andric   //
39200b57cec5SDimitry Andric   // template<typename T> struct A {
39210b57cec5SDimitry Andric   //   template<typename U> void f() {}
39220b57cec5SDimitry Andric   //   template<> void f<int>() {}
39230b57cec5SDimitry Andric   // };
39240b57cec5SDimitry Andric   //
39250b57cec5SDimitry Andric   // For A<int>::f<int>():
39260b57cec5SDimitry Andric   // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
39270b57cec5SDimitry Andric   // * getTemplateSpecializationKindForInstantiation() will return
39280b57cec5SDimitry Andric   //       TSK_ImplicitInstantiation
39290b57cec5SDimitry Andric   //
39300b57cec5SDimitry Andric   // This reflects the facts that A<int>::f<int> is an explicit specialization
39310b57cec5SDimitry Andric   // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
39320b57cec5SDimitry Andric   // from A::f<int> if a definition is needed.
39330b57cec5SDimitry Andric   if (FunctionTemplateSpecializationInfo *FTSInfo =
39340b57cec5SDimitry Andric           TemplateOrSpecialization
39350b57cec5SDimitry Andric               .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
39360b57cec5SDimitry Andric     if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
39370b57cec5SDimitry Andric       return MSInfo->getTemplateSpecializationKind();
39380b57cec5SDimitry Andric     return FTSInfo->getTemplateSpecializationKind();
39390b57cec5SDimitry Andric   }
39400b57cec5SDimitry Andric 
39410b57cec5SDimitry Andric   if (MemberSpecializationInfo *MSInfo =
39420b57cec5SDimitry Andric           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
39430b57cec5SDimitry Andric     return MSInfo->getTemplateSpecializationKind();
39440b57cec5SDimitry Andric 
39450b57cec5SDimitry Andric   return TSK_Undeclared;
39460b57cec5SDimitry Andric }
39470b57cec5SDimitry Andric 
39480b57cec5SDimitry Andric void
39490b57cec5SDimitry Andric FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
39500b57cec5SDimitry Andric                                           SourceLocation PointOfInstantiation) {
39510b57cec5SDimitry Andric   if (FunctionTemplateSpecializationInfo *FTSInfo
39520b57cec5SDimitry Andric         = TemplateOrSpecialization.dyn_cast<
39530b57cec5SDimitry Andric                                     FunctionTemplateSpecializationInfo*>()) {
39540b57cec5SDimitry Andric     FTSInfo->setTemplateSpecializationKind(TSK);
39550b57cec5SDimitry Andric     if (TSK != TSK_ExplicitSpecialization &&
39560b57cec5SDimitry Andric         PointOfInstantiation.isValid() &&
39570b57cec5SDimitry Andric         FTSInfo->getPointOfInstantiation().isInvalid()) {
39580b57cec5SDimitry Andric       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
39590b57cec5SDimitry Andric       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
39600b57cec5SDimitry Andric         L->InstantiationRequested(this);
39610b57cec5SDimitry Andric     }
39620b57cec5SDimitry Andric   } else if (MemberSpecializationInfo *MSInfo
39630b57cec5SDimitry Andric              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
39640b57cec5SDimitry Andric     MSInfo->setTemplateSpecializationKind(TSK);
39650b57cec5SDimitry Andric     if (TSK != TSK_ExplicitSpecialization &&
39660b57cec5SDimitry Andric         PointOfInstantiation.isValid() &&
39670b57cec5SDimitry Andric         MSInfo->getPointOfInstantiation().isInvalid()) {
39680b57cec5SDimitry Andric       MSInfo->setPointOfInstantiation(PointOfInstantiation);
39690b57cec5SDimitry Andric       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
39700b57cec5SDimitry Andric         L->InstantiationRequested(this);
39710b57cec5SDimitry Andric     }
39720b57cec5SDimitry Andric   } else
39730b57cec5SDimitry Andric     llvm_unreachable("Function cannot have a template specialization kind");
39740b57cec5SDimitry Andric }
39750b57cec5SDimitry Andric 
39760b57cec5SDimitry Andric SourceLocation FunctionDecl::getPointOfInstantiation() const {
39770b57cec5SDimitry Andric   if (FunctionTemplateSpecializationInfo *FTSInfo
39780b57cec5SDimitry Andric         = TemplateOrSpecialization.dyn_cast<
39790b57cec5SDimitry Andric                                         FunctionTemplateSpecializationInfo*>())
39800b57cec5SDimitry Andric     return FTSInfo->getPointOfInstantiation();
3981e8d8bef9SDimitry Andric   if (MemberSpecializationInfo *MSInfo =
3982e8d8bef9SDimitry Andric           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
39830b57cec5SDimitry Andric     return MSInfo->getPointOfInstantiation();
39840b57cec5SDimitry Andric 
39850b57cec5SDimitry Andric   return SourceLocation();
39860b57cec5SDimitry Andric }
39870b57cec5SDimitry Andric 
39880b57cec5SDimitry Andric bool FunctionDecl::isOutOfLine() const {
39890b57cec5SDimitry Andric   if (Decl::isOutOfLine())
39900b57cec5SDimitry Andric     return true;
39910b57cec5SDimitry Andric 
39920b57cec5SDimitry Andric   // If this function was instantiated from a member function of a
39930b57cec5SDimitry Andric   // class template, check whether that member function was defined out-of-line.
39940b57cec5SDimitry Andric   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
39950b57cec5SDimitry Andric     const FunctionDecl *Definition;
39960b57cec5SDimitry Andric     if (FD->hasBody(Definition))
39970b57cec5SDimitry Andric       return Definition->isOutOfLine();
39980b57cec5SDimitry Andric   }
39990b57cec5SDimitry Andric 
40000b57cec5SDimitry Andric   // If this function was instantiated from a function template,
40010b57cec5SDimitry Andric   // check whether that function template was defined out-of-line.
40020b57cec5SDimitry Andric   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
40030b57cec5SDimitry Andric     const FunctionDecl *Definition;
40040b57cec5SDimitry Andric     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
40050b57cec5SDimitry Andric       return Definition->isOutOfLine();
40060b57cec5SDimitry Andric   }
40070b57cec5SDimitry Andric 
40080b57cec5SDimitry Andric   return false;
40090b57cec5SDimitry Andric }
40100b57cec5SDimitry Andric 
40110b57cec5SDimitry Andric SourceRange FunctionDecl::getSourceRange() const {
40120b57cec5SDimitry Andric   return SourceRange(getOuterLocStart(), EndRangeLoc);
40130b57cec5SDimitry Andric }
40140b57cec5SDimitry Andric 
40150b57cec5SDimitry Andric unsigned FunctionDecl::getMemoryFunctionKind() const {
40160b57cec5SDimitry Andric   IdentifierInfo *FnInfo = getIdentifier();
40170b57cec5SDimitry Andric 
40180b57cec5SDimitry Andric   if (!FnInfo)
40190b57cec5SDimitry Andric     return 0;
40200b57cec5SDimitry Andric 
40210b57cec5SDimitry Andric   // Builtin handling.
40220b57cec5SDimitry Andric   switch (getBuiltinID()) {
40230b57cec5SDimitry Andric   case Builtin::BI__builtin_memset:
40240b57cec5SDimitry Andric   case Builtin::BI__builtin___memset_chk:
40250b57cec5SDimitry Andric   case Builtin::BImemset:
40260b57cec5SDimitry Andric     return Builtin::BImemset;
40270b57cec5SDimitry Andric 
40280b57cec5SDimitry Andric   case Builtin::BI__builtin_memcpy:
40290b57cec5SDimitry Andric   case Builtin::BI__builtin___memcpy_chk:
40300b57cec5SDimitry Andric   case Builtin::BImemcpy:
40310b57cec5SDimitry Andric     return Builtin::BImemcpy;
40320b57cec5SDimitry Andric 
4033480093f4SDimitry Andric   case Builtin::BI__builtin_mempcpy:
4034480093f4SDimitry Andric   case Builtin::BI__builtin___mempcpy_chk:
4035480093f4SDimitry Andric   case Builtin::BImempcpy:
4036480093f4SDimitry Andric     return Builtin::BImempcpy;
4037480093f4SDimitry Andric 
40380b57cec5SDimitry Andric   case Builtin::BI__builtin_memmove:
40390b57cec5SDimitry Andric   case Builtin::BI__builtin___memmove_chk:
40400b57cec5SDimitry Andric   case Builtin::BImemmove:
40410b57cec5SDimitry Andric     return Builtin::BImemmove;
40420b57cec5SDimitry Andric 
40430b57cec5SDimitry Andric   case Builtin::BIstrlcpy:
40440b57cec5SDimitry Andric   case Builtin::BI__builtin___strlcpy_chk:
40450b57cec5SDimitry Andric     return Builtin::BIstrlcpy;
40460b57cec5SDimitry Andric 
40470b57cec5SDimitry Andric   case Builtin::BIstrlcat:
40480b57cec5SDimitry Andric   case Builtin::BI__builtin___strlcat_chk:
40490b57cec5SDimitry Andric     return Builtin::BIstrlcat;
40500b57cec5SDimitry Andric 
40510b57cec5SDimitry Andric   case Builtin::BI__builtin_memcmp:
40520b57cec5SDimitry Andric   case Builtin::BImemcmp:
40530b57cec5SDimitry Andric     return Builtin::BImemcmp;
40540b57cec5SDimitry Andric 
40550b57cec5SDimitry Andric   case Builtin::BI__builtin_bcmp:
40560b57cec5SDimitry Andric   case Builtin::BIbcmp:
40570b57cec5SDimitry Andric     return Builtin::BIbcmp;
40580b57cec5SDimitry Andric 
40590b57cec5SDimitry Andric   case Builtin::BI__builtin_strncpy:
40600b57cec5SDimitry Andric   case Builtin::BI__builtin___strncpy_chk:
40610b57cec5SDimitry Andric   case Builtin::BIstrncpy:
40620b57cec5SDimitry Andric     return Builtin::BIstrncpy;
40630b57cec5SDimitry Andric 
40640b57cec5SDimitry Andric   case Builtin::BI__builtin_strncmp:
40650b57cec5SDimitry Andric   case Builtin::BIstrncmp:
40660b57cec5SDimitry Andric     return Builtin::BIstrncmp;
40670b57cec5SDimitry Andric 
40680b57cec5SDimitry Andric   case Builtin::BI__builtin_strncasecmp:
40690b57cec5SDimitry Andric   case Builtin::BIstrncasecmp:
40700b57cec5SDimitry Andric     return Builtin::BIstrncasecmp;
40710b57cec5SDimitry Andric 
40720b57cec5SDimitry Andric   case Builtin::BI__builtin_strncat:
40730b57cec5SDimitry Andric   case Builtin::BI__builtin___strncat_chk:
40740b57cec5SDimitry Andric   case Builtin::BIstrncat:
40750b57cec5SDimitry Andric     return Builtin::BIstrncat;
40760b57cec5SDimitry Andric 
40770b57cec5SDimitry Andric   case Builtin::BI__builtin_strndup:
40780b57cec5SDimitry Andric   case Builtin::BIstrndup:
40790b57cec5SDimitry Andric     return Builtin::BIstrndup;
40800b57cec5SDimitry Andric 
40810b57cec5SDimitry Andric   case Builtin::BI__builtin_strlen:
40820b57cec5SDimitry Andric   case Builtin::BIstrlen:
40830b57cec5SDimitry Andric     return Builtin::BIstrlen;
40840b57cec5SDimitry Andric 
40850b57cec5SDimitry Andric   case Builtin::BI__builtin_bzero:
40860b57cec5SDimitry Andric   case Builtin::BIbzero:
40870b57cec5SDimitry Andric     return Builtin::BIbzero;
40880b57cec5SDimitry Andric 
4089e8d8bef9SDimitry Andric   case Builtin::BIfree:
4090e8d8bef9SDimitry Andric     return Builtin::BIfree;
4091e8d8bef9SDimitry Andric 
40920b57cec5SDimitry Andric   default:
40930b57cec5SDimitry Andric     if (isExternC()) {
40940b57cec5SDimitry Andric       if (FnInfo->isStr("memset"))
40950b57cec5SDimitry Andric         return Builtin::BImemset;
4096e8d8bef9SDimitry Andric       if (FnInfo->isStr("memcpy"))
40970b57cec5SDimitry Andric         return Builtin::BImemcpy;
4098e8d8bef9SDimitry Andric       if (FnInfo->isStr("mempcpy"))
4099480093f4SDimitry Andric         return Builtin::BImempcpy;
4100e8d8bef9SDimitry Andric       if (FnInfo->isStr("memmove"))
41010b57cec5SDimitry Andric         return Builtin::BImemmove;
4102e8d8bef9SDimitry Andric       if (FnInfo->isStr("memcmp"))
41030b57cec5SDimitry Andric         return Builtin::BImemcmp;
4104e8d8bef9SDimitry Andric       if (FnInfo->isStr("bcmp"))
41050b57cec5SDimitry Andric         return Builtin::BIbcmp;
4106e8d8bef9SDimitry Andric       if (FnInfo->isStr("strncpy"))
41070b57cec5SDimitry Andric         return Builtin::BIstrncpy;
4108e8d8bef9SDimitry Andric       if (FnInfo->isStr("strncmp"))
41090b57cec5SDimitry Andric         return Builtin::BIstrncmp;
4110e8d8bef9SDimitry Andric       if (FnInfo->isStr("strncasecmp"))
41110b57cec5SDimitry Andric         return Builtin::BIstrncasecmp;
4112e8d8bef9SDimitry Andric       if (FnInfo->isStr("strncat"))
41130b57cec5SDimitry Andric         return Builtin::BIstrncat;
4114e8d8bef9SDimitry Andric       if (FnInfo->isStr("strndup"))
41150b57cec5SDimitry Andric         return Builtin::BIstrndup;
4116e8d8bef9SDimitry Andric       if (FnInfo->isStr("strlen"))
41170b57cec5SDimitry Andric         return Builtin::BIstrlen;
4118e8d8bef9SDimitry Andric       if (FnInfo->isStr("bzero"))
41190b57cec5SDimitry Andric         return Builtin::BIbzero;
4120e8d8bef9SDimitry Andric     } else if (isInStdNamespace()) {
4121e8d8bef9SDimitry Andric       if (FnInfo->isStr("free"))
4122e8d8bef9SDimitry Andric         return Builtin::BIfree;
41230b57cec5SDimitry Andric     }
41240b57cec5SDimitry Andric     break;
41250b57cec5SDimitry Andric   }
41260b57cec5SDimitry Andric   return 0;
41270b57cec5SDimitry Andric }
41280b57cec5SDimitry Andric 
41290b57cec5SDimitry Andric unsigned FunctionDecl::getODRHash() const {
41300b57cec5SDimitry Andric   assert(hasODRHash());
41310b57cec5SDimitry Andric   return ODRHash;
41320b57cec5SDimitry Andric }
41330b57cec5SDimitry Andric 
41340b57cec5SDimitry Andric unsigned FunctionDecl::getODRHash() {
41350b57cec5SDimitry Andric   if (hasODRHash())
41360b57cec5SDimitry Andric     return ODRHash;
41370b57cec5SDimitry Andric 
41380b57cec5SDimitry Andric   if (auto *FT = getInstantiatedFromMemberFunction()) {
41390b57cec5SDimitry Andric     setHasODRHash(true);
41400b57cec5SDimitry Andric     ODRHash = FT->getODRHash();
41410b57cec5SDimitry Andric     return ODRHash;
41420b57cec5SDimitry Andric   }
41430b57cec5SDimitry Andric 
41440b57cec5SDimitry Andric   class ODRHash Hash;
41450b57cec5SDimitry Andric   Hash.AddFunctionDecl(this);
41460b57cec5SDimitry Andric   setHasODRHash(true);
41470b57cec5SDimitry Andric   ODRHash = Hash.CalculateHash();
41480b57cec5SDimitry Andric   return ODRHash;
41490b57cec5SDimitry Andric }
41500b57cec5SDimitry Andric 
41510b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
41520b57cec5SDimitry Andric // FieldDecl Implementation
41530b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
41540b57cec5SDimitry Andric 
41550b57cec5SDimitry Andric FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
41560b57cec5SDimitry Andric                              SourceLocation StartLoc, SourceLocation IdLoc,
41570b57cec5SDimitry Andric                              IdentifierInfo *Id, QualType T,
41580b57cec5SDimitry Andric                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
41590b57cec5SDimitry Andric                              InClassInitStyle InitStyle) {
41600b57cec5SDimitry Andric   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
41610b57cec5SDimitry Andric                                BW, Mutable, InitStyle);
41620b57cec5SDimitry Andric }
41630b57cec5SDimitry Andric 
41640b57cec5SDimitry Andric FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
41650b57cec5SDimitry Andric   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
41660b57cec5SDimitry Andric                                SourceLocation(), nullptr, QualType(), nullptr,
41670b57cec5SDimitry Andric                                nullptr, false, ICIS_NoInit);
41680b57cec5SDimitry Andric }
41690b57cec5SDimitry Andric 
41700b57cec5SDimitry Andric bool FieldDecl::isAnonymousStructOrUnion() const {
41710b57cec5SDimitry Andric   if (!isImplicit() || getDeclName())
41720b57cec5SDimitry Andric     return false;
41730b57cec5SDimitry Andric 
41740b57cec5SDimitry Andric   if (const auto *Record = getType()->getAs<RecordType>())
41750b57cec5SDimitry Andric     return Record->getDecl()->isAnonymousStructOrUnion();
41760b57cec5SDimitry Andric 
41770b57cec5SDimitry Andric   return false;
41780b57cec5SDimitry Andric }
41790b57cec5SDimitry Andric 
41800b57cec5SDimitry Andric unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
41810b57cec5SDimitry Andric   assert(isBitField() && "not a bitfield");
41820b57cec5SDimitry Andric   return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
41830b57cec5SDimitry Andric }
41840b57cec5SDimitry Andric 
41850b57cec5SDimitry Andric bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
41860b57cec5SDimitry Andric   return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
41870b57cec5SDimitry Andric          getBitWidthValue(Ctx) == 0;
41880b57cec5SDimitry Andric }
41890b57cec5SDimitry Andric 
41900b57cec5SDimitry Andric bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
41910b57cec5SDimitry Andric   if (isZeroLengthBitField(Ctx))
41920b57cec5SDimitry Andric     return true;
41930b57cec5SDimitry Andric 
41940b57cec5SDimitry Andric   // C++2a [intro.object]p7:
41950b57cec5SDimitry Andric   //   An object has nonzero size if it
41960b57cec5SDimitry Andric   //     -- is not a potentially-overlapping subobject, or
41970b57cec5SDimitry Andric   if (!hasAttr<NoUniqueAddressAttr>())
41980b57cec5SDimitry Andric     return false;
41990b57cec5SDimitry Andric 
42000b57cec5SDimitry Andric   //     -- is not of class type, or
42010b57cec5SDimitry Andric   const auto *RT = getType()->getAs<RecordType>();
42020b57cec5SDimitry Andric   if (!RT)
42030b57cec5SDimitry Andric     return false;
42040b57cec5SDimitry Andric   const RecordDecl *RD = RT->getDecl()->getDefinition();
42050b57cec5SDimitry Andric   if (!RD) {
42060b57cec5SDimitry Andric     assert(isInvalidDecl() && "valid field has incomplete type");
42070b57cec5SDimitry Andric     return false;
42080b57cec5SDimitry Andric   }
42090b57cec5SDimitry Andric 
42100b57cec5SDimitry Andric   //     -- [has] virtual member functions or virtual base classes, or
42110b57cec5SDimitry Andric   //     -- has subobjects of nonzero size or bit-fields of nonzero length
42120b57cec5SDimitry Andric   const auto *CXXRD = cast<CXXRecordDecl>(RD);
42130b57cec5SDimitry Andric   if (!CXXRD->isEmpty())
42140b57cec5SDimitry Andric     return false;
42150b57cec5SDimitry Andric 
42160b57cec5SDimitry Andric   // Otherwise, [...] the circumstances under which the object has zero size
42170b57cec5SDimitry Andric   // are implementation-defined.
42180b57cec5SDimitry Andric   // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
42190b57cec5SDimitry Andric   // ABI will do.
42200b57cec5SDimitry Andric   return true;
42210b57cec5SDimitry Andric }
42220b57cec5SDimitry Andric 
42230b57cec5SDimitry Andric unsigned FieldDecl::getFieldIndex() const {
42240b57cec5SDimitry Andric   const FieldDecl *Canonical = getCanonicalDecl();
42250b57cec5SDimitry Andric   if (Canonical != this)
42260b57cec5SDimitry Andric     return Canonical->getFieldIndex();
42270b57cec5SDimitry Andric 
42280b57cec5SDimitry Andric   if (CachedFieldIndex) return CachedFieldIndex - 1;
42290b57cec5SDimitry Andric 
42300b57cec5SDimitry Andric   unsigned Index = 0;
42310b57cec5SDimitry Andric   const RecordDecl *RD = getParent()->getDefinition();
42320b57cec5SDimitry Andric   assert(RD && "requested index for field of struct with no definition");
42330b57cec5SDimitry Andric 
42340b57cec5SDimitry Andric   for (auto *Field : RD->fields()) {
42350b57cec5SDimitry Andric     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
42360b57cec5SDimitry Andric     ++Index;
42370b57cec5SDimitry Andric   }
42380b57cec5SDimitry Andric 
42390b57cec5SDimitry Andric   assert(CachedFieldIndex && "failed to find field in parent");
42400b57cec5SDimitry Andric   return CachedFieldIndex - 1;
42410b57cec5SDimitry Andric }
42420b57cec5SDimitry Andric 
42430b57cec5SDimitry Andric SourceRange FieldDecl::getSourceRange() const {
42440b57cec5SDimitry Andric   const Expr *FinalExpr = getInClassInitializer();
42450b57cec5SDimitry Andric   if (!FinalExpr)
42460b57cec5SDimitry Andric     FinalExpr = getBitWidth();
42470b57cec5SDimitry Andric   if (FinalExpr)
42480b57cec5SDimitry Andric     return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
42490b57cec5SDimitry Andric   return DeclaratorDecl::getSourceRange();
42500b57cec5SDimitry Andric }
42510b57cec5SDimitry Andric 
42520b57cec5SDimitry Andric void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
42530b57cec5SDimitry Andric   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
42540b57cec5SDimitry Andric          "capturing type in non-lambda or captured record.");
42550b57cec5SDimitry Andric   assert(InitStorage.getInt() == ISK_NoInit &&
42560b57cec5SDimitry Andric          InitStorage.getPointer() == nullptr &&
42570b57cec5SDimitry Andric          "bit width, initializer or captured type already set");
42580b57cec5SDimitry Andric   InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
42590b57cec5SDimitry Andric                                ISK_CapturedVLAType);
42600b57cec5SDimitry Andric }
42610b57cec5SDimitry Andric 
42620b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
42630b57cec5SDimitry Andric // TagDecl Implementation
42640b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
42650b57cec5SDimitry Andric 
42660b57cec5SDimitry Andric TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
42670b57cec5SDimitry Andric                  SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
42680b57cec5SDimitry Andric                  SourceLocation StartL)
42690b57cec5SDimitry Andric     : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
42700b57cec5SDimitry Andric       TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
42710b57cec5SDimitry Andric   assert((DK != Enum || TK == TTK_Enum) &&
42720b57cec5SDimitry Andric          "EnumDecl not matched with TTK_Enum");
42730b57cec5SDimitry Andric   setPreviousDecl(PrevDecl);
42740b57cec5SDimitry Andric   setTagKind(TK);
42750b57cec5SDimitry Andric   setCompleteDefinition(false);
42760b57cec5SDimitry Andric   setBeingDefined(false);
42770b57cec5SDimitry Andric   setEmbeddedInDeclarator(false);
42780b57cec5SDimitry Andric   setFreeStanding(false);
42790b57cec5SDimitry Andric   setCompleteDefinitionRequired(false);
42800b57cec5SDimitry Andric }
42810b57cec5SDimitry Andric 
42820b57cec5SDimitry Andric SourceLocation TagDecl::getOuterLocStart() const {
42830b57cec5SDimitry Andric   return getTemplateOrInnerLocStart(this);
42840b57cec5SDimitry Andric }
42850b57cec5SDimitry Andric 
42860b57cec5SDimitry Andric SourceRange TagDecl::getSourceRange() const {
42870b57cec5SDimitry Andric   SourceLocation RBraceLoc = BraceRange.getEnd();
42880b57cec5SDimitry Andric   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
42890b57cec5SDimitry Andric   return SourceRange(getOuterLocStart(), E);
42900b57cec5SDimitry Andric }
42910b57cec5SDimitry Andric 
42920b57cec5SDimitry Andric TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
42930b57cec5SDimitry Andric 
42940b57cec5SDimitry Andric void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
42950b57cec5SDimitry Andric   TypedefNameDeclOrQualifier = TDD;
42960b57cec5SDimitry Andric   if (const Type *T = getTypeForDecl()) {
42970b57cec5SDimitry Andric     (void)T;
42980b57cec5SDimitry Andric     assert(T->isLinkageValid());
42990b57cec5SDimitry Andric   }
43000b57cec5SDimitry Andric   assert(isLinkageValid());
43010b57cec5SDimitry Andric }
43020b57cec5SDimitry Andric 
43030b57cec5SDimitry Andric void TagDecl::startDefinition() {
43040b57cec5SDimitry Andric   setBeingDefined(true);
43050b57cec5SDimitry Andric 
43060b57cec5SDimitry Andric   if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
43070b57cec5SDimitry Andric     struct CXXRecordDecl::DefinitionData *Data =
43080b57cec5SDimitry Andric       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
43090b57cec5SDimitry Andric     for (auto I : redecls())
43100b57cec5SDimitry Andric       cast<CXXRecordDecl>(I)->DefinitionData = Data;
43110b57cec5SDimitry Andric   }
43120b57cec5SDimitry Andric }
43130b57cec5SDimitry Andric 
43140b57cec5SDimitry Andric void TagDecl::completeDefinition() {
43150b57cec5SDimitry Andric   assert((!isa<CXXRecordDecl>(this) ||
43160b57cec5SDimitry Andric           cast<CXXRecordDecl>(this)->hasDefinition()) &&
43170b57cec5SDimitry Andric          "definition completed but not started");
43180b57cec5SDimitry Andric 
43190b57cec5SDimitry Andric   setCompleteDefinition(true);
43200b57cec5SDimitry Andric   setBeingDefined(false);
43210b57cec5SDimitry Andric 
43220b57cec5SDimitry Andric   if (ASTMutationListener *L = getASTMutationListener())
43230b57cec5SDimitry Andric     L->CompletedTagDefinition(this);
43240b57cec5SDimitry Andric }
43250b57cec5SDimitry Andric 
43260b57cec5SDimitry Andric TagDecl *TagDecl::getDefinition() const {
43270b57cec5SDimitry Andric   if (isCompleteDefinition())
43280b57cec5SDimitry Andric     return const_cast<TagDecl *>(this);
43290b57cec5SDimitry Andric 
43300b57cec5SDimitry Andric   // If it's possible for us to have an out-of-date definition, check now.
43310b57cec5SDimitry Andric   if (mayHaveOutOfDateDef()) {
43320b57cec5SDimitry Andric     if (IdentifierInfo *II = getIdentifier()) {
43330b57cec5SDimitry Andric       if (II->isOutOfDate()) {
43340b57cec5SDimitry Andric         updateOutOfDate(*II);
43350b57cec5SDimitry Andric       }
43360b57cec5SDimitry Andric     }
43370b57cec5SDimitry Andric   }
43380b57cec5SDimitry Andric 
43390b57cec5SDimitry Andric   if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
43400b57cec5SDimitry Andric     return CXXRD->getDefinition();
43410b57cec5SDimitry Andric 
43420b57cec5SDimitry Andric   for (auto R : redecls())
43430b57cec5SDimitry Andric     if (R->isCompleteDefinition())
43440b57cec5SDimitry Andric       return R;
43450b57cec5SDimitry Andric 
43460b57cec5SDimitry Andric   return nullptr;
43470b57cec5SDimitry Andric }
43480b57cec5SDimitry Andric 
43490b57cec5SDimitry Andric void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
43500b57cec5SDimitry Andric   if (QualifierLoc) {
43510b57cec5SDimitry Andric     // Make sure the extended qualifier info is allocated.
43520b57cec5SDimitry Andric     if (!hasExtInfo())
43530b57cec5SDimitry Andric       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
43540b57cec5SDimitry Andric     // Set qualifier info.
43550b57cec5SDimitry Andric     getExtInfo()->QualifierLoc = QualifierLoc;
43560b57cec5SDimitry Andric   } else {
43570b57cec5SDimitry Andric     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
43580b57cec5SDimitry Andric     if (hasExtInfo()) {
43590b57cec5SDimitry Andric       if (getExtInfo()->NumTemplParamLists == 0) {
43600b57cec5SDimitry Andric         getASTContext().Deallocate(getExtInfo());
43610b57cec5SDimitry Andric         TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
43620b57cec5SDimitry Andric       }
43630b57cec5SDimitry Andric       else
43640b57cec5SDimitry Andric         getExtInfo()->QualifierLoc = QualifierLoc;
43650b57cec5SDimitry Andric     }
43660b57cec5SDimitry Andric   }
43670b57cec5SDimitry Andric }
43680b57cec5SDimitry Andric 
43690b57cec5SDimitry Andric void TagDecl::setTemplateParameterListsInfo(
43700b57cec5SDimitry Andric     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
43710b57cec5SDimitry Andric   assert(!TPLists.empty());
43720b57cec5SDimitry Andric   // Make sure the extended decl info is allocated.
43730b57cec5SDimitry Andric   if (!hasExtInfo())
43740b57cec5SDimitry Andric     // Allocate external info struct.
43750b57cec5SDimitry Andric     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
43760b57cec5SDimitry Andric   // Set the template parameter lists info.
43770b57cec5SDimitry Andric   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
43780b57cec5SDimitry Andric }
43790b57cec5SDimitry Andric 
43800b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
43810b57cec5SDimitry Andric // EnumDecl Implementation
43820b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
43830b57cec5SDimitry Andric 
43840b57cec5SDimitry Andric EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
43850b57cec5SDimitry Andric                    SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
43860b57cec5SDimitry Andric                    bool Scoped, bool ScopedUsingClassTag, bool Fixed)
43870b57cec5SDimitry Andric     : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
43880b57cec5SDimitry Andric   assert(Scoped || !ScopedUsingClassTag);
43890b57cec5SDimitry Andric   IntegerType = nullptr;
43900b57cec5SDimitry Andric   setNumPositiveBits(0);
43910b57cec5SDimitry Andric   setNumNegativeBits(0);
43920b57cec5SDimitry Andric   setScoped(Scoped);
43930b57cec5SDimitry Andric   setScopedUsingClassTag(ScopedUsingClassTag);
43940b57cec5SDimitry Andric   setFixed(Fixed);
43950b57cec5SDimitry Andric   setHasODRHash(false);
43960b57cec5SDimitry Andric   ODRHash = 0;
43970b57cec5SDimitry Andric }
43980b57cec5SDimitry Andric 
43990b57cec5SDimitry Andric void EnumDecl::anchor() {}
44000b57cec5SDimitry Andric 
44010b57cec5SDimitry Andric EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
44020b57cec5SDimitry Andric                            SourceLocation StartLoc, SourceLocation IdLoc,
44030b57cec5SDimitry Andric                            IdentifierInfo *Id,
44040b57cec5SDimitry Andric                            EnumDecl *PrevDecl, bool IsScoped,
44050b57cec5SDimitry Andric                            bool IsScopedUsingClassTag, bool IsFixed) {
44060b57cec5SDimitry Andric   auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
44070b57cec5SDimitry Andric                                     IsScoped, IsScopedUsingClassTag, IsFixed);
44080b57cec5SDimitry Andric   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
44090b57cec5SDimitry Andric   C.getTypeDeclType(Enum, PrevDecl);
44100b57cec5SDimitry Andric   return Enum;
44110b57cec5SDimitry Andric }
44120b57cec5SDimitry Andric 
44130b57cec5SDimitry Andric EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
44140b57cec5SDimitry Andric   EnumDecl *Enum =
44150b57cec5SDimitry Andric       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
44160b57cec5SDimitry Andric                            nullptr, nullptr, false, false, false);
44170b57cec5SDimitry Andric   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
44180b57cec5SDimitry Andric   return Enum;
44190b57cec5SDimitry Andric }
44200b57cec5SDimitry Andric 
44210b57cec5SDimitry Andric SourceRange EnumDecl::getIntegerTypeRange() const {
44220b57cec5SDimitry Andric   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
44230b57cec5SDimitry Andric     return TI->getTypeLoc().getSourceRange();
44240b57cec5SDimitry Andric   return SourceRange();
44250b57cec5SDimitry Andric }
44260b57cec5SDimitry Andric 
44270b57cec5SDimitry Andric void EnumDecl::completeDefinition(QualType NewType,
44280b57cec5SDimitry Andric                                   QualType NewPromotionType,
44290b57cec5SDimitry Andric                                   unsigned NumPositiveBits,
44300b57cec5SDimitry Andric                                   unsigned NumNegativeBits) {
44310b57cec5SDimitry Andric   assert(!isCompleteDefinition() && "Cannot redefine enums!");
44320b57cec5SDimitry Andric   if (!IntegerType)
44330b57cec5SDimitry Andric     IntegerType = NewType.getTypePtr();
44340b57cec5SDimitry Andric   PromotionType = NewPromotionType;
44350b57cec5SDimitry Andric   setNumPositiveBits(NumPositiveBits);
44360b57cec5SDimitry Andric   setNumNegativeBits(NumNegativeBits);
44370b57cec5SDimitry Andric   TagDecl::completeDefinition();
44380b57cec5SDimitry Andric }
44390b57cec5SDimitry Andric 
44400b57cec5SDimitry Andric bool EnumDecl::isClosed() const {
44410b57cec5SDimitry Andric   if (const auto *A = getAttr<EnumExtensibilityAttr>())
44420b57cec5SDimitry Andric     return A->getExtensibility() == EnumExtensibilityAttr::Closed;
44430b57cec5SDimitry Andric   return true;
44440b57cec5SDimitry Andric }
44450b57cec5SDimitry Andric 
44460b57cec5SDimitry Andric bool EnumDecl::isClosedFlag() const {
44470b57cec5SDimitry Andric   return isClosed() && hasAttr<FlagEnumAttr>();
44480b57cec5SDimitry Andric }
44490b57cec5SDimitry Andric 
44500b57cec5SDimitry Andric bool EnumDecl::isClosedNonFlag() const {
44510b57cec5SDimitry Andric   return isClosed() && !hasAttr<FlagEnumAttr>();
44520b57cec5SDimitry Andric }
44530b57cec5SDimitry Andric 
44540b57cec5SDimitry Andric TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
44550b57cec5SDimitry Andric   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
44560b57cec5SDimitry Andric     return MSI->getTemplateSpecializationKind();
44570b57cec5SDimitry Andric 
44580b57cec5SDimitry Andric   return TSK_Undeclared;
44590b57cec5SDimitry Andric }
44600b57cec5SDimitry Andric 
44610b57cec5SDimitry Andric void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
44620b57cec5SDimitry Andric                                          SourceLocation PointOfInstantiation) {
44630b57cec5SDimitry Andric   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
44640b57cec5SDimitry Andric   assert(MSI && "Not an instantiated member enumeration?");
44650b57cec5SDimitry Andric   MSI->setTemplateSpecializationKind(TSK);
44660b57cec5SDimitry Andric   if (TSK != TSK_ExplicitSpecialization &&
44670b57cec5SDimitry Andric       PointOfInstantiation.isValid() &&
44680b57cec5SDimitry Andric       MSI->getPointOfInstantiation().isInvalid())
44690b57cec5SDimitry Andric     MSI->setPointOfInstantiation(PointOfInstantiation);
44700b57cec5SDimitry Andric }
44710b57cec5SDimitry Andric 
44720b57cec5SDimitry Andric EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
44730b57cec5SDimitry Andric   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
44740b57cec5SDimitry Andric     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
44750b57cec5SDimitry Andric       EnumDecl *ED = getInstantiatedFromMemberEnum();
44760b57cec5SDimitry Andric       while (auto *NewED = ED->getInstantiatedFromMemberEnum())
44770b57cec5SDimitry Andric         ED = NewED;
44780b57cec5SDimitry Andric       return getDefinitionOrSelf(ED);
44790b57cec5SDimitry Andric     }
44800b57cec5SDimitry Andric   }
44810b57cec5SDimitry Andric 
44820b57cec5SDimitry Andric   assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
44830b57cec5SDimitry Andric          "couldn't find pattern for enum instantiation");
44840b57cec5SDimitry Andric   return nullptr;
44850b57cec5SDimitry Andric }
44860b57cec5SDimitry Andric 
44870b57cec5SDimitry Andric EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
44880b57cec5SDimitry Andric   if (SpecializationInfo)
44890b57cec5SDimitry Andric     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
44900b57cec5SDimitry Andric 
44910b57cec5SDimitry Andric   return nullptr;
44920b57cec5SDimitry Andric }
44930b57cec5SDimitry Andric 
44940b57cec5SDimitry Andric void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
44950b57cec5SDimitry Andric                                             TemplateSpecializationKind TSK) {
44960b57cec5SDimitry Andric   assert(!SpecializationInfo && "Member enum is already a specialization");
44970b57cec5SDimitry Andric   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
44980b57cec5SDimitry Andric }
44990b57cec5SDimitry Andric 
45000b57cec5SDimitry Andric unsigned EnumDecl::getODRHash() {
45010b57cec5SDimitry Andric   if (hasODRHash())
45020b57cec5SDimitry Andric     return ODRHash;
45030b57cec5SDimitry Andric 
45040b57cec5SDimitry Andric   class ODRHash Hash;
45050b57cec5SDimitry Andric   Hash.AddEnumDecl(this);
45060b57cec5SDimitry Andric   setHasODRHash(true);
45070b57cec5SDimitry Andric   ODRHash = Hash.CalculateHash();
45080b57cec5SDimitry Andric   return ODRHash;
45090b57cec5SDimitry Andric }
45100b57cec5SDimitry Andric 
4511*349cc55cSDimitry Andric SourceRange EnumDecl::getSourceRange() const {
4512*349cc55cSDimitry Andric   auto Res = TagDecl::getSourceRange();
4513*349cc55cSDimitry Andric   // Set end-point to enum-base, e.g. enum foo : ^bar
4514*349cc55cSDimitry Andric   if (auto *TSI = getIntegerTypeSourceInfo()) {
4515*349cc55cSDimitry Andric     // TagDecl doesn't know about the enum base.
4516*349cc55cSDimitry Andric     if (!getBraceRange().getEnd().isValid())
4517*349cc55cSDimitry Andric       Res.setEnd(TSI->getTypeLoc().getEndLoc());
4518*349cc55cSDimitry Andric   }
4519*349cc55cSDimitry Andric   return Res;
4520*349cc55cSDimitry Andric }
4521*349cc55cSDimitry Andric 
45220b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
45230b57cec5SDimitry Andric // RecordDecl Implementation
45240b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
45250b57cec5SDimitry Andric 
45260b57cec5SDimitry Andric RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
45270b57cec5SDimitry Andric                        DeclContext *DC, SourceLocation StartLoc,
45280b57cec5SDimitry Andric                        SourceLocation IdLoc, IdentifierInfo *Id,
45290b57cec5SDimitry Andric                        RecordDecl *PrevDecl)
45300b57cec5SDimitry Andric     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
45310b57cec5SDimitry Andric   assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
45320b57cec5SDimitry Andric   setHasFlexibleArrayMember(false);
45330b57cec5SDimitry Andric   setAnonymousStructOrUnion(false);
45340b57cec5SDimitry Andric   setHasObjectMember(false);
45350b57cec5SDimitry Andric   setHasVolatileMember(false);
45360b57cec5SDimitry Andric   setHasLoadedFieldsFromExternalStorage(false);
45370b57cec5SDimitry Andric   setNonTrivialToPrimitiveDefaultInitialize(false);
45380b57cec5SDimitry Andric   setNonTrivialToPrimitiveCopy(false);
45390b57cec5SDimitry Andric   setNonTrivialToPrimitiveDestroy(false);
45400b57cec5SDimitry Andric   setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
45410b57cec5SDimitry Andric   setHasNonTrivialToPrimitiveDestructCUnion(false);
45420b57cec5SDimitry Andric   setHasNonTrivialToPrimitiveCopyCUnion(false);
45430b57cec5SDimitry Andric   setParamDestroyedInCallee(false);
45440b57cec5SDimitry Andric   setArgPassingRestrictions(APK_CanPassInRegs);
45450b57cec5SDimitry Andric }
45460b57cec5SDimitry Andric 
45470b57cec5SDimitry Andric RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
45480b57cec5SDimitry Andric                                SourceLocation StartLoc, SourceLocation IdLoc,
45490b57cec5SDimitry Andric                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
45500b57cec5SDimitry Andric   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
45510b57cec5SDimitry Andric                                          StartLoc, IdLoc, Id, PrevDecl);
45520b57cec5SDimitry Andric   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
45530b57cec5SDimitry Andric 
45540b57cec5SDimitry Andric   C.getTypeDeclType(R, PrevDecl);
45550b57cec5SDimitry Andric   return R;
45560b57cec5SDimitry Andric }
45570b57cec5SDimitry Andric 
45580b57cec5SDimitry Andric RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
45590b57cec5SDimitry Andric   RecordDecl *R =
45600b57cec5SDimitry Andric       new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
45610b57cec5SDimitry Andric                              SourceLocation(), nullptr, nullptr);
45620b57cec5SDimitry Andric   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
45630b57cec5SDimitry Andric   return R;
45640b57cec5SDimitry Andric }
45650b57cec5SDimitry Andric 
45660b57cec5SDimitry Andric bool RecordDecl::isInjectedClassName() const {
45670b57cec5SDimitry Andric   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
45680b57cec5SDimitry Andric     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
45690b57cec5SDimitry Andric }
45700b57cec5SDimitry Andric 
45710b57cec5SDimitry Andric bool RecordDecl::isLambda() const {
45720b57cec5SDimitry Andric   if (auto RD = dyn_cast<CXXRecordDecl>(this))
45730b57cec5SDimitry Andric     return RD->isLambda();
45740b57cec5SDimitry Andric   return false;
45750b57cec5SDimitry Andric }
45760b57cec5SDimitry Andric 
45770b57cec5SDimitry Andric bool RecordDecl::isCapturedRecord() const {
45780b57cec5SDimitry Andric   return hasAttr<CapturedRecordAttr>();
45790b57cec5SDimitry Andric }
45800b57cec5SDimitry Andric 
45810b57cec5SDimitry Andric void RecordDecl::setCapturedRecord() {
45820b57cec5SDimitry Andric   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
45830b57cec5SDimitry Andric }
45840b57cec5SDimitry Andric 
45855ffd83dbSDimitry Andric bool RecordDecl::isOrContainsUnion() const {
45865ffd83dbSDimitry Andric   if (isUnion())
45875ffd83dbSDimitry Andric     return true;
45885ffd83dbSDimitry Andric 
45895ffd83dbSDimitry Andric   if (const RecordDecl *Def = getDefinition()) {
45905ffd83dbSDimitry Andric     for (const FieldDecl *FD : Def->fields()) {
45915ffd83dbSDimitry Andric       const RecordType *RT = FD->getType()->getAs<RecordType>();
45925ffd83dbSDimitry Andric       if (RT && RT->getDecl()->isOrContainsUnion())
45935ffd83dbSDimitry Andric         return true;
45945ffd83dbSDimitry Andric     }
45955ffd83dbSDimitry Andric   }
45965ffd83dbSDimitry Andric 
45975ffd83dbSDimitry Andric   return false;
45985ffd83dbSDimitry Andric }
45995ffd83dbSDimitry Andric 
46000b57cec5SDimitry Andric RecordDecl::field_iterator RecordDecl::field_begin() const {
46010b57cec5SDimitry Andric   if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
46020b57cec5SDimitry Andric     LoadFieldsFromExternalStorage();
46030b57cec5SDimitry Andric 
46040b57cec5SDimitry Andric   return field_iterator(decl_iterator(FirstDecl));
46050b57cec5SDimitry Andric }
46060b57cec5SDimitry Andric 
46070b57cec5SDimitry Andric /// completeDefinition - Notes that the definition of this type is now
46080b57cec5SDimitry Andric /// complete.
46090b57cec5SDimitry Andric void RecordDecl::completeDefinition() {
46100b57cec5SDimitry Andric   assert(!isCompleteDefinition() && "Cannot redefine record!");
46110b57cec5SDimitry Andric   TagDecl::completeDefinition();
4612fe6060f1SDimitry Andric 
4613fe6060f1SDimitry Andric   ASTContext &Ctx = getASTContext();
4614fe6060f1SDimitry Andric 
4615fe6060f1SDimitry Andric   // Layouts are dumped when computed, so if we are dumping for all complete
4616fe6060f1SDimitry Andric   // types, we need to force usage to get types that wouldn't be used elsewhere.
4617fe6060f1SDimitry Andric   if (Ctx.getLangOpts().DumpRecordLayoutsComplete)
4618fe6060f1SDimitry Andric     (void)Ctx.getASTRecordLayout(this);
46190b57cec5SDimitry Andric }
46200b57cec5SDimitry Andric 
46210b57cec5SDimitry Andric /// isMsStruct - Get whether or not this record uses ms_struct layout.
46220b57cec5SDimitry Andric /// This which can be turned on with an attribute, pragma, or the
46230b57cec5SDimitry Andric /// -mms-bitfields command-line option.
46240b57cec5SDimitry Andric bool RecordDecl::isMsStruct(const ASTContext &C) const {
46250b57cec5SDimitry Andric   return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
46260b57cec5SDimitry Andric }
46270b57cec5SDimitry Andric 
46280b57cec5SDimitry Andric void RecordDecl::LoadFieldsFromExternalStorage() const {
46290b57cec5SDimitry Andric   ExternalASTSource *Source = getASTContext().getExternalSource();
46300b57cec5SDimitry Andric   assert(hasExternalLexicalStorage() && Source && "No external storage?");
46310b57cec5SDimitry Andric 
46320b57cec5SDimitry Andric   // Notify that we have a RecordDecl doing some initialization.
46330b57cec5SDimitry Andric   ExternalASTSource::Deserializing TheFields(Source);
46340b57cec5SDimitry Andric 
46350b57cec5SDimitry Andric   SmallVector<Decl*, 64> Decls;
46360b57cec5SDimitry Andric   setHasLoadedFieldsFromExternalStorage(true);
46370b57cec5SDimitry Andric   Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
46380b57cec5SDimitry Andric     return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
46390b57cec5SDimitry Andric   }, Decls);
46400b57cec5SDimitry Andric 
46410b57cec5SDimitry Andric #ifndef NDEBUG
46420b57cec5SDimitry Andric   // Check that all decls we got were FieldDecls.
46430b57cec5SDimitry Andric   for (unsigned i=0, e=Decls.size(); i != e; ++i)
46440b57cec5SDimitry Andric     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
46450b57cec5SDimitry Andric #endif
46460b57cec5SDimitry Andric 
46470b57cec5SDimitry Andric   if (Decls.empty())
46480b57cec5SDimitry Andric     return;
46490b57cec5SDimitry Andric 
46500b57cec5SDimitry Andric   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
46510b57cec5SDimitry Andric                                                  /*FieldsAlreadyLoaded=*/false);
46520b57cec5SDimitry Andric }
46530b57cec5SDimitry Andric 
46540b57cec5SDimitry Andric bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
46550b57cec5SDimitry Andric   ASTContext &Context = getASTContext();
46560b57cec5SDimitry Andric   const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
46570b57cec5SDimitry Andric       (SanitizerKind::Address | SanitizerKind::KernelAddress);
46580b57cec5SDimitry Andric   if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
46590b57cec5SDimitry Andric     return false;
4660fe6060f1SDimitry Andric   const auto &NoSanitizeList = Context.getNoSanitizeList();
46610b57cec5SDimitry Andric   const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
46620b57cec5SDimitry Andric   // We may be able to relax some of these requirements.
46630b57cec5SDimitry Andric   int ReasonToReject = -1;
46640b57cec5SDimitry Andric   if (!CXXRD || CXXRD->isExternCContext())
46650b57cec5SDimitry Andric     ReasonToReject = 0;  // is not C++.
46660b57cec5SDimitry Andric   else if (CXXRD->hasAttr<PackedAttr>())
46670b57cec5SDimitry Andric     ReasonToReject = 1;  // is packed.
46680b57cec5SDimitry Andric   else if (CXXRD->isUnion())
46690b57cec5SDimitry Andric     ReasonToReject = 2;  // is a union.
46700b57cec5SDimitry Andric   else if (CXXRD->isTriviallyCopyable())
46710b57cec5SDimitry Andric     ReasonToReject = 3;  // is trivially copyable.
46720b57cec5SDimitry Andric   else if (CXXRD->hasTrivialDestructor())
46730b57cec5SDimitry Andric     ReasonToReject = 4;  // has trivial destructor.
46740b57cec5SDimitry Andric   else if (CXXRD->isStandardLayout())
46750b57cec5SDimitry Andric     ReasonToReject = 5;  // is standard layout.
4676fe6060f1SDimitry Andric   else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
46770b57cec5SDimitry Andric                                            "field-padding"))
46785ffd83dbSDimitry Andric     ReasonToReject = 6;  // is in an excluded file.
4679fe6060f1SDimitry Andric   else if (NoSanitizeList.containsType(
4680fe6060f1SDimitry Andric                EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
46815ffd83dbSDimitry Andric     ReasonToReject = 7;  // The type is excluded.
46820b57cec5SDimitry Andric 
46830b57cec5SDimitry Andric   if (EmitRemark) {
46840b57cec5SDimitry Andric     if (ReasonToReject >= 0)
46850b57cec5SDimitry Andric       Context.getDiagnostics().Report(
46860b57cec5SDimitry Andric           getLocation(),
46870b57cec5SDimitry Andric           diag::remark_sanitize_address_insert_extra_padding_rejected)
46880b57cec5SDimitry Andric           << getQualifiedNameAsString() << ReasonToReject;
46890b57cec5SDimitry Andric     else
46900b57cec5SDimitry Andric       Context.getDiagnostics().Report(
46910b57cec5SDimitry Andric           getLocation(),
46920b57cec5SDimitry Andric           diag::remark_sanitize_address_insert_extra_padding_accepted)
46930b57cec5SDimitry Andric           << getQualifiedNameAsString();
46940b57cec5SDimitry Andric   }
46950b57cec5SDimitry Andric   return ReasonToReject < 0;
46960b57cec5SDimitry Andric }
46970b57cec5SDimitry Andric 
46980b57cec5SDimitry Andric const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
46990b57cec5SDimitry Andric   for (const auto *I : fields()) {
47000b57cec5SDimitry Andric     if (I->getIdentifier())
47010b57cec5SDimitry Andric       return I;
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric     if (const auto *RT = I->getType()->getAs<RecordType>())
47040b57cec5SDimitry Andric       if (const FieldDecl *NamedDataMember =
47050b57cec5SDimitry Andric               RT->getDecl()->findFirstNamedDataMember())
47060b57cec5SDimitry Andric         return NamedDataMember;
47070b57cec5SDimitry Andric   }
47080b57cec5SDimitry Andric 
47090b57cec5SDimitry Andric   // We didn't find a named data member.
47100b57cec5SDimitry Andric   return nullptr;
47110b57cec5SDimitry Andric }
47120b57cec5SDimitry Andric 
47130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
47140b57cec5SDimitry Andric // BlockDecl Implementation
47150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
47160b57cec5SDimitry Andric 
47170b57cec5SDimitry Andric BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
47180b57cec5SDimitry Andric     : Decl(Block, DC, CaretLoc), DeclContext(Block) {
47190b57cec5SDimitry Andric   setIsVariadic(false);
47200b57cec5SDimitry Andric   setCapturesCXXThis(false);
47210b57cec5SDimitry Andric   setBlockMissingReturnType(true);
47220b57cec5SDimitry Andric   setIsConversionFromLambda(false);
47230b57cec5SDimitry Andric   setDoesNotEscape(false);
47240b57cec5SDimitry Andric   setCanAvoidCopyToHeap(false);
47250b57cec5SDimitry Andric }
47260b57cec5SDimitry Andric 
47270b57cec5SDimitry Andric void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
47280b57cec5SDimitry Andric   assert(!ParamInfo && "Already has param info!");
47290b57cec5SDimitry Andric 
47300b57cec5SDimitry Andric   // Zero params -> null pointer.
47310b57cec5SDimitry Andric   if (!NewParamInfo.empty()) {
47320b57cec5SDimitry Andric     NumParams = NewParamInfo.size();
47330b57cec5SDimitry Andric     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
47340b57cec5SDimitry Andric     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
47350b57cec5SDimitry Andric   }
47360b57cec5SDimitry Andric }
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
47390b57cec5SDimitry Andric                             bool CapturesCXXThis) {
47400b57cec5SDimitry Andric   this->setCapturesCXXThis(CapturesCXXThis);
47410b57cec5SDimitry Andric   this->NumCaptures = Captures.size();
47420b57cec5SDimitry Andric 
47430b57cec5SDimitry Andric   if (Captures.empty()) {
47440b57cec5SDimitry Andric     this->Captures = nullptr;
47450b57cec5SDimitry Andric     return;
47460b57cec5SDimitry Andric   }
47470b57cec5SDimitry Andric 
47480b57cec5SDimitry Andric   this->Captures = Captures.copy(Context).data();
47490b57cec5SDimitry Andric }
47500b57cec5SDimitry Andric 
47510b57cec5SDimitry Andric bool BlockDecl::capturesVariable(const VarDecl *variable) const {
47520b57cec5SDimitry Andric   for (const auto &I : captures())
47530b57cec5SDimitry Andric     // Only auto vars can be captured, so no redeclaration worries.
47540b57cec5SDimitry Andric     if (I.getVariable() == variable)
47550b57cec5SDimitry Andric       return true;
47560b57cec5SDimitry Andric 
47570b57cec5SDimitry Andric   return false;
47580b57cec5SDimitry Andric }
47590b57cec5SDimitry Andric 
47600b57cec5SDimitry Andric SourceRange BlockDecl::getSourceRange() const {
47610b57cec5SDimitry Andric   return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
47620b57cec5SDimitry Andric }
47630b57cec5SDimitry Andric 
47640b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
47650b57cec5SDimitry Andric // Other Decl Allocation/Deallocation Method Implementations
47660b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
47670b57cec5SDimitry Andric 
47680b57cec5SDimitry Andric void TranslationUnitDecl::anchor() {}
47690b57cec5SDimitry Andric 
47700b57cec5SDimitry Andric TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
47710b57cec5SDimitry Andric   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
47720b57cec5SDimitry Andric }
47730b57cec5SDimitry Andric 
47740b57cec5SDimitry Andric void PragmaCommentDecl::anchor() {}
47750b57cec5SDimitry Andric 
47760b57cec5SDimitry Andric PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
47770b57cec5SDimitry Andric                                              TranslationUnitDecl *DC,
47780b57cec5SDimitry Andric                                              SourceLocation CommentLoc,
47790b57cec5SDimitry Andric                                              PragmaMSCommentKind CommentKind,
47800b57cec5SDimitry Andric                                              StringRef Arg) {
47810b57cec5SDimitry Andric   PragmaCommentDecl *PCD =
47820b57cec5SDimitry Andric       new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
47830b57cec5SDimitry Andric           PragmaCommentDecl(DC, CommentLoc, CommentKind);
47840b57cec5SDimitry Andric   memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
47850b57cec5SDimitry Andric   PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
47860b57cec5SDimitry Andric   return PCD;
47870b57cec5SDimitry Andric }
47880b57cec5SDimitry Andric 
47890b57cec5SDimitry Andric PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
47900b57cec5SDimitry Andric                                                          unsigned ID,
47910b57cec5SDimitry Andric                                                          unsigned ArgSize) {
47920b57cec5SDimitry Andric   return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
47930b57cec5SDimitry Andric       PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
47940b57cec5SDimitry Andric }
47950b57cec5SDimitry Andric 
47960b57cec5SDimitry Andric void PragmaDetectMismatchDecl::anchor() {}
47970b57cec5SDimitry Andric 
47980b57cec5SDimitry Andric PragmaDetectMismatchDecl *
47990b57cec5SDimitry Andric PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
48000b57cec5SDimitry Andric                                  SourceLocation Loc, StringRef Name,
48010b57cec5SDimitry Andric                                  StringRef Value) {
48020b57cec5SDimitry Andric   size_t ValueStart = Name.size() + 1;
48030b57cec5SDimitry Andric   PragmaDetectMismatchDecl *PDMD =
48040b57cec5SDimitry Andric       new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
48050b57cec5SDimitry Andric           PragmaDetectMismatchDecl(DC, Loc, ValueStart);
48060b57cec5SDimitry Andric   memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
48070b57cec5SDimitry Andric   PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
48080b57cec5SDimitry Andric   memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
48090b57cec5SDimitry Andric          Value.size());
48100b57cec5SDimitry Andric   PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
48110b57cec5SDimitry Andric   return PDMD;
48120b57cec5SDimitry Andric }
48130b57cec5SDimitry Andric 
48140b57cec5SDimitry Andric PragmaDetectMismatchDecl *
48150b57cec5SDimitry Andric PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
48160b57cec5SDimitry Andric                                              unsigned NameValueSize) {
48170b57cec5SDimitry Andric   return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
48180b57cec5SDimitry Andric       PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
48190b57cec5SDimitry Andric }
48200b57cec5SDimitry Andric 
48210b57cec5SDimitry Andric void ExternCContextDecl::anchor() {}
48220b57cec5SDimitry Andric 
48230b57cec5SDimitry Andric ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
48240b57cec5SDimitry Andric                                                TranslationUnitDecl *DC) {
48250b57cec5SDimitry Andric   return new (C, DC) ExternCContextDecl(DC);
48260b57cec5SDimitry Andric }
48270b57cec5SDimitry Andric 
48280b57cec5SDimitry Andric void LabelDecl::anchor() {}
48290b57cec5SDimitry Andric 
48300b57cec5SDimitry Andric LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
48310b57cec5SDimitry Andric                              SourceLocation IdentL, IdentifierInfo *II) {
48320b57cec5SDimitry Andric   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
48330b57cec5SDimitry Andric }
48340b57cec5SDimitry Andric 
48350b57cec5SDimitry Andric LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
48360b57cec5SDimitry Andric                              SourceLocation IdentL, IdentifierInfo *II,
48370b57cec5SDimitry Andric                              SourceLocation GnuLabelL) {
48380b57cec5SDimitry Andric   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
48390b57cec5SDimitry Andric   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
48400b57cec5SDimitry Andric }
48410b57cec5SDimitry Andric 
48420b57cec5SDimitry Andric LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
48430b57cec5SDimitry Andric   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
48440b57cec5SDimitry Andric                                SourceLocation());
48450b57cec5SDimitry Andric }
48460b57cec5SDimitry Andric 
48470b57cec5SDimitry Andric void LabelDecl::setMSAsmLabel(StringRef Name) {
48480b57cec5SDimitry Andric char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
48490b57cec5SDimitry Andric   memcpy(Buffer, Name.data(), Name.size());
48500b57cec5SDimitry Andric   Buffer[Name.size()] = '\0';
48510b57cec5SDimitry Andric   MSAsmName = Buffer;
48520b57cec5SDimitry Andric }
48530b57cec5SDimitry Andric 
48540b57cec5SDimitry Andric void ValueDecl::anchor() {}
48550b57cec5SDimitry Andric 
48560b57cec5SDimitry Andric bool ValueDecl::isWeak() const {
4857e8d8bef9SDimitry Andric   auto *MostRecent = getMostRecentDecl();
4858e8d8bef9SDimitry Andric   return MostRecent->hasAttr<WeakAttr>() ||
4859e8d8bef9SDimitry Andric          MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
48600b57cec5SDimitry Andric }
48610b57cec5SDimitry Andric 
48620b57cec5SDimitry Andric void ImplicitParamDecl::anchor() {}
48630b57cec5SDimitry Andric 
48640b57cec5SDimitry Andric ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
48650b57cec5SDimitry Andric                                              SourceLocation IdLoc,
48660b57cec5SDimitry Andric                                              IdentifierInfo *Id, QualType Type,
48670b57cec5SDimitry Andric                                              ImplicitParamKind ParamKind) {
48680b57cec5SDimitry Andric   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
48690b57cec5SDimitry Andric }
48700b57cec5SDimitry Andric 
48710b57cec5SDimitry Andric ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
48720b57cec5SDimitry Andric                                              ImplicitParamKind ParamKind) {
48730b57cec5SDimitry Andric   return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
48740b57cec5SDimitry Andric }
48750b57cec5SDimitry Andric 
48760b57cec5SDimitry Andric ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
48770b57cec5SDimitry Andric                                                          unsigned ID) {
48780b57cec5SDimitry Andric   return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
48790b57cec5SDimitry Andric }
48800b57cec5SDimitry Andric 
4881*349cc55cSDimitry Andric FunctionDecl *
4882*349cc55cSDimitry Andric FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4883*349cc55cSDimitry Andric                      const DeclarationNameInfo &NameInfo, QualType T,
4884*349cc55cSDimitry Andric                      TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
4885*349cc55cSDimitry Andric                      bool isInlineSpecified, bool hasWrittenPrototype,
4886480093f4SDimitry Andric                      ConstexprSpecKind ConstexprKind,
4887480093f4SDimitry Andric                      Expr *TrailingRequiresClause) {
4888*349cc55cSDimitry Andric   FunctionDecl *New = new (C, DC) FunctionDecl(
4889*349cc55cSDimitry Andric       Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
4890*349cc55cSDimitry Andric       isInlineSpecified, ConstexprKind, TrailingRequiresClause);
48910b57cec5SDimitry Andric   New->setHasWrittenPrototype(hasWrittenPrototype);
48920b57cec5SDimitry Andric   return New;
48930b57cec5SDimitry Andric }
48940b57cec5SDimitry Andric 
48950b57cec5SDimitry Andric FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4896e8d8bef9SDimitry Andric   return new (C, ID) FunctionDecl(
4897e8d8bef9SDimitry Andric       Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),
4898*349cc55cSDimitry Andric       nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr);
48990b57cec5SDimitry Andric }
49000b57cec5SDimitry Andric 
49010b57cec5SDimitry Andric BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
49020b57cec5SDimitry Andric   return new (C, DC) BlockDecl(DC, L);
49030b57cec5SDimitry Andric }
49040b57cec5SDimitry Andric 
49050b57cec5SDimitry Andric BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
49060b57cec5SDimitry Andric   return new (C, ID) BlockDecl(nullptr, SourceLocation());
49070b57cec5SDimitry Andric }
49080b57cec5SDimitry Andric 
49090b57cec5SDimitry Andric CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
49100b57cec5SDimitry Andric     : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
49110b57cec5SDimitry Andric       NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
49120b57cec5SDimitry Andric 
49130b57cec5SDimitry Andric CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
49140b57cec5SDimitry Andric                                    unsigned NumParams) {
49150b57cec5SDimitry Andric   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
49160b57cec5SDimitry Andric       CapturedDecl(DC, NumParams);
49170b57cec5SDimitry Andric }
49180b57cec5SDimitry Andric 
49190b57cec5SDimitry Andric CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
49200b57cec5SDimitry Andric                                                unsigned NumParams) {
49210b57cec5SDimitry Andric   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
49220b57cec5SDimitry Andric       CapturedDecl(nullptr, NumParams);
49230b57cec5SDimitry Andric }
49240b57cec5SDimitry Andric 
49250b57cec5SDimitry Andric Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
49260b57cec5SDimitry Andric void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
49270b57cec5SDimitry Andric 
49280b57cec5SDimitry Andric bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
49290b57cec5SDimitry Andric void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
49300b57cec5SDimitry Andric 
49310b57cec5SDimitry Andric EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
49320b57cec5SDimitry Andric                                            SourceLocation L,
49330b57cec5SDimitry Andric                                            IdentifierInfo *Id, QualType T,
49340b57cec5SDimitry Andric                                            Expr *E, const llvm::APSInt &V) {
49350b57cec5SDimitry Andric   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
49360b57cec5SDimitry Andric }
49370b57cec5SDimitry Andric 
49380b57cec5SDimitry Andric EnumConstantDecl *
49390b57cec5SDimitry Andric EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
49400b57cec5SDimitry Andric   return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
49410b57cec5SDimitry Andric                                       QualType(), nullptr, llvm::APSInt());
49420b57cec5SDimitry Andric }
49430b57cec5SDimitry Andric 
49440b57cec5SDimitry Andric void IndirectFieldDecl::anchor() {}
49450b57cec5SDimitry Andric 
49460b57cec5SDimitry Andric IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
49470b57cec5SDimitry Andric                                      SourceLocation L, DeclarationName N,
49480b57cec5SDimitry Andric                                      QualType T,
49490b57cec5SDimitry Andric                                      MutableArrayRef<NamedDecl *> CH)
49500b57cec5SDimitry Andric     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
49510b57cec5SDimitry Andric       ChainingSize(CH.size()) {
49520b57cec5SDimitry Andric   // In C++, indirect field declarations conflict with tag declarations in the
49530b57cec5SDimitry Andric   // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
49540b57cec5SDimitry Andric   if (C.getLangOpts().CPlusPlus)
49550b57cec5SDimitry Andric     IdentifierNamespace |= IDNS_Tag;
49560b57cec5SDimitry Andric }
49570b57cec5SDimitry Andric 
49580b57cec5SDimitry Andric IndirectFieldDecl *
49590b57cec5SDimitry Andric IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
49600b57cec5SDimitry Andric                           IdentifierInfo *Id, QualType T,
49610b57cec5SDimitry Andric                           llvm::MutableArrayRef<NamedDecl *> CH) {
49620b57cec5SDimitry Andric   return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
49630b57cec5SDimitry Andric }
49640b57cec5SDimitry Andric 
49650b57cec5SDimitry Andric IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
49660b57cec5SDimitry Andric                                                          unsigned ID) {
49670b57cec5SDimitry Andric   return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
49680b57cec5SDimitry Andric                                        DeclarationName(), QualType(), None);
49690b57cec5SDimitry Andric }
49700b57cec5SDimitry Andric 
49710b57cec5SDimitry Andric SourceRange EnumConstantDecl::getSourceRange() const {
49720b57cec5SDimitry Andric   SourceLocation End = getLocation();
49730b57cec5SDimitry Andric   if (Init)
49740b57cec5SDimitry Andric     End = Init->getEndLoc();
49750b57cec5SDimitry Andric   return SourceRange(getLocation(), End);
49760b57cec5SDimitry Andric }
49770b57cec5SDimitry Andric 
49780b57cec5SDimitry Andric void TypeDecl::anchor() {}
49790b57cec5SDimitry Andric 
49800b57cec5SDimitry Andric TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
49810b57cec5SDimitry Andric                                  SourceLocation StartLoc, SourceLocation IdLoc,
49820b57cec5SDimitry Andric                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
49830b57cec5SDimitry Andric   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
49840b57cec5SDimitry Andric }
49850b57cec5SDimitry Andric 
49860b57cec5SDimitry Andric void TypedefNameDecl::anchor() {}
49870b57cec5SDimitry Andric 
49880b57cec5SDimitry Andric TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
49890b57cec5SDimitry Andric   if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
49900b57cec5SDimitry Andric     auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
49910b57cec5SDimitry Andric     auto *ThisTypedef = this;
49920b57cec5SDimitry Andric     if (AnyRedecl && OwningTypedef) {
49930b57cec5SDimitry Andric       OwningTypedef = OwningTypedef->getCanonicalDecl();
49940b57cec5SDimitry Andric       ThisTypedef = ThisTypedef->getCanonicalDecl();
49950b57cec5SDimitry Andric     }
49960b57cec5SDimitry Andric     if (OwningTypedef == ThisTypedef)
49970b57cec5SDimitry Andric       return TT->getDecl();
49980b57cec5SDimitry Andric   }
49990b57cec5SDimitry Andric 
50000b57cec5SDimitry Andric   return nullptr;
50010b57cec5SDimitry Andric }
50020b57cec5SDimitry Andric 
50030b57cec5SDimitry Andric bool TypedefNameDecl::isTransparentTagSlow() const {
50040b57cec5SDimitry Andric   auto determineIsTransparent = [&]() {
50050b57cec5SDimitry Andric     if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
50060b57cec5SDimitry Andric       if (auto *TD = TT->getDecl()) {
50070b57cec5SDimitry Andric         if (TD->getName() != getName())
50080b57cec5SDimitry Andric           return false;
50090b57cec5SDimitry Andric         SourceLocation TTLoc = getLocation();
50100b57cec5SDimitry Andric         SourceLocation TDLoc = TD->getLocation();
50110b57cec5SDimitry Andric         if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
50120b57cec5SDimitry Andric           return false;
50130b57cec5SDimitry Andric         SourceManager &SM = getASTContext().getSourceManager();
50140b57cec5SDimitry Andric         return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
50150b57cec5SDimitry Andric       }
50160b57cec5SDimitry Andric     }
50170b57cec5SDimitry Andric     return false;
50180b57cec5SDimitry Andric   };
50190b57cec5SDimitry Andric 
50200b57cec5SDimitry Andric   bool isTransparent = determineIsTransparent();
50210b57cec5SDimitry Andric   MaybeModedTInfo.setInt((isTransparent << 1) | 1);
50220b57cec5SDimitry Andric   return isTransparent;
50230b57cec5SDimitry Andric }
50240b57cec5SDimitry Andric 
50250b57cec5SDimitry Andric TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
50260b57cec5SDimitry Andric   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
50270b57cec5SDimitry Andric                                  nullptr, nullptr);
50280b57cec5SDimitry Andric }
50290b57cec5SDimitry Andric 
50300b57cec5SDimitry Andric TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
50310b57cec5SDimitry Andric                                      SourceLocation StartLoc,
50320b57cec5SDimitry Andric                                      SourceLocation IdLoc, IdentifierInfo *Id,
50330b57cec5SDimitry Andric                                      TypeSourceInfo *TInfo) {
50340b57cec5SDimitry Andric   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
50350b57cec5SDimitry Andric }
50360b57cec5SDimitry Andric 
50370b57cec5SDimitry Andric TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
50380b57cec5SDimitry Andric   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
50390b57cec5SDimitry Andric                                    SourceLocation(), nullptr, nullptr);
50400b57cec5SDimitry Andric }
50410b57cec5SDimitry Andric 
50420b57cec5SDimitry Andric SourceRange TypedefDecl::getSourceRange() const {
50430b57cec5SDimitry Andric   SourceLocation RangeEnd = getLocation();
50440b57cec5SDimitry Andric   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
50450b57cec5SDimitry Andric     if (typeIsPostfix(TInfo->getType()))
50460b57cec5SDimitry Andric       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
50470b57cec5SDimitry Andric   }
50480b57cec5SDimitry Andric   return SourceRange(getBeginLoc(), RangeEnd);
50490b57cec5SDimitry Andric }
50500b57cec5SDimitry Andric 
50510b57cec5SDimitry Andric SourceRange TypeAliasDecl::getSourceRange() const {
50520b57cec5SDimitry Andric   SourceLocation RangeEnd = getBeginLoc();
50530b57cec5SDimitry Andric   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
50540b57cec5SDimitry Andric     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
50550b57cec5SDimitry Andric   return SourceRange(getBeginLoc(), RangeEnd);
50560b57cec5SDimitry Andric }
50570b57cec5SDimitry Andric 
50580b57cec5SDimitry Andric void FileScopeAsmDecl::anchor() {}
50590b57cec5SDimitry Andric 
50600b57cec5SDimitry Andric FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
50610b57cec5SDimitry Andric                                            StringLiteral *Str,
50620b57cec5SDimitry Andric                                            SourceLocation AsmLoc,
50630b57cec5SDimitry Andric                                            SourceLocation RParenLoc) {
50640b57cec5SDimitry Andric   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
50650b57cec5SDimitry Andric }
50660b57cec5SDimitry Andric 
50670b57cec5SDimitry Andric FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
50680b57cec5SDimitry Andric                                                        unsigned ID) {
50690b57cec5SDimitry Andric   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
50700b57cec5SDimitry Andric                                       SourceLocation());
50710b57cec5SDimitry Andric }
50720b57cec5SDimitry Andric 
50730b57cec5SDimitry Andric void EmptyDecl::anchor() {}
50740b57cec5SDimitry Andric 
50750b57cec5SDimitry Andric EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
50760b57cec5SDimitry Andric   return new (C, DC) EmptyDecl(DC, L);
50770b57cec5SDimitry Andric }
50780b57cec5SDimitry Andric 
50790b57cec5SDimitry Andric EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
50800b57cec5SDimitry Andric   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
50810b57cec5SDimitry Andric }
50820b57cec5SDimitry Andric 
50830b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
50840b57cec5SDimitry Andric // ImportDecl Implementation
50850b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
50860b57cec5SDimitry Andric 
50870b57cec5SDimitry Andric /// Retrieve the number of module identifiers needed to name the given
50880b57cec5SDimitry Andric /// module.
50890b57cec5SDimitry Andric static unsigned getNumModuleIdentifiers(Module *Mod) {
50900b57cec5SDimitry Andric   unsigned Result = 1;
50910b57cec5SDimitry Andric   while (Mod->Parent) {
50920b57cec5SDimitry Andric     Mod = Mod->Parent;
50930b57cec5SDimitry Andric     ++Result;
50940b57cec5SDimitry Andric   }
50950b57cec5SDimitry Andric   return Result;
50960b57cec5SDimitry Andric }
50970b57cec5SDimitry Andric 
50980b57cec5SDimitry Andric ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
50990b57cec5SDimitry Andric                        Module *Imported,
51000b57cec5SDimitry Andric                        ArrayRef<SourceLocation> IdentifierLocs)
51015ffd83dbSDimitry Andric     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
51025ffd83dbSDimitry Andric       NextLocalImportAndComplete(nullptr, true) {
51030b57cec5SDimitry Andric   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
51040b57cec5SDimitry Andric   auto *StoredLocs = getTrailingObjects<SourceLocation>();
51050b57cec5SDimitry Andric   std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
51060b57cec5SDimitry Andric                           StoredLocs);
51070b57cec5SDimitry Andric }
51080b57cec5SDimitry Andric 
51090b57cec5SDimitry Andric ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
51100b57cec5SDimitry Andric                        Module *Imported, SourceLocation EndLoc)
51115ffd83dbSDimitry Andric     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
51125ffd83dbSDimitry Andric       NextLocalImportAndComplete(nullptr, false) {
51130b57cec5SDimitry Andric   *getTrailingObjects<SourceLocation>() = EndLoc;
51140b57cec5SDimitry Andric }
51150b57cec5SDimitry Andric 
51160b57cec5SDimitry Andric ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
51170b57cec5SDimitry Andric                                SourceLocation StartLoc, Module *Imported,
51180b57cec5SDimitry Andric                                ArrayRef<SourceLocation> IdentifierLocs) {
51190b57cec5SDimitry Andric   return new (C, DC,
51200b57cec5SDimitry Andric               additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
51210b57cec5SDimitry Andric       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
51220b57cec5SDimitry Andric }
51230b57cec5SDimitry Andric 
51240b57cec5SDimitry Andric ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
51250b57cec5SDimitry Andric                                        SourceLocation StartLoc,
51260b57cec5SDimitry Andric                                        Module *Imported,
51270b57cec5SDimitry Andric                                        SourceLocation EndLoc) {
51280b57cec5SDimitry Andric   ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
51290b57cec5SDimitry Andric       ImportDecl(DC, StartLoc, Imported, EndLoc);
51300b57cec5SDimitry Andric   Import->setImplicit();
51310b57cec5SDimitry Andric   return Import;
51320b57cec5SDimitry Andric }
51330b57cec5SDimitry Andric 
51340b57cec5SDimitry Andric ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
51350b57cec5SDimitry Andric                                            unsigned NumLocations) {
51360b57cec5SDimitry Andric   return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
51370b57cec5SDimitry Andric       ImportDecl(EmptyShell());
51380b57cec5SDimitry Andric }
51390b57cec5SDimitry Andric 
51400b57cec5SDimitry Andric ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
51415ffd83dbSDimitry Andric   if (!isImportComplete())
51420b57cec5SDimitry Andric     return None;
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric   const auto *StoredLocs = getTrailingObjects<SourceLocation>();
51450b57cec5SDimitry Andric   return llvm::makeArrayRef(StoredLocs,
51460b57cec5SDimitry Andric                             getNumModuleIdentifiers(getImportedModule()));
51470b57cec5SDimitry Andric }
51480b57cec5SDimitry Andric 
51490b57cec5SDimitry Andric SourceRange ImportDecl::getSourceRange() const {
51505ffd83dbSDimitry Andric   if (!isImportComplete())
51510b57cec5SDimitry Andric     return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
51520b57cec5SDimitry Andric 
51530b57cec5SDimitry Andric   return SourceRange(getLocation(), getIdentifierLocs().back());
51540b57cec5SDimitry Andric }
51550b57cec5SDimitry Andric 
51560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
51570b57cec5SDimitry Andric // ExportDecl Implementation
51580b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
51590b57cec5SDimitry Andric 
51600b57cec5SDimitry Andric void ExportDecl::anchor() {}
51610b57cec5SDimitry Andric 
51620b57cec5SDimitry Andric ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
51630b57cec5SDimitry Andric                                SourceLocation ExportLoc) {
51640b57cec5SDimitry Andric   return new (C, DC) ExportDecl(DC, ExportLoc);
51650b57cec5SDimitry Andric }
51660b57cec5SDimitry Andric 
51670b57cec5SDimitry Andric ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
51680b57cec5SDimitry Andric   return new (C, ID) ExportDecl(nullptr, SourceLocation());
51690b57cec5SDimitry Andric }
5170