clang API Documentation

Decl.cpp
Go to the documentation of this file.
00001 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Decl subclasses.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/AST/Decl.h"
00015 #include "clang/AST/ASTContext.h"
00016 #include "clang/AST/ASTLambda.h"
00017 #include "clang/AST/ASTMutationListener.h"
00018 #include "clang/AST/Attr.h"
00019 #include "clang/AST/DeclCXX.h"
00020 #include "clang/AST/DeclObjC.h"
00021 #include "clang/AST/DeclTemplate.h"
00022 #include "clang/AST/Expr.h"
00023 #include "clang/AST/ExprCXX.h"
00024 #include "clang/AST/PrettyPrinter.h"
00025 #include "clang/AST/Stmt.h"
00026 #include "clang/AST/TypeLoc.h"
00027 #include "clang/Basic/Builtins.h"
00028 #include "clang/Basic/IdentifierTable.h"
00029 #include "clang/Basic/Module.h"
00030 #include "clang/Basic/Specifiers.h"
00031 #include "clang/Basic/TargetInfo.h"
00032 #include "clang/Frontend/FrontendDiagnostic.h"
00033 #include "llvm/Support/ErrorHandling.h"
00034 #include <algorithm>
00035 
00036 using namespace clang;
00037 
00038 Decl *clang::getPrimaryMergedDecl(Decl *D) {
00039   return D->getASTContext().getPrimaryMergedDecl(D);
00040 }
00041 
00042 // Defined here so that it can be inlined into its direct callers.
00043 bool Decl::isOutOfLine() const {
00044   return !getLexicalDeclContext()->Equals(getDeclContext());
00045 }
00046 
00047 //===----------------------------------------------------------------------===//
00048 // NamedDecl Implementation
00049 //===----------------------------------------------------------------------===//
00050 
00051 // Visibility rules aren't rigorously externally specified, but here
00052 // are the basic principles behind what we implement:
00053 //
00054 // 1. An explicit visibility attribute is generally a direct expression
00055 // of the user's intent and should be honored.  Only the innermost
00056 // visibility attribute applies.  If no visibility attribute applies,
00057 // global visibility settings are considered.
00058 //
00059 // 2. There is one caveat to the above: on or in a template pattern,
00060 // an explicit visibility attribute is just a default rule, and
00061 // visibility can be decreased by the visibility of template
00062 // arguments.  But this, too, has an exception: an attribute on an
00063 // explicit specialization or instantiation causes all the visibility
00064 // restrictions of the template arguments to be ignored.
00065 //
00066 // 3. A variable that does not otherwise have explicit visibility can
00067 // be restricted by the visibility of its type.
00068 //
00069 // 4. A visibility restriction is explicit if it comes from an
00070 // attribute (or something like it), not a global visibility setting.
00071 // When emitting a reference to an external symbol, visibility
00072 // restrictions are ignored unless they are explicit.
00073 //
00074 // 5. When computing the visibility of a non-type, including a
00075 // non-type member of a class, only non-type visibility restrictions
00076 // are considered: the 'visibility' attribute, global value-visibility
00077 // settings, and a few special cases like __private_extern.
00078 //
00079 // 6. When computing the visibility of a type, including a type member
00080 // of a class, only type visibility restrictions are considered:
00081 // the 'type_visibility' attribute and global type-visibility settings.
00082 // However, a 'visibility' attribute counts as a 'type_visibility'
00083 // attribute on any declaration that only has the former.
00084 //
00085 // The visibility of a "secondary" entity, like a template argument,
00086 // is computed using the kind of that entity, not the kind of the
00087 // primary entity for which we are computing visibility.  For example,
00088 // the visibility of a specialization of either of these templates:
00089 //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
00090 //   template <class T, bool (&compare)(T, X)> class matcher;
00091 // is restricted according to the type visibility of the argument 'T',
00092 // the type visibility of 'bool(&)(T,X)', and the value visibility of
00093 // the argument function 'compare'.  That 'has_match' is a value
00094 // and 'matcher' is a type only matters when looking for attributes
00095 // and settings from the immediate context.
00096 
00097 const unsigned IgnoreExplicitVisibilityBit = 2;
00098 const unsigned IgnoreAllVisibilityBit = 4;
00099 
00100 /// Kinds of LV computation.  The linkage side of the computation is
00101 /// always the same, but different things can change how visibility is
00102 /// computed.
00103 enum LVComputationKind {
00104   /// Do an LV computation for, ultimately, a type.
00105   /// Visibility may be restricted by type visibility settings and
00106   /// the visibility of template arguments.
00107   LVForType = NamedDecl::VisibilityForType,
00108 
00109   /// Do an LV computation for, ultimately, a non-type declaration.
00110   /// Visibility may be restricted by value visibility settings and
00111   /// the visibility of template arguments.
00112   LVForValue = NamedDecl::VisibilityForValue,
00113 
00114   /// Do an LV computation for, ultimately, a type that already has
00115   /// some sort of explicit visibility.  Visibility may only be
00116   /// restricted by the visibility of template arguments.
00117   LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
00118 
00119   /// Do an LV computation for, ultimately, a non-type declaration
00120   /// that already has some sort of explicit visibility.  Visibility
00121   /// may only be restricted by the visibility of template arguments.
00122   LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
00123 
00124   /// Do an LV computation when we only care about the linkage.
00125   LVForLinkageOnly =
00126       LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
00127 };
00128 
00129 /// Does this computation kind permit us to consider additional
00130 /// visibility settings from attributes and the like?
00131 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
00132   return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
00133 }
00134 
00135 /// Given an LVComputationKind, return one of the same type/value sort
00136 /// that records that it already has explicit visibility.
00137 static LVComputationKind
00138 withExplicitVisibilityAlready(LVComputationKind oldKind) {
00139   LVComputationKind newKind =
00140     static_cast<LVComputationKind>(unsigned(oldKind) |
00141                                    IgnoreExplicitVisibilityBit);
00142   assert(oldKind != LVForType          || newKind == LVForExplicitType);
00143   assert(oldKind != LVForValue         || newKind == LVForExplicitValue);
00144   assert(oldKind != LVForExplicitType  || newKind == LVForExplicitType);
00145   assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
00146   return newKind;
00147 }
00148 
00149 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
00150                                                   LVComputationKind kind) {
00151   assert(!hasExplicitVisibilityAlready(kind) &&
00152          "asking for explicit visibility when we shouldn't be");
00153   return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
00154 }
00155 
00156 /// Is the given declaration a "type" or a "value" for the purposes of
00157 /// visibility computation?
00158 static bool usesTypeVisibility(const NamedDecl *D) {
00159   return isa<TypeDecl>(D) ||
00160          isa<ClassTemplateDecl>(D) ||
00161          isa<ObjCInterfaceDecl>(D);
00162 }
00163 
00164 /// Does the given declaration have member specialization information,
00165 /// and if so, is it an explicit specialization?
00166 template <class T> static typename
00167 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
00168 isExplicitMemberSpecialization(const T *D) {
00169   if (const MemberSpecializationInfo *member =
00170         D->getMemberSpecializationInfo()) {
00171     return member->isExplicitSpecialization();
00172   }
00173   return false;
00174 }
00175 
00176 /// For templates, this question is easier: a member template can't be
00177 /// explicitly instantiated, so there's a single bit indicating whether
00178 /// or not this is an explicit member specialization.
00179 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
00180   return D->isMemberSpecialization();
00181 }
00182 
00183 /// Given a visibility attribute, return the explicit visibility
00184 /// associated with it.
00185 template <class T>
00186 static Visibility getVisibilityFromAttr(const T *attr) {
00187   switch (attr->getVisibility()) {
00188   case T::Default:
00189     return DefaultVisibility;
00190   case T::Hidden:
00191     return HiddenVisibility;
00192   case T::Protected:
00193     return ProtectedVisibility;
00194   }
00195   llvm_unreachable("bad visibility kind");
00196 }
00197 
00198 /// Return the explicit visibility of the given declaration.
00199 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
00200                                     NamedDecl::ExplicitVisibilityKind kind) {
00201   // If we're ultimately computing the visibility of a type, look for
00202   // a 'type_visibility' attribute before looking for 'visibility'.
00203   if (kind == NamedDecl::VisibilityForType) {
00204     if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
00205       return getVisibilityFromAttr(A);
00206     }
00207   }
00208 
00209   // If this declaration has an explicit visibility attribute, use it.
00210   if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
00211     return getVisibilityFromAttr(A);
00212   }
00213 
00214   // If we're on Mac OS X, an 'availability' for Mac OS X attribute
00215   // implies visibility(default).
00216   if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
00217     for (const auto *A : D->specific_attrs<AvailabilityAttr>())
00218       if (A->getPlatform()->getName().equals("macosx"))
00219         return DefaultVisibility;
00220   }
00221 
00222   return None;
00223 }
00224 
00225 static LinkageInfo
00226 getLVForType(const Type &T, LVComputationKind computation) {
00227   if (computation == LVForLinkageOnly)
00228     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
00229   return T.getLinkageAndVisibility();
00230 }
00231 
00232 /// \brief Get the most restrictive linkage for the types in the given
00233 /// template parameter list.  For visibility purposes, template
00234 /// parameters are part of the signature of a template.
00235 static LinkageInfo
00236 getLVForTemplateParameterList(const TemplateParameterList *Params,
00237                               LVComputationKind computation) {
00238   LinkageInfo LV;
00239   for (const NamedDecl *P : *Params) {
00240     // Template type parameters are the most common and never
00241     // contribute to visibility, pack or not.
00242     if (isa<TemplateTypeParmDecl>(P))
00243       continue;
00244 
00245     // Non-type template parameters can be restricted by the value type, e.g.
00246     //   template <enum X> class A { ... };
00247     // We have to be careful here, though, because we can be dealing with
00248     // dependent types.
00249     if (const NonTypeTemplateParmDecl *NTTP =
00250             dyn_cast<NonTypeTemplateParmDecl>(P)) {
00251       // Handle the non-pack case first.
00252       if (!NTTP->isExpandedParameterPack()) {
00253         if (!NTTP->getType()->isDependentType()) {
00254           LV.merge(getLVForType(*NTTP->getType(), computation));
00255         }
00256         continue;
00257       }
00258 
00259       // Look at all the types in an expanded pack.
00260       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
00261         QualType type = NTTP->getExpansionType(i);
00262         if (!type->isDependentType())
00263           LV.merge(type->getLinkageAndVisibility());
00264       }
00265       continue;
00266     }
00267 
00268     // Template template parameters can be restricted by their
00269     // template parameters, recursively.
00270     const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
00271 
00272     // Handle the non-pack case first.
00273     if (!TTP->isExpandedParameterPack()) {
00274       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
00275                                              computation));
00276       continue;
00277     }
00278 
00279     // Look at all expansions in an expanded pack.
00280     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
00281            i != n; ++i) {
00282       LV.merge(getLVForTemplateParameterList(
00283           TTP->getExpansionTemplateParameters(i), computation));
00284     }
00285   }
00286 
00287   return LV;
00288 }
00289 
00290 /// getLVForDecl - Get the linkage and visibility for the given declaration.
00291 static LinkageInfo getLVForDecl(const NamedDecl *D,
00292                                 LVComputationKind computation);
00293 
00294 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
00295   const Decl *Ret = nullptr;
00296   const DeclContext *DC = D->getDeclContext();
00297   while (DC->getDeclKind() != Decl::TranslationUnit) {
00298     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
00299       Ret = cast<Decl>(DC);
00300     DC = DC->getParent();
00301   }
00302   return Ret;
00303 }
00304 
00305 /// \brief Get the most restrictive linkage for the types and
00306 /// declarations in the given template argument list.
00307 ///
00308 /// Note that we don't take an LVComputationKind because we always
00309 /// want to honor the visibility of template arguments in the same way.
00310 static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
00311                                                 LVComputationKind computation) {
00312   LinkageInfo LV;
00313 
00314   for (const TemplateArgument &Arg : Args) {
00315     switch (Arg.getKind()) {
00316     case TemplateArgument::Null:
00317     case TemplateArgument::Integral:
00318     case TemplateArgument::Expression:
00319       continue;
00320 
00321     case TemplateArgument::Type:
00322       LV.merge(getLVForType(*Arg.getAsType(), computation));
00323       continue;
00324 
00325     case TemplateArgument::Declaration:
00326       if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
00327         assert(!usesTypeVisibility(ND));
00328         LV.merge(getLVForDecl(ND, computation));
00329       }
00330       continue;
00331 
00332     case TemplateArgument::NullPtr:
00333       LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
00334       continue;
00335 
00336     case TemplateArgument::Template:
00337     case TemplateArgument::TemplateExpansion:
00338       if (TemplateDecl *Template =
00339               Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
00340         LV.merge(getLVForDecl(Template, computation));
00341       continue;
00342 
00343     case TemplateArgument::Pack:
00344       LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
00345       continue;
00346     }
00347     llvm_unreachable("bad template argument kind");
00348   }
00349 
00350   return LV;
00351 }
00352 
00353 static LinkageInfo
00354 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
00355                              LVComputationKind computation) {
00356   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
00357 }
00358 
00359 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
00360                         const FunctionTemplateSpecializationInfo *specInfo) {
00361   // Include visibility from the template parameters and arguments
00362   // only if this is not an explicit instantiation or specialization
00363   // with direct explicit visibility.  (Implicit instantiations won't
00364   // have a direct attribute.)
00365   if (!specInfo->isExplicitInstantiationOrSpecialization())
00366     return true;
00367 
00368   return !fn->hasAttr<VisibilityAttr>();
00369 }
00370 
00371 /// Merge in template-related linkage and visibility for the given
00372 /// function template specialization.
00373 ///
00374 /// We don't need a computation kind here because we can assume
00375 /// LVForValue.
00376 ///
00377 /// \param[out] LV the computation to use for the parent
00378 static void
00379 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
00380                 const FunctionTemplateSpecializationInfo *specInfo,
00381                 LVComputationKind computation) {
00382   bool considerVisibility =
00383     shouldConsiderTemplateVisibility(fn, specInfo);
00384 
00385   // Merge information from the template parameters.
00386   FunctionTemplateDecl *temp = specInfo->getTemplate();
00387   LinkageInfo tempLV =
00388     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
00389   LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
00390 
00391   // Merge information from the template arguments.
00392   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
00393   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
00394   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
00395 }
00396 
00397 /// Does the given declaration have a direct visibility attribute
00398 /// that would match the given rules?
00399 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
00400                                          LVComputationKind computation) {
00401   switch (computation) {
00402   case LVForType:
00403   case LVForExplicitType:
00404     if (D->hasAttr<TypeVisibilityAttr>())
00405       return true;
00406     // fallthrough
00407   case LVForValue:
00408   case LVForExplicitValue:
00409     if (D->hasAttr<VisibilityAttr>())
00410       return true;
00411     return false;
00412   case LVForLinkageOnly:
00413     return false;
00414   }
00415   llvm_unreachable("bad visibility computation kind");
00416 }
00417 
00418 /// Should we consider visibility associated with the template
00419 /// arguments and parameters of the given class template specialization?
00420 static bool shouldConsiderTemplateVisibility(
00421                                  const ClassTemplateSpecializationDecl *spec,
00422                                  LVComputationKind computation) {
00423   // Include visibility from the template parameters and arguments
00424   // only if this is not an explicit instantiation or specialization
00425   // with direct explicit visibility (and note that implicit
00426   // instantiations won't have a direct attribute).
00427   //
00428   // Furthermore, we want to ignore template parameters and arguments
00429   // for an explicit specialization when computing the visibility of a
00430   // member thereof with explicit visibility.
00431   //
00432   // This is a bit complex; let's unpack it.
00433   //
00434   // An explicit class specialization is an independent, top-level
00435   // declaration.  As such, if it or any of its members has an
00436   // explicit visibility attribute, that must directly express the
00437   // user's intent, and we should honor it.  The same logic applies to
00438   // an explicit instantiation of a member of such a thing.
00439 
00440   // Fast path: if this is not an explicit instantiation or
00441   // specialization, we always want to consider template-related
00442   // visibility restrictions.
00443   if (!spec->isExplicitInstantiationOrSpecialization())
00444     return true;
00445 
00446   // This is the 'member thereof' check.
00447   if (spec->isExplicitSpecialization() &&
00448       hasExplicitVisibilityAlready(computation))
00449     return false;
00450 
00451   return !hasDirectVisibilityAttribute(spec, computation);
00452 }
00453 
00454 /// Merge in template-related linkage and visibility for the given
00455 /// class template specialization.
00456 static void mergeTemplateLV(LinkageInfo &LV,
00457                             const ClassTemplateSpecializationDecl *spec,
00458                             LVComputationKind computation) {
00459   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
00460 
00461   // Merge information from the template parameters, but ignore
00462   // visibility if we're only considering template arguments.
00463 
00464   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
00465   LinkageInfo tempLV =
00466     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
00467   LV.mergeMaybeWithVisibility(tempLV,
00468            considerVisibility && !hasExplicitVisibilityAlready(computation));
00469 
00470   // Merge information from the template arguments.  We ignore
00471   // template-argument visibility if we've got an explicit
00472   // instantiation with a visibility attribute.
00473   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
00474   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
00475   if (considerVisibility)
00476     LV.mergeVisibility(argsLV);
00477   LV.mergeExternalVisibility(argsLV);
00478 }
00479 
00480 /// Should we consider visibility associated with the template
00481 /// arguments and parameters of the given variable template
00482 /// specialization? As usual, follow class template specialization
00483 /// logic up to initialization.
00484 static bool shouldConsiderTemplateVisibility(
00485                                  const VarTemplateSpecializationDecl *spec,
00486                                  LVComputationKind computation) {
00487   // Include visibility from the template parameters and arguments
00488   // only if this is not an explicit instantiation or specialization
00489   // with direct explicit visibility (and note that implicit
00490   // instantiations won't have a direct attribute).
00491   if (!spec->isExplicitInstantiationOrSpecialization())
00492     return true;
00493 
00494   // An explicit variable specialization is an independent, top-level
00495   // declaration.  As such, if it has an explicit visibility attribute,
00496   // that must directly express the user's intent, and we should honor
00497   // it.
00498   if (spec->isExplicitSpecialization() &&
00499       hasExplicitVisibilityAlready(computation))
00500     return false;
00501 
00502   return !hasDirectVisibilityAttribute(spec, computation);
00503 }
00504 
00505 /// Merge in template-related linkage and visibility for the given
00506 /// variable template specialization. As usual, follow class template
00507 /// specialization logic up to initialization.
00508 static void mergeTemplateLV(LinkageInfo &LV,
00509                             const VarTemplateSpecializationDecl *spec,
00510                             LVComputationKind computation) {
00511   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
00512 
00513   // Merge information from the template parameters, but ignore
00514   // visibility if we're only considering template arguments.
00515 
00516   VarTemplateDecl *temp = spec->getSpecializedTemplate();
00517   LinkageInfo tempLV =
00518     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
00519   LV.mergeMaybeWithVisibility(tempLV,
00520            considerVisibility && !hasExplicitVisibilityAlready(computation));
00521 
00522   // Merge information from the template arguments.  We ignore
00523   // template-argument visibility if we've got an explicit
00524   // instantiation with a visibility attribute.
00525   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
00526   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
00527   if (considerVisibility)
00528     LV.mergeVisibility(argsLV);
00529   LV.mergeExternalVisibility(argsLV);
00530 }
00531 
00532 static bool useInlineVisibilityHidden(const NamedDecl *D) {
00533   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
00534   const LangOptions &Opts = D->getASTContext().getLangOpts();
00535   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
00536     return false;
00537 
00538   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
00539   if (!FD)
00540     return false;
00541 
00542   TemplateSpecializationKind TSK = TSK_Undeclared;
00543   if (FunctionTemplateSpecializationInfo *spec
00544       = FD->getTemplateSpecializationInfo()) {
00545     TSK = spec->getTemplateSpecializationKind();
00546   } else if (MemberSpecializationInfo *MSI =
00547              FD->getMemberSpecializationInfo()) {
00548     TSK = MSI->getTemplateSpecializationKind();
00549   }
00550 
00551   const FunctionDecl *Def = nullptr;
00552   // InlineVisibilityHidden only applies to definitions, and
00553   // isInlined() only gives meaningful answers on definitions
00554   // anyway.
00555   return TSK != TSK_ExplicitInstantiationDeclaration &&
00556     TSK != TSK_ExplicitInstantiationDefinition &&
00557     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
00558 }
00559 
00560 template <typename T> static bool isFirstInExternCContext(T *D) {
00561   const T *First = D->getFirstDecl();
00562   return First->isInExternCContext();
00563 }
00564 
00565 static bool isSingleLineLanguageLinkage(const Decl &D) {
00566   if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
00567     if (!SD->hasBraces())
00568       return true;
00569   return false;
00570 }
00571 
00572 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
00573                                               LVComputationKind computation) {
00574   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
00575          "Not a name having namespace scope");
00576   ASTContext &Context = D->getASTContext();
00577 
00578   // C++ [basic.link]p3:
00579   //   A name having namespace scope (3.3.6) has internal linkage if it
00580   //   is the name of
00581   //     - an object, reference, function or function template that is
00582   //       explicitly declared static; or,
00583   // (This bullet corresponds to C99 6.2.2p3.)
00584   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
00585     // Explicitly declared static.
00586     if (Var->getStorageClass() == SC_Static)
00587       return LinkageInfo::internal();
00588 
00589     // - a non-volatile object or reference that is explicitly declared const
00590     //   or constexpr and neither explicitly declared extern nor previously
00591     //   declared to have external linkage; or (there is no equivalent in C99)
00592     if (Context.getLangOpts().CPlusPlus &&
00593         Var->getType().isConstQualified() && 
00594         !Var->getType().isVolatileQualified()) {
00595       const VarDecl *PrevVar = Var->getPreviousDecl();
00596       if (PrevVar)
00597         return getLVForDecl(PrevVar, computation);
00598 
00599       if (Var->getStorageClass() != SC_Extern &&
00600           Var->getStorageClass() != SC_PrivateExtern &&
00601           !isSingleLineLanguageLinkage(*Var))
00602         return LinkageInfo::internal();
00603     }
00604 
00605     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
00606          PrevVar = PrevVar->getPreviousDecl()) {
00607       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
00608           Var->getStorageClass() == SC_None)
00609         return PrevVar->getLinkageAndVisibility();
00610       // Explicitly declared static.
00611       if (PrevVar->getStorageClass() == SC_Static)
00612         return LinkageInfo::internal();
00613     }
00614   } else if (const FunctionDecl *Function = D->getAsFunction()) {
00615     // C++ [temp]p4:
00616     //   A non-member function template can have internal linkage; any
00617     //   other template name shall have external linkage.
00618 
00619     // Explicitly declared static.
00620     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
00621       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
00622   }
00623   //   - a data member of an anonymous union.
00624   assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
00625   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
00626 
00627   if (D->isInAnonymousNamespace()) {
00628     const VarDecl *Var = dyn_cast<VarDecl>(D);
00629     const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
00630     if ((!Var || !isFirstInExternCContext(Var)) &&
00631         (!Func || !isFirstInExternCContext(Func)))
00632       return LinkageInfo::uniqueExternal();
00633   }
00634 
00635   // Set up the defaults.
00636 
00637   // C99 6.2.2p5:
00638   //   If the declaration of an identifier for an object has file
00639   //   scope and no storage-class specifier, its linkage is
00640   //   external.
00641   LinkageInfo LV;
00642 
00643   if (!hasExplicitVisibilityAlready(computation)) {
00644     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
00645       LV.mergeVisibility(*Vis, true);
00646     } else {
00647       // If we're declared in a namespace with a visibility attribute,
00648       // use that namespace's visibility, and it still counts as explicit.
00649       for (const DeclContext *DC = D->getDeclContext();
00650            !isa<TranslationUnitDecl>(DC);
00651            DC = DC->getParent()) {
00652         const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
00653         if (!ND) continue;
00654         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
00655           LV.mergeVisibility(*Vis, true);
00656           break;
00657         }
00658       }
00659     }
00660 
00661     // Add in global settings if the above didn't give us direct visibility.
00662     if (!LV.isVisibilityExplicit()) {
00663       // Use global type/value visibility as appropriate.
00664       Visibility globalVisibility;
00665       if (computation == LVForValue) {
00666         globalVisibility = Context.getLangOpts().getValueVisibilityMode();
00667       } else {
00668         assert(computation == LVForType);
00669         globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
00670       }
00671       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
00672 
00673       // If we're paying attention to global visibility, apply
00674       // -finline-visibility-hidden if this is an inline method.
00675       if (useInlineVisibilityHidden(D))
00676         LV.mergeVisibility(HiddenVisibility, true);
00677     }
00678   }
00679 
00680   // C++ [basic.link]p4:
00681 
00682   //   A name having namespace scope has external linkage if it is the
00683   //   name of
00684   //
00685   //     - an object or reference, unless it has internal linkage; or
00686   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
00687     // GCC applies the following optimization to variables and static
00688     // data members, but not to functions:
00689     //
00690     // Modify the variable's LV by the LV of its type unless this is
00691     // C or extern "C".  This follows from [basic.link]p9:
00692     //   A type without linkage shall not be used as the type of a
00693     //   variable or function with external linkage unless
00694     //    - the entity has C language linkage, or
00695     //    - the entity is declared within an unnamed namespace, or
00696     //    - the entity is not used or is defined in the same
00697     //      translation unit.
00698     // and [basic.link]p10:
00699     //   ...the types specified by all declarations referring to a
00700     //   given variable or function shall be identical...
00701     // C does not have an equivalent rule.
00702     //
00703     // Ignore this if we've got an explicit attribute;  the user
00704     // probably knows what they're doing.
00705     //
00706     // Note that we don't want to make the variable non-external
00707     // because of this, but unique-external linkage suits us.
00708     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
00709       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
00710       if (TypeLV.getLinkage() != ExternalLinkage)
00711         return LinkageInfo::uniqueExternal();
00712       if (!LV.isVisibilityExplicit())
00713         LV.mergeVisibility(TypeLV);
00714     }
00715 
00716     if (Var->getStorageClass() == SC_PrivateExtern)
00717       LV.mergeVisibility(HiddenVisibility, true);
00718 
00719     // Note that Sema::MergeVarDecl already takes care of implementing
00720     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
00721     // to do it here.
00722 
00723     // As per function and class template specializations (below),
00724     // consider LV for the template and template arguments.  We're at file
00725     // scope, so we do not need to worry about nested specializations.
00726     if (const VarTemplateSpecializationDecl *spec
00727               = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
00728       mergeTemplateLV(LV, spec, computation);
00729     }
00730 
00731   //     - a function, unless it has internal linkage; or
00732   } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
00733     // In theory, we can modify the function's LV by the LV of its
00734     // type unless it has C linkage (see comment above about variables
00735     // for justification).  In practice, GCC doesn't do this, so it's
00736     // just too painful to make work.
00737 
00738     if (Function->getStorageClass() == SC_PrivateExtern)
00739       LV.mergeVisibility(HiddenVisibility, true);
00740 
00741     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
00742     // merging storage classes and visibility attributes, so we don't have to
00743     // look at previous decls in here.
00744 
00745     // In C++, then if the type of the function uses a type with
00746     // unique-external linkage, it's not legally usable from outside
00747     // this translation unit.  However, we should use the C linkage
00748     // rules instead for extern "C" declarations.
00749     if (Context.getLangOpts().CPlusPlus &&
00750         !Function->isInExternCContext()) {
00751       // Only look at the type-as-written. If this function has an auto-deduced
00752       // return type, we can't compute the linkage of that type because it could
00753       // require looking at the linkage of this function, and we don't need this
00754       // for correctness because the type is not part of the function's
00755       // signature.
00756       // FIXME: This is a hack. We should be able to solve this circularity and 
00757       // the one in getLVForClassMember for Functions some other way.
00758       QualType TypeAsWritten = Function->getType();
00759       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
00760         TypeAsWritten = TSI->getType();
00761       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
00762         return LinkageInfo::uniqueExternal();
00763     }
00764 
00765     // Consider LV from the template and the template arguments.
00766     // We're at file scope, so we do not need to worry about nested
00767     // specializations.
00768     if (FunctionTemplateSpecializationInfo *specInfo
00769                                = Function->getTemplateSpecializationInfo()) {
00770       mergeTemplateLV(LV, Function, specInfo, computation);
00771     }
00772 
00773   //     - a named class (Clause 9), or an unnamed class defined in a
00774   //       typedef declaration in which the class has the typedef name
00775   //       for linkage purposes (7.1.3); or
00776   //     - a named enumeration (7.2), or an unnamed enumeration
00777   //       defined in a typedef declaration in which the enumeration
00778   //       has the typedef name for linkage purposes (7.1.3); or
00779   } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
00780     // Unnamed tags have no linkage.
00781     if (!Tag->hasNameForLinkage())
00782       return LinkageInfo::none();
00783 
00784     // If this is a class template specialization, consider the
00785     // linkage of the template and template arguments.  We're at file
00786     // scope, so we do not need to worry about nested specializations.
00787     if (const ClassTemplateSpecializationDecl *spec
00788           = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
00789       mergeTemplateLV(LV, spec, computation);
00790     }
00791 
00792   //     - an enumerator belonging to an enumeration with external linkage;
00793   } else if (isa<EnumConstantDecl>(D)) {
00794     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
00795                                       computation);
00796     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
00797       return LinkageInfo::none();
00798     LV.merge(EnumLV);
00799 
00800   //     - a template, unless it is a function template that has
00801   //       internal linkage (Clause 14);
00802   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
00803     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
00804     LinkageInfo tempLV =
00805       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
00806     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
00807 
00808   //     - a namespace (7.3), unless it is declared within an unnamed
00809   //       namespace.
00810   } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
00811     return LV;
00812 
00813   // By extension, we assign external linkage to Objective-C
00814   // interfaces.
00815   } else if (isa<ObjCInterfaceDecl>(D)) {
00816     // fallout
00817 
00818   // Everything not covered here has no linkage.
00819   } else {
00820     // FIXME: A typedef declaration has linkage if it gives a type a name for
00821     // linkage purposes.
00822     return LinkageInfo::none();
00823   }
00824 
00825   // If we ended up with non-external linkage, visibility should
00826   // always be default.
00827   if (LV.getLinkage() != ExternalLinkage)
00828     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
00829 
00830   return LV;
00831 }
00832 
00833 static LinkageInfo getLVForClassMember(const NamedDecl *D,
00834                                        LVComputationKind computation) {
00835   // Only certain class members have linkage.  Note that fields don't
00836   // really have linkage, but it's convenient to say they do for the
00837   // purposes of calculating linkage of pointer-to-data-member
00838   // template arguments.
00839   //
00840   // Templates also don't officially have linkage, but since we ignore
00841   // the C++ standard and look at template arguments when determining
00842   // linkage and visibility of a template specialization, we might hit
00843   // a template template argument that way. If we do, we need to
00844   // consider its linkage.
00845   if (!(isa<CXXMethodDecl>(D) ||
00846         isa<VarDecl>(D) ||
00847         isa<FieldDecl>(D) ||
00848         isa<IndirectFieldDecl>(D) ||
00849         isa<TagDecl>(D) ||
00850         isa<TemplateDecl>(D)))
00851     return LinkageInfo::none();
00852 
00853   LinkageInfo LV;
00854 
00855   // If we have an explicit visibility attribute, merge that in.
00856   if (!hasExplicitVisibilityAlready(computation)) {
00857     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
00858       LV.mergeVisibility(*Vis, true);
00859     // If we're paying attention to global visibility, apply
00860     // -finline-visibility-hidden if this is an inline method.
00861     //
00862     // Note that we do this before merging information about
00863     // the class visibility.
00864     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
00865       LV.mergeVisibility(HiddenVisibility, true);
00866   }
00867 
00868   // If this class member has an explicit visibility attribute, the only
00869   // thing that can change its visibility is the template arguments, so
00870   // only look for them when processing the class.
00871   LVComputationKind classComputation = computation;
00872   if (LV.isVisibilityExplicit())
00873     classComputation = withExplicitVisibilityAlready(computation);
00874 
00875   LinkageInfo classLV =
00876     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
00877   // If the class already has unique-external linkage, we can't improve.
00878   if (classLV.getLinkage() == UniqueExternalLinkage)
00879     return LinkageInfo::uniqueExternal();
00880 
00881   if (!isExternallyVisible(classLV.getLinkage()))
00882     return LinkageInfo::none();
00883 
00884 
00885   // Otherwise, don't merge in classLV yet, because in certain cases
00886   // we need to completely ignore the visibility from it.
00887 
00888   // Specifically, if this decl exists and has an explicit attribute.
00889   const NamedDecl *explicitSpecSuppressor = nullptr;
00890 
00891   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
00892     // If the type of the function uses a type with unique-external
00893     // linkage, it's not legally usable from outside this translation unit.
00894     // But only look at the type-as-written. If this function has an auto-deduced
00895     // return type, we can't compute the linkage of that type because it could
00896     // require looking at the linkage of this function, and we don't need this
00897     // for correctness because the type is not part of the function's
00898     // signature.
00899     // FIXME: This is a hack. We should be able to solve this circularity and the
00900     // one in getLVForNamespaceScopeDecl for Functions some other way.
00901     {
00902       QualType TypeAsWritten = MD->getType();
00903       if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
00904         TypeAsWritten = TSI->getType();
00905       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
00906         return LinkageInfo::uniqueExternal();
00907     }
00908     // If this is a method template specialization, use the linkage for
00909     // the template parameters and arguments.
00910     if (FunctionTemplateSpecializationInfo *spec
00911            = MD->getTemplateSpecializationInfo()) {
00912       mergeTemplateLV(LV, MD, spec, computation);
00913       if (spec->isExplicitSpecialization()) {
00914         explicitSpecSuppressor = MD;
00915       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
00916         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
00917       }
00918     } else if (isExplicitMemberSpecialization(MD)) {
00919       explicitSpecSuppressor = MD;
00920     }
00921 
00922   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
00923     if (const ClassTemplateSpecializationDecl *spec
00924         = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
00925       mergeTemplateLV(LV, spec, computation);
00926       if (spec->isExplicitSpecialization()) {
00927         explicitSpecSuppressor = spec;
00928       } else {
00929         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
00930         if (isExplicitMemberSpecialization(temp)) {
00931           explicitSpecSuppressor = temp->getTemplatedDecl();
00932         }
00933       }
00934     } else if (isExplicitMemberSpecialization(RD)) {
00935       explicitSpecSuppressor = RD;
00936     }
00937 
00938   // Static data members.
00939   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
00940     if (const VarTemplateSpecializationDecl *spec
00941         = dyn_cast<VarTemplateSpecializationDecl>(VD))
00942       mergeTemplateLV(LV, spec, computation);
00943 
00944     // Modify the variable's linkage by its type, but ignore the
00945     // type's visibility unless it's a definition.
00946     LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
00947     if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
00948       LV.mergeVisibility(typeLV);
00949     LV.mergeExternalVisibility(typeLV);
00950 
00951     if (isExplicitMemberSpecialization(VD)) {
00952       explicitSpecSuppressor = VD;
00953     }
00954 
00955   // Template members.
00956   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
00957     bool considerVisibility =
00958       (!LV.isVisibilityExplicit() &&
00959        !classLV.isVisibilityExplicit() &&
00960        !hasExplicitVisibilityAlready(computation));
00961     LinkageInfo tempLV =
00962       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
00963     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
00964 
00965     if (const RedeclarableTemplateDecl *redeclTemp =
00966           dyn_cast<RedeclarableTemplateDecl>(temp)) {
00967       if (isExplicitMemberSpecialization(redeclTemp)) {
00968         explicitSpecSuppressor = temp->getTemplatedDecl();
00969       }
00970     }
00971   }
00972 
00973   // We should never be looking for an attribute directly on a template.
00974   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
00975 
00976   // If this member is an explicit member specialization, and it has
00977   // an explicit attribute, ignore visibility from the parent.
00978   bool considerClassVisibility = true;
00979   if (explicitSpecSuppressor &&
00980       // optimization: hasDVA() is true only with explicit visibility.
00981       LV.isVisibilityExplicit() &&
00982       classLV.getVisibility() != DefaultVisibility &&
00983       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
00984     considerClassVisibility = false;
00985   }
00986 
00987   // Finally, merge in information from the class.
00988   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
00989   return LV;
00990 }
00991 
00992 void NamedDecl::anchor() { }
00993 
00994 static LinkageInfo computeLVForDecl(const NamedDecl *D,
00995                                     LVComputationKind computation);
00996 
00997 bool NamedDecl::isLinkageValid() const {
00998   if (!hasCachedLinkage())
00999     return true;
01000 
01001   return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
01002          getCachedLinkage();
01003 }
01004 
01005 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
01006   StringRef name = getName();
01007   if (name.empty()) return SFF_None;
01008   
01009   if (name.front() == 'C')
01010     if (name == "CFStringCreateWithFormat" ||
01011         name == "CFStringCreateWithFormatAndArguments" ||
01012         name == "CFStringAppendFormat" ||
01013         name == "CFStringAppendFormatAndArguments")
01014       return SFF_CFString;
01015   return SFF_None;
01016 }
01017 
01018 Linkage NamedDecl::getLinkageInternal() const {
01019   // We don't care about visibility here, so ask for the cheapest
01020   // possible visibility analysis.
01021   return getLVForDecl(this, LVForLinkageOnly).getLinkage();
01022 }
01023 
01024 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
01025   LVComputationKind computation =
01026     (usesTypeVisibility(this) ? LVForType : LVForValue);
01027   return getLVForDecl(this, computation);
01028 }
01029 
01030 static Optional<Visibility>
01031 getExplicitVisibilityAux(const NamedDecl *ND,
01032                          NamedDecl::ExplicitVisibilityKind kind,
01033                          bool IsMostRecent) {
01034   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
01035 
01036   // Check the declaration itself first.
01037   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
01038     return V;
01039 
01040   // If this is a member class of a specialization of a class template
01041   // and the corresponding decl has explicit visibility, use that.
01042   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
01043     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
01044     if (InstantiatedFrom)
01045       return getVisibilityOf(InstantiatedFrom, kind);
01046   }
01047 
01048   // If there wasn't explicit visibility there, and this is a
01049   // specialization of a class template, check for visibility
01050   // on the pattern.
01051   if (const ClassTemplateSpecializationDecl *spec
01052         = dyn_cast<ClassTemplateSpecializationDecl>(ND))
01053     return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
01054                            kind);
01055 
01056   // Use the most recent declaration.
01057   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
01058     const NamedDecl *MostRecent = ND->getMostRecentDecl();
01059     if (MostRecent != ND)
01060       return getExplicitVisibilityAux(MostRecent, kind, true);
01061   }
01062 
01063   if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
01064     if (Var->isStaticDataMember()) {
01065       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
01066       if (InstantiatedFrom)
01067         return getVisibilityOf(InstantiatedFrom, kind);
01068     }
01069 
01070     if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
01071       return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
01072                              kind);
01073 
01074     return None;
01075   }
01076   // Also handle function template specializations.
01077   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
01078     // If the function is a specialization of a template with an
01079     // explicit visibility attribute, use that.
01080     if (FunctionTemplateSpecializationInfo *templateInfo
01081           = fn->getTemplateSpecializationInfo())
01082       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
01083                              kind);
01084 
01085     // If the function is a member of a specialization of a class template
01086     // and the corresponding decl has explicit visibility, use that.
01087     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
01088     if (InstantiatedFrom)
01089       return getVisibilityOf(InstantiatedFrom, kind);
01090 
01091     return None;
01092   }
01093 
01094   // The visibility of a template is stored in the templated decl.
01095   if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
01096     return getVisibilityOf(TD->getTemplatedDecl(), kind);
01097 
01098   return None;
01099 }
01100 
01101 Optional<Visibility>
01102 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
01103   return getExplicitVisibilityAux(this, kind, false);
01104 }
01105 
01106 static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
01107                                    LVComputationKind computation) {
01108   // This lambda has its linkage/visibility determined by its owner.
01109   if (ContextDecl) {
01110     if (isa<ParmVarDecl>(ContextDecl))
01111       DC = ContextDecl->getDeclContext()->getRedeclContext();
01112     else
01113       return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
01114   }
01115 
01116   if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
01117     return getLVForDecl(ND, computation);
01118 
01119   return LinkageInfo::external();
01120 }
01121 
01122 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
01123                                      LVComputationKind computation) {
01124   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
01125     if (Function->isInAnonymousNamespace() &&
01126         !Function->isInExternCContext())
01127       return LinkageInfo::uniqueExternal();
01128 
01129     // This is a "void f();" which got merged with a file static.
01130     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
01131       return LinkageInfo::internal();
01132 
01133     LinkageInfo LV;
01134     if (!hasExplicitVisibilityAlready(computation)) {
01135       if (Optional<Visibility> Vis =
01136               getExplicitVisibility(Function, computation))
01137         LV.mergeVisibility(*Vis, true);
01138     }
01139 
01140     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
01141     // merging storage classes and visibility attributes, so we don't have to
01142     // look at previous decls in here.
01143 
01144     return LV;
01145   }
01146 
01147   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
01148     if (Var->hasExternalStorage()) {
01149       if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
01150         return LinkageInfo::uniqueExternal();
01151 
01152       LinkageInfo LV;
01153       if (Var->getStorageClass() == SC_PrivateExtern)
01154         LV.mergeVisibility(HiddenVisibility, true);
01155       else if (!hasExplicitVisibilityAlready(computation)) {
01156         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
01157           LV.mergeVisibility(*Vis, true);
01158       }
01159 
01160       if (const VarDecl *Prev = Var->getPreviousDecl()) {
01161         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
01162         if (PrevLV.getLinkage())
01163           LV.setLinkage(PrevLV.getLinkage());
01164         LV.mergeVisibility(PrevLV);
01165       }
01166 
01167       return LV;
01168     }
01169 
01170     if (!Var->isStaticLocal())
01171       return LinkageInfo::none();
01172   }
01173 
01174   ASTContext &Context = D->getASTContext();
01175   if (!Context.getLangOpts().CPlusPlus)
01176     return LinkageInfo::none();
01177 
01178   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
01179   if (!OuterD)
01180     return LinkageInfo::none();
01181 
01182   LinkageInfo LV;
01183   if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
01184     if (!BD->getBlockManglingNumber())
01185       return LinkageInfo::none();
01186 
01187     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
01188                          BD->getBlockManglingContextDecl(), computation);
01189   } else {
01190     const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
01191     if (!FD->isInlined() &&
01192         FD->getTemplateSpecializationKind() == TSK_Undeclared)
01193       return LinkageInfo::none();
01194 
01195     LV = getLVForDecl(FD, computation);
01196   }
01197   if (!isExternallyVisible(LV.getLinkage()))
01198     return LinkageInfo::none();
01199   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
01200                      LV.isVisibilityExplicit());
01201 }
01202 
01203 static inline const CXXRecordDecl*
01204 getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
01205   const CXXRecordDecl *Ret = Record;
01206   while (Record && Record->isLambda()) {
01207     Ret = Record;
01208     if (!Record->getParent()) break;
01209     // Get the Containing Class of this Lambda Class
01210     Record = dyn_cast_or_null<CXXRecordDecl>(
01211       Record->getParent()->getParent());
01212   }
01213   return Ret;
01214 }
01215 
01216 static LinkageInfo computeLVForDecl(const NamedDecl *D,
01217                                     LVComputationKind computation) {
01218   // Objective-C: treat all Objective-C declarations as having external
01219   // linkage.
01220   switch (D->getKind()) {
01221     default:
01222       break;
01223     case Decl::ParmVar:
01224       return LinkageInfo::none();
01225     case Decl::TemplateTemplateParm: // count these as external
01226     case Decl::NonTypeTemplateParm:
01227     case Decl::ObjCAtDefsField:
01228     case Decl::ObjCCategory:
01229     case Decl::ObjCCategoryImpl:
01230     case Decl::ObjCCompatibleAlias:
01231     case Decl::ObjCImplementation:
01232     case Decl::ObjCMethod:
01233     case Decl::ObjCProperty:
01234     case Decl::ObjCPropertyImpl:
01235     case Decl::ObjCProtocol:
01236       return LinkageInfo::external();
01237       
01238     case Decl::CXXRecord: {
01239       const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
01240       if (Record->isLambda()) {
01241         if (!Record->getLambdaManglingNumber()) {
01242           // This lambda has no mangling number, so it's internal.
01243           return LinkageInfo::internal();
01244         }
01245 
01246         // This lambda has its linkage/visibility determined:
01247         //  - either by the outermost lambda if that lambda has no mangling 
01248         //    number. 
01249         //  - or by the parent of the outer most lambda
01250         // This prevents infinite recursion in settings such as nested lambdas 
01251         // used in NSDMI's, for e.g. 
01252         //  struct L {
01253         //    int t{};
01254         //    int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);    
01255         //  };
01256         const CXXRecordDecl *OuterMostLambda = 
01257             getOutermostEnclosingLambda(Record);
01258         if (!OuterMostLambda->getLambdaManglingNumber())
01259           return LinkageInfo::internal();
01260         
01261         return getLVForClosure(
01262                   OuterMostLambda->getDeclContext()->getRedeclContext(),
01263                   OuterMostLambda->getLambdaContextDecl(), computation);
01264       }
01265       
01266       break;
01267     }
01268   }
01269 
01270   // Handle linkage for namespace-scope names.
01271   if (D->getDeclContext()->getRedeclContext()->isFileContext())
01272     return getLVForNamespaceScopeDecl(D, computation);
01273   
01274   // C++ [basic.link]p5:
01275   //   In addition, a member function, static data member, a named
01276   //   class or enumeration of class scope, or an unnamed class or
01277   //   enumeration defined in a class-scope typedef declaration such
01278   //   that the class or enumeration has the typedef name for linkage
01279   //   purposes (7.1.3), has external linkage if the name of the class
01280   //   has external linkage.
01281   if (D->getDeclContext()->isRecord())
01282     return getLVForClassMember(D, computation);
01283 
01284   // C++ [basic.link]p6:
01285   //   The name of a function declared in block scope and the name of
01286   //   an object declared by a block scope extern declaration have
01287   //   linkage. If there is a visible declaration of an entity with
01288   //   linkage having the same name and type, ignoring entities
01289   //   declared outside the innermost enclosing namespace scope, the
01290   //   block scope declaration declares that same entity and receives
01291   //   the linkage of the previous declaration. If there is more than
01292   //   one such matching entity, the program is ill-formed. Otherwise,
01293   //   if no matching entity is found, the block scope entity receives
01294   //   external linkage.
01295   if (D->getDeclContext()->isFunctionOrMethod())
01296     return getLVForLocalDecl(D, computation);
01297 
01298   // C++ [basic.link]p6:
01299   //   Names not covered by these rules have no linkage.
01300   return LinkageInfo::none();
01301 }
01302 
01303 namespace clang {
01304 class LinkageComputer {
01305 public:
01306   static LinkageInfo getLVForDecl(const NamedDecl *D,
01307                                   LVComputationKind computation) {
01308     if (computation == LVForLinkageOnly && D->hasCachedLinkage())
01309       return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
01310 
01311     LinkageInfo LV = computeLVForDecl(D, computation);
01312     if (D->hasCachedLinkage())
01313       assert(D->getCachedLinkage() == LV.getLinkage());
01314 
01315     D->setCachedLinkage(LV.getLinkage());
01316 
01317 #ifndef NDEBUG
01318     // In C (because of gnu inline) and in c++ with microsoft extensions an
01319     // static can follow an extern, so we can have two decls with different
01320     // linkages.
01321     const LangOptions &Opts = D->getASTContext().getLangOpts();
01322     if (!Opts.CPlusPlus || Opts.MicrosoftExt)
01323       return LV;
01324 
01325     // We have just computed the linkage for this decl. By induction we know
01326     // that all other computed linkages match, check that the one we just
01327     // computed also does.
01328     NamedDecl *Old = nullptr;
01329     for (auto I : D->redecls()) {
01330       NamedDecl *T = cast<NamedDecl>(I);
01331       if (T == D)
01332         continue;
01333       if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
01334         Old = T;
01335         break;
01336       }
01337     }
01338     assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
01339 #endif
01340 
01341     return LV;
01342   }
01343 };
01344 }
01345 
01346 static LinkageInfo getLVForDecl(const NamedDecl *D,
01347                                 LVComputationKind computation) {
01348   return clang::LinkageComputer::getLVForDecl(D, computation);
01349 }
01350 
01351 std::string NamedDecl::getQualifiedNameAsString() const {
01352   std::string QualName;
01353   llvm::raw_string_ostream OS(QualName);
01354   printQualifiedName(OS, getASTContext().getPrintingPolicy());
01355   return OS.str();
01356 }
01357 
01358 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
01359   printQualifiedName(OS, getASTContext().getPrintingPolicy());
01360 }
01361 
01362 void NamedDecl::printQualifiedName(raw_ostream &OS,
01363                                    const PrintingPolicy &P) const {
01364   const DeclContext *Ctx = getDeclContext();
01365 
01366   if (Ctx->isFunctionOrMethod()) {
01367     printName(OS);
01368     return;
01369   }
01370 
01371   typedef SmallVector<const DeclContext *, 8> ContextsTy;
01372   ContextsTy Contexts;
01373 
01374   // Collect contexts.
01375   while (Ctx && isa<NamedDecl>(Ctx)) {
01376     Contexts.push_back(Ctx);
01377     Ctx = Ctx->getParent();
01378   }
01379 
01380   for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
01381        I != E; ++I) {
01382     if (const ClassTemplateSpecializationDecl *Spec
01383           = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
01384       OS << Spec->getName();
01385       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
01386       TemplateSpecializationType::PrintTemplateArgumentList(OS,
01387                                                             TemplateArgs.data(),
01388                                                             TemplateArgs.size(),
01389                                                             P);
01390     } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
01391       if (P.SuppressUnwrittenScope &&
01392           (ND->isAnonymousNamespace() || ND->isInline()))
01393         continue;
01394       if (ND->isAnonymousNamespace())
01395         OS << "(anonymous namespace)";
01396       else
01397         OS << *ND;
01398     } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
01399       if (!RD->getIdentifier())
01400         OS << "(anonymous " << RD->getKindName() << ')';
01401       else
01402         OS << *RD;
01403     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
01404       const FunctionProtoType *FT = nullptr;
01405       if (FD->hasWrittenPrototype())
01406         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
01407 
01408       OS << *FD << '(';
01409       if (FT) {
01410         unsigned NumParams = FD->getNumParams();
01411         for (unsigned i = 0; i < NumParams; ++i) {
01412           if (i)
01413             OS << ", ";
01414           OS << FD->getParamDecl(i)->getType().stream(P);
01415         }
01416 
01417         if (FT->isVariadic()) {
01418           if (NumParams > 0)
01419             OS << ", ";
01420           OS << "...";
01421         }
01422       }
01423       OS << ')';
01424     } else {
01425       OS << *cast<NamedDecl>(*I);
01426     }
01427     OS << "::";
01428   }
01429 
01430   if (getDeclName())
01431     OS << *this;
01432   else
01433     OS << "(anonymous)";
01434 }
01435 
01436 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
01437                                      const PrintingPolicy &Policy,
01438                                      bool Qualified) const {
01439   if (Qualified)
01440     printQualifiedName(OS, Policy);
01441   else
01442     printName(OS);
01443 }
01444 
01445 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
01446   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
01447 
01448   // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
01449   // We want to keep it, unless it nominates same namespace.
01450   if (getKind() == Decl::UsingDirective) {
01451     return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
01452              ->getOriginalNamespace() ==
01453            cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
01454              ->getOriginalNamespace();
01455   }
01456 
01457   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
01458     // For function declarations, we keep track of redeclarations.
01459     return FD->getPreviousDecl() == OldD;
01460 
01461   // For function templates, the underlying function declarations are linked.
01462   if (const FunctionTemplateDecl *FunctionTemplate
01463         = dyn_cast<FunctionTemplateDecl>(this))
01464     if (const FunctionTemplateDecl *OldFunctionTemplate
01465           = dyn_cast<FunctionTemplateDecl>(OldD))
01466       return FunctionTemplate->getTemplatedDecl()
01467                ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
01468 
01469   // For method declarations, we keep track of redeclarations.
01470   if (isa<ObjCMethodDecl>(this))
01471     return false;
01472 
01473   // FIXME: Is this correct if one of the decls comes from an inline namespace?
01474   if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
01475     return true;
01476 
01477   if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
01478     return cast<UsingShadowDecl>(this)->getTargetDecl() ==
01479            cast<UsingShadowDecl>(OldD)->getTargetDecl();
01480 
01481   if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
01482     ASTContext &Context = getASTContext();
01483     return Context.getCanonicalNestedNameSpecifier(
01484                                      cast<UsingDecl>(this)->getQualifier()) ==
01485            Context.getCanonicalNestedNameSpecifier(
01486                                         cast<UsingDecl>(OldD)->getQualifier());
01487   }
01488 
01489   if (isa<UnresolvedUsingValueDecl>(this) &&
01490       isa<UnresolvedUsingValueDecl>(OldD)) {
01491     ASTContext &Context = getASTContext();
01492     return Context.getCanonicalNestedNameSpecifier(
01493                       cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
01494            Context.getCanonicalNestedNameSpecifier(
01495                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
01496   }
01497 
01498   // A typedef of an Objective-C class type can replace an Objective-C class
01499   // declaration or definition, and vice versa.
01500   // FIXME: Is this correct if one of the decls comes from an inline namespace?
01501   if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
01502       (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
01503     return true;
01504 
01505   // For non-function declarations, if the declarations are of the
01506   // same kind and have the same parent then this must be a redeclaration,
01507   // or semantic analysis would not have given us the new declaration.
01508   // Note that inline namespaces can give us two declarations with the same
01509   // name and kind in the same scope but different contexts.
01510   return this->getKind() == OldD->getKind() &&
01511          this->getDeclContext()->getRedeclContext()->Equals(
01512              OldD->getDeclContext()->getRedeclContext());
01513 }
01514 
01515 bool NamedDecl::hasLinkage() const {
01516   return getFormalLinkage() != NoLinkage;
01517 }
01518 
01519 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
01520   NamedDecl *ND = this;
01521   while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
01522     ND = UD->getTargetDecl();
01523 
01524   if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
01525     return AD->getClassInterface();
01526 
01527   return ND;
01528 }
01529 
01530 bool NamedDecl::isCXXInstanceMember() const {
01531   if (!isCXXClassMember())
01532     return false;
01533   
01534   const NamedDecl *D = this;
01535   if (isa<UsingShadowDecl>(D))
01536     D = cast<UsingShadowDecl>(D)->getTargetDecl();
01537 
01538   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
01539     return true;
01540   if (const CXXMethodDecl *MD =
01541           dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
01542     return MD->isInstance();
01543   return false;
01544 }
01545 
01546 //===----------------------------------------------------------------------===//
01547 // DeclaratorDecl Implementation
01548 //===----------------------------------------------------------------------===//
01549 
01550 template <typename DeclT>
01551 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
01552   if (decl->getNumTemplateParameterLists() > 0)
01553     return decl->getTemplateParameterList(0)->getTemplateLoc();
01554   else
01555     return decl->getInnerLocStart();
01556 }
01557 
01558 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
01559   TypeSourceInfo *TSI = getTypeSourceInfo();
01560   if (TSI) return TSI->getTypeLoc().getBeginLoc();
01561   return SourceLocation();
01562 }
01563 
01564 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
01565   if (QualifierLoc) {
01566     // Make sure the extended decl info is allocated.
01567     if (!hasExtInfo()) {
01568       // Save (non-extended) type source info pointer.
01569       TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
01570       // Allocate external info struct.
01571       DeclInfo = new (getASTContext()) ExtInfo;
01572       // Restore savedTInfo into (extended) decl info.
01573       getExtInfo()->TInfo = savedTInfo;
01574     }
01575     // Set qualifier info.
01576     getExtInfo()->QualifierLoc = QualifierLoc;
01577   } else {
01578     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
01579     if (hasExtInfo()) {
01580       if (getExtInfo()->NumTemplParamLists == 0) {
01581         // Save type source info pointer.
01582         TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
01583         // Deallocate the extended decl info.
01584         getASTContext().Deallocate(getExtInfo());
01585         // Restore savedTInfo into (non-extended) decl info.
01586         DeclInfo = savedTInfo;
01587       }
01588       else
01589         getExtInfo()->QualifierLoc = QualifierLoc;
01590     }
01591   }
01592 }
01593 
01594 void
01595 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
01596                                               unsigned NumTPLists,
01597                                               TemplateParameterList **TPLists) {
01598   assert(NumTPLists > 0);
01599   // Make sure the extended decl info is allocated.
01600   if (!hasExtInfo()) {
01601     // Save (non-extended) type source info pointer.
01602     TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
01603     // Allocate external info struct.
01604     DeclInfo = new (getASTContext()) ExtInfo;
01605     // Restore savedTInfo into (extended) decl info.
01606     getExtInfo()->TInfo = savedTInfo;
01607   }
01608   // Set the template parameter lists info.
01609   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
01610 }
01611 
01612 SourceLocation DeclaratorDecl::getOuterLocStart() const {
01613   return getTemplateOrInnerLocStart(this);
01614 }
01615 
01616 namespace {
01617 
01618 // Helper function: returns true if QT is or contains a type
01619 // having a postfix component.
01620 bool typeIsPostfix(clang::QualType QT) {
01621   while (true) {
01622     const Type* T = QT.getTypePtr();
01623     switch (T->getTypeClass()) {
01624     default:
01625       return false;
01626     case Type::Pointer:
01627       QT = cast<PointerType>(T)->getPointeeType();
01628       break;
01629     case Type::BlockPointer:
01630       QT = cast<BlockPointerType>(T)->getPointeeType();
01631       break;
01632     case Type::MemberPointer:
01633       QT = cast<MemberPointerType>(T)->getPointeeType();
01634       break;
01635     case Type::LValueReference:
01636     case Type::RValueReference:
01637       QT = cast<ReferenceType>(T)->getPointeeType();
01638       break;
01639     case Type::PackExpansion:
01640       QT = cast<PackExpansionType>(T)->getPattern();
01641       break;
01642     case Type::Paren:
01643     case Type::ConstantArray:
01644     case Type::DependentSizedArray:
01645     case Type::IncompleteArray:
01646     case Type::VariableArray:
01647     case Type::FunctionProto:
01648     case Type::FunctionNoProto:
01649       return true;
01650     }
01651   }
01652 }
01653 
01654 } // namespace
01655 
01656 SourceRange DeclaratorDecl::getSourceRange() const {
01657   SourceLocation RangeEnd = getLocation();
01658   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
01659     // If the declaration has no name or the type extends past the name take the
01660     // end location of the type.
01661     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
01662       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
01663   }
01664   return SourceRange(getOuterLocStart(), RangeEnd);
01665 }
01666 
01667 void
01668 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
01669                                              unsigned NumTPLists,
01670                                              TemplateParameterList **TPLists) {
01671   assert((NumTPLists == 0 || TPLists != nullptr) &&
01672          "Empty array of template parameters with positive size!");
01673 
01674   // Free previous template parameters (if any).
01675   if (NumTemplParamLists > 0) {
01676     Context.Deallocate(TemplParamLists);
01677     TemplParamLists = nullptr;
01678     NumTemplParamLists = 0;
01679   }
01680   // Set info on matched template parameter lists (if any).
01681   if (NumTPLists > 0) {
01682     TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
01683     NumTemplParamLists = NumTPLists;
01684     for (unsigned i = NumTPLists; i-- > 0; )
01685       TemplParamLists[i] = TPLists[i];
01686   }
01687 }
01688 
01689 //===----------------------------------------------------------------------===//
01690 // VarDecl Implementation
01691 //===----------------------------------------------------------------------===//
01692 
01693 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
01694   switch (SC) {
01695   case SC_None:                 break;
01696   case SC_Auto:                 return "auto";
01697   case SC_Extern:               return "extern";
01698   case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
01699   case SC_PrivateExtern:        return "__private_extern__";
01700   case SC_Register:             return "register";
01701   case SC_Static:               return "static";
01702   }
01703 
01704   llvm_unreachable("Invalid storage class");
01705 }
01706 
01707 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
01708                  SourceLocation StartLoc, SourceLocation IdLoc,
01709                  IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
01710                  StorageClass SC)
01711     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
01712       redeclarable_base(C), Init() {
01713   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
01714                 "VarDeclBitfields too large!");
01715   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
01716                 "ParmVarDeclBitfields too large!");
01717   AllBits = 0;
01718   VarDeclBits.SClass = SC;
01719   // Everything else is implicitly initialized to false.
01720 }
01721 
01722 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
01723                          SourceLocation StartL, SourceLocation IdL,
01724                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
01725                          StorageClass S) {
01726   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
01727 }
01728 
01729 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
01730   return new (C, ID)
01731       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
01732               QualType(), nullptr, SC_None);
01733 }
01734 
01735 void VarDecl::setStorageClass(StorageClass SC) {
01736   assert(isLegalForVariable(SC));
01737   VarDeclBits.SClass = SC;
01738 }
01739 
01740 VarDecl::TLSKind VarDecl::getTLSKind() const {
01741   switch (VarDeclBits.TSCSpec) {
01742   case TSCS_unspecified:
01743     if (hasAttr<ThreadAttr>())
01744       return TLS_Static;
01745     return TLS_None;
01746   case TSCS___thread: // Fall through.
01747   case TSCS__Thread_local:
01748       return TLS_Static;
01749   case TSCS_thread_local:
01750     return TLS_Dynamic;
01751   }
01752   llvm_unreachable("Unknown thread storage class specifier!");
01753 }
01754 
01755 SourceRange VarDecl::getSourceRange() const {
01756   if (const Expr *Init = getInit()) {
01757     SourceLocation InitEnd = Init->getLocEnd();
01758     // If Init is implicit, ignore its source range and fallback on 
01759     // DeclaratorDecl::getSourceRange() to handle postfix elements.
01760     if (InitEnd.isValid() && InitEnd != getLocation())
01761       return SourceRange(getOuterLocStart(), InitEnd);
01762   }
01763   return DeclaratorDecl::getSourceRange();
01764 }
01765 
01766 template<typename T>
01767 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
01768   // C++ [dcl.link]p1: All function types, function names with external linkage,
01769   // and variable names with external linkage have a language linkage.
01770   if (!D.hasExternalFormalLinkage())
01771     return NoLanguageLinkage;
01772 
01773   // Language linkage is a C++ concept, but saying that everything else in C has
01774   // C language linkage fits the implementation nicely.
01775   ASTContext &Context = D.getASTContext();
01776   if (!Context.getLangOpts().CPlusPlus)
01777     return CLanguageLinkage;
01778 
01779   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
01780   // language linkage of the names of class members and the function type of
01781   // class member functions.
01782   const DeclContext *DC = D.getDeclContext();
01783   if (DC->isRecord())
01784     return CXXLanguageLinkage;
01785 
01786   // If the first decl is in an extern "C" context, any other redeclaration
01787   // will have C language linkage. If the first one is not in an extern "C"
01788   // context, we would have reported an error for any other decl being in one.
01789   if (isFirstInExternCContext(&D))
01790     return CLanguageLinkage;
01791   return CXXLanguageLinkage;
01792 }
01793 
01794 template<typename T>
01795 static bool isDeclExternC(const T &D) {
01796   // Since the context is ignored for class members, they can only have C++
01797   // language linkage or no language linkage.
01798   const DeclContext *DC = D.getDeclContext();
01799   if (DC->isRecord()) {
01800     assert(D.getASTContext().getLangOpts().CPlusPlus);
01801     return false;
01802   }
01803 
01804   return D.getLanguageLinkage() == CLanguageLinkage;
01805 }
01806 
01807 LanguageLinkage VarDecl::getLanguageLinkage() const {
01808   return getDeclLanguageLinkage(*this);
01809 }
01810 
01811 bool VarDecl::isExternC() const {
01812   return isDeclExternC(*this);
01813 }
01814 
01815 bool VarDecl::isInExternCContext() const {
01816   return getLexicalDeclContext()->isExternCContext();
01817 }
01818 
01819 bool VarDecl::isInExternCXXContext() const {
01820   return getLexicalDeclContext()->isExternCXXContext();
01821 }
01822 
01823 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
01824 
01825 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
01826   ASTContext &C) const
01827 {
01828   // C++ [basic.def]p2:
01829   //   A declaration is a definition unless [...] it contains the 'extern'
01830   //   specifier or a linkage-specification and neither an initializer [...],
01831   //   it declares a static data member in a class declaration [...].
01832   // C++1y [temp.expl.spec]p15:
01833   //   An explicit specialization of a static data member or an explicit
01834   //   specialization of a static data member template is a definition if the
01835   //   declaration includes an initializer; otherwise, it is a declaration.
01836   //
01837   // FIXME: How do you declare (but not define) a partial specialization of
01838   // a static data member template outside the containing class?
01839   if (isStaticDataMember()) {
01840     if (isOutOfLine() &&
01841         (hasInit() ||
01842          // If the first declaration is out-of-line, this may be an
01843          // instantiation of an out-of-line partial specialization of a variable
01844          // template for which we have not yet instantiated the initializer.
01845          (getFirstDecl()->isOutOfLine()
01846               ? getTemplateSpecializationKind() == TSK_Undeclared
01847               : getTemplateSpecializationKind() !=
01848                     TSK_ExplicitSpecialization) ||
01849          isa<VarTemplatePartialSpecializationDecl>(this)))
01850       return Definition;
01851     else
01852       return DeclarationOnly;
01853   }
01854   // C99 6.7p5:
01855   //   A definition of an identifier is a declaration for that identifier that
01856   //   [...] causes storage to be reserved for that object.
01857   // Note: that applies for all non-file-scope objects.
01858   // C99 6.9.2p1:
01859   //   If the declaration of an identifier for an object has file scope and an
01860   //   initializer, the declaration is an external definition for the identifier
01861   if (hasInit())
01862     return Definition;
01863 
01864   if (hasAttr<AliasAttr>())
01865     return Definition;
01866 
01867   // A variable template specialization (other than a static data member
01868   // template or an explicit specialization) is a declaration until we
01869   // instantiate its initializer.
01870   if (isa<VarTemplateSpecializationDecl>(this) &&
01871       getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
01872     return DeclarationOnly;
01873 
01874   if (hasExternalStorage())
01875     return DeclarationOnly;
01876 
01877   // [dcl.link] p7:
01878   //   A declaration directly contained in a linkage-specification is treated
01879   //   as if it contains the extern specifier for the purpose of determining
01880   //   the linkage of the declared name and whether it is a definition.
01881   if (isSingleLineLanguageLinkage(*this))
01882     return DeclarationOnly;
01883 
01884   // C99 6.9.2p2:
01885   //   A declaration of an object that has file scope without an initializer,
01886   //   and without a storage class specifier or the scs 'static', constitutes
01887   //   a tentative definition.
01888   // No such thing in C++.
01889   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
01890     return TentativeDefinition;
01891 
01892   // What's left is (in C, block-scope) declarations without initializers or
01893   // external storage. These are definitions.
01894   return Definition;
01895 }
01896 
01897 VarDecl *VarDecl::getActingDefinition() {
01898   DefinitionKind Kind = isThisDeclarationADefinition();
01899   if (Kind != TentativeDefinition)
01900     return nullptr;
01901 
01902   VarDecl *LastTentative = nullptr;
01903   VarDecl *First = getFirstDecl();
01904   for (auto I : First->redecls()) {
01905     Kind = I->isThisDeclarationADefinition();
01906     if (Kind == Definition)
01907       return nullptr;
01908     else if (Kind == TentativeDefinition)
01909       LastTentative = I;
01910   }
01911   return LastTentative;
01912 }
01913 
01914 VarDecl *VarDecl::getDefinition(ASTContext &C) {
01915   VarDecl *First = getFirstDecl();
01916   for (auto I : First->redecls()) {
01917     if (I->isThisDeclarationADefinition(C) == Definition)
01918       return I;
01919   }
01920   return nullptr;
01921 }
01922 
01923 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
01924   DefinitionKind Kind = DeclarationOnly;
01925   
01926   const VarDecl *First = getFirstDecl();
01927   for (auto I : First->redecls()) {
01928     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
01929     if (Kind == Definition)
01930       break;
01931   }
01932 
01933   return Kind;
01934 }
01935 
01936 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
01937   for (auto I : redecls()) {
01938     if (auto Expr = I->getInit()) {
01939       D = I;
01940       return Expr;
01941     }
01942   }
01943   return nullptr;
01944 }
01945 
01946 bool VarDecl::isOutOfLine() const {
01947   if (Decl::isOutOfLine())
01948     return true;
01949 
01950   if (!isStaticDataMember())
01951     return false;
01952 
01953   // If this static data member was instantiated from a static data member of
01954   // a class template, check whether that static data member was defined 
01955   // out-of-line.
01956   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
01957     return VD->isOutOfLine();
01958   
01959   return false;
01960 }
01961 
01962 VarDecl *VarDecl::getOutOfLineDefinition() {
01963   if (!isStaticDataMember())
01964     return nullptr;
01965 
01966   for (auto RD : redecls()) {
01967     if (RD->getLexicalDeclContext()->isFileContext())
01968       return RD;
01969   }
01970 
01971   return nullptr;
01972 }
01973 
01974 void VarDecl::setInit(Expr *I) {
01975   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
01976     Eval->~EvaluatedStmt();
01977     getASTContext().Deallocate(Eval);
01978   }
01979 
01980   Init = I;
01981 }
01982 
01983 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
01984   const LangOptions &Lang = C.getLangOpts();
01985 
01986   if (!Lang.CPlusPlus)
01987     return false;
01988 
01989   // In C++11, any variable of reference type can be used in a constant
01990   // expression if it is initialized by a constant expression.
01991   if (Lang.CPlusPlus11 && getType()->isReferenceType())
01992     return true;
01993 
01994   // Only const objects can be used in constant expressions in C++. C++98 does
01995   // not require the variable to be non-volatile, but we consider this to be a
01996   // defect.
01997   if (!getType().isConstQualified() || getType().isVolatileQualified())
01998     return false;
01999 
02000   // In C++, const, non-volatile variables of integral or enumeration types
02001   // can be used in constant expressions.
02002   if (getType()->isIntegralOrEnumerationType())
02003     return true;
02004 
02005   // Additionally, in C++11, non-volatile constexpr variables can be used in
02006   // constant expressions.
02007   return Lang.CPlusPlus11 && isConstexpr();
02008 }
02009 
02010 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
02011 /// form, which contains extra information on the evaluated value of the
02012 /// initializer.
02013 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
02014   EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
02015   if (!Eval) {
02016     Stmt *S = Init.get<Stmt *>();
02017     // Note: EvaluatedStmt contains an APValue, which usually holds
02018     // resources not allocated from the ASTContext.  We need to do some
02019     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
02020     // where we can detect whether there's anything to clean up or not.
02021     Eval = new (getASTContext()) EvaluatedStmt;
02022     Eval->Value = S;
02023     Init = Eval;
02024   }
02025   return Eval;
02026 }
02027 
02028 APValue *VarDecl::evaluateValue() const {
02029   SmallVector<PartialDiagnosticAt, 8> Notes;
02030   return evaluateValue(Notes);
02031 }
02032 
02033 namespace {
02034 // Destroy an APValue that was allocated in an ASTContext.
02035 void DestroyAPValue(void* UntypedValue) {
02036   static_cast<APValue*>(UntypedValue)->~APValue();
02037 }
02038 } // namespace
02039 
02040 APValue *VarDecl::evaluateValue(
02041     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
02042   EvaluatedStmt *Eval = ensureEvaluatedStmt();
02043 
02044   // We only produce notes indicating why an initializer is non-constant the
02045   // first time it is evaluated. FIXME: The notes won't always be emitted the
02046   // first time we try evaluation, so might not be produced at all.
02047   if (Eval->WasEvaluated)
02048     return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
02049 
02050   const Expr *Init = cast<Expr>(Eval->Value);
02051   assert(!Init->isValueDependent());
02052 
02053   if (Eval->IsEvaluating) {
02054     // FIXME: Produce a diagnostic for self-initialization.
02055     Eval->CheckedICE = true;
02056     Eval->IsICE = false;
02057     return nullptr;
02058   }
02059 
02060   Eval->IsEvaluating = true;
02061 
02062   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
02063                                             this, Notes);
02064 
02065   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
02066   // or that it's empty (so that there's nothing to clean up) if evaluation
02067   // failed.
02068   if (!Result)
02069     Eval->Evaluated = APValue();
02070   else if (Eval->Evaluated.needsCleanup())
02071     getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
02072 
02073   Eval->IsEvaluating = false;
02074   Eval->WasEvaluated = true;
02075 
02076   // In C++11, we have determined whether the initializer was a constant
02077   // expression as a side-effect.
02078   if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
02079     Eval->CheckedICE = true;
02080     Eval->IsICE = Result && Notes.empty();
02081   }
02082 
02083   return Result ? &Eval->Evaluated : nullptr;
02084 }
02085 
02086 bool VarDecl::checkInitIsICE() const {
02087   // Initializers of weak variables are never ICEs.
02088   if (isWeak())
02089     return false;
02090 
02091   EvaluatedStmt *Eval = ensureEvaluatedStmt();
02092   if (Eval->CheckedICE)
02093     // We have already checked whether this subexpression is an
02094     // integral constant expression.
02095     return Eval->IsICE;
02096 
02097   const Expr *Init = cast<Expr>(Eval->Value);
02098   assert(!Init->isValueDependent());
02099 
02100   // In C++11, evaluate the initializer to check whether it's a constant
02101   // expression.
02102   if (getASTContext().getLangOpts().CPlusPlus11) {
02103     SmallVector<PartialDiagnosticAt, 8> Notes;
02104     evaluateValue(Notes);
02105     return Eval->IsICE;
02106   }
02107 
02108   // It's an ICE whether or not the definition we found is
02109   // out-of-line.  See DR 721 and the discussion in Clang PR
02110   // 6206 for details.
02111 
02112   if (Eval->CheckingICE)
02113     return false;
02114   Eval->CheckingICE = true;
02115 
02116   Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
02117   Eval->CheckingICE = false;
02118   Eval->CheckedICE = true;
02119   return Eval->IsICE;
02120 }
02121 
02122 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
02123   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
02124     return cast<VarDecl>(MSI->getInstantiatedFrom());
02125 
02126   return nullptr;
02127 }
02128 
02129 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
02130   if (const VarTemplateSpecializationDecl *Spec =
02131           dyn_cast<VarTemplateSpecializationDecl>(this))
02132     return Spec->getSpecializationKind();
02133 
02134   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
02135     return MSI->getTemplateSpecializationKind();
02136 
02137   return TSK_Undeclared;
02138 }
02139 
02140 SourceLocation VarDecl::getPointOfInstantiation() const {
02141   if (const VarTemplateSpecializationDecl *Spec =
02142           dyn_cast<VarTemplateSpecializationDecl>(this))
02143     return Spec->getPointOfInstantiation();
02144 
02145   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
02146     return MSI->getPointOfInstantiation();
02147 
02148   return SourceLocation();
02149 }
02150 
02151 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
02152   return getASTContext().getTemplateOrSpecializationInfo(this)
02153       .dyn_cast<VarTemplateDecl *>();
02154 }
02155 
02156 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
02157   getASTContext().setTemplateOrSpecializationInfo(this, Template);
02158 }
02159 
02160 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
02161   if (isStaticDataMember())
02162     // FIXME: Remove ?
02163     // return getASTContext().getInstantiatedFromStaticDataMember(this);
02164     return getASTContext().getTemplateOrSpecializationInfo(this)
02165         .dyn_cast<MemberSpecializationInfo *>();
02166   return nullptr;
02167 }
02168 
02169 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
02170                                          SourceLocation PointOfInstantiation) {
02171   assert((isa<VarTemplateSpecializationDecl>(this) ||
02172           getMemberSpecializationInfo()) &&
02173          "not a variable or static data member template specialization");
02174 
02175   if (VarTemplateSpecializationDecl *Spec =
02176           dyn_cast<VarTemplateSpecializationDecl>(this)) {
02177     Spec->setSpecializationKind(TSK);
02178     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
02179         Spec->getPointOfInstantiation().isInvalid())
02180       Spec->setPointOfInstantiation(PointOfInstantiation);
02181   }
02182 
02183   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
02184     MSI->setTemplateSpecializationKind(TSK);
02185     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
02186         MSI->getPointOfInstantiation().isInvalid())
02187       MSI->setPointOfInstantiation(PointOfInstantiation);
02188   }
02189 }
02190 
02191 void
02192 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
02193                                             TemplateSpecializationKind TSK) {
02194   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
02195          "Previous template or instantiation?");
02196   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
02197 }
02198 
02199 //===----------------------------------------------------------------------===//
02200 // ParmVarDecl Implementation
02201 //===----------------------------------------------------------------------===//
02202 
02203 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
02204                                  SourceLocation StartLoc,
02205                                  SourceLocation IdLoc, IdentifierInfo *Id,
02206                                  QualType T, TypeSourceInfo *TInfo,
02207                                  StorageClass S, Expr *DefArg) {
02208   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
02209                                  S, DefArg);
02210 }
02211 
02212 QualType ParmVarDecl::getOriginalType() const {
02213   TypeSourceInfo *TSI = getTypeSourceInfo();
02214   QualType T = TSI ? TSI->getType() : getType();
02215   if (const DecayedType *DT = dyn_cast<DecayedType>(T))
02216     return DT->getOriginalType();
02217   return T;
02218 }
02219 
02220 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
02221   return new (C, ID)
02222       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
02223                   nullptr, QualType(), nullptr, SC_None, nullptr);
02224 }
02225 
02226 SourceRange ParmVarDecl::getSourceRange() const {
02227   if (!hasInheritedDefaultArg()) {
02228     SourceRange ArgRange = getDefaultArgRange();
02229     if (ArgRange.isValid())
02230       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
02231   }
02232 
02233   // DeclaratorDecl considers the range of postfix types as overlapping with the
02234   // declaration name, but this is not the case with parameters in ObjC methods.
02235   if (isa<ObjCMethodDecl>(getDeclContext()))
02236     return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
02237 
02238   return DeclaratorDecl::getSourceRange();
02239 }
02240 
02241 Expr *ParmVarDecl::getDefaultArg() {
02242   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
02243   assert(!hasUninstantiatedDefaultArg() &&
02244          "Default argument is not yet instantiated!");
02245   
02246   Expr *Arg = getInit();
02247   if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
02248     return E->getSubExpr();
02249 
02250   return Arg;
02251 }
02252 
02253 SourceRange ParmVarDecl::getDefaultArgRange() const {
02254   if (const Expr *E = getInit())
02255     return E->getSourceRange();
02256 
02257   if (hasUninstantiatedDefaultArg())
02258     return getUninstantiatedDefaultArg()->getSourceRange();
02259 
02260   return SourceRange();
02261 }
02262 
02263 bool ParmVarDecl::isParameterPack() const {
02264   return isa<PackExpansionType>(getType());
02265 }
02266 
02267 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
02268   getASTContext().setParameterIndex(this, parameterIndex);
02269   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
02270 }
02271 
02272 unsigned ParmVarDecl::getParameterIndexLarge() const {
02273   return getASTContext().getParameterIndex(this);
02274 }
02275 
02276 //===----------------------------------------------------------------------===//
02277 // FunctionDecl Implementation
02278 //===----------------------------------------------------------------------===//
02279 
02280 void FunctionDecl::getNameForDiagnostic(
02281     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
02282   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
02283   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
02284   if (TemplateArgs)
02285     TemplateSpecializationType::PrintTemplateArgumentList(
02286         OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
02287 }
02288 
02289 bool FunctionDecl::isVariadic() const {
02290   if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
02291     return FT->isVariadic();
02292   return false;
02293 }
02294 
02295 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
02296   for (auto I : redecls()) {
02297     if (I->Body || I->IsLateTemplateParsed) {
02298       Definition = I;
02299       return true;
02300     }
02301   }
02302 
02303   return false;
02304 }
02305 
02306 bool FunctionDecl::hasTrivialBody() const
02307 {
02308   Stmt *S = getBody();
02309   if (!S) {
02310     // Since we don't have a body for this function, we don't know if it's
02311     // trivial or not.
02312     return false;
02313   }
02314 
02315   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
02316     return true;
02317   return false;
02318 }
02319 
02320 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
02321   for (auto I : redecls()) {
02322     if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
02323         I->hasAttr<AliasAttr>()) {
02324       Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
02325       return true;
02326     }
02327   }
02328 
02329   return false;
02330 }
02331 
02332 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
02333   if (!hasBody(Definition))
02334     return nullptr;
02335 
02336   if (Definition->Body)
02337     return Definition->Body.get(getASTContext().getExternalSource());
02338 
02339   return nullptr;
02340 }
02341 
02342 void FunctionDecl::setBody(Stmt *B) {
02343   Body = B;
02344   if (B)
02345     EndRangeLoc = B->getLocEnd();
02346 }
02347 
02348 void FunctionDecl::setPure(bool P) {
02349   IsPure = P;
02350   if (P)
02351     if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
02352       Parent->markedVirtualFunctionPure();
02353 }
02354 
02355 template<std::size_t Len>
02356 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
02357   IdentifierInfo *II = ND->getIdentifier();
02358   return II && II->isStr(Str);
02359 }
02360 
02361 bool FunctionDecl::isMain() const {
02362   const TranslationUnitDecl *tunit =
02363     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
02364   return tunit &&
02365          !tunit->getASTContext().getLangOpts().Freestanding &&
02366          isNamed(this, "main");
02367 }
02368 
02369 bool FunctionDecl::isMSVCRTEntryPoint() const {
02370   const TranslationUnitDecl *TUnit =
02371       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
02372   if (!TUnit)
02373     return false;
02374 
02375   // Even though we aren't really targeting MSVCRT if we are freestanding,
02376   // semantic analysis for these functions remains the same.
02377 
02378   // MSVCRT entry points only exist on MSVCRT targets.
02379   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
02380     return false;
02381 
02382   // Nameless functions like constructors cannot be entry points.
02383   if (!getIdentifier())
02384     return false;
02385 
02386   return llvm::StringSwitch<bool>(getName())
02387       .Cases("main",     // an ANSI console app
02388              "wmain",    // a Unicode console App
02389              "WinMain",  // an ANSI GUI app
02390              "wWinMain", // a Unicode GUI app
02391              "DllMain",  // a DLL
02392              true)
02393       .Default(false);
02394 }
02395 
02396 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
02397   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
02398   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
02399          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
02400          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
02401          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
02402 
02403   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
02404     return false;
02405 
02406   const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
02407   if (proto->getNumParams() != 2 || proto->isVariadic())
02408     return false;
02409 
02410   ASTContext &Context =
02411     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
02412       ->getASTContext();
02413 
02414   // The result type and first argument type are constant across all
02415   // these operators.  The second argument must be exactly void*.
02416   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
02417 }
02418 
02419 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
02420   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
02421     return false;
02422   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
02423       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
02424       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
02425       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
02426     return false;
02427 
02428   if (isa<CXXRecordDecl>(getDeclContext()))
02429     return false;
02430 
02431   // This can only fail for an invalid 'operator new' declaration.
02432   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
02433     return false;
02434 
02435   const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
02436   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
02437     return false;
02438 
02439   // If this is a single-parameter function, it must be a replaceable global
02440   // allocation or deallocation function.
02441   if (FPT->getNumParams() == 1)
02442     return true;
02443 
02444   // Otherwise, we're looking for a second parameter whose type is
02445   // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
02446   QualType Ty = FPT->getParamType(1);
02447   ASTContext &Ctx = getASTContext();
02448   if (Ctx.getLangOpts().SizedDeallocation &&
02449       Ctx.hasSameType(Ty, Ctx.getSizeType()))
02450     return true;
02451   if (!Ty->isReferenceType())
02452     return false;
02453   Ty = Ty->getPointeeType();
02454   if (Ty.getCVRQualifiers() != Qualifiers::Const)
02455     return false;
02456   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
02457   return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
02458 }
02459 
02460 FunctionDecl *
02461 FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
02462   ASTContext &Ctx = getASTContext();
02463   if (!Ctx.getLangOpts().SizedDeallocation)
02464     return nullptr;
02465 
02466   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
02467     return nullptr;
02468   if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
02469       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
02470     return nullptr;
02471   if (isa<CXXRecordDecl>(getDeclContext()))
02472     return nullptr;
02473 
02474   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
02475     return nullptr;
02476 
02477   if (getNumParams() != 2 || isVariadic() ||
02478       !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
02479                        Ctx.getSizeType()))
02480     return nullptr;
02481 
02482   // This is a sized deallocation function. Find the corresponding unsized
02483   // deallocation function.
02484   lookup_const_result R = getDeclContext()->lookup(getDeclName());
02485   for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
02486        ++RI)
02487     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
02488       if (FD->getNumParams() == 1 && !FD->isVariadic())
02489         return FD;
02490   return nullptr;
02491 }
02492 
02493 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
02494   return getDeclLanguageLinkage(*this);
02495 }
02496 
02497 bool FunctionDecl::isExternC() const {
02498   return isDeclExternC(*this);
02499 }
02500 
02501 bool FunctionDecl::isInExternCContext() const {
02502   return getLexicalDeclContext()->isExternCContext();
02503 }
02504 
02505 bool FunctionDecl::isInExternCXXContext() const {
02506   return getLexicalDeclContext()->isExternCXXContext();
02507 }
02508 
02509 bool FunctionDecl::isGlobal() const {
02510   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
02511     return Method->isStatic();
02512 
02513   if (getCanonicalDecl()->getStorageClass() == SC_Static)
02514     return false;
02515 
02516   for (const DeclContext *DC = getDeclContext();
02517        DC->isNamespace();
02518        DC = DC->getParent()) {
02519     if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
02520       if (!Namespace->getDeclName())
02521         return false;
02522       break;
02523     }
02524   }
02525 
02526   return true;
02527 }
02528 
02529 bool FunctionDecl::isNoReturn() const {
02530   return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
02531          hasAttr<C11NoReturnAttr>() ||
02532          getType()->getAs<FunctionType>()->getNoReturnAttr();
02533 }
02534 
02535 void
02536 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
02537   redeclarable_base::setPreviousDecl(PrevDecl);
02538 
02539   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
02540     FunctionTemplateDecl *PrevFunTmpl
02541       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
02542     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
02543     FunTmpl->setPreviousDecl(PrevFunTmpl);
02544   }
02545   
02546   if (PrevDecl && PrevDecl->IsInline)
02547     IsInline = true;
02548 }
02549 
02550 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
02551   return getFirstDecl();
02552 }
02553 
02554 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
02555 
02556 /// \brief Returns a value indicating whether this function
02557 /// corresponds to a builtin function.
02558 ///
02559 /// The function corresponds to a built-in function if it is
02560 /// declared at translation scope or within an extern "C" block and
02561 /// its name matches with the name of a builtin. The returned value
02562 /// will be 0 for functions that do not correspond to a builtin, a
02563 /// value of type \c Builtin::ID if in the target-independent range
02564 /// \c [1,Builtin::First), or a target-specific builtin value.
02565 unsigned FunctionDecl::getBuiltinID() const {
02566   if (!getIdentifier())
02567     return 0;
02568 
02569   unsigned BuiltinID = getIdentifier()->getBuiltinID();
02570   if (!BuiltinID)
02571     return 0;
02572 
02573   ASTContext &Context = getASTContext();
02574   if (Context.getLangOpts().CPlusPlus) {
02575     const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
02576         getFirstDecl()->getDeclContext());
02577     // In C++, the first declaration of a builtin is always inside an implicit
02578     // extern "C".
02579     // FIXME: A recognised library function may not be directly in an extern "C"
02580     // declaration, for instance "extern "C" { namespace std { decl } }".
02581     if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
02582       return 0;
02583   }
02584 
02585   // If the function is marked "overloadable", it has a different mangled name
02586   // and is not the C library function.
02587   if (hasAttr<OverloadableAttr>())
02588     return 0;
02589 
02590   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
02591     return BuiltinID;
02592 
02593   // This function has the name of a known C library
02594   // function. Determine whether it actually refers to the C library
02595   // function or whether it just has the same name.
02596 
02597   // If this is a static function, it's not a builtin.
02598   if (getStorageClass() == SC_Static)
02599     return 0;
02600 
02601   return BuiltinID;
02602 }
02603 
02604 
02605 /// getNumParams - Return the number of parameters this function must have
02606 /// based on its FunctionType.  This is the length of the ParamInfo array
02607 /// after it has been created.
02608 unsigned FunctionDecl::getNumParams() const {
02609   const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
02610   return FPT ? FPT->getNumParams() : 0;
02611 }
02612 
02613 void FunctionDecl::setParams(ASTContext &C,
02614                              ArrayRef<ParmVarDecl *> NewParamInfo) {
02615   assert(!ParamInfo && "Already has param info!");
02616   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
02617 
02618   // Zero params -> null pointer.
02619   if (!NewParamInfo.empty()) {
02620     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
02621     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
02622   }
02623 }
02624 
02625 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
02626   assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
02627 
02628   if (!NewDecls.empty()) {
02629     NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
02630     std::copy(NewDecls.begin(), NewDecls.end(), A);
02631     DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
02632     // Move declarations introduced in prototype to the function context.
02633     for (auto I : NewDecls) {
02634       DeclContext *DC = I->getDeclContext();
02635       // Forward-declared reference to an enumeration is not added to
02636       // declaration scope, so skip declaration that is absent from its
02637       // declaration contexts.
02638       if (DC->containsDecl(I)) {
02639           DC->removeDecl(I);
02640           I->setDeclContext(this);
02641           addDecl(I);
02642       }
02643     }
02644   }
02645 }
02646 
02647 /// getMinRequiredArguments - Returns the minimum number of arguments
02648 /// needed to call this function. This may be fewer than the number of
02649 /// function parameters, if some of the parameters have default
02650 /// arguments (in C++) or are parameter packs (C++11).
02651 unsigned FunctionDecl::getMinRequiredArguments() const {
02652   if (!getASTContext().getLangOpts().CPlusPlus)
02653     return getNumParams();
02654 
02655   unsigned NumRequiredArgs = 0;
02656   for (auto *Param : params())
02657     if (!Param->isParameterPack() && !Param->hasDefaultArg())
02658       ++NumRequiredArgs;
02659   return NumRequiredArgs;
02660 }
02661 
02662 /// \brief The combination of the extern and inline keywords under MSVC forces
02663 /// the function to be required.
02664 ///
02665 /// Note: This function assumes that we will only get called when isInlined()
02666 /// would return true for this FunctionDecl.
02667 bool FunctionDecl::isMSExternInline() const {
02668   assert(isInlined() && "expected to get called on an inlined function!");
02669 
02670   const ASTContext &Context = getASTContext();
02671   if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
02672     return false;
02673 
02674   for (const FunctionDecl *FD = this; FD; FD = FD->getPreviousDecl())
02675     if (FD->getStorageClass() == SC_Extern)
02676       return true;
02677 
02678   return false;
02679 }
02680 
02681 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
02682   if (Redecl->getStorageClass() != SC_Extern)
02683     return false;
02684 
02685   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
02686        FD = FD->getPreviousDecl())
02687     if (FD->getStorageClass() == SC_Extern)
02688       return false;
02689 
02690   return true;
02691 }
02692 
02693 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
02694   // Only consider file-scope declarations in this test.
02695   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
02696     return false;
02697 
02698   // Only consider explicit declarations; the presence of a builtin for a
02699   // libcall shouldn't affect whether a definition is externally visible.
02700   if (Redecl->isImplicit())
02701     return false;
02702 
02703   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 
02704     return true; // Not an inline definition
02705 
02706   return false;
02707 }
02708 
02709 /// \brief For a function declaration in C or C++, determine whether this
02710 /// declaration causes the definition to be externally visible.
02711 ///
02712 /// For instance, this determines if adding the current declaration to the set
02713 /// of redeclarations of the given functions causes
02714 /// isInlineDefinitionExternallyVisible to change from false to true.
02715 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
02716   assert(!doesThisDeclarationHaveABody() &&
02717          "Must have a declaration without a body.");
02718 
02719   ASTContext &Context = getASTContext();
02720 
02721   if (Context.getLangOpts().MSVCCompat) {
02722     const FunctionDecl *Definition;
02723     if (hasBody(Definition) && Definition->isInlined() &&
02724         redeclForcesDefMSVC(this))
02725       return true;
02726   }
02727 
02728   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
02729     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
02730     // an externally visible definition.
02731     //
02732     // FIXME: What happens if gnu_inline gets added on after the first
02733     // declaration?
02734     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
02735       return false;
02736 
02737     const FunctionDecl *Prev = this;
02738     bool FoundBody = false;
02739     while ((Prev = Prev->getPreviousDecl())) {
02740       FoundBody |= Prev->Body.isValid();
02741 
02742       if (Prev->Body) {
02743         // If it's not the case that both 'inline' and 'extern' are
02744         // specified on the definition, then it is always externally visible.
02745         if (!Prev->isInlineSpecified() ||
02746             Prev->getStorageClass() != SC_Extern)
02747           return false;
02748       } else if (Prev->isInlineSpecified() && 
02749                  Prev->getStorageClass() != SC_Extern) {
02750         return false;
02751       }
02752     }
02753     return FoundBody;
02754   }
02755 
02756   if (Context.getLangOpts().CPlusPlus)
02757     return false;
02758 
02759   // C99 6.7.4p6:
02760   //   [...] If all of the file scope declarations for a function in a 
02761   //   translation unit include the inline function specifier without extern, 
02762   //   then the definition in that translation unit is an inline definition.
02763   if (isInlineSpecified() && getStorageClass() != SC_Extern)
02764     return false;
02765   const FunctionDecl *Prev = this;
02766   bool FoundBody = false;
02767   while ((Prev = Prev->getPreviousDecl())) {
02768     FoundBody |= Prev->Body.isValid();
02769     if (RedeclForcesDefC99(Prev))
02770       return false;
02771   }
02772   return FoundBody;
02773 }
02774 
02775 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
02776   const TypeSourceInfo *TSI = getTypeSourceInfo();
02777   if (!TSI)
02778     return SourceRange();
02779   FunctionTypeLoc FTL =
02780       TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
02781   if (!FTL)
02782     return SourceRange();
02783 
02784   // Skip self-referential return types.
02785   const SourceManager &SM = getASTContext().getSourceManager();
02786   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
02787   SourceLocation Boundary = getNameInfo().getLocStart();
02788   if (RTRange.isInvalid() || Boundary.isInvalid() ||
02789       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
02790     return SourceRange();
02791 
02792   return RTRange;
02793 }
02794 
02795 /// \brief For an inline function definition in C, or for a gnu_inline function
02796 /// in C++, determine whether the definition will be externally visible.
02797 ///
02798 /// Inline function definitions are always available for inlining optimizations.
02799 /// However, depending on the language dialect, declaration specifiers, and
02800 /// attributes, the definition of an inline function may or may not be
02801 /// "externally" visible to other translation units in the program.
02802 ///
02803 /// In C99, inline definitions are not externally visible by default. However,
02804 /// if even one of the global-scope declarations is marked "extern inline", the
02805 /// inline definition becomes externally visible (C99 6.7.4p6).
02806 ///
02807 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
02808 /// definition, we use the GNU semantics for inline, which are nearly the 
02809 /// opposite of C99 semantics. In particular, "inline" by itself will create 
02810 /// an externally visible symbol, but "extern inline" will not create an 
02811 /// externally visible symbol.
02812 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
02813   assert(doesThisDeclarationHaveABody() && "Must have the function definition");
02814   assert(isInlined() && "Function must be inline");
02815   ASTContext &Context = getASTContext();
02816   
02817   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
02818     // Note: If you change the logic here, please change
02819     // doesDeclarationForceExternallyVisibleDefinition as well.
02820     //
02821     // If it's not the case that both 'inline' and 'extern' are
02822     // specified on the definition, then this inline definition is
02823     // externally visible.
02824     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
02825       return true;
02826     
02827     // If any declaration is 'inline' but not 'extern', then this definition
02828     // is externally visible.
02829     for (auto Redecl : redecls()) {
02830       if (Redecl->isInlineSpecified() && 
02831           Redecl->getStorageClass() != SC_Extern)
02832         return true;
02833     }    
02834     
02835     return false;
02836   }
02837 
02838   // The rest of this function is C-only.
02839   assert(!Context.getLangOpts().CPlusPlus &&
02840          "should not use C inline rules in C++");
02841 
02842   // C99 6.7.4p6:
02843   //   [...] If all of the file scope declarations for a function in a 
02844   //   translation unit include the inline function specifier without extern, 
02845   //   then the definition in that translation unit is an inline definition.
02846   for (auto Redecl : redecls()) {
02847     if (RedeclForcesDefC99(Redecl))
02848       return true;
02849   }
02850   
02851   // C99 6.7.4p6:
02852   //   An inline definition does not provide an external definition for the 
02853   //   function, and does not forbid an external definition in another 
02854   //   translation unit.
02855   return false;
02856 }
02857 
02858 /// getOverloadedOperator - Which C++ overloaded operator this
02859 /// function represents, if any.
02860 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
02861   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
02862     return getDeclName().getCXXOverloadedOperator();
02863   else
02864     return OO_None;
02865 }
02866 
02867 /// getLiteralIdentifier - The literal suffix identifier this function
02868 /// represents, if any.
02869 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
02870   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
02871     return getDeclName().getCXXLiteralIdentifier();
02872   else
02873     return nullptr;
02874 }
02875 
02876 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
02877   if (TemplateOrSpecialization.isNull())
02878     return TK_NonTemplate;
02879   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
02880     return TK_FunctionTemplate;
02881   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
02882     return TK_MemberSpecialization;
02883   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
02884     return TK_FunctionTemplateSpecialization;
02885   if (TemplateOrSpecialization.is
02886                                <DependentFunctionTemplateSpecializationInfo*>())
02887     return TK_DependentFunctionTemplateSpecialization;
02888 
02889   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
02890 }
02891 
02892 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
02893   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
02894     return cast<FunctionDecl>(Info->getInstantiatedFrom());
02895 
02896   return nullptr;
02897 }
02898 
02899 void 
02900 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
02901                                                FunctionDecl *FD,
02902                                                TemplateSpecializationKind TSK) {
02903   assert(TemplateOrSpecialization.isNull() && 
02904          "Member function is already a specialization");
02905   MemberSpecializationInfo *Info 
02906     = new (C) MemberSpecializationInfo(FD, TSK);
02907   TemplateOrSpecialization = Info;
02908 }
02909 
02910 bool FunctionDecl::isImplicitlyInstantiable() const {
02911   // If the function is invalid, it can't be implicitly instantiated.
02912   if (isInvalidDecl())
02913     return false;
02914   
02915   switch (getTemplateSpecializationKind()) {
02916   case TSK_Undeclared:
02917   case TSK_ExplicitInstantiationDefinition:
02918     return false;
02919       
02920   case TSK_ImplicitInstantiation:
02921     return true;
02922 
02923   // It is possible to instantiate TSK_ExplicitSpecialization kind
02924   // if the FunctionDecl has a class scope specialization pattern.
02925   case TSK_ExplicitSpecialization:
02926     return getClassScopeSpecializationPattern() != nullptr;
02927 
02928   case TSK_ExplicitInstantiationDeclaration:
02929     // Handled below.
02930     break;
02931   }
02932 
02933   // Find the actual template from which we will instantiate.
02934   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
02935   bool HasPattern = false;
02936   if (PatternDecl)
02937     HasPattern = PatternDecl->hasBody(PatternDecl);
02938   
02939   // C++0x [temp.explicit]p9:
02940   //   Except for inline functions, other explicit instantiation declarations
02941   //   have the effect of suppressing the implicit instantiation of the entity
02942   //   to which they refer. 
02943   if (!HasPattern || !PatternDecl) 
02944     return true;
02945 
02946   return PatternDecl->isInlined();
02947 }
02948 
02949 bool FunctionDecl::isTemplateInstantiation() const {
02950   switch (getTemplateSpecializationKind()) {
02951     case TSK_Undeclared:
02952     case TSK_ExplicitSpecialization:
02953       return false;      
02954     case TSK_ImplicitInstantiation:
02955     case TSK_ExplicitInstantiationDeclaration:
02956     case TSK_ExplicitInstantiationDefinition:
02957       return true;
02958   }
02959   llvm_unreachable("All TSK values handled.");
02960 }
02961    
02962 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
02963   // Handle class scope explicit specialization special case.
02964   if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
02965     return getClassScopeSpecializationPattern();
02966   
02967   // If this is a generic lambda call operator specialization, its 
02968   // instantiation pattern is always its primary template's pattern
02969   // even if its primary template was instantiated from another 
02970   // member template (which happens with nested generic lambdas).
02971   // Since a lambda's call operator's body is transformed eagerly, 
02972   // we don't have to go hunting for a prototype definition template 
02973   // (i.e. instantiated-from-member-template) to use as an instantiation 
02974   // pattern.
02975 
02976   if (isGenericLambdaCallOperatorSpecialization(
02977           dyn_cast<CXXMethodDecl>(this))) {
02978     assert(getPrimaryTemplate() && "A generic lambda specialization must be "
02979                                    "generated from a primary call operator "
02980                                    "template");
02981     assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
02982            "A generic lambda call operator template must always have a body - "
02983            "even if instantiated from a prototype (i.e. as written) member "
02984            "template");
02985     return getPrimaryTemplate()->getTemplatedDecl();
02986   }
02987   
02988   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
02989     while (Primary->getInstantiatedFromMemberTemplate()) {
02990       // If we have hit a point where the user provided a specialization of
02991       // this template, we're done looking.
02992       if (Primary->isMemberSpecialization())
02993         break;
02994       Primary = Primary->getInstantiatedFromMemberTemplate();
02995     }
02996     
02997     return Primary->getTemplatedDecl();
02998   } 
02999     
03000   return getInstantiatedFromMemberFunction();
03001 }
03002 
03003 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
03004   if (FunctionTemplateSpecializationInfo *Info
03005         = TemplateOrSpecialization
03006             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
03007     return Info->Template.getPointer();
03008   }
03009   return nullptr;
03010 }
03011 
03012 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
03013     return getASTContext().getClassScopeSpecializationPattern(this);
03014 }
03015 
03016 const TemplateArgumentList *
03017 FunctionDecl::getTemplateSpecializationArgs() const {
03018   if (FunctionTemplateSpecializationInfo *Info
03019         = TemplateOrSpecialization
03020             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
03021     return Info->TemplateArguments;
03022   }
03023   return nullptr;
03024 }
03025 
03026 const ASTTemplateArgumentListInfo *
03027 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
03028   if (FunctionTemplateSpecializationInfo *Info
03029         = TemplateOrSpecialization
03030             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
03031     return Info->TemplateArgumentsAsWritten;
03032   }
03033   return nullptr;
03034 }
03035 
03036 void
03037 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
03038                                                 FunctionTemplateDecl *Template,
03039                                      const TemplateArgumentList *TemplateArgs,
03040                                                 void *InsertPos,
03041                                                 TemplateSpecializationKind TSK,
03042                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
03043                                           SourceLocation PointOfInstantiation) {
03044   assert(TSK != TSK_Undeclared && 
03045          "Must specify the type of function template specialization");
03046   FunctionTemplateSpecializationInfo *Info
03047     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
03048   if (!Info)
03049     Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
03050                                                       TemplateArgs,
03051                                                       TemplateArgsAsWritten,
03052                                                       PointOfInstantiation);
03053   TemplateOrSpecialization = Info;
03054   Template->addSpecialization(Info, InsertPos);
03055 }
03056 
03057 void
03058 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
03059                                     const UnresolvedSetImpl &Templates,
03060                              const TemplateArgumentListInfo &TemplateArgs) {
03061   assert(TemplateOrSpecialization.isNull());
03062   size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
03063   Size += Templates.size() * sizeof(FunctionTemplateDecl*);
03064   Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
03065   void *Buffer = Context.Allocate(Size);
03066   DependentFunctionTemplateSpecializationInfo *Info =
03067     new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
03068                                                              TemplateArgs);
03069   TemplateOrSpecialization = Info;
03070 }
03071 
03072 DependentFunctionTemplateSpecializationInfo::
03073 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
03074                                       const TemplateArgumentListInfo &TArgs)
03075   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
03076 
03077   d.NumTemplates = Ts.size();
03078   d.NumArgs = TArgs.size();
03079 
03080   FunctionTemplateDecl **TsArray =
03081     const_cast<FunctionTemplateDecl**>(getTemplates());
03082   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
03083     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
03084 
03085   TemplateArgumentLoc *ArgsArray =
03086     const_cast<TemplateArgumentLoc*>(getTemplateArgs());
03087   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
03088     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
03089 }
03090 
03091 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
03092   // For a function template specialization, query the specialization
03093   // information object.
03094   FunctionTemplateSpecializationInfo *FTSInfo
03095     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
03096   if (FTSInfo)
03097     return FTSInfo->getTemplateSpecializationKind();
03098 
03099   MemberSpecializationInfo *MSInfo
03100     = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
03101   if (MSInfo)
03102     return MSInfo->getTemplateSpecializationKind();
03103   
03104   return TSK_Undeclared;
03105 }
03106 
03107 void
03108 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
03109                                           SourceLocation PointOfInstantiation) {
03110   if (FunctionTemplateSpecializationInfo *FTSInfo
03111         = TemplateOrSpecialization.dyn_cast<
03112                                     FunctionTemplateSpecializationInfo*>()) {
03113     FTSInfo->setTemplateSpecializationKind(TSK);
03114     if (TSK != TSK_ExplicitSpecialization &&
03115         PointOfInstantiation.isValid() &&
03116         FTSInfo->getPointOfInstantiation().isInvalid())
03117       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
03118   } else if (MemberSpecializationInfo *MSInfo
03119              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
03120     MSInfo->setTemplateSpecializationKind(TSK);
03121     if (TSK != TSK_ExplicitSpecialization &&
03122         PointOfInstantiation.isValid() &&
03123         MSInfo->getPointOfInstantiation().isInvalid())
03124       MSInfo->setPointOfInstantiation(PointOfInstantiation);
03125   } else
03126     llvm_unreachable("Function cannot have a template specialization kind");
03127 }
03128 
03129 SourceLocation FunctionDecl::getPointOfInstantiation() const {
03130   if (FunctionTemplateSpecializationInfo *FTSInfo
03131         = TemplateOrSpecialization.dyn_cast<
03132                                         FunctionTemplateSpecializationInfo*>())
03133     return FTSInfo->getPointOfInstantiation();
03134   else if (MemberSpecializationInfo *MSInfo
03135              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
03136     return MSInfo->getPointOfInstantiation();
03137   
03138   return SourceLocation();
03139 }
03140 
03141 bool FunctionDecl::isOutOfLine() const {
03142   if (Decl::isOutOfLine())
03143     return true;
03144   
03145   // If this function was instantiated from a member function of a 
03146   // class template, check whether that member function was defined out-of-line.
03147   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
03148     const FunctionDecl *Definition;
03149     if (FD->hasBody(Definition))
03150       return Definition->isOutOfLine();
03151   }
03152   
03153   // If this function was instantiated from a function template,
03154   // check whether that function template was defined out-of-line.
03155   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
03156     const FunctionDecl *Definition;
03157     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
03158       return Definition->isOutOfLine();
03159   }
03160   
03161   return false;
03162 }
03163 
03164 SourceRange FunctionDecl::getSourceRange() const {
03165   return SourceRange(getOuterLocStart(), EndRangeLoc);
03166 }
03167 
03168 unsigned FunctionDecl::getMemoryFunctionKind() const {
03169   IdentifierInfo *FnInfo = getIdentifier();
03170 
03171   if (!FnInfo)
03172     return 0;
03173     
03174   // Builtin handling.
03175   switch (getBuiltinID()) {
03176   case Builtin::BI__builtin_memset:
03177   case Builtin::BI__builtin___memset_chk:
03178   case Builtin::BImemset:
03179     return Builtin::BImemset;
03180 
03181   case Builtin::BI__builtin_memcpy:
03182   case Builtin::BI__builtin___memcpy_chk:
03183   case Builtin::BImemcpy:
03184     return Builtin::BImemcpy;
03185 
03186   case Builtin::BI__builtin_memmove:
03187   case Builtin::BI__builtin___memmove_chk:
03188   case Builtin::BImemmove:
03189     return Builtin::BImemmove;
03190 
03191   case Builtin::BIstrlcpy:
03192   case Builtin::BI__builtin___strlcpy_chk:
03193     return Builtin::BIstrlcpy;
03194 
03195   case Builtin::BIstrlcat:
03196   case Builtin::BI__builtin___strlcat_chk:
03197     return Builtin::BIstrlcat;
03198 
03199   case Builtin::BI__builtin_memcmp:
03200   case Builtin::BImemcmp:
03201     return Builtin::BImemcmp;
03202 
03203   case Builtin::BI__builtin_strncpy:
03204   case Builtin::BI__builtin___strncpy_chk:
03205   case Builtin::BIstrncpy:
03206     return Builtin::BIstrncpy;
03207 
03208   case Builtin::BI__builtin_strncmp:
03209   case Builtin::BIstrncmp:
03210     return Builtin::BIstrncmp;
03211 
03212   case Builtin::BI__builtin_strncasecmp:
03213   case Builtin::BIstrncasecmp:
03214     return Builtin::BIstrncasecmp;
03215 
03216   case Builtin::BI__builtin_strncat:
03217   case Builtin::BI__builtin___strncat_chk:
03218   case Builtin::BIstrncat:
03219     return Builtin::BIstrncat;
03220 
03221   case Builtin::BI__builtin_strndup:
03222   case Builtin::BIstrndup:
03223     return Builtin::BIstrndup;
03224 
03225   case Builtin::BI__builtin_strlen:
03226   case Builtin::BIstrlen:
03227     return Builtin::BIstrlen;
03228 
03229   default:
03230     if (isExternC()) {
03231       if (FnInfo->isStr("memset"))
03232         return Builtin::BImemset;
03233       else if (FnInfo->isStr("memcpy"))
03234         return Builtin::BImemcpy;
03235       else if (FnInfo->isStr("memmove"))
03236         return Builtin::BImemmove;
03237       else if (FnInfo->isStr("memcmp"))
03238         return Builtin::BImemcmp;
03239       else if (FnInfo->isStr("strncpy"))
03240         return Builtin::BIstrncpy;
03241       else if (FnInfo->isStr("strncmp"))
03242         return Builtin::BIstrncmp;
03243       else if (FnInfo->isStr("strncasecmp"))
03244         return Builtin::BIstrncasecmp;
03245       else if (FnInfo->isStr("strncat"))
03246         return Builtin::BIstrncat;
03247       else if (FnInfo->isStr("strndup"))
03248         return Builtin::BIstrndup;
03249       else if (FnInfo->isStr("strlen"))
03250         return Builtin::BIstrlen;
03251     }
03252     break;
03253   }
03254   return 0;
03255 }
03256 
03257 //===----------------------------------------------------------------------===//
03258 // FieldDecl Implementation
03259 //===----------------------------------------------------------------------===//
03260 
03261 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
03262                              SourceLocation StartLoc, SourceLocation IdLoc,
03263                              IdentifierInfo *Id, QualType T,
03264                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
03265                              InClassInitStyle InitStyle) {
03266   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
03267                                BW, Mutable, InitStyle);
03268 }
03269 
03270 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
03271   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
03272                                SourceLocation(), nullptr, QualType(), nullptr,
03273                                nullptr, false, ICIS_NoInit);
03274 }
03275 
03276 bool FieldDecl::isAnonymousStructOrUnion() const {
03277   if (!isImplicit() || getDeclName())
03278     return false;
03279 
03280   if (const RecordType *Record = getType()->getAs<RecordType>())
03281     return Record->getDecl()->isAnonymousStructOrUnion();
03282 
03283   return false;
03284 }
03285 
03286 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
03287   assert(isBitField() && "not a bitfield");
03288   Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
03289   return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
03290 }
03291 
03292 unsigned FieldDecl::getFieldIndex() const {
03293   const FieldDecl *Canonical = getCanonicalDecl();
03294   if (Canonical != this)
03295     return Canonical->getFieldIndex();
03296 
03297   if (CachedFieldIndex) return CachedFieldIndex - 1;
03298 
03299   unsigned Index = 0;
03300   const RecordDecl *RD = getParent();
03301 
03302   for (auto *Field : RD->fields()) {
03303     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
03304     ++Index;
03305   }
03306 
03307   assert(CachedFieldIndex && "failed to find field in parent");
03308   return CachedFieldIndex - 1;
03309 }
03310 
03311 SourceRange FieldDecl::getSourceRange() const {
03312   switch (InitStorage.getInt()) {
03313   // All three of these cases store an optional Expr*.
03314   case ISK_BitWidthOrNothing:
03315   case ISK_InClassCopyInit:
03316   case ISK_InClassListInit:
03317     if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer()))
03318       return SourceRange(getInnerLocStart(), E->getLocEnd());
03319     // FALLTHROUGH
03320 
03321   case ISK_CapturedVLAType:
03322     return DeclaratorDecl::getSourceRange();
03323   }
03324   llvm_unreachable("bad init storage kind");
03325 }
03326 
03327 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
03328   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
03329          "capturing type in non-lambda or captured record.");
03330   assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
03331          InitStorage.getPointer() == nullptr &&
03332          "bit width, initializer or captured type already set");
03333   InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
03334                                ISK_CapturedVLAType);
03335 }
03336 
03337 //===----------------------------------------------------------------------===//
03338 // TagDecl Implementation
03339 //===----------------------------------------------------------------------===//
03340 
03341 SourceLocation TagDecl::getOuterLocStart() const {
03342   return getTemplateOrInnerLocStart(this);
03343 }
03344 
03345 SourceRange TagDecl::getSourceRange() const {
03346   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
03347   return SourceRange(getOuterLocStart(), E);
03348 }
03349 
03350 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
03351 
03352 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
03353   NamedDeclOrQualifier = TDD;
03354   if (const Type *T = getTypeForDecl()) {
03355     (void)T;
03356     assert(T->isLinkageValid());
03357   }
03358   assert(isLinkageValid());
03359 }
03360 
03361 void TagDecl::startDefinition() {
03362   IsBeingDefined = true;
03363 
03364   if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
03365     struct CXXRecordDecl::DefinitionData *Data =
03366       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
03367     for (auto I : redecls())
03368       cast<CXXRecordDecl>(I)->DefinitionData = Data;
03369   }
03370 }
03371 
03372 void TagDecl::completeDefinition() {
03373   assert((!isa<CXXRecordDecl>(this) ||
03374           cast<CXXRecordDecl>(this)->hasDefinition()) &&
03375          "definition completed but not started");
03376 
03377   IsCompleteDefinition = true;
03378   IsBeingDefined = false;
03379 
03380   if (ASTMutationListener *L = getASTMutationListener())
03381     L->CompletedTagDefinition(this);
03382 }
03383 
03384 TagDecl *TagDecl::getDefinition() const {
03385   if (isCompleteDefinition())
03386     return const_cast<TagDecl *>(this);
03387 
03388   // If it's possible for us to have an out-of-date definition, check now.
03389   if (MayHaveOutOfDateDef) {
03390     if (IdentifierInfo *II = getIdentifier()) {
03391       if (II->isOutOfDate()) {
03392         updateOutOfDate(*II);
03393       }
03394     }
03395   }
03396 
03397   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
03398     return CXXRD->getDefinition();
03399 
03400   for (auto R : redecls())
03401     if (R->isCompleteDefinition())
03402       return R;
03403 
03404   return nullptr;
03405 }
03406 
03407 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
03408   if (QualifierLoc) {
03409     // Make sure the extended qualifier info is allocated.
03410     if (!hasExtInfo())
03411       NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
03412     // Set qualifier info.
03413     getExtInfo()->QualifierLoc = QualifierLoc;
03414   } else {
03415     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
03416     if (hasExtInfo()) {
03417       if (getExtInfo()->NumTemplParamLists == 0) {
03418         getASTContext().Deallocate(getExtInfo());
03419         NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
03420       }
03421       else
03422         getExtInfo()->QualifierLoc = QualifierLoc;
03423     }
03424   }
03425 }
03426 
03427 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
03428                                             unsigned NumTPLists,
03429                                             TemplateParameterList **TPLists) {
03430   assert(NumTPLists > 0);
03431   // Make sure the extended decl info is allocated.
03432   if (!hasExtInfo())
03433     // Allocate external info struct.
03434     NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
03435   // Set the template parameter lists info.
03436   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
03437 }
03438 
03439 //===----------------------------------------------------------------------===//
03440 // EnumDecl Implementation
03441 //===----------------------------------------------------------------------===//
03442 
03443 void EnumDecl::anchor() { }
03444 
03445 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
03446                            SourceLocation StartLoc, SourceLocation IdLoc,
03447                            IdentifierInfo *Id,
03448                            EnumDecl *PrevDecl, bool IsScoped,
03449                            bool IsScopedUsingClassTag, bool IsFixed) {
03450   EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
03451                                         IsScoped, IsScopedUsingClassTag,
03452                                         IsFixed);
03453   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
03454   C.getTypeDeclType(Enum, PrevDecl);
03455   return Enum;
03456 }
03457 
03458 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
03459   EnumDecl *Enum =
03460       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
03461                            nullptr, nullptr, false, false, false);
03462   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
03463   return Enum;
03464 }
03465 
03466 SourceRange EnumDecl::getIntegerTypeRange() const {
03467   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
03468     return TI->getTypeLoc().getSourceRange();
03469   return SourceRange();
03470 }
03471 
03472 void EnumDecl::completeDefinition(QualType NewType,
03473                                   QualType NewPromotionType,
03474                                   unsigned NumPositiveBits,
03475                                   unsigned NumNegativeBits) {
03476   assert(!isCompleteDefinition() && "Cannot redefine enums!");
03477   if (!IntegerType)
03478     IntegerType = NewType.getTypePtr();
03479   PromotionType = NewPromotionType;
03480   setNumPositiveBits(NumPositiveBits);
03481   setNumNegativeBits(NumNegativeBits);
03482   TagDecl::completeDefinition();
03483 }
03484 
03485 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
03486   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
03487     return MSI->getTemplateSpecializationKind();
03488 
03489   return TSK_Undeclared;
03490 }
03491 
03492 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
03493                                          SourceLocation PointOfInstantiation) {
03494   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
03495   assert(MSI && "Not an instantiated member enumeration?");
03496   MSI->setTemplateSpecializationKind(TSK);
03497   if (TSK != TSK_ExplicitSpecialization &&
03498       PointOfInstantiation.isValid() &&
03499       MSI->getPointOfInstantiation().isInvalid())
03500     MSI->setPointOfInstantiation(PointOfInstantiation);
03501 }
03502 
03503 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
03504   if (SpecializationInfo)
03505     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
03506 
03507   return nullptr;
03508 }
03509 
03510 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
03511                                             TemplateSpecializationKind TSK) {
03512   assert(!SpecializationInfo && "Member enum is already a specialization");
03513   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
03514 }
03515 
03516 //===----------------------------------------------------------------------===//
03517 // RecordDecl Implementation
03518 //===----------------------------------------------------------------------===//
03519 
03520 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
03521                        DeclContext *DC, SourceLocation StartLoc,
03522                        SourceLocation IdLoc, IdentifierInfo *Id,
03523                        RecordDecl *PrevDecl)
03524     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
03525   HasFlexibleArrayMember = false;
03526   AnonymousStructOrUnion = false;
03527   HasObjectMember = false;
03528   HasVolatileMember = false;
03529   LoadedFieldsFromExternalStorage = false;
03530   assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
03531 }
03532 
03533 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
03534                                SourceLocation StartLoc, SourceLocation IdLoc,
03535                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
03536   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
03537                                          StartLoc, IdLoc, Id, PrevDecl);
03538   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
03539 
03540   C.getTypeDeclType(R, PrevDecl);
03541   return R;
03542 }
03543 
03544 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
03545   RecordDecl *R =
03546       new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
03547                              SourceLocation(), nullptr, nullptr);
03548   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
03549   return R;
03550 }
03551 
03552 bool RecordDecl::isInjectedClassName() const {
03553   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
03554     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
03555 }
03556 
03557 bool RecordDecl::isLambda() const {
03558   if (auto RD = dyn_cast<CXXRecordDecl>(this))
03559     return RD->isLambda();
03560   return false;
03561 }
03562 
03563 bool RecordDecl::isCapturedRecord() const {
03564   return hasAttr<CapturedRecordAttr>();
03565 }
03566 
03567 void RecordDecl::setCapturedRecord() {
03568   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
03569 }
03570 
03571 RecordDecl::field_iterator RecordDecl::field_begin() const {
03572   if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
03573     LoadFieldsFromExternalStorage();
03574 
03575   return field_iterator(decl_iterator(FirstDecl));
03576 }
03577 
03578 /// completeDefinition - Notes that the definition of this type is now
03579 /// complete.
03580 void RecordDecl::completeDefinition() {
03581   assert(!isCompleteDefinition() && "Cannot redefine record!");
03582   TagDecl::completeDefinition();
03583 }
03584 
03585 /// isMsStruct - Get whether or not this record uses ms_struct layout.
03586 /// This which can be turned on with an attribute, pragma, or the
03587 /// -mms-bitfields command-line option.
03588 bool RecordDecl::isMsStruct(const ASTContext &C) const {
03589   return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
03590 }
03591 
03592 static bool isFieldOrIndirectField(Decl::Kind K) {
03593   return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
03594 }
03595 
03596 void RecordDecl::LoadFieldsFromExternalStorage() const {
03597   ExternalASTSource *Source = getASTContext().getExternalSource();
03598   assert(hasExternalLexicalStorage() && Source && "No external storage?");
03599 
03600   // Notify that we have a RecordDecl doing some initialization.
03601   ExternalASTSource::Deserializing TheFields(Source);
03602 
03603   SmallVector<Decl*, 64> Decls;
03604   LoadedFieldsFromExternalStorage = true;  
03605   switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
03606                                            Decls)) {
03607   case ELR_Success:
03608     break;
03609     
03610   case ELR_AlreadyLoaded:
03611   case ELR_Failure:
03612     return;
03613   }
03614 
03615 #ifndef NDEBUG
03616   // Check that all decls we got were FieldDecls.
03617   for (unsigned i=0, e=Decls.size(); i != e; ++i)
03618     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
03619 #endif
03620 
03621   if (Decls.empty())
03622     return;
03623 
03624   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
03625                                                  /*FieldsAlreadyLoaded=*/false);
03626 }
03627 
03628 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
03629   ASTContext &Context = getASTContext();
03630   if (!Context.getLangOpts().Sanitize.has(SanitizerKind::Address) ||
03631       !Context.getLangOpts().SanitizeAddressFieldPadding)
03632     return false;
03633   const auto &Blacklist = Context.getSanitizerBlacklist();
03634   const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this);
03635   // We may be able to relax some of these requirements.
03636   int ReasonToReject = -1;
03637   if (!CXXRD || CXXRD->isExternCContext())
03638     ReasonToReject = 0;  // is not C++.
03639   else if (CXXRD->hasAttr<PackedAttr>())
03640     ReasonToReject = 1;  // is packed.
03641   else if (CXXRD->isUnion())
03642     ReasonToReject = 2;  // is a union.
03643   else if (CXXRD->isTriviallyCopyable())
03644     ReasonToReject = 3;  // is trivially copyable.
03645   else if (CXXRD->hasTrivialDestructor())
03646     ReasonToReject = 4;  // has trivial destructor.
03647   else if (CXXRD->isStandardLayout())
03648     ReasonToReject = 5;  // is standard layout.
03649   else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
03650     ReasonToReject = 6;  // is in a blacklisted file.
03651   else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
03652                                        "field-padding"))
03653     ReasonToReject = 7;  // is blacklisted.
03654 
03655   if (EmitRemark) {
03656     if (ReasonToReject >= 0)
03657       Context.getDiagnostics().Report(
03658           getLocation(),
03659           diag::remark_sanitize_address_insert_extra_padding_rejected)
03660           << getQualifiedNameAsString() << ReasonToReject;
03661     else
03662       Context.getDiagnostics().Report(
03663           getLocation(),
03664           diag::remark_sanitize_address_insert_extra_padding_accepted)
03665           << getQualifiedNameAsString();
03666   }
03667   return ReasonToReject < 0;
03668 }
03669 
03670 //===----------------------------------------------------------------------===//
03671 // BlockDecl Implementation
03672 //===----------------------------------------------------------------------===//
03673 
03674 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
03675   assert(!ParamInfo && "Already has param info!");
03676 
03677   // Zero params -> null pointer.
03678   if (!NewParamInfo.empty()) {
03679     NumParams = NewParamInfo.size();
03680     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
03681     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
03682   }
03683 }
03684 
03685 void BlockDecl::setCaptures(ASTContext &Context,
03686                             const Capture *begin,
03687                             const Capture *end,
03688                             bool capturesCXXThis) {
03689   CapturesCXXThis = capturesCXXThis;
03690 
03691   if (begin == end) {
03692     NumCaptures = 0;
03693     Captures = nullptr;
03694     return;
03695   }
03696 
03697   NumCaptures = end - begin;
03698 
03699   // Avoid new Capture[] because we don't want to provide a default
03700   // constructor.
03701   size_t allocationSize = NumCaptures * sizeof(Capture);
03702   void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
03703   memcpy(buffer, begin, allocationSize);
03704   Captures = static_cast<Capture*>(buffer);
03705 }
03706 
03707 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
03708   for (const auto &I : captures())
03709     // Only auto vars can be captured, so no redeclaration worries.
03710     if (I.getVariable() == variable)
03711       return true;
03712 
03713   return false;
03714 }
03715 
03716 SourceRange BlockDecl::getSourceRange() const {
03717   return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
03718 }
03719 
03720 //===----------------------------------------------------------------------===//
03721 // Other Decl Allocation/Deallocation Method Implementations
03722 //===----------------------------------------------------------------------===//
03723 
03724 void TranslationUnitDecl::anchor() { }
03725 
03726 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
03727   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
03728 }
03729 
03730 void LabelDecl::anchor() { }
03731 
03732 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
03733                              SourceLocation IdentL, IdentifierInfo *II) {
03734   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
03735 }
03736 
03737 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
03738                              SourceLocation IdentL, IdentifierInfo *II,
03739                              SourceLocation GnuLabelL) {
03740   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
03741   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
03742 }
03743 
03744 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
03745   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
03746                                SourceLocation());
03747 }
03748 
03749 void LabelDecl::setMSAsmLabel(StringRef Name) {
03750   char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
03751   memcpy(Buffer, Name.data(), Name.size());
03752   Buffer[Name.size()] = '\0';
03753   MSAsmName = Buffer;
03754 }
03755 
03756 void ValueDecl::anchor() { }
03757 
03758 bool ValueDecl::isWeak() const {
03759   for (const auto *I : attrs())
03760     if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
03761       return true;
03762 
03763   return isWeakImported();
03764 }
03765 
03766 void ImplicitParamDecl::anchor() { }
03767 
03768 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
03769                                              SourceLocation IdLoc,
03770                                              IdentifierInfo *Id,
03771                                              QualType Type) {
03772   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
03773 }
03774 
03775 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
03776                                                          unsigned ID) {
03777   return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
03778                                        QualType());
03779 }
03780 
03781 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
03782                                    SourceLocation StartLoc,
03783                                    const DeclarationNameInfo &NameInfo,
03784                                    QualType T, TypeSourceInfo *TInfo,
03785                                    StorageClass SC,
03786                                    bool isInlineSpecified,
03787                                    bool hasWrittenPrototype,
03788                                    bool isConstexprSpecified) {
03789   FunctionDecl *New =
03790       new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
03791                                SC, isInlineSpecified, isConstexprSpecified);
03792   New->HasWrittenPrototype = hasWrittenPrototype;
03793   return New;
03794 }
03795 
03796 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
03797   return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
03798                                   DeclarationNameInfo(), QualType(), nullptr,
03799                                   SC_None, false, false);
03800 }
03801 
03802 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
03803   return new (C, DC) BlockDecl(DC, L);
03804 }
03805 
03806 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
03807   return new (C, ID) BlockDecl(nullptr, SourceLocation());
03808 }
03809 
03810 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
03811                                    unsigned NumParams) {
03812   return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
03813       CapturedDecl(DC, NumParams);
03814 }
03815 
03816 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
03817                                                unsigned NumParams) {
03818   return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
03819       CapturedDecl(nullptr, NumParams);
03820 }
03821 
03822 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
03823                                            SourceLocation L,
03824                                            IdentifierInfo *Id, QualType T,
03825                                            Expr *E, const llvm::APSInt &V) {
03826   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
03827 }
03828 
03829 EnumConstantDecl *
03830 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
03831   return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
03832                                       QualType(), nullptr, llvm::APSInt());
03833 }
03834 
03835 void IndirectFieldDecl::anchor() { }
03836 
03837 IndirectFieldDecl *
03838 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
03839                           IdentifierInfo *Id, QualType T, NamedDecl **CH,
03840                           unsigned CHS) {
03841   return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
03842 }
03843 
03844 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
03845                                                          unsigned ID) {
03846   return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
03847                                        DeclarationName(), QualType(), nullptr,
03848                                        0);
03849 }
03850 
03851 SourceRange EnumConstantDecl::getSourceRange() const {
03852   SourceLocation End = getLocation();
03853   if (Init)
03854     End = Init->getLocEnd();
03855   return SourceRange(getLocation(), End);
03856 }
03857 
03858 void TypeDecl::anchor() { }
03859 
03860 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
03861                                  SourceLocation StartLoc, SourceLocation IdLoc,
03862                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
03863   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
03864 }
03865 
03866 void TypedefNameDecl::anchor() { }
03867 
03868 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
03869   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
03870                                  nullptr, nullptr);
03871 }
03872 
03873 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
03874                                      SourceLocation StartLoc,
03875                                      SourceLocation IdLoc, IdentifierInfo *Id,
03876                                      TypeSourceInfo *TInfo) {
03877   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
03878 }
03879 
03880 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
03881   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
03882                                    SourceLocation(), nullptr, nullptr);
03883 }
03884 
03885 SourceRange TypedefDecl::getSourceRange() const {
03886   SourceLocation RangeEnd = getLocation();
03887   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
03888     if (typeIsPostfix(TInfo->getType()))
03889       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
03890   }
03891   return SourceRange(getLocStart(), RangeEnd);
03892 }
03893 
03894 SourceRange TypeAliasDecl::getSourceRange() const {
03895   SourceLocation RangeEnd = getLocStart();
03896   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
03897     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
03898   return SourceRange(getLocStart(), RangeEnd);
03899 }
03900 
03901 void FileScopeAsmDecl::anchor() { }
03902 
03903 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
03904                                            StringLiteral *Str,
03905                                            SourceLocation AsmLoc,
03906                                            SourceLocation RParenLoc) {
03907   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
03908 }
03909 
03910 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
03911                                                        unsigned ID) {
03912   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
03913                                       SourceLocation());
03914 }
03915 
03916 void EmptyDecl::anchor() {}
03917 
03918 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
03919   return new (C, DC) EmptyDecl(DC, L);
03920 }
03921 
03922 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
03923   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
03924 }
03925 
03926 //===----------------------------------------------------------------------===//
03927 // ImportDecl Implementation
03928 //===----------------------------------------------------------------------===//
03929 
03930 /// \brief Retrieve the number of module identifiers needed to name the given
03931 /// module.
03932 static unsigned getNumModuleIdentifiers(Module *Mod) {
03933   unsigned Result = 1;
03934   while (Mod->Parent) {
03935     Mod = Mod->Parent;
03936     ++Result;
03937   }
03938   return Result;
03939 }
03940 
03941 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 
03942                        Module *Imported,
03943                        ArrayRef<SourceLocation> IdentifierLocs)
03944   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
03945     NextLocalImport()
03946 {
03947   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
03948   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
03949   memcpy(StoredLocs, IdentifierLocs.data(), 
03950          IdentifierLocs.size() * sizeof(SourceLocation));
03951 }
03952 
03953 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 
03954                        Module *Imported, SourceLocation EndLoc)
03955   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
03956     NextLocalImport()
03957 {
03958   *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
03959 }
03960 
03961 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
03962                                SourceLocation StartLoc, Module *Imported,
03963                                ArrayRef<SourceLocation> IdentifierLocs) {
03964   return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
03965       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
03966 }
03967 
03968 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
03969                                        SourceLocation StartLoc,
03970                                        Module *Imported,
03971                                        SourceLocation EndLoc) {
03972   ImportDecl *Import =
03973       new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
03974                                                      Imported, EndLoc);
03975   Import->setImplicit();
03976   return Import;
03977 }
03978 
03979 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
03980                                            unsigned NumLocations) {
03981   return new (C, ID, NumLocations * sizeof(SourceLocation))
03982       ImportDecl(EmptyShell());
03983 }
03984 
03985 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
03986   if (!ImportedAndComplete.getInt())
03987     return None;
03988 
03989   const SourceLocation *StoredLocs
03990     = reinterpret_cast<const SourceLocation *>(this + 1);
03991   return llvm::makeArrayRef(StoredLocs,
03992                             getNumModuleIdentifiers(getImportedModule()));
03993 }
03994 
03995 SourceRange ImportDecl::getSourceRange() const {
03996   if (!ImportedAndComplete.getInt())
03997     return SourceRange(getLocation(), 
03998                        *reinterpret_cast<const SourceLocation *>(this + 1));
03999   
04000   return SourceRange(getLocation(), getIdentifierLocs().back());
04001 }