Home | History | Annotate | Download | only in Sema
      1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file implements semantic analysis for declarations.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Sema/SemaInternal.h"
     15 #include "TypeLocBuilder.h"
     16 #include "clang/AST/ASTConsumer.h"
     17 #include "clang/AST/ASTContext.h"
     18 #include "clang/AST/ASTLambda.h"
     19 #include "clang/AST/CXXInheritance.h"
     20 #include "clang/AST/CharUnits.h"
     21 #include "clang/AST/CommentDiagnostic.h"
     22 #include "clang/AST/DeclCXX.h"
     23 #include "clang/AST/DeclObjC.h"
     24 #include "clang/AST/DeclTemplate.h"
     25 #include "clang/AST/EvaluatedExprVisitor.h"
     26 #include "clang/AST/ExprCXX.h"
     27 #include "clang/AST/StmtCXX.h"
     28 #include "clang/Basic/Builtins.h"
     29 #include "clang/Basic/PartialDiagnostic.h"
     30 #include "clang/Basic/SourceManager.h"
     31 #include "clang/Basic/TargetInfo.h"
     32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
     33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
     34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
     35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
     36 #include "clang/Sema/CXXFieldCollector.h"
     37 #include "clang/Sema/DeclSpec.h"
     38 #include "clang/Sema/DelayedDiagnostic.h"
     39 #include "clang/Sema/Initialization.h"
     40 #include "clang/Sema/Lookup.h"
     41 #include "clang/Sema/ParsedTemplate.h"
     42 #include "clang/Sema/Scope.h"
     43 #include "clang/Sema/ScopeInfo.h"
     44 #include "clang/Sema/Template.h"
     45 #include "llvm/ADT/SmallString.h"
     46 #include "llvm/ADT/Triple.h"
     47 #include <algorithm>
     48 #include <cstring>
     49 #include <functional>
     50 using namespace clang;
     51 using namespace sema;
     52 
     53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
     54   if (OwnedType) {
     55     Decl *Group[2] = { OwnedType, Ptr };
     56     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
     57   }
     58 
     59   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
     60 }
     61 
     62 namespace {
     63 
     64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
     65  public:
     66   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
     67                        bool AllowTemplates=false)
     68       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
     69         AllowClassTemplates(AllowTemplates) {
     70     WantExpressionKeywords = false;
     71     WantCXXNamedCasts = false;
     72     WantRemainingKeywords = false;
     73   }
     74 
     75   bool ValidateCandidate(const TypoCorrection &candidate) override {
     76     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
     77       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
     78       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
     79       return (IsType || AllowedTemplate) &&
     80              (AllowInvalidDecl || !ND->isInvalidDecl());
     81     }
     82     return !WantClassName && candidate.isKeyword();
     83   }
     84 
     85  private:
     86   bool AllowInvalidDecl;
     87   bool WantClassName;
     88   bool AllowClassTemplates;
     89 };
     90 
     91 }
     92 
     93 /// \brief Determine whether the token kind starts a simple-type-specifier.
     94 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
     95   switch (Kind) {
     96   // FIXME: Take into account the current language when deciding whether a
     97   // token kind is a valid type specifier
     98   case tok::kw_short:
     99   case tok::kw_long:
    100   case tok::kw___int64:
    101   case tok::kw___int128:
    102   case tok::kw_signed:
    103   case tok::kw_unsigned:
    104   case tok::kw_void:
    105   case tok::kw_char:
    106   case tok::kw_int:
    107   case tok::kw_half:
    108   case tok::kw_float:
    109   case tok::kw_double:
    110   case tok::kw_wchar_t:
    111   case tok::kw_bool:
    112   case tok::kw___underlying_type:
    113   case tok::kw___auto_type:
    114     return true;
    115 
    116   case tok::annot_typename:
    117   case tok::kw_char16_t:
    118   case tok::kw_char32_t:
    119   case tok::kw_typeof:
    120   case tok::annot_decltype:
    121   case tok::kw_decltype:
    122     return getLangOpts().CPlusPlus;
    123 
    124   default:
    125     break;
    126   }
    127 
    128   return false;
    129 }
    130 
    131 namespace {
    132 enum class UnqualifiedTypeNameLookupResult {
    133   NotFound,
    134   FoundNonType,
    135   FoundType
    136 };
    137 } // namespace
    138 
    139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
    140 /// dependent class.
    141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
    142 /// type decl, \a FoundType if only type decls are found.
    143 static UnqualifiedTypeNameLookupResult
    144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
    145                                 SourceLocation NameLoc,
    146                                 const CXXRecordDecl *RD) {
    147   if (!RD->hasDefinition())
    148     return UnqualifiedTypeNameLookupResult::NotFound;
    149   // Look for type decls in base classes.
    150   UnqualifiedTypeNameLookupResult FoundTypeDecl =
    151       UnqualifiedTypeNameLookupResult::NotFound;
    152   for (const auto &Base : RD->bases()) {
    153     const CXXRecordDecl *BaseRD = nullptr;
    154     if (auto *BaseTT = Base.getType()->getAs<TagType>())
    155       BaseRD = BaseTT->getAsCXXRecordDecl();
    156     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
    157       // Look for type decls in dependent base classes that have known primary
    158       // templates.
    159       if (!TST || !TST->isDependentType())
    160         continue;
    161       auto *TD = TST->getTemplateName().getAsTemplateDecl();
    162       if (!TD)
    163         continue;
    164       auto *BasePrimaryTemplate =
    165           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
    166       if (!BasePrimaryTemplate)
    167         continue;
    168       BaseRD = BasePrimaryTemplate;
    169     }
    170     if (BaseRD) {
    171       for (NamedDecl *ND : BaseRD->lookup(&II)) {
    172         if (!isa<TypeDecl>(ND))
    173           return UnqualifiedTypeNameLookupResult::FoundNonType;
    174         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
    175       }
    176       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
    177         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
    178         case UnqualifiedTypeNameLookupResult::FoundNonType:
    179           return UnqualifiedTypeNameLookupResult::FoundNonType;
    180         case UnqualifiedTypeNameLookupResult::FoundType:
    181           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
    182           break;
    183         case UnqualifiedTypeNameLookupResult::NotFound:
    184           break;
    185         }
    186       }
    187     }
    188   }
    189 
    190   return FoundTypeDecl;
    191 }
    192 
    193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
    194                                                       const IdentifierInfo &II,
    195                                                       SourceLocation NameLoc) {
    196   // Lookup in the parent class template context, if any.
    197   const CXXRecordDecl *RD = nullptr;
    198   UnqualifiedTypeNameLookupResult FoundTypeDecl =
    199       UnqualifiedTypeNameLookupResult::NotFound;
    200   for (DeclContext *DC = S.CurContext;
    201        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
    202        DC = DC->getParent()) {
    203     // Look for type decls in dependent base classes that have known primary
    204     // templates.
    205     RD = dyn_cast<CXXRecordDecl>(DC);
    206     if (RD && RD->getDescribedClassTemplate())
    207       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
    208   }
    209   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
    210     return ParsedType();
    211 
    212   // We found some types in dependent base classes.  Recover as if the user
    213   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
    214   // lookup during template instantiation.
    215   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
    216 
    217   ASTContext &Context = S.Context;
    218   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
    219                                           cast<Type>(Context.getRecordType(RD)));
    220   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
    221 
    222   CXXScopeSpec SS;
    223   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
    224 
    225   TypeLocBuilder Builder;
    226   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
    227   DepTL.setNameLoc(NameLoc);
    228   DepTL.setElaboratedKeywordLoc(SourceLocation());
    229   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
    230   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
    231 }
    232 
    233 /// \brief If the identifier refers to a type name within this scope,
    234 /// return the declaration of that type.
    235 ///
    236 /// This routine performs ordinary name lookup of the identifier II
    237 /// within the given scope, with optional C++ scope specifier SS, to
    238 /// determine whether the name refers to a type. If so, returns an
    239 /// opaque pointer (actually a QualType) corresponding to that
    240 /// type. Otherwise, returns NULL.
    241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
    242                              Scope *S, CXXScopeSpec *SS,
    243                              bool isClassName, bool HasTrailingDot,
    244                              ParsedType ObjectTypePtr,
    245                              bool IsCtorOrDtorName,
    246                              bool WantNontrivialTypeSourceInfo,
    247                              IdentifierInfo **CorrectedII) {
    248   // Determine where we will perform name lookup.
    249   DeclContext *LookupCtx = nullptr;
    250   if (ObjectTypePtr) {
    251     QualType ObjectType = ObjectTypePtr.get();
    252     if (ObjectType->isRecordType())
    253       LookupCtx = computeDeclContext(ObjectType);
    254   } else if (SS && SS->isNotEmpty()) {
    255     LookupCtx = computeDeclContext(*SS, false);
    256 
    257     if (!LookupCtx) {
    258       if (isDependentScopeSpecifier(*SS)) {
    259         // C++ [temp.res]p3:
    260         //   A qualified-id that refers to a type and in which the
    261         //   nested-name-specifier depends on a template-parameter (14.6.2)
    262         //   shall be prefixed by the keyword typename to indicate that the
    263         //   qualified-id denotes a type, forming an
    264         //   elaborated-type-specifier (7.1.5.3).
    265         //
    266         // We therefore do not perform any name lookup if the result would
    267         // refer to a member of an unknown specialization.
    268         if (!isClassName && !IsCtorOrDtorName)
    269           return ParsedType();
    270 
    271         // We know from the grammar that this name refers to a type,
    272         // so build a dependent node to describe the type.
    273         if (WantNontrivialTypeSourceInfo)
    274           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
    275 
    276         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
    277         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
    278                                        II, NameLoc);
    279         return ParsedType::make(T);
    280       }
    281 
    282       return ParsedType();
    283     }
    284 
    285     if (!LookupCtx->isDependentContext() &&
    286         RequireCompleteDeclContext(*SS, LookupCtx))
    287       return ParsedType();
    288   }
    289 
    290   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
    291   // lookup for class-names.
    292   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
    293                                       LookupOrdinaryName;
    294   LookupResult Result(*this, &II, NameLoc, Kind);
    295   if (LookupCtx) {
    296     // Perform "qualified" name lookup into the declaration context we
    297     // computed, which is either the type of the base of a member access
    298     // expression or the declaration context associated with a prior
    299     // nested-name-specifier.
    300     LookupQualifiedName(Result, LookupCtx);
    301 
    302     if (ObjectTypePtr && Result.empty()) {
    303       // C++ [basic.lookup.classref]p3:
    304       //   If the unqualified-id is ~type-name, the type-name is looked up
    305       //   in the context of the entire postfix-expression. If the type T of
    306       //   the object expression is of a class type C, the type-name is also
    307       //   looked up in the scope of class C. At least one of the lookups shall
    308       //   find a name that refers to (possibly cv-qualified) T.
    309       LookupName(Result, S);
    310     }
    311   } else {
    312     // Perform unqualified name lookup.
    313     LookupName(Result, S);
    314 
    315     // For unqualified lookup in a class template in MSVC mode, look into
    316     // dependent base classes where the primary class template is known.
    317     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
    318       if (ParsedType TypeInBase =
    319               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
    320         return TypeInBase;
    321     }
    322   }
    323 
    324   NamedDecl *IIDecl = nullptr;
    325   switch (Result.getResultKind()) {
    326   case LookupResult::NotFound:
    327   case LookupResult::NotFoundInCurrentInstantiation:
    328     if (CorrectedII) {
    329       TypoCorrection Correction = CorrectTypo(
    330           Result.getLookupNameInfo(), Kind, S, SS,
    331           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
    332           CTK_ErrorRecovery);
    333       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
    334       TemplateTy Template;
    335       bool MemberOfUnknownSpecialization;
    336       UnqualifiedId TemplateName;
    337       TemplateName.setIdentifier(NewII, NameLoc);
    338       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
    339       CXXScopeSpec NewSS, *NewSSPtr = SS;
    340       if (SS && NNS) {
    341         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
    342         NewSSPtr = &NewSS;
    343       }
    344       if (Correction && (NNS || NewII != &II) &&
    345           // Ignore a correction to a template type as the to-be-corrected
    346           // identifier is not a template (typo correction for template names
    347           // is handled elsewhere).
    348           !(getLangOpts().CPlusPlus && NewSSPtr &&
    349             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
    350                            false, Template, MemberOfUnknownSpecialization))) {
    351         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
    352                                     isClassName, HasTrailingDot, ObjectTypePtr,
    353                                     IsCtorOrDtorName,
    354                                     WantNontrivialTypeSourceInfo);
    355         if (Ty) {
    356           diagnoseTypo(Correction,
    357                        PDiag(diag::err_unknown_type_or_class_name_suggest)
    358                          << Result.getLookupName() << isClassName);
    359           if (SS && NNS)
    360             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
    361           *CorrectedII = NewII;
    362           return Ty;
    363         }
    364       }
    365     }
    366     // If typo correction failed or was not performed, fall through
    367   case LookupResult::FoundOverloaded:
    368   case LookupResult::FoundUnresolvedValue:
    369     Result.suppressDiagnostics();
    370     return ParsedType();
    371 
    372   case LookupResult::Ambiguous:
    373     // Recover from type-hiding ambiguities by hiding the type.  We'll
    374     // do the lookup again when looking for an object, and we can
    375     // diagnose the error then.  If we don't do this, then the error
    376     // about hiding the type will be immediately followed by an error
    377     // that only makes sense if the identifier was treated like a type.
    378     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
    379       Result.suppressDiagnostics();
    380       return ParsedType();
    381     }
    382 
    383     // Look to see if we have a type anywhere in the list of results.
    384     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
    385          Res != ResEnd; ++Res) {
    386       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
    387         if (!IIDecl ||
    388             (*Res)->getLocation().getRawEncoding() <
    389               IIDecl->getLocation().getRawEncoding())
    390           IIDecl = *Res;
    391       }
    392     }
    393 
    394     if (!IIDecl) {
    395       // None of the entities we found is a type, so there is no way
    396       // to even assume that the result is a type. In this case, don't
    397       // complain about the ambiguity. The parser will either try to
    398       // perform this lookup again (e.g., as an object name), which
    399       // will produce the ambiguity, or will complain that it expected
    400       // a type name.
    401       Result.suppressDiagnostics();
    402       return ParsedType();
    403     }
    404 
    405     // We found a type within the ambiguous lookup; diagnose the
    406     // ambiguity and then return that type. This might be the right
    407     // answer, or it might not be, but it suppresses any attempt to
    408     // perform the name lookup again.
    409     break;
    410 
    411   case LookupResult::Found:
    412     IIDecl = Result.getFoundDecl();
    413     break;
    414   }
    415 
    416   assert(IIDecl && "Didn't find decl");
    417 
    418   QualType T;
    419   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
    420     DiagnoseUseOfDecl(IIDecl, NameLoc);
    421 
    422     T = Context.getTypeDeclType(TD);
    423     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
    424 
    425     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
    426     // constructor or destructor name (in such a case, the scope specifier
    427     // will be attached to the enclosing Expr or Decl node).
    428     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
    429       if (WantNontrivialTypeSourceInfo) {
    430         // Construct a type with type-source information.
    431         TypeLocBuilder Builder;
    432         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
    433 
    434         T = getElaboratedType(ETK_None, *SS, T);
    435         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
    436         ElabTL.setElaboratedKeywordLoc(SourceLocation());
    437         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
    438         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
    439       } else {
    440         T = getElaboratedType(ETK_None, *SS, T);
    441       }
    442     }
    443   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
    444     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
    445     if (!HasTrailingDot)
    446       T = Context.getObjCInterfaceType(IDecl);
    447   }
    448 
    449   if (T.isNull()) {
    450     // If it's not plausibly a type, suppress diagnostics.
    451     Result.suppressDiagnostics();
    452     return ParsedType();
    453   }
    454   return ParsedType::make(T);
    455 }
    456 
    457 // Builds a fake NNS for the given decl context.
    458 static NestedNameSpecifier *
    459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
    460   for (;; DC = DC->getLookupParent()) {
    461     DC = DC->getPrimaryContext();
    462     auto *ND = dyn_cast<NamespaceDecl>(DC);
    463     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
    464       return NestedNameSpecifier::Create(Context, nullptr, ND);
    465     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
    466       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
    467                                          RD->getTypeForDecl());
    468     else if (isa<TranslationUnitDecl>(DC))
    469       return NestedNameSpecifier::GlobalSpecifier(Context);
    470   }
    471   llvm_unreachable("something isn't in TU scope?");
    472 }
    473 
    474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
    475                                                 SourceLocation NameLoc) {
    476   // Accepting an undeclared identifier as a default argument for a template
    477   // type parameter is a Microsoft extension.
    478   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
    479 
    480   // Build a fake DependentNameType that will perform lookup into CurContext at
    481   // instantiation time.  The name specifier isn't dependent, so template
    482   // instantiation won't transform it.  It will retry the lookup, however.
    483   NestedNameSpecifier *NNS =
    484       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
    485   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
    486 
    487   // Build type location information.  We synthesized the qualifier, so we have
    488   // to build a fake NestedNameSpecifierLoc.
    489   NestedNameSpecifierLocBuilder NNSLocBuilder;
    490   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
    491   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
    492 
    493   TypeLocBuilder Builder;
    494   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
    495   DepTL.setNameLoc(NameLoc);
    496   DepTL.setElaboratedKeywordLoc(SourceLocation());
    497   DepTL.setQualifierLoc(QualifierLoc);
    498   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
    499 }
    500 
    501 /// isTagName() - This method is called *for error recovery purposes only*
    502 /// to determine if the specified name is a valid tag name ("struct foo").  If
    503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
    504 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
    505 /// cases in C where the user forgot to specify the tag.
    506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
    507   // Do a tag name lookup in this scope.
    508   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
    509   LookupName(R, S, false);
    510   R.suppressDiagnostics();
    511   if (R.getResultKind() == LookupResult::Found)
    512     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
    513       switch (TD->getTagKind()) {
    514       case TTK_Struct: return DeclSpec::TST_struct;
    515       case TTK_Interface: return DeclSpec::TST_interface;
    516       case TTK_Union:  return DeclSpec::TST_union;
    517       case TTK_Class:  return DeclSpec::TST_class;
    518       case TTK_Enum:   return DeclSpec::TST_enum;
    519       }
    520     }
    521 
    522   return DeclSpec::TST_unspecified;
    523 }
    524 
    525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
    526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
    527 /// then downgrade the missing typename error to a warning.
    528 /// This is needed for MSVC compatibility; Example:
    529 /// @code
    530 /// template<class T> class A {
    531 /// public:
    532 ///   typedef int TYPE;
    533 /// };
    534 /// template<class T> class B : public A<T> {
    535 /// public:
    536 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
    537 /// };
    538 /// @endcode
    539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
    540   if (CurContext->isRecord()) {
    541     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
    542       return true;
    543 
    544     const Type *Ty = SS->getScopeRep()->getAsType();
    545 
    546     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
    547     for (const auto &Base : RD->bases())
    548       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
    549         return true;
    550     return S->isFunctionPrototypeScope();
    551   }
    552   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
    553 }
    554 
    555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
    556                                    SourceLocation IILoc,
    557                                    Scope *S,
    558                                    CXXScopeSpec *SS,
    559                                    ParsedType &SuggestedType,
    560                                    bool AllowClassTemplates) {
    561   // We don't have anything to suggest (yet).
    562   SuggestedType = ParsedType();
    563 
    564   // There may have been a typo in the name of the type. Look up typo
    565   // results, in case we have something that we can suggest.
    566   if (TypoCorrection Corrected =
    567           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
    568                       llvm::make_unique<TypeNameValidatorCCC>(
    569                           false, false, AllowClassTemplates),
    570                       CTK_ErrorRecovery)) {
    571     if (Corrected.isKeyword()) {
    572       // We corrected to a keyword.
    573       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
    574       II = Corrected.getCorrectionAsIdentifierInfo();
    575     } else {
    576       // We found a similarly-named type or interface; suggest that.
    577       if (!SS || !SS->isSet()) {
    578         diagnoseTypo(Corrected,
    579                      PDiag(diag::err_unknown_typename_suggest) << II);
    580       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
    581         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
    582         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
    583                                 II->getName().equals(CorrectedStr);
    584         diagnoseTypo(Corrected,
    585                      PDiag(diag::err_unknown_nested_typename_suggest)
    586                        << II << DC << DroppedSpecifier << SS->getRange());
    587       } else {
    588         llvm_unreachable("could not have corrected a typo here");
    589       }
    590 
    591       CXXScopeSpec tmpSS;
    592       if (Corrected.getCorrectionSpecifier())
    593         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
    594                           SourceRange(IILoc));
    595       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
    596                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
    597                                   false, ParsedType(),
    598                                   /*IsCtorOrDtorName=*/false,
    599                                   /*NonTrivialTypeSourceInfo=*/true);
    600     }
    601     return;
    602   }
    603 
    604   if (getLangOpts().CPlusPlus) {
    605     // See if II is a class template that the user forgot to pass arguments to.
    606     UnqualifiedId Name;
    607     Name.setIdentifier(II, IILoc);
    608     CXXScopeSpec EmptySS;
    609     TemplateTy TemplateResult;
    610     bool MemberOfUnknownSpecialization;
    611     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
    612                        Name, ParsedType(), true, TemplateResult,
    613                        MemberOfUnknownSpecialization) == TNK_Type_template) {
    614       TemplateName TplName = TemplateResult.get();
    615       Diag(IILoc, diag::err_template_missing_args) << TplName;
    616       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
    617         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
    618           << TplDecl->getTemplateParameters()->getSourceRange();
    619       }
    620       return;
    621     }
    622   }
    623 
    624   // FIXME: Should we move the logic that tries to recover from a missing tag
    625   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
    626 
    627   if (!SS || (!SS->isSet() && !SS->isInvalid()))
    628     Diag(IILoc, diag::err_unknown_typename) << II;
    629   else if (DeclContext *DC = computeDeclContext(*SS, false))
    630     Diag(IILoc, diag::err_typename_nested_not_found)
    631       << II << DC << SS->getRange();
    632   else if (isDependentScopeSpecifier(*SS)) {
    633     unsigned DiagID = diag::err_typename_missing;
    634     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
    635       DiagID = diag::ext_typename_missing;
    636 
    637     Diag(SS->getRange().getBegin(), DiagID)
    638       << SS->getScopeRep() << II->getName()
    639       << SourceRange(SS->getRange().getBegin(), IILoc)
    640       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
    641     SuggestedType = ActOnTypenameType(S, SourceLocation(),
    642                                       *SS, *II, IILoc).get();
    643   } else {
    644     assert(SS && SS->isInvalid() &&
    645            "Invalid scope specifier has already been diagnosed");
    646   }
    647 }
    648 
    649 /// \brief Determine whether the given result set contains either a type name
    650 /// or
    651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
    652   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
    653                        NextToken.is(tok::less);
    654 
    655   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
    656     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
    657       return true;
    658 
    659     if (CheckTemplate && isa<TemplateDecl>(*I))
    660       return true;
    661   }
    662 
    663   return false;
    664 }
    665 
    666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
    667                                     Scope *S, CXXScopeSpec &SS,
    668                                     IdentifierInfo *&Name,
    669                                     SourceLocation NameLoc) {
    670   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
    671   SemaRef.LookupParsedName(R, S, &SS);
    672   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
    673     StringRef FixItTagName;
    674     switch (Tag->getTagKind()) {
    675       case TTK_Class:
    676         FixItTagName = "class ";
    677         break;
    678 
    679       case TTK_Enum:
    680         FixItTagName = "enum ";
    681         break;
    682 
    683       case TTK_Struct:
    684         FixItTagName = "struct ";
    685         break;
    686 
    687       case TTK_Interface:
    688         FixItTagName = "__interface ";
    689         break;
    690 
    691       case TTK_Union:
    692         FixItTagName = "union ";
    693         break;
    694     }
    695 
    696     StringRef TagName = FixItTagName.drop_back();
    697     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
    698       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
    699       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
    700 
    701     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
    702          I != IEnd; ++I)
    703       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
    704         << Name << TagName;
    705 
    706     // Replace lookup results with just the tag decl.
    707     Result.clear(Sema::LookupTagName);
    708     SemaRef.LookupParsedName(Result, S, &SS);
    709     return true;
    710   }
    711 
    712   return false;
    713 }
    714 
    715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
    716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
    717                                   QualType T, SourceLocation NameLoc) {
    718   ASTContext &Context = S.Context;
    719 
    720   TypeLocBuilder Builder;
    721   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
    722 
    723   T = S.getElaboratedType(ETK_None, SS, T);
    724   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
    725   ElabTL.setElaboratedKeywordLoc(SourceLocation());
    726   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
    727   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
    728 }
    729 
    730 Sema::NameClassification
    731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
    732                    SourceLocation NameLoc, const Token &NextToken,
    733                    bool IsAddressOfOperand,
    734                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
    735   DeclarationNameInfo NameInfo(Name, NameLoc);
    736   ObjCMethodDecl *CurMethod = getCurMethodDecl();
    737 
    738   if (NextToken.is(tok::coloncolon)) {
    739     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
    740                                 QualType(), false, SS, nullptr, false);
    741   }
    742 
    743   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
    744   LookupParsedName(Result, S, &SS, !CurMethod);
    745 
    746   // For unqualified lookup in a class template in MSVC mode, look into
    747   // dependent base classes where the primary class template is known.
    748   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
    749     if (ParsedType TypeInBase =
    750             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
    751       return TypeInBase;
    752   }
    753 
    754   // Perform lookup for Objective-C instance variables (including automatically
    755   // synthesized instance variables), if we're in an Objective-C method.
    756   // FIXME: This lookup really, really needs to be folded in to the normal
    757   // unqualified lookup mechanism.
    758   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
    759     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
    760     if (E.get() || E.isInvalid())
    761       return E;
    762   }
    763 
    764   bool SecondTry = false;
    765   bool IsFilteredTemplateName = false;
    766 
    767 Corrected:
    768   switch (Result.getResultKind()) {
    769   case LookupResult::NotFound:
    770     // If an unqualified-id is followed by a '(', then we have a function
    771     // call.
    772     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
    773       // In C++, this is an ADL-only call.
    774       // FIXME: Reference?
    775       if (getLangOpts().CPlusPlus)
    776         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
    777 
    778       // C90 6.3.2.2:
    779       //   If the expression that precedes the parenthesized argument list in a
    780       //   function call consists solely of an identifier, and if no
    781       //   declaration is visible for this identifier, the identifier is
    782       //   implicitly declared exactly as if, in the innermost block containing
    783       //   the function call, the declaration
    784       //
    785       //     extern int identifier ();
    786       //
    787       //   appeared.
    788       //
    789       // We also allow this in C99 as an extension.
    790       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
    791         Result.addDecl(D);
    792         Result.resolveKind();
    793         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
    794       }
    795     }
    796 
    797     // In C, we first see whether there is a tag type by the same name, in
    798     // which case it's likely that the user just forget to write "enum",
    799     // "struct", or "union".
    800     if (!getLangOpts().CPlusPlus && !SecondTry &&
    801         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
    802       break;
    803     }
    804 
    805     // Perform typo correction to determine if there is another name that is
    806     // close to this name.
    807     if (!SecondTry && CCC) {
    808       SecondTry = true;
    809       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
    810                                                  Result.getLookupKind(), S,
    811                                                  &SS, std::move(CCC),
    812                                                  CTK_ErrorRecovery)) {
    813         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
    814         unsigned QualifiedDiag = diag::err_no_member_suggest;
    815 
    816         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
    817         NamedDecl *UnderlyingFirstDecl
    818           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
    819         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
    820             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
    821           UnqualifiedDiag = diag::err_no_template_suggest;
    822           QualifiedDiag = diag::err_no_member_template_suggest;
    823         } else if (UnderlyingFirstDecl &&
    824                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
    825                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
    826                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
    827           UnqualifiedDiag = diag::err_unknown_typename_suggest;
    828           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
    829         }
    830 
    831         if (SS.isEmpty()) {
    832           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
    833         } else {// FIXME: is this even reachable? Test it.
    834           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
    835           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
    836                                   Name->getName().equals(CorrectedStr);
    837           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
    838                                     << Name << computeDeclContext(SS, false)
    839                                     << DroppedSpecifier << SS.getRange());
    840         }
    841 
    842         // Update the name, so that the caller has the new name.
    843         Name = Corrected.getCorrectionAsIdentifierInfo();
    844 
    845         // Typo correction corrected to a keyword.
    846         if (Corrected.isKeyword())
    847           return Name;
    848 
    849         // Also update the LookupResult...
    850         // FIXME: This should probably go away at some point
    851         Result.clear();
    852         Result.setLookupName(Corrected.getCorrection());
    853         if (FirstDecl)
    854           Result.addDecl(FirstDecl);
    855 
    856         // If we found an Objective-C instance variable, let
    857         // LookupInObjCMethod build the appropriate expression to
    858         // reference the ivar.
    859         // FIXME: This is a gross hack.
    860         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
    861           Result.clear();
    862           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
    863           return E;
    864         }
    865 
    866         goto Corrected;
    867       }
    868     }
    869 
    870     // We failed to correct; just fall through and let the parser deal with it.
    871     Result.suppressDiagnostics();
    872     return NameClassification::Unknown();
    873 
    874   case LookupResult::NotFoundInCurrentInstantiation: {
    875     // We performed name lookup into the current instantiation, and there were
    876     // dependent bases, so we treat this result the same way as any other
    877     // dependent nested-name-specifier.
    878 
    879     // C++ [temp.res]p2:
    880     //   A name used in a template declaration or definition and that is
    881     //   dependent on a template-parameter is assumed not to name a type
    882     //   unless the applicable name lookup finds a type name or the name is
    883     //   qualified by the keyword typename.
    884     //
    885     // FIXME: If the next token is '<', we might want to ask the parser to
    886     // perform some heroics to see if we actually have a
    887     // template-argument-list, which would indicate a missing 'template'
    888     // keyword here.
    889     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
    890                                       NameInfo, IsAddressOfOperand,
    891                                       /*TemplateArgs=*/nullptr);
    892   }
    893 
    894   case LookupResult::Found:
    895   case LookupResult::FoundOverloaded:
    896   case LookupResult::FoundUnresolvedValue:
    897     break;
    898 
    899   case LookupResult::Ambiguous:
    900     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
    901         hasAnyAcceptableTemplateNames(Result)) {
    902       // C++ [temp.local]p3:
    903       //   A lookup that finds an injected-class-name (10.2) can result in an
    904       //   ambiguity in certain cases (for example, if it is found in more than
    905       //   one base class). If all of the injected-class-names that are found
    906       //   refer to specializations of the same class template, and if the name
    907       //   is followed by a template-argument-list, the reference refers to the
    908       //   class template itself and not a specialization thereof, and is not
    909       //   ambiguous.
    910       //
    911       // This filtering can make an ambiguous result into an unambiguous one,
    912       // so try again after filtering out template names.
    913       FilterAcceptableTemplateNames(Result);
    914       if (!Result.isAmbiguous()) {
    915         IsFilteredTemplateName = true;
    916         break;
    917       }
    918     }
    919 
    920     // Diagnose the ambiguity and return an error.
    921     return NameClassification::Error();
    922   }
    923 
    924   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
    925       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
    926     // C++ [temp.names]p3:
    927     //   After name lookup (3.4) finds that a name is a template-name or that
    928     //   an operator-function-id or a literal- operator-id refers to a set of
    929     //   overloaded functions any member of which is a function template if
    930     //   this is followed by a <, the < is always taken as the delimiter of a
    931     //   template-argument-list and never as the less-than operator.
    932     if (!IsFilteredTemplateName)
    933       FilterAcceptableTemplateNames(Result);
    934 
    935     if (!Result.empty()) {
    936       bool IsFunctionTemplate;
    937       bool IsVarTemplate;
    938       TemplateName Template;
    939       if (Result.end() - Result.begin() > 1) {
    940         IsFunctionTemplate = true;
    941         Template = Context.getOverloadedTemplateName(Result.begin(),
    942                                                      Result.end());
    943       } else {
    944         TemplateDecl *TD
    945           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
    946         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
    947         IsVarTemplate = isa<VarTemplateDecl>(TD);
    948 
    949         if (SS.isSet() && !SS.isInvalid())
    950           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
    951                                                     /*TemplateKeyword=*/false,
    952                                                       TD);
    953         else
    954           Template = TemplateName(TD);
    955       }
    956 
    957       if (IsFunctionTemplate) {
    958         // Function templates always go through overload resolution, at which
    959         // point we'll perform the various checks (e.g., accessibility) we need
    960         // to based on which function we selected.
    961         Result.suppressDiagnostics();
    962 
    963         return NameClassification::FunctionTemplate(Template);
    964       }
    965 
    966       return IsVarTemplate ? NameClassification::VarTemplate(Template)
    967                            : NameClassification::TypeTemplate(Template);
    968     }
    969   }
    970 
    971   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
    972   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
    973     DiagnoseUseOfDecl(Type, NameLoc);
    974     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
    975     QualType T = Context.getTypeDeclType(Type);
    976     if (SS.isNotEmpty())
    977       return buildNestedType(*this, SS, T, NameLoc);
    978     return ParsedType::make(T);
    979   }
    980 
    981   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
    982   if (!Class) {
    983     // FIXME: It's unfortunate that we don't have a Type node for handling this.
    984     if (ObjCCompatibleAliasDecl *Alias =
    985             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
    986       Class = Alias->getClassInterface();
    987   }
    988 
    989   if (Class) {
    990     DiagnoseUseOfDecl(Class, NameLoc);
    991 
    992     if (NextToken.is(tok::period)) {
    993       // Interface. <something> is parsed as a property reference expression.
    994       // Just return "unknown" as a fall-through for now.
    995       Result.suppressDiagnostics();
    996       return NameClassification::Unknown();
    997     }
    998 
    999     QualType T = Context.getObjCInterfaceType(Class);
   1000     return ParsedType::make(T);
   1001   }
   1002 
   1003   // We can have a type template here if we're classifying a template argument.
   1004   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
   1005     return NameClassification::TypeTemplate(
   1006         TemplateName(cast<TemplateDecl>(FirstDecl)));
   1007 
   1008   // Check for a tag type hidden by a non-type decl in a few cases where it
   1009   // seems likely a type is wanted instead of the non-type that was found.
   1010   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
   1011   if ((NextToken.is(tok::identifier) ||
   1012        (NextIsOp &&
   1013         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
   1014       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
   1015     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
   1016     DiagnoseUseOfDecl(Type, NameLoc);
   1017     QualType T = Context.getTypeDeclType(Type);
   1018     if (SS.isNotEmpty())
   1019       return buildNestedType(*this, SS, T, NameLoc);
   1020     return ParsedType::make(T);
   1021   }
   1022 
   1023   if (FirstDecl->isCXXClassMember())
   1024     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
   1025                                            nullptr, S);
   1026 
   1027   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
   1028   return BuildDeclarationNameExpr(SS, Result, ADL);
   1029 }
   1030 
   1031 // Determines the context to return to after temporarily entering a
   1032 // context.  This depends in an unnecessarily complicated way on the
   1033 // exact ordering of callbacks from the parser.
   1034 DeclContext *Sema::getContainingDC(DeclContext *DC) {
   1035 
   1036   // Functions defined inline within classes aren't parsed until we've
   1037   // finished parsing the top-level class, so the top-level class is
   1038   // the context we'll need to return to.
   1039   // A Lambda call operator whose parent is a class must not be treated
   1040   // as an inline member function.  A Lambda can be used legally
   1041   // either as an in-class member initializer or a default argument.  These
   1042   // are parsed once the class has been marked complete and so the containing
   1043   // context would be the nested class (when the lambda is defined in one);
   1044   // If the class is not complete, then the lambda is being used in an
   1045   // ill-formed fashion (such as to specify the width of a bit-field, or
   1046   // in an array-bound) - in which case we still want to return the
   1047   // lexically containing DC (which could be a nested class).
   1048   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
   1049     DC = DC->getLexicalParent();
   1050 
   1051     // A function not defined within a class will always return to its
   1052     // lexical context.
   1053     if (!isa<CXXRecordDecl>(DC))
   1054       return DC;
   1055 
   1056     // A C++ inline method/friend is parsed *after* the topmost class
   1057     // it was declared in is fully parsed ("complete");  the topmost
   1058     // class is the context we need to return to.
   1059     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
   1060       DC = RD;
   1061 
   1062     // Return the declaration context of the topmost class the inline method is
   1063     // declared in.
   1064     return DC;
   1065   }
   1066 
   1067   return DC->getLexicalParent();
   1068 }
   1069 
   1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
   1071   assert(getContainingDC(DC) == CurContext &&
   1072       "The next DeclContext should be lexically contained in the current one.");
   1073   CurContext = DC;
   1074   S->setEntity(DC);
   1075 }
   1076 
   1077 void Sema::PopDeclContext() {
   1078   assert(CurContext && "DeclContext imbalance!");
   1079 
   1080   CurContext = getContainingDC(CurContext);
   1081   assert(CurContext && "Popped translation unit!");
   1082 }
   1083 
   1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
   1085                                                                     Decl *D) {
   1086   // Unlike PushDeclContext, the context to which we return is not necessarily
   1087   // the containing DC of TD, because the new context will be some pre-existing
   1088   // TagDecl definition instead of a fresh one.
   1089   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
   1090   CurContext = cast<TagDecl>(D)->getDefinition();
   1091   assert(CurContext && "skipping definition of undefined tag");
   1092   // Start lookups from the parent of the current context; we don't want to look
   1093   // into the pre-existing complete definition.
   1094   S->setEntity(CurContext->getLookupParent());
   1095   return Result;
   1096 }
   1097 
   1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
   1099   CurContext = static_cast<decltype(CurContext)>(Context);
   1100 }
   1101 
   1102 /// EnterDeclaratorContext - Used when we must lookup names in the context
   1103 /// of a declarator's nested name specifier.
   1104 ///
   1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
   1106   // C++0x [basic.lookup.unqual]p13:
   1107   //   A name used in the definition of a static data member of class
   1108   //   X (after the qualified-id of the static member) is looked up as
   1109   //   if the name was used in a member function of X.
   1110   // C++0x [basic.lookup.unqual]p14:
   1111   //   If a variable member of a namespace is defined outside of the
   1112   //   scope of its namespace then any name used in the definition of
   1113   //   the variable member (after the declarator-id) is looked up as
   1114   //   if the definition of the variable member occurred in its
   1115   //   namespace.
   1116   // Both of these imply that we should push a scope whose context
   1117   // is the semantic context of the declaration.  We can't use
   1118   // PushDeclContext here because that context is not necessarily
   1119   // lexically contained in the current context.  Fortunately,
   1120   // the containing scope should have the appropriate information.
   1121 
   1122   assert(!S->getEntity() && "scope already has entity");
   1123 
   1124 #ifndef NDEBUG
   1125   Scope *Ancestor = S->getParent();
   1126   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
   1127   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
   1128 #endif
   1129 
   1130   CurContext = DC;
   1131   S->setEntity(DC);
   1132 }
   1133 
   1134 void Sema::ExitDeclaratorContext(Scope *S) {
   1135   assert(S->getEntity() == CurContext && "Context imbalance!");
   1136 
   1137   // Switch back to the lexical context.  The safety of this is
   1138   // enforced by an assert in EnterDeclaratorContext.
   1139   Scope *Ancestor = S->getParent();
   1140   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
   1141   CurContext = Ancestor->getEntity();
   1142 
   1143   // We don't need to do anything with the scope, which is going to
   1144   // disappear.
   1145 }
   1146 
   1147 
   1148 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
   1149   // We assume that the caller has already called
   1150   // ActOnReenterTemplateScope so getTemplatedDecl() works.
   1151   FunctionDecl *FD = D->getAsFunction();
   1152   if (!FD)
   1153     return;
   1154 
   1155   // Same implementation as PushDeclContext, but enters the context
   1156   // from the lexical parent, rather than the top-level class.
   1157   assert(CurContext == FD->getLexicalParent() &&
   1158     "The next DeclContext should be lexically contained in the current one.");
   1159   CurContext = FD;
   1160   S->setEntity(CurContext);
   1161 
   1162   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
   1163     ParmVarDecl *Param = FD->getParamDecl(P);
   1164     // If the parameter has an identifier, then add it to the scope
   1165     if (Param->getIdentifier()) {
   1166       S->AddDecl(Param);
   1167       IdResolver.AddDecl(Param);
   1168     }
   1169   }
   1170 }
   1171 
   1172 
   1173 void Sema::ActOnExitFunctionContext() {
   1174   // Same implementation as PopDeclContext, but returns to the lexical parent,
   1175   // rather than the top-level class.
   1176   assert(CurContext && "DeclContext imbalance!");
   1177   CurContext = CurContext->getLexicalParent();
   1178   assert(CurContext && "Popped translation unit!");
   1179 }
   1180 
   1181 
   1182 /// \brief Determine whether we allow overloading of the function
   1183 /// PrevDecl with another declaration.
   1184 ///
   1185 /// This routine determines whether overloading is possible, not
   1186 /// whether some new function is actually an overload. It will return
   1187 /// true in C++ (where we can always provide overloads) or, as an
   1188 /// extension, in C when the previous function is already an
   1189 /// overloaded function declaration or has the "overloadable"
   1190 /// attribute.
   1191 static bool AllowOverloadingOfFunction(LookupResult &Previous,
   1192                                        ASTContext &Context) {
   1193   if (Context.getLangOpts().CPlusPlus)
   1194     return true;
   1195 
   1196   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
   1197     return true;
   1198 
   1199   return (Previous.getResultKind() == LookupResult::Found
   1200           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
   1201 }
   1202 
   1203 /// Add this decl to the scope shadowed decl chains.
   1204 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
   1205   // Move up the scope chain until we find the nearest enclosing
   1206   // non-transparent context. The declaration will be introduced into this
   1207   // scope.
   1208   while (S->getEntity() && S->getEntity()->isTransparentContext())
   1209     S = S->getParent();
   1210 
   1211   // Add scoped declarations into their context, so that they can be
   1212   // found later. Declarations without a context won't be inserted
   1213   // into any context.
   1214   if (AddToContext)
   1215     CurContext->addDecl(D);
   1216 
   1217   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
   1218   // are function-local declarations.
   1219   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
   1220       !D->getDeclContext()->getRedeclContext()->Equals(
   1221         D->getLexicalDeclContext()->getRedeclContext()) &&
   1222       !D->getLexicalDeclContext()->isFunctionOrMethod())
   1223     return;
   1224 
   1225   // Template instantiations should also not be pushed into scope.
   1226   if (isa<FunctionDecl>(D) &&
   1227       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
   1228     return;
   1229 
   1230   // If this replaces anything in the current scope,
   1231   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
   1232                                IEnd = IdResolver.end();
   1233   for (; I != IEnd; ++I) {
   1234     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
   1235       S->RemoveDecl(*I);
   1236       IdResolver.RemoveDecl(*I);
   1237 
   1238       // Should only need to replace one decl.
   1239       break;
   1240     }
   1241   }
   1242 
   1243   S->AddDecl(D);
   1244 
   1245   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
   1246     // Implicitly-generated labels may end up getting generated in an order that
   1247     // isn't strictly lexical, which breaks name lookup. Be careful to insert
   1248     // the label at the appropriate place in the identifier chain.
   1249     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
   1250       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
   1251       if (IDC == CurContext) {
   1252         if (!S->isDeclScope(*I))
   1253           continue;
   1254       } else if (IDC->Encloses(CurContext))
   1255         break;
   1256     }
   1257 
   1258     IdResolver.InsertDeclAfter(I, D);
   1259   } else {
   1260     IdResolver.AddDecl(D);
   1261   }
   1262 }
   1263 
   1264 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
   1265   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
   1266     TUScope->AddDecl(D);
   1267 }
   1268 
   1269 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
   1270                          bool AllowInlineNamespace) {
   1271   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
   1272 }
   1273 
   1274 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
   1275   DeclContext *TargetDC = DC->getPrimaryContext();
   1276   do {
   1277     if (DeclContext *ScopeDC = S->getEntity())
   1278       if (ScopeDC->getPrimaryContext() == TargetDC)
   1279         return S;
   1280   } while ((S = S->getParent()));
   1281 
   1282   return nullptr;
   1283 }
   1284 
   1285 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
   1286                                             DeclContext*,
   1287                                             ASTContext&);
   1288 
   1289 /// Filters out lookup results that don't fall within the given scope
   1290 /// as determined by isDeclInScope.
   1291 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
   1292                                 bool ConsiderLinkage,
   1293                                 bool AllowInlineNamespace) {
   1294   LookupResult::Filter F = R.makeFilter();
   1295   while (F.hasNext()) {
   1296     NamedDecl *D = F.next();
   1297 
   1298     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
   1299       continue;
   1300 
   1301     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
   1302       continue;
   1303 
   1304     F.erase();
   1305   }
   1306 
   1307   F.done();
   1308 }
   1309 
   1310 static bool isUsingDecl(NamedDecl *D) {
   1311   return isa<UsingShadowDecl>(D) ||
   1312          isa<UnresolvedUsingTypenameDecl>(D) ||
   1313          isa<UnresolvedUsingValueDecl>(D);
   1314 }
   1315 
   1316 /// Removes using shadow declarations from the lookup results.
   1317 static void RemoveUsingDecls(LookupResult &R) {
   1318   LookupResult::Filter F = R.makeFilter();
   1319   while (F.hasNext())
   1320     if (isUsingDecl(F.next()))
   1321       F.erase();
   1322 
   1323   F.done();
   1324 }
   1325 
   1326 /// \brief Check for this common pattern:
   1327 /// @code
   1328 /// class S {
   1329 ///   S(const S&); // DO NOT IMPLEMENT
   1330 ///   void operator=(const S&); // DO NOT IMPLEMENT
   1331 /// };
   1332 /// @endcode
   1333 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
   1334   // FIXME: Should check for private access too but access is set after we get
   1335   // the decl here.
   1336   if (D->doesThisDeclarationHaveABody())
   1337     return false;
   1338 
   1339   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
   1340     return CD->isCopyConstructor();
   1341   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
   1342     return Method->isCopyAssignmentOperator();
   1343   return false;
   1344 }
   1345 
   1346 // We need this to handle
   1347 //
   1348 // typedef struct {
   1349 //   void *foo() { return 0; }
   1350 // } A;
   1351 //
   1352 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
   1353 // for example. If 'A', foo will have external linkage. If we have '*A',
   1354 // foo will have no linkage. Since we can't know until we get to the end
   1355 // of the typedef, this function finds out if D might have non-external linkage.
   1356 // Callers should verify at the end of the TU if it D has external linkage or
   1357 // not.
   1358 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
   1359   const DeclContext *DC = D->getDeclContext();
   1360   while (!DC->isTranslationUnit()) {
   1361     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
   1362       if (!RD->hasNameForLinkage())
   1363         return true;
   1364     }
   1365     DC = DC->getParent();
   1366   }
   1367 
   1368   return !D->isExternallyVisible();
   1369 }
   1370 
   1371 // FIXME: This needs to be refactored; some other isInMainFile users want
   1372 // these semantics.
   1373 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
   1374   if (S.TUKind != TU_Complete)
   1375     return false;
   1376   return S.SourceMgr.isInMainFile(Loc);
   1377 }
   1378 
   1379 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
   1380   assert(D);
   1381 
   1382   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
   1383     return false;
   1384 
   1385   // Ignore all entities declared within templates, and out-of-line definitions
   1386   // of members of class templates.
   1387   if (D->getDeclContext()->isDependentContext() ||
   1388       D->getLexicalDeclContext()->isDependentContext())
   1389     return false;
   1390 
   1391   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   1392     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
   1393       return false;
   1394 
   1395     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
   1396       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
   1397         return false;
   1398     } else {
   1399       // 'static inline' functions are defined in headers; don't warn.
   1400       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
   1401         return false;
   1402     }
   1403 
   1404     if (FD->doesThisDeclarationHaveABody() &&
   1405         Context.DeclMustBeEmitted(FD))
   1406       return false;
   1407   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
   1408     // Constants and utility variables are defined in headers with internal
   1409     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
   1410     // like "inline".)
   1411     if (!isMainFileLoc(*this, VD->getLocation()))
   1412       return false;
   1413 
   1414     if (Context.DeclMustBeEmitted(VD))
   1415       return false;
   1416 
   1417     if (VD->isStaticDataMember() &&
   1418         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
   1419       return false;
   1420   } else {
   1421     return false;
   1422   }
   1423 
   1424   // Only warn for unused decls internal to the translation unit.
   1425   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
   1426   // for inline functions defined in the main source file, for instance.
   1427   return mightHaveNonExternalLinkage(D);
   1428 }
   1429 
   1430 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
   1431   if (!D)
   1432     return;
   1433 
   1434   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   1435     const FunctionDecl *First = FD->getFirstDecl();
   1436     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
   1437       return; // First should already be in the vector.
   1438   }
   1439 
   1440   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
   1441     const VarDecl *First = VD->getFirstDecl();
   1442     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
   1443       return; // First should already be in the vector.
   1444   }
   1445 
   1446   if (ShouldWarnIfUnusedFileScopedDecl(D))
   1447     UnusedFileScopedDecls.push_back(D);
   1448 }
   1449 
   1450 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
   1451   if (D->isInvalidDecl())
   1452     return false;
   1453 
   1454   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
   1455       D->hasAttr<ObjCPreciseLifetimeAttr>())
   1456     return false;
   1457 
   1458   if (isa<LabelDecl>(D))
   1459     return true;
   1460 
   1461   // Except for labels, we only care about unused decls that are local to
   1462   // functions.
   1463   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
   1464   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
   1465     // For dependent types, the diagnostic is deferred.
   1466     WithinFunction =
   1467         WithinFunction || (R->isLocalClass() && !R->isDependentType());
   1468   if (!WithinFunction)
   1469     return false;
   1470 
   1471   if (isa<TypedefNameDecl>(D))
   1472     return true;
   1473 
   1474   // White-list anything that isn't a local variable.
   1475   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
   1476     return false;
   1477 
   1478   // Types of valid local variables should be complete, so this should succeed.
   1479   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
   1480 
   1481     // White-list anything with an __attribute__((unused)) type.
   1482     QualType Ty = VD->getType();
   1483 
   1484     // Only look at the outermost level of typedef.
   1485     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
   1486       if (TT->getDecl()->hasAttr<UnusedAttr>())
   1487         return false;
   1488     }
   1489 
   1490     // If we failed to complete the type for some reason, or if the type is
   1491     // dependent, don't diagnose the variable.
   1492     if (Ty->isIncompleteType() || Ty->isDependentType())
   1493       return false;
   1494 
   1495     if (const TagType *TT = Ty->getAs<TagType>()) {
   1496       const TagDecl *Tag = TT->getDecl();
   1497       if (Tag->hasAttr<UnusedAttr>())
   1498         return false;
   1499 
   1500       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
   1501         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
   1502           return false;
   1503 
   1504         if (const Expr *Init = VD->getInit()) {
   1505           if (const ExprWithCleanups *Cleanups =
   1506                   dyn_cast<ExprWithCleanups>(Init))
   1507             Init = Cleanups->getSubExpr();
   1508           const CXXConstructExpr *Construct =
   1509             dyn_cast<CXXConstructExpr>(Init);
   1510           if (Construct && !Construct->isElidable()) {
   1511             CXXConstructorDecl *CD = Construct->getConstructor();
   1512             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
   1513               return false;
   1514           }
   1515         }
   1516       }
   1517     }
   1518 
   1519     // TODO: __attribute__((unused)) templates?
   1520   }
   1521 
   1522   return true;
   1523 }
   1524 
   1525 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
   1526                                      FixItHint &Hint) {
   1527   if (isa<LabelDecl>(D)) {
   1528     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
   1529                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
   1530     if (AfterColon.isInvalid())
   1531       return;
   1532     Hint = FixItHint::CreateRemoval(CharSourceRange::
   1533                                     getCharRange(D->getLocStart(), AfterColon));
   1534   }
   1535   return;
   1536 }
   1537 
   1538 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
   1539   if (D->getTypeForDecl()->isDependentType())
   1540     return;
   1541 
   1542   for (auto *TmpD : D->decls()) {
   1543     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
   1544       DiagnoseUnusedDecl(T);
   1545     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
   1546       DiagnoseUnusedNestedTypedefs(R);
   1547   }
   1548 }
   1549 
   1550 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
   1551 /// unless they are marked attr(unused).
   1552 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
   1553   if (!ShouldDiagnoseUnusedDecl(D))
   1554     return;
   1555 
   1556   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
   1557     // typedefs can be referenced later on, so the diagnostics are emitted
   1558     // at end-of-translation-unit.
   1559     UnusedLocalTypedefNameCandidates.insert(TD);
   1560     return;
   1561   }
   1562 
   1563   FixItHint Hint;
   1564   GenerateFixForUnusedDecl(D, Context, Hint);
   1565 
   1566   unsigned DiagID;
   1567   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
   1568     DiagID = diag::warn_unused_exception_param;
   1569   else if (isa<LabelDecl>(D))
   1570     DiagID = diag::warn_unused_label;
   1571   else
   1572     DiagID = diag::warn_unused_variable;
   1573 
   1574   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
   1575 }
   1576 
   1577 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
   1578   // Verify that we have no forward references left.  If so, there was a goto
   1579   // or address of a label taken, but no definition of it.  Label fwd
   1580   // definitions are indicated with a null substmt which is also not a resolved
   1581   // MS inline assembly label name.
   1582   bool Diagnose = false;
   1583   if (L->isMSAsmLabel())
   1584     Diagnose = !L->isResolvedMSAsmLabel();
   1585   else
   1586     Diagnose = L->getStmt() == nullptr;
   1587   if (Diagnose)
   1588     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
   1589 }
   1590 
   1591 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
   1592   S->mergeNRVOIntoParent();
   1593 
   1594   if (S->decl_empty()) return;
   1595   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
   1596          "Scope shouldn't contain decls!");
   1597 
   1598   for (auto *TmpD : S->decls()) {
   1599     assert(TmpD && "This decl didn't get pushed??");
   1600 
   1601     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
   1602     NamedDecl *D = cast<NamedDecl>(TmpD);
   1603 
   1604     if (!D->getDeclName()) continue;
   1605 
   1606     // Diagnose unused variables in this scope.
   1607     if (!S->hasUnrecoverableErrorOccurred()) {
   1608       DiagnoseUnusedDecl(D);
   1609       if (const auto *RD = dyn_cast<RecordDecl>(D))
   1610         DiagnoseUnusedNestedTypedefs(RD);
   1611     }
   1612 
   1613     // If this was a forward reference to a label, verify it was defined.
   1614     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
   1615       CheckPoppedLabel(LD, *this);
   1616 
   1617     // Remove this name from our lexical scope.
   1618     IdResolver.RemoveDecl(D);
   1619   }
   1620 }
   1621 
   1622 /// \brief Look for an Objective-C class in the translation unit.
   1623 ///
   1624 /// \param Id The name of the Objective-C class we're looking for. If
   1625 /// typo-correction fixes this name, the Id will be updated
   1626 /// to the fixed name.
   1627 ///
   1628 /// \param IdLoc The location of the name in the translation unit.
   1629 ///
   1630 /// \param DoTypoCorrection If true, this routine will attempt typo correction
   1631 /// if there is no class with the given name.
   1632 ///
   1633 /// \returns The declaration of the named Objective-C class, or NULL if the
   1634 /// class could not be found.
   1635 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
   1636                                               SourceLocation IdLoc,
   1637                                               bool DoTypoCorrection) {
   1638   // The third "scope" argument is 0 since we aren't enabling lazy built-in
   1639   // creation from this context.
   1640   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
   1641 
   1642   if (!IDecl && DoTypoCorrection) {
   1643     // Perform typo correction at the given location, but only if we
   1644     // find an Objective-C class name.
   1645     if (TypoCorrection C = CorrectTypo(
   1646             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
   1647             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
   1648             CTK_ErrorRecovery)) {
   1649       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
   1650       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
   1651       Id = IDecl->getIdentifier();
   1652     }
   1653   }
   1654   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
   1655   // This routine must always return a class definition, if any.
   1656   if (Def && Def->getDefinition())
   1657       Def = Def->getDefinition();
   1658   return Def;
   1659 }
   1660 
   1661 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
   1662 /// from S, where a non-field would be declared. This routine copes
   1663 /// with the difference between C and C++ scoping rules in structs and
   1664 /// unions. For example, the following code is well-formed in C but
   1665 /// ill-formed in C++:
   1666 /// @code
   1667 /// struct S6 {
   1668 ///   enum { BAR } e;
   1669 /// };
   1670 ///
   1671 /// void test_S6() {
   1672 ///   struct S6 a;
   1673 ///   a.e = BAR;
   1674 /// }
   1675 /// @endcode
   1676 /// For the declaration of BAR, this routine will return a different
   1677 /// scope. The scope S will be the scope of the unnamed enumeration
   1678 /// within S6. In C++, this routine will return the scope associated
   1679 /// with S6, because the enumeration's scope is a transparent
   1680 /// context but structures can contain non-field names. In C, this
   1681 /// routine will return the translation unit scope, since the
   1682 /// enumeration's scope is a transparent context and structures cannot
   1683 /// contain non-field names.
   1684 Scope *Sema::getNonFieldDeclScope(Scope *S) {
   1685   while (((S->getFlags() & Scope::DeclScope) == 0) ||
   1686          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
   1687          (S->isClassScope() && !getLangOpts().CPlusPlus))
   1688     S = S->getParent();
   1689   return S;
   1690 }
   1691 
   1692 /// \brief Looks up the declaration of "struct objc_super" and
   1693 /// saves it for later use in building builtin declaration of
   1694 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
   1695 /// pre-existing declaration exists no action takes place.
   1696 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
   1697                                         IdentifierInfo *II) {
   1698   if (!II->isStr("objc_msgSendSuper"))
   1699     return;
   1700   ASTContext &Context = ThisSema.Context;
   1701 
   1702   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
   1703                       SourceLocation(), Sema::LookupTagName);
   1704   ThisSema.LookupName(Result, S);
   1705   if (Result.getResultKind() == LookupResult::Found)
   1706     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
   1707       Context.setObjCSuperType(Context.getTagDeclType(TD));
   1708 }
   1709 
   1710 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
   1711   switch (Error) {
   1712   case ASTContext::GE_None:
   1713     return "";
   1714   case ASTContext::GE_Missing_stdio:
   1715     return "stdio.h";
   1716   case ASTContext::GE_Missing_setjmp:
   1717     return "setjmp.h";
   1718   case ASTContext::GE_Missing_ucontext:
   1719     return "ucontext.h";
   1720   }
   1721   llvm_unreachable("unhandled error kind");
   1722 }
   1723 
   1724 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
   1725 /// file scope.  lazily create a decl for it. ForRedeclaration is true
   1726 /// if we're creating this built-in in anticipation of redeclaring the
   1727 /// built-in.
   1728 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
   1729                                      Scope *S, bool ForRedeclaration,
   1730                                      SourceLocation Loc) {
   1731   LookupPredefedObjCSuperType(*this, S, II);
   1732 
   1733   ASTContext::GetBuiltinTypeError Error;
   1734   QualType R = Context.GetBuiltinType(ID, Error);
   1735   if (Error) {
   1736     if (ForRedeclaration)
   1737       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
   1738           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
   1739     return nullptr;
   1740   }
   1741 
   1742   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
   1743     Diag(Loc, diag::ext_implicit_lib_function_decl)
   1744         << Context.BuiltinInfo.getName(ID) << R;
   1745     if (Context.BuiltinInfo.getHeaderName(ID) &&
   1746         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
   1747       Diag(Loc, diag::note_include_header_or_declare)
   1748           << Context.BuiltinInfo.getHeaderName(ID)
   1749           << Context.BuiltinInfo.getName(ID);
   1750   }
   1751 
   1752   DeclContext *Parent = Context.getTranslationUnitDecl();
   1753   if (getLangOpts().CPlusPlus) {
   1754     LinkageSpecDecl *CLinkageDecl =
   1755         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
   1756                                 LinkageSpecDecl::lang_c, false);
   1757     CLinkageDecl->setImplicit();
   1758     Parent->addDecl(CLinkageDecl);
   1759     Parent = CLinkageDecl;
   1760   }
   1761 
   1762   FunctionDecl *New = FunctionDecl::Create(Context,
   1763                                            Parent,
   1764                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
   1765                                            SC_Extern,
   1766                                            false,
   1767                                            R->isFunctionProtoType());
   1768   New->setImplicit();
   1769 
   1770   // Create Decl objects for each parameter, adding them to the
   1771   // FunctionDecl.
   1772   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
   1773     SmallVector<ParmVarDecl*, 16> Params;
   1774     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
   1775       ParmVarDecl *parm =
   1776           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
   1777                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
   1778                               SC_None, nullptr);
   1779       parm->setScopeInfo(0, i);
   1780       Params.push_back(parm);
   1781     }
   1782     New->setParams(Params);
   1783   }
   1784 
   1785   AddKnownFunctionAttributes(New);
   1786   RegisterLocallyScopedExternCDecl(New, S);
   1787 
   1788   // TUScope is the translation-unit scope to insert this function into.
   1789   // FIXME: This is hideous. We need to teach PushOnScopeChains to
   1790   // relate Scopes to DeclContexts, and probably eliminate CurContext
   1791   // entirely, but we're not there yet.
   1792   DeclContext *SavedContext = CurContext;
   1793   CurContext = Parent;
   1794   PushOnScopeChains(New, TUScope);
   1795   CurContext = SavedContext;
   1796   return New;
   1797 }
   1798 
   1799 /// Typedef declarations don't have linkage, but they still denote the same
   1800 /// entity if their types are the same.
   1801 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
   1802 /// isSameEntity.
   1803 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
   1804                                                      TypedefNameDecl *Decl,
   1805                                                      LookupResult &Previous) {
   1806   // This is only interesting when modules are enabled.
   1807   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
   1808     return;
   1809 
   1810   // Empty sets are uninteresting.
   1811   if (Previous.empty())
   1812     return;
   1813 
   1814   LookupResult::Filter Filter = Previous.makeFilter();
   1815   while (Filter.hasNext()) {
   1816     NamedDecl *Old = Filter.next();
   1817 
   1818     // Non-hidden declarations are never ignored.
   1819     if (S.isVisible(Old))
   1820       continue;
   1821 
   1822     // Declarations of the same entity are not ignored, even if they have
   1823     // different linkages.
   1824     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
   1825       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
   1826                                 Decl->getUnderlyingType()))
   1827         continue;
   1828 
   1829       // If both declarations give a tag declaration a typedef name for linkage
   1830       // purposes, then they declare the same entity.
   1831       if (S.getLangOpts().CPlusPlus &&
   1832           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
   1833           Decl->getAnonDeclWithTypedefName())
   1834         continue;
   1835     }
   1836 
   1837     Filter.erase();
   1838   }
   1839 
   1840   Filter.done();
   1841 }
   1842 
   1843 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
   1844   QualType OldType;
   1845   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
   1846     OldType = OldTypedef->getUnderlyingType();
   1847   else
   1848     OldType = Context.getTypeDeclType(Old);
   1849   QualType NewType = New->getUnderlyingType();
   1850 
   1851   if (NewType->isVariablyModifiedType()) {
   1852     // Must not redefine a typedef with a variably-modified type.
   1853     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
   1854     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
   1855       << Kind << NewType;
   1856     if (Old->getLocation().isValid())
   1857       Diag(Old->getLocation(), diag::note_previous_definition);
   1858     New->setInvalidDecl();
   1859     return true;
   1860   }
   1861 
   1862   if (OldType != NewType &&
   1863       !OldType->isDependentType() &&
   1864       !NewType->isDependentType() &&
   1865       !Context.hasSameType(OldType, NewType)) {
   1866     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
   1867     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
   1868       << Kind << NewType << OldType;
   1869     if (Old->getLocation().isValid())
   1870       Diag(Old->getLocation(), diag::note_previous_definition);
   1871     New->setInvalidDecl();
   1872     return true;
   1873   }
   1874   return false;
   1875 }
   1876 
   1877 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
   1878 /// same name and scope as a previous declaration 'Old'.  Figure out
   1879 /// how to resolve this situation, merging decls or emitting
   1880 /// diagnostics as appropriate. If there was an error, set New to be invalid.
   1881 ///
   1882 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
   1883                                 LookupResult &OldDecls) {
   1884   // If the new decl is known invalid already, don't bother doing any
   1885   // merging checks.
   1886   if (New->isInvalidDecl()) return;
   1887 
   1888   // Allow multiple definitions for ObjC built-in typedefs.
   1889   // FIXME: Verify the underlying types are equivalent!
   1890   if (getLangOpts().ObjC1) {
   1891     const IdentifierInfo *TypeID = New->getIdentifier();
   1892     switch (TypeID->getLength()) {
   1893     default: break;
   1894     case 2:
   1895       {
   1896         if (!TypeID->isStr("id"))
   1897           break;
   1898         QualType T = New->getUnderlyingType();
   1899         if (!T->isPointerType())
   1900           break;
   1901         if (!T->isVoidPointerType()) {
   1902           QualType PT = T->getAs<PointerType>()->getPointeeType();
   1903           if (!PT->isStructureType())
   1904             break;
   1905         }
   1906         Context.setObjCIdRedefinitionType(T);
   1907         // Install the built-in type for 'id', ignoring the current definition.
   1908         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
   1909         return;
   1910       }
   1911     case 5:
   1912       if (!TypeID->isStr("Class"))
   1913         break;
   1914       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
   1915       // Install the built-in type for 'Class', ignoring the current definition.
   1916       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
   1917       return;
   1918     case 3:
   1919       if (!TypeID->isStr("SEL"))
   1920         break;
   1921       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
   1922       // Install the built-in type for 'SEL', ignoring the current definition.
   1923       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
   1924       return;
   1925     }
   1926     // Fall through - the typedef name was not a builtin type.
   1927   }
   1928 
   1929   // Verify the old decl was also a type.
   1930   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
   1931   if (!Old) {
   1932     Diag(New->getLocation(), diag::err_redefinition_different_kind)
   1933       << New->getDeclName();
   1934 
   1935     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
   1936     if (OldD->getLocation().isValid())
   1937       Diag(OldD->getLocation(), diag::note_previous_definition);
   1938 
   1939     return New->setInvalidDecl();
   1940   }
   1941 
   1942   // If the old declaration is invalid, just give up here.
   1943   if (Old->isInvalidDecl())
   1944     return New->setInvalidDecl();
   1945 
   1946   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
   1947     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
   1948     auto *NewTag = New->getAnonDeclWithTypedefName();
   1949     NamedDecl *Hidden = nullptr;
   1950     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
   1951         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
   1952         !hasVisibleDefinition(OldTag, &Hidden)) {
   1953       // There is a definition of this tag, but it is not visible. Use it
   1954       // instead of our tag.
   1955       New->setTypeForDecl(OldTD->getTypeForDecl());
   1956       if (OldTD->isModed())
   1957         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
   1958                                     OldTD->getUnderlyingType());
   1959       else
   1960         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
   1961 
   1962       // Make the old tag definition visible.
   1963       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
   1964 
   1965       // If this was an unscoped enumeration, yank all of its enumerators
   1966       // out of the scope.
   1967       if (isa<EnumDecl>(NewTag)) {
   1968         Scope *EnumScope = getNonFieldDeclScope(S);
   1969         for (auto *D : NewTag->decls()) {
   1970           auto *ED = cast<EnumConstantDecl>(D);
   1971           assert(EnumScope->isDeclScope(ED));
   1972           EnumScope->RemoveDecl(ED);
   1973           IdResolver.RemoveDecl(ED);
   1974           ED->getLexicalDeclContext()->removeDecl(ED);
   1975         }
   1976       }
   1977     }
   1978   }
   1979 
   1980   // If the typedef types are not identical, reject them in all languages and
   1981   // with any extensions enabled.
   1982   if (isIncompatibleTypedef(Old, New))
   1983     return;
   1984 
   1985   // The types match.  Link up the redeclaration chain and merge attributes if
   1986   // the old declaration was a typedef.
   1987   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
   1988     New->setPreviousDecl(Typedef);
   1989     mergeDeclAttributes(New, Old);
   1990   }
   1991 
   1992   if (getLangOpts().MicrosoftExt)
   1993     return;
   1994 
   1995   if (getLangOpts().CPlusPlus) {
   1996     // C++ [dcl.typedef]p2:
   1997     //   In a given non-class scope, a typedef specifier can be used to
   1998     //   redefine the name of any type declared in that scope to refer
   1999     //   to the type to which it already refers.
   2000     if (!isa<CXXRecordDecl>(CurContext))
   2001       return;
   2002 
   2003     // C++0x [dcl.typedef]p4:
   2004     //   In a given class scope, a typedef specifier can be used to redefine
   2005     //   any class-name declared in that scope that is not also a typedef-name
   2006     //   to refer to the type to which it already refers.
   2007     //
   2008     // This wording came in via DR424, which was a correction to the
   2009     // wording in DR56, which accidentally banned code like:
   2010     //
   2011     //   struct S {
   2012     //     typedef struct A { } A;
   2013     //   };
   2014     //
   2015     // in the C++03 standard. We implement the C++0x semantics, which
   2016     // allow the above but disallow
   2017     //
   2018     //   struct S {
   2019     //     typedef int I;
   2020     //     typedef int I;
   2021     //   };
   2022     //
   2023     // since that was the intent of DR56.
   2024     if (!isa<TypedefNameDecl>(Old))
   2025       return;
   2026 
   2027     Diag(New->getLocation(), diag::err_redefinition)
   2028       << New->getDeclName();
   2029     Diag(Old->getLocation(), diag::note_previous_definition);
   2030     return New->setInvalidDecl();
   2031   }
   2032 
   2033   // Modules always permit redefinition of typedefs, as does C11.
   2034   if (getLangOpts().Modules || getLangOpts().C11)
   2035     return;
   2036 
   2037   // If we have a redefinition of a typedef in C, emit a warning.  This warning
   2038   // is normally mapped to an error, but can be controlled with
   2039   // -Wtypedef-redefinition.  If either the original or the redefinition is
   2040   // in a system header, don't emit this for compatibility with GCC.
   2041   if (getDiagnostics().getSuppressSystemWarnings() &&
   2042       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
   2043        Context.getSourceManager().isInSystemHeader(New->getLocation())))
   2044     return;
   2045 
   2046   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
   2047     << New->getDeclName();
   2048   Diag(Old->getLocation(), diag::note_previous_definition);
   2049 }
   2050 
   2051 /// DeclhasAttr - returns true if decl Declaration already has the target
   2052 /// attribute.
   2053 static bool DeclHasAttr(const Decl *D, const Attr *A) {
   2054   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
   2055   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
   2056   for (const auto *i : D->attrs())
   2057     if (i->getKind() == A->getKind()) {
   2058       if (Ann) {
   2059         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
   2060           return true;
   2061         continue;
   2062       }
   2063       // FIXME: Don't hardcode this check
   2064       if (OA && isa<OwnershipAttr>(i))
   2065         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
   2066       return true;
   2067     }
   2068 
   2069   return false;
   2070 }
   2071 
   2072 static bool isAttributeTargetADefinition(Decl *D) {
   2073   if (VarDecl *VD = dyn_cast<VarDecl>(D))
   2074     return VD->isThisDeclarationADefinition();
   2075   if (TagDecl *TD = dyn_cast<TagDecl>(D))
   2076     return TD->isCompleteDefinition() || TD->isBeingDefined();
   2077   return true;
   2078 }
   2079 
   2080 /// Merge alignment attributes from \p Old to \p New, taking into account the
   2081 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
   2082 ///
   2083 /// \return \c true if any attributes were added to \p New.
   2084 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
   2085   // Look for alignas attributes on Old, and pick out whichever attribute
   2086   // specifies the strictest alignment requirement.
   2087   AlignedAttr *OldAlignasAttr = nullptr;
   2088   AlignedAttr *OldStrictestAlignAttr = nullptr;
   2089   unsigned OldAlign = 0;
   2090   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
   2091     // FIXME: We have no way of representing inherited dependent alignments
   2092     // in a case like:
   2093     //   template<int A, int B> struct alignas(A) X;
   2094     //   template<int A, int B> struct alignas(B) X {};
   2095     // For now, we just ignore any alignas attributes which are not on the
   2096     // definition in such a case.
   2097     if (I->isAlignmentDependent())
   2098       return false;
   2099 
   2100     if (I->isAlignas())
   2101       OldAlignasAttr = I;
   2102 
   2103     unsigned Align = I->getAlignment(S.Context);
   2104     if (Align > OldAlign) {
   2105       OldAlign = Align;
   2106       OldStrictestAlignAttr = I;
   2107     }
   2108   }
   2109 
   2110   // Look for alignas attributes on New.
   2111   AlignedAttr *NewAlignasAttr = nullptr;
   2112   unsigned NewAlign = 0;
   2113   for (auto *I : New->specific_attrs<AlignedAttr>()) {
   2114     if (I->isAlignmentDependent())
   2115       return false;
   2116 
   2117     if (I->isAlignas())
   2118       NewAlignasAttr = I;
   2119 
   2120     unsigned Align = I->getAlignment(S.Context);
   2121     if (Align > NewAlign)
   2122       NewAlign = Align;
   2123   }
   2124 
   2125   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
   2126     // Both declarations have 'alignas' attributes. We require them to match.
   2127     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
   2128     // fall short. (If two declarations both have alignas, they must both match
   2129     // every definition, and so must match each other if there is a definition.)
   2130 
   2131     // If either declaration only contains 'alignas(0)' specifiers, then it
   2132     // specifies the natural alignment for the type.
   2133     if (OldAlign == 0 || NewAlign == 0) {
   2134       QualType Ty;
   2135       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
   2136         Ty = VD->getType();
   2137       else
   2138         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
   2139 
   2140       if (OldAlign == 0)
   2141         OldAlign = S.Context.getTypeAlign(Ty);
   2142       if (NewAlign == 0)
   2143         NewAlign = S.Context.getTypeAlign(Ty);
   2144     }
   2145 
   2146     if (OldAlign != NewAlign) {
   2147       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
   2148         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
   2149         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
   2150       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
   2151     }
   2152   }
   2153 
   2154   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
   2155     // C++11 [dcl.align]p6:
   2156     //   if any declaration of an entity has an alignment-specifier,
   2157     //   every defining declaration of that entity shall specify an
   2158     //   equivalent alignment.
   2159     // C11 6.7.5/7:
   2160     //   If the definition of an object does not have an alignment
   2161     //   specifier, any other declaration of that object shall also
   2162     //   have no alignment specifier.
   2163     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
   2164       << OldAlignasAttr;
   2165     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
   2166       << OldAlignasAttr;
   2167   }
   2168 
   2169   bool AnyAdded = false;
   2170 
   2171   // Ensure we have an attribute representing the strictest alignment.
   2172   if (OldAlign > NewAlign) {
   2173     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
   2174     Clone->setInherited(true);
   2175     New->addAttr(Clone);
   2176     AnyAdded = true;
   2177   }
   2178 
   2179   // Ensure we have an alignas attribute if the old declaration had one.
   2180   if (OldAlignasAttr && !NewAlignasAttr &&
   2181       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
   2182     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
   2183     Clone->setInherited(true);
   2184     New->addAttr(Clone);
   2185     AnyAdded = true;
   2186   }
   2187 
   2188   return AnyAdded;
   2189 }
   2190 
   2191 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
   2192                                const InheritableAttr *Attr,
   2193                                Sema::AvailabilityMergeKind AMK) {
   2194   InheritableAttr *NewAttr = nullptr;
   2195   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
   2196   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
   2197     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
   2198                                       AA->getIntroduced(), AA->getDeprecated(),
   2199                                       AA->getObsoleted(), AA->getUnavailable(),
   2200                                       AA->getMessage(), AMK,
   2201                                       AttrSpellingListIndex);
   2202   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
   2203     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
   2204                                     AttrSpellingListIndex);
   2205   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
   2206     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
   2207                                         AttrSpellingListIndex);
   2208   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
   2209     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
   2210                                    AttrSpellingListIndex);
   2211   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
   2212     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
   2213                                    AttrSpellingListIndex);
   2214   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
   2215     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
   2216                                 FA->getFormatIdx(), FA->getFirstArg(),
   2217                                 AttrSpellingListIndex);
   2218   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
   2219     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
   2220                                  AttrSpellingListIndex);
   2221   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
   2222     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
   2223                                        AttrSpellingListIndex,
   2224                                        IA->getSemanticSpelling());
   2225   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
   2226     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
   2227                                       &S.Context.Idents.get(AA->getSpelling()),
   2228                                       AttrSpellingListIndex);
   2229   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
   2230     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
   2231   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
   2232     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
   2233   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
   2234     NewAttr = S.mergeInternalLinkageAttr(
   2235         D, InternalLinkageA->getRange(),
   2236         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
   2237         AttrSpellingListIndex);
   2238   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
   2239     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
   2240                                 &S.Context.Idents.get(CommonA->getSpelling()),
   2241                                 AttrSpellingListIndex);
   2242   else if (isa<AlignedAttr>(Attr))
   2243     // AlignedAttrs are handled separately, because we need to handle all
   2244     // such attributes on a declaration at the same time.
   2245     NewAttr = nullptr;
   2246   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
   2247            (AMK == Sema::AMK_Override ||
   2248             AMK == Sema::AMK_ProtocolImplementation))
   2249     NewAttr = nullptr;
   2250   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
   2251     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
   2252 
   2253   if (NewAttr) {
   2254     NewAttr->setInherited(true);
   2255     D->addAttr(NewAttr);
   2256     return true;
   2257   }
   2258 
   2259   return false;
   2260 }
   2261 
   2262 static const Decl *getDefinition(const Decl *D) {
   2263   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
   2264     return TD->getDefinition();
   2265   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
   2266     const VarDecl *Def = VD->getDefinition();
   2267     if (Def)
   2268       return Def;
   2269     return VD->getActingDefinition();
   2270   }
   2271   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   2272     const FunctionDecl* Def;
   2273     if (FD->isDefined(Def))
   2274       return Def;
   2275   }
   2276   return nullptr;
   2277 }
   2278 
   2279 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
   2280   for (const auto *Attribute : D->attrs())
   2281     if (Attribute->getKind() == Kind)
   2282       return true;
   2283   return false;
   2284 }
   2285 
   2286 /// checkNewAttributesAfterDef - If we already have a definition, check that
   2287 /// there are no new attributes in this declaration.
   2288 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
   2289   if (!New->hasAttrs())
   2290     return;
   2291 
   2292   const Decl *Def = getDefinition(Old);
   2293   if (!Def || Def == New)
   2294     return;
   2295 
   2296   AttrVec &NewAttributes = New->getAttrs();
   2297   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
   2298     const Attr *NewAttribute = NewAttributes[I];
   2299 
   2300     if (isa<AliasAttr>(NewAttribute)) {
   2301       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
   2302         Sema::SkipBodyInfo SkipBody;
   2303         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
   2304 
   2305         // If we're skipping this definition, drop the "alias" attribute.
   2306         if (SkipBody.ShouldSkip) {
   2307           NewAttributes.erase(NewAttributes.begin() + I);
   2308           --E;
   2309           continue;
   2310         }
   2311       } else {
   2312         VarDecl *VD = cast<VarDecl>(New);
   2313         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
   2314                                 VarDecl::TentativeDefinition
   2315                             ? diag::err_alias_after_tentative
   2316                             : diag::err_redefinition;
   2317         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
   2318         S.Diag(Def->getLocation(), diag::note_previous_definition);
   2319         VD->setInvalidDecl();
   2320       }
   2321       ++I;
   2322       continue;
   2323     }
   2324 
   2325     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
   2326       // Tentative definitions are only interesting for the alias check above.
   2327       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
   2328         ++I;
   2329         continue;
   2330       }
   2331     }
   2332 
   2333     if (hasAttribute(Def, NewAttribute->getKind())) {
   2334       ++I;
   2335       continue; // regular attr merging will take care of validating this.
   2336     }
   2337 
   2338     if (isa<C11NoReturnAttr>(NewAttribute)) {
   2339       // C's _Noreturn is allowed to be added to a function after it is defined.
   2340       ++I;
   2341       continue;
   2342     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
   2343       if (AA->isAlignas()) {
   2344         // C++11 [dcl.align]p6:
   2345         //   if any declaration of an entity has an alignment-specifier,
   2346         //   every defining declaration of that entity shall specify an
   2347         //   equivalent alignment.
   2348         // C11 6.7.5/7:
   2349         //   If the definition of an object does not have an alignment
   2350         //   specifier, any other declaration of that object shall also
   2351         //   have no alignment specifier.
   2352         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
   2353           << AA;
   2354         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
   2355           << AA;
   2356         NewAttributes.erase(NewAttributes.begin() + I);
   2357         --E;
   2358         continue;
   2359       }
   2360     }
   2361 
   2362     S.Diag(NewAttribute->getLocation(),
   2363            diag::warn_attribute_precede_definition);
   2364     S.Diag(Def->getLocation(), diag::note_previous_definition);
   2365     NewAttributes.erase(NewAttributes.begin() + I);
   2366     --E;
   2367   }
   2368 }
   2369 
   2370 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
   2371 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
   2372                                AvailabilityMergeKind AMK) {
   2373   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
   2374     UsedAttr *NewAttr = OldAttr->clone(Context);
   2375     NewAttr->setInherited(true);
   2376     New->addAttr(NewAttr);
   2377   }
   2378 
   2379   if (!Old->hasAttrs() && !New->hasAttrs())
   2380     return;
   2381 
   2382   // Attributes declared post-definition are currently ignored.
   2383   checkNewAttributesAfterDef(*this, New, Old);
   2384 
   2385   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
   2386     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
   2387       if (OldA->getLabel() != NewA->getLabel()) {
   2388         // This redeclaration changes __asm__ label.
   2389         Diag(New->getLocation(), diag::err_different_asm_label);
   2390         Diag(OldA->getLocation(), diag::note_previous_declaration);
   2391       }
   2392     } else if (Old->isUsed()) {
   2393       // This redeclaration adds an __asm__ label to a declaration that has
   2394       // already been ODR-used.
   2395       Diag(New->getLocation(), diag::err_late_asm_label_name)
   2396         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
   2397     }
   2398   }
   2399 
   2400   if (!Old->hasAttrs())
   2401     return;
   2402 
   2403   bool foundAny = New->hasAttrs();
   2404 
   2405   // Ensure that any moving of objects within the allocated map is done before
   2406   // we process them.
   2407   if (!foundAny) New->setAttrs(AttrVec());
   2408 
   2409   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
   2410     // Ignore deprecated/unavailable/availability attributes if requested.
   2411     AvailabilityMergeKind LocalAMK = AMK_None;
   2412     if (isa<DeprecatedAttr>(I) ||
   2413         isa<UnavailableAttr>(I) ||
   2414         isa<AvailabilityAttr>(I)) {
   2415       switch (AMK) {
   2416       case AMK_None:
   2417         continue;
   2418 
   2419       case AMK_Redeclaration:
   2420       case AMK_Override:
   2421       case AMK_ProtocolImplementation:
   2422         LocalAMK = AMK;
   2423         break;
   2424       }
   2425     }
   2426 
   2427     // Already handled.
   2428     if (isa<UsedAttr>(I))
   2429       continue;
   2430 
   2431     if (mergeDeclAttribute(*this, New, I, LocalAMK))
   2432       foundAny = true;
   2433   }
   2434 
   2435   if (mergeAlignedAttrs(*this, New, Old))
   2436     foundAny = true;
   2437 
   2438   if (!foundAny) New->dropAttrs();
   2439 }
   2440 
   2441 /// mergeParamDeclAttributes - Copy attributes from the old parameter
   2442 /// to the new one.
   2443 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
   2444                                      const ParmVarDecl *oldDecl,
   2445                                      Sema &S) {
   2446   // C++11 [dcl.attr.depend]p2:
   2447   //   The first declaration of a function shall specify the
   2448   //   carries_dependency attribute for its declarator-id if any declaration
   2449   //   of the function specifies the carries_dependency attribute.
   2450   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
   2451   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
   2452     S.Diag(CDA->getLocation(),
   2453            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
   2454     // Find the first declaration of the parameter.
   2455     // FIXME: Should we build redeclaration chains for function parameters?
   2456     const FunctionDecl *FirstFD =
   2457       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
   2458     const ParmVarDecl *FirstVD =
   2459       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
   2460     S.Diag(FirstVD->getLocation(),
   2461            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
   2462   }
   2463 
   2464   if (!oldDecl->hasAttrs())
   2465     return;
   2466 
   2467   bool foundAny = newDecl->hasAttrs();
   2468 
   2469   // Ensure that any moving of objects within the allocated map is
   2470   // done before we process them.
   2471   if (!foundAny) newDecl->setAttrs(AttrVec());
   2472 
   2473   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
   2474     if (!DeclHasAttr(newDecl, I)) {
   2475       InheritableAttr *newAttr =
   2476         cast<InheritableParamAttr>(I->clone(S.Context));
   2477       newAttr->setInherited(true);
   2478       newDecl->addAttr(newAttr);
   2479       foundAny = true;
   2480     }
   2481   }
   2482 
   2483   if (!foundAny) newDecl->dropAttrs();
   2484 }
   2485 
   2486 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
   2487                                 const ParmVarDecl *OldParam,
   2488                                 Sema &S) {
   2489   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
   2490     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
   2491       if (*Oldnullability != *Newnullability) {
   2492         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
   2493           << DiagNullabilityKind(
   2494                *Newnullability,
   2495                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
   2496                 != 0))
   2497           << DiagNullabilityKind(
   2498                *Oldnullability,
   2499                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
   2500                 != 0));
   2501         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
   2502       }
   2503     } else {
   2504       QualType NewT = NewParam->getType();
   2505       NewT = S.Context.getAttributedType(
   2506                          AttributedType::getNullabilityAttrKind(*Oldnullability),
   2507                          NewT, NewT);
   2508       NewParam->setType(NewT);
   2509     }
   2510   }
   2511 }
   2512 
   2513 namespace {
   2514 
   2515 /// Used in MergeFunctionDecl to keep track of function parameters in
   2516 /// C.
   2517 struct GNUCompatibleParamWarning {
   2518   ParmVarDecl *OldParm;
   2519   ParmVarDecl *NewParm;
   2520   QualType PromotedType;
   2521 };
   2522 
   2523 }
   2524 
   2525 /// getSpecialMember - get the special member enum for a method.
   2526 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
   2527   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
   2528     if (Ctor->isDefaultConstructor())
   2529       return Sema::CXXDefaultConstructor;
   2530 
   2531     if (Ctor->isCopyConstructor())
   2532       return Sema::CXXCopyConstructor;
   2533 
   2534     if (Ctor->isMoveConstructor())
   2535       return Sema::CXXMoveConstructor;
   2536   } else if (isa<CXXDestructorDecl>(MD)) {
   2537     return Sema::CXXDestructor;
   2538   } else if (MD->isCopyAssignmentOperator()) {
   2539     return Sema::CXXCopyAssignment;
   2540   } else if (MD->isMoveAssignmentOperator()) {
   2541     return Sema::CXXMoveAssignment;
   2542   }
   2543 
   2544   return Sema::CXXInvalid;
   2545 }
   2546 
   2547 // Determine whether the previous declaration was a definition, implicit
   2548 // declaration, or a declaration.
   2549 template <typename T>
   2550 static std::pair<diag::kind, SourceLocation>
   2551 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
   2552   diag::kind PrevDiag;
   2553   SourceLocation OldLocation = Old->getLocation();
   2554   if (Old->isThisDeclarationADefinition())
   2555     PrevDiag = diag::note_previous_definition;
   2556   else if (Old->isImplicit()) {
   2557     PrevDiag = diag::note_previous_implicit_declaration;
   2558     if (OldLocation.isInvalid())
   2559       OldLocation = New->getLocation();
   2560   } else
   2561     PrevDiag = diag::note_previous_declaration;
   2562   return std::make_pair(PrevDiag, OldLocation);
   2563 }
   2564 
   2565 /// canRedefineFunction - checks if a function can be redefined. Currently,
   2566 /// only extern inline functions can be redefined, and even then only in
   2567 /// GNU89 mode.
   2568 static bool canRedefineFunction(const FunctionDecl *FD,
   2569                                 const LangOptions& LangOpts) {
   2570   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
   2571           !LangOpts.CPlusPlus &&
   2572           FD->isInlineSpecified() &&
   2573           FD->getStorageClass() == SC_Extern);
   2574 }
   2575 
   2576 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
   2577   const AttributedType *AT = T->getAs<AttributedType>();
   2578   while (AT && !AT->isCallingConv())
   2579     AT = AT->getModifiedType()->getAs<AttributedType>();
   2580   return AT;
   2581 }
   2582 
   2583 template <typename T>
   2584 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
   2585   const DeclContext *DC = Old->getDeclContext();
   2586   if (DC->isRecord())
   2587     return false;
   2588 
   2589   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
   2590   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
   2591     return true;
   2592   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
   2593     return true;
   2594   return false;
   2595 }
   2596 
   2597 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
   2598 static bool isExternC(VarTemplateDecl *) { return false; }
   2599 
   2600 /// \brief Check whether a redeclaration of an entity introduced by a
   2601 /// using-declaration is valid, given that we know it's not an overload
   2602 /// (nor a hidden tag declaration).
   2603 template<typename ExpectedDecl>
   2604 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
   2605                                    ExpectedDecl *New) {
   2606   // C++11 [basic.scope.declarative]p4:
   2607   //   Given a set of declarations in a single declarative region, each of
   2608   //   which specifies the same unqualified name,
   2609   //   -- they shall all refer to the same entity, or all refer to functions
   2610   //      and function templates; or
   2611   //   -- exactly one declaration shall declare a class name or enumeration
   2612   //      name that is not a typedef name and the other declarations shall all
   2613   //      refer to the same variable or enumerator, or all refer to functions
   2614   //      and function templates; in this case the class name or enumeration
   2615   //      name is hidden (3.3.10).
   2616 
   2617   // C++11 [namespace.udecl]p14:
   2618   //   If a function declaration in namespace scope or block scope has the
   2619   //   same name and the same parameter-type-list as a function introduced
   2620   //   by a using-declaration, and the declarations do not declare the same
   2621   //   function, the program is ill-formed.
   2622 
   2623   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
   2624   if (Old &&
   2625       !Old->getDeclContext()->getRedeclContext()->Equals(
   2626           New->getDeclContext()->getRedeclContext()) &&
   2627       !(isExternC(Old) && isExternC(New)))
   2628     Old = nullptr;
   2629 
   2630   if (!Old) {
   2631     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
   2632     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
   2633     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
   2634     return true;
   2635   }
   2636   return false;
   2637 }
   2638 
   2639 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
   2640                                             const FunctionDecl *B) {
   2641   assert(A->getNumParams() == B->getNumParams());
   2642 
   2643   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
   2644     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
   2645     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
   2646     if (AttrA == AttrB)
   2647       return true;
   2648     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
   2649   };
   2650 
   2651   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
   2652 }
   2653 
   2654 /// MergeFunctionDecl - We just parsed a function 'New' from
   2655 /// declarator D which has the same name and scope as a previous
   2656 /// declaration 'Old'.  Figure out how to resolve this situation,
   2657 /// merging decls or emitting diagnostics as appropriate.
   2658 ///
   2659 /// In C++, New and Old must be declarations that are not
   2660 /// overloaded. Use IsOverload to determine whether New and Old are
   2661 /// overloaded, and to select the Old declaration that New should be
   2662 /// merged with.
   2663 ///
   2664 /// Returns true if there was an error, false otherwise.
   2665 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
   2666                              Scope *S, bool MergeTypeWithOld) {
   2667   // Verify the old decl was also a function.
   2668   FunctionDecl *Old = OldD->getAsFunction();
   2669   if (!Old) {
   2670     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
   2671       if (New->getFriendObjectKind()) {
   2672         Diag(New->getLocation(), diag::err_using_decl_friend);
   2673         Diag(Shadow->getTargetDecl()->getLocation(),
   2674              diag::note_using_decl_target);
   2675         Diag(Shadow->getUsingDecl()->getLocation(),
   2676              diag::note_using_decl) << 0;
   2677         return true;
   2678       }
   2679 
   2680       // Check whether the two declarations might declare the same function.
   2681       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
   2682         return true;
   2683       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
   2684     } else {
   2685       Diag(New->getLocation(), diag::err_redefinition_different_kind)
   2686         << New->getDeclName();
   2687       Diag(OldD->getLocation(), diag::note_previous_definition);
   2688       return true;
   2689     }
   2690   }
   2691 
   2692   // If the old declaration is invalid, just give up here.
   2693   if (Old->isInvalidDecl())
   2694     return true;
   2695 
   2696   diag::kind PrevDiag;
   2697   SourceLocation OldLocation;
   2698   std::tie(PrevDiag, OldLocation) =
   2699       getNoteDiagForInvalidRedeclaration(Old, New);
   2700 
   2701   // Don't complain about this if we're in GNU89 mode and the old function
   2702   // is an extern inline function.
   2703   // Don't complain about specializations. They are not supposed to have
   2704   // storage classes.
   2705   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
   2706       New->getStorageClass() == SC_Static &&
   2707       Old->hasExternalFormalLinkage() &&
   2708       !New->getTemplateSpecializationInfo() &&
   2709       !canRedefineFunction(Old, getLangOpts())) {
   2710     if (getLangOpts().MicrosoftExt) {
   2711       Diag(New->getLocation(), diag::ext_static_non_static) << New;
   2712       Diag(OldLocation, PrevDiag);
   2713     } else {
   2714       Diag(New->getLocation(), diag::err_static_non_static) << New;
   2715       Diag(OldLocation, PrevDiag);
   2716       return true;
   2717     }
   2718   }
   2719 
   2720   if (New->hasAttr<InternalLinkageAttr>() &&
   2721       !Old->hasAttr<InternalLinkageAttr>()) {
   2722     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
   2723         << New->getDeclName();
   2724     Diag(Old->getLocation(), diag::note_previous_definition);
   2725     New->dropAttr<InternalLinkageAttr>();
   2726   }
   2727 
   2728   // If a function is first declared with a calling convention, but is later
   2729   // declared or defined without one, all following decls assume the calling
   2730   // convention of the first.
   2731   //
   2732   // It's OK if a function is first declared without a calling convention,
   2733   // but is later declared or defined with the default calling convention.
   2734   //
   2735   // To test if either decl has an explicit calling convention, we look for
   2736   // AttributedType sugar nodes on the type as written.  If they are missing or
   2737   // were canonicalized away, we assume the calling convention was implicit.
   2738   //
   2739   // Note also that we DO NOT return at this point, because we still have
   2740   // other tests to run.
   2741   QualType OldQType = Context.getCanonicalType(Old->getType());
   2742   QualType NewQType = Context.getCanonicalType(New->getType());
   2743   const FunctionType *OldType = cast<FunctionType>(OldQType);
   2744   const FunctionType *NewType = cast<FunctionType>(NewQType);
   2745   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
   2746   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
   2747   bool RequiresAdjustment = false;
   2748 
   2749   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
   2750     FunctionDecl *First = Old->getFirstDecl();
   2751     const FunctionType *FT =
   2752         First->getType().getCanonicalType()->castAs<FunctionType>();
   2753     FunctionType::ExtInfo FI = FT->getExtInfo();
   2754     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
   2755     if (!NewCCExplicit) {
   2756       // Inherit the CC from the previous declaration if it was specified
   2757       // there but not here.
   2758       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
   2759       RequiresAdjustment = true;
   2760     } else {
   2761       // Calling conventions aren't compatible, so complain.
   2762       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
   2763       Diag(New->getLocation(), diag::err_cconv_change)
   2764         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
   2765         << !FirstCCExplicit
   2766         << (!FirstCCExplicit ? "" :
   2767             FunctionType::getNameForCallConv(FI.getCC()));
   2768 
   2769       // Put the note on the first decl, since it is the one that matters.
   2770       Diag(First->getLocation(), diag::note_previous_declaration);
   2771       return true;
   2772     }
   2773   }
   2774 
   2775   // FIXME: diagnose the other way around?
   2776   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
   2777     NewTypeInfo = NewTypeInfo.withNoReturn(true);
   2778     RequiresAdjustment = true;
   2779   }
   2780 
   2781   // Merge regparm attribute.
   2782   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
   2783       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
   2784     if (NewTypeInfo.getHasRegParm()) {
   2785       Diag(New->getLocation(), diag::err_regparm_mismatch)
   2786         << NewType->getRegParmType()
   2787         << OldType->getRegParmType();
   2788       Diag(OldLocation, diag::note_previous_declaration);
   2789       return true;
   2790     }
   2791 
   2792     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
   2793     RequiresAdjustment = true;
   2794   }
   2795 
   2796   // Merge ns_returns_retained attribute.
   2797   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
   2798     if (NewTypeInfo.getProducesResult()) {
   2799       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
   2800       Diag(OldLocation, diag::note_previous_declaration);
   2801       return true;
   2802     }
   2803 
   2804     NewTypeInfo = NewTypeInfo.withProducesResult(true);
   2805     RequiresAdjustment = true;
   2806   }
   2807 
   2808   if (RequiresAdjustment) {
   2809     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
   2810     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
   2811     New->setType(QualType(AdjustedType, 0));
   2812     NewQType = Context.getCanonicalType(New->getType());
   2813     NewType = cast<FunctionType>(NewQType);
   2814   }
   2815 
   2816   // If this redeclaration makes the function inline, we may need to add it to
   2817   // UndefinedButUsed.
   2818   if (!Old->isInlined() && New->isInlined() &&
   2819       !New->hasAttr<GNUInlineAttr>() &&
   2820       !getLangOpts().GNUInline &&
   2821       Old->isUsed(false) &&
   2822       !Old->isDefined() && !New->isThisDeclarationADefinition())
   2823     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
   2824                                            SourceLocation()));
   2825 
   2826   // If this redeclaration makes it newly gnu_inline, we don't want to warn
   2827   // about it.
   2828   if (New->hasAttr<GNUInlineAttr>() &&
   2829       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
   2830     UndefinedButUsed.erase(Old->getCanonicalDecl());
   2831   }
   2832 
   2833   // If pass_object_size params don't match up perfectly, this isn't a valid
   2834   // redeclaration.
   2835   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
   2836       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
   2837     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
   2838         << New->getDeclName();
   2839     Diag(OldLocation, PrevDiag) << Old << Old->getType();
   2840     return true;
   2841   }
   2842 
   2843   if (getLangOpts().CPlusPlus) {
   2844     // (C++98 13.1p2):
   2845     //   Certain function declarations cannot be overloaded:
   2846     //     -- Function declarations that differ only in the return type
   2847     //        cannot be overloaded.
   2848 
   2849     // Go back to the type source info to compare the declared return types,
   2850     // per C++1y [dcl.type.auto]p13:
   2851     //   Redeclarations or specializations of a function or function template
   2852     //   with a declared return type that uses a placeholder type shall also
   2853     //   use that placeholder, not a deduced type.
   2854     QualType OldDeclaredReturnType =
   2855         (Old->getTypeSourceInfo()
   2856              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
   2857              : OldType)->getReturnType();
   2858     QualType NewDeclaredReturnType =
   2859         (New->getTypeSourceInfo()
   2860              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
   2861              : NewType)->getReturnType();
   2862     QualType ResQT;
   2863     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
   2864         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
   2865           New->isLocalExternDecl())) {
   2866       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
   2867           OldDeclaredReturnType->isObjCObjectPointerType())
   2868         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
   2869       if (ResQT.isNull()) {
   2870         if (New->isCXXClassMember() && New->isOutOfLine())
   2871           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
   2872               << New << New->getReturnTypeSourceRange();
   2873         else
   2874           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
   2875               << New->getReturnTypeSourceRange();
   2876         Diag(OldLocation, PrevDiag) << Old << Old->getType()
   2877                                     << Old->getReturnTypeSourceRange();
   2878         return true;
   2879       }
   2880       else
   2881         NewQType = ResQT;
   2882     }
   2883 
   2884     QualType OldReturnType = OldType->getReturnType();
   2885     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
   2886     if (OldReturnType != NewReturnType) {
   2887       // If this function has a deduced return type and has already been
   2888       // defined, copy the deduced value from the old declaration.
   2889       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
   2890       if (OldAT && OldAT->isDeduced()) {
   2891         New->setType(
   2892             SubstAutoType(New->getType(),
   2893                           OldAT->isDependentType() ? Context.DependentTy
   2894                                                    : OldAT->getDeducedType()));
   2895         NewQType = Context.getCanonicalType(
   2896             SubstAutoType(NewQType,
   2897                           OldAT->isDependentType() ? Context.DependentTy
   2898                                                    : OldAT->getDeducedType()));
   2899       }
   2900     }
   2901 
   2902     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
   2903     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
   2904     if (OldMethod && NewMethod) {
   2905       // Preserve triviality.
   2906       NewMethod->setTrivial(OldMethod->isTrivial());
   2907 
   2908       // MSVC allows explicit template specialization at class scope:
   2909       // 2 CXXMethodDecls referring to the same function will be injected.
   2910       // We don't want a redeclaration error.
   2911       bool IsClassScopeExplicitSpecialization =
   2912                               OldMethod->isFunctionTemplateSpecialization() &&
   2913                               NewMethod->isFunctionTemplateSpecialization();
   2914       bool isFriend = NewMethod->getFriendObjectKind();
   2915 
   2916       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
   2917           !IsClassScopeExplicitSpecialization) {
   2918         //    -- Member function declarations with the same name and the
   2919         //       same parameter types cannot be overloaded if any of them
   2920         //       is a static member function declaration.
   2921         if (OldMethod->isStatic() != NewMethod->isStatic()) {
   2922           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
   2923           Diag(OldLocation, PrevDiag) << Old << Old->getType();
   2924           return true;
   2925         }
   2926 
   2927         // C++ [class.mem]p1:
   2928         //   [...] A member shall not be declared twice in the
   2929         //   member-specification, except that a nested class or member
   2930         //   class template can be declared and then later defined.
   2931         if (ActiveTemplateInstantiations.empty()) {
   2932           unsigned NewDiag;
   2933           if (isa<CXXConstructorDecl>(OldMethod))
   2934             NewDiag = diag::err_constructor_redeclared;
   2935           else if (isa<CXXDestructorDecl>(NewMethod))
   2936             NewDiag = diag::err_destructor_redeclared;
   2937           else if (isa<CXXConversionDecl>(NewMethod))
   2938             NewDiag = diag::err_conv_function_redeclared;
   2939           else
   2940             NewDiag = diag::err_member_redeclared;
   2941 
   2942           Diag(New->getLocation(), NewDiag);
   2943         } else {
   2944           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
   2945             << New << New->getType();
   2946         }
   2947         Diag(OldLocation, PrevDiag) << Old << Old->getType();
   2948         return true;
   2949 
   2950       // Complain if this is an explicit declaration of a special
   2951       // member that was initially declared implicitly.
   2952       //
   2953       // As an exception, it's okay to befriend such methods in order
   2954       // to permit the implicit constructor/destructor/operator calls.
   2955       } else if (OldMethod->isImplicit()) {
   2956         if (isFriend) {
   2957           NewMethod->setImplicit();
   2958         } else {
   2959           Diag(NewMethod->getLocation(),
   2960                diag::err_definition_of_implicitly_declared_member)
   2961             << New << getSpecialMember(OldMethod);
   2962           return true;
   2963         }
   2964       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
   2965         Diag(NewMethod->getLocation(),
   2966              diag::err_definition_of_explicitly_defaulted_member)
   2967           << getSpecialMember(OldMethod);
   2968         return true;
   2969       }
   2970     }
   2971 
   2972     // C++11 [dcl.attr.noreturn]p1:
   2973     //   The first declaration of a function shall specify the noreturn
   2974     //   attribute if any declaration of that function specifies the noreturn
   2975     //   attribute.
   2976     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
   2977     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
   2978       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
   2979       Diag(Old->getFirstDecl()->getLocation(),
   2980            diag::note_noreturn_missing_first_decl);
   2981     }
   2982 
   2983     // C++11 [dcl.attr.depend]p2:
   2984     //   The first declaration of a function shall specify the
   2985     //   carries_dependency attribute for its declarator-id if any declaration
   2986     //   of the function specifies the carries_dependency attribute.
   2987     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
   2988     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
   2989       Diag(CDA->getLocation(),
   2990            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
   2991       Diag(Old->getFirstDecl()->getLocation(),
   2992            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
   2993     }
   2994 
   2995     // (C++98 8.3.5p3):
   2996     //   All declarations for a function shall agree exactly in both the
   2997     //   return type and the parameter-type-list.
   2998     // We also want to respect all the extended bits except noreturn.
   2999 
   3000     // noreturn should now match unless the old type info didn't have it.
   3001     QualType OldQTypeForComparison = OldQType;
   3002     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
   3003       assert(OldQType == QualType(OldType, 0));
   3004       const FunctionType *OldTypeForComparison
   3005         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
   3006       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
   3007       assert(OldQTypeForComparison.isCanonical());
   3008     }
   3009 
   3010     if (haveIncompatibleLanguageLinkages(Old, New)) {
   3011       // As a special case, retain the language linkage from previous
   3012       // declarations of a friend function as an extension.
   3013       //
   3014       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
   3015       // and is useful because there's otherwise no way to specify language
   3016       // linkage within class scope.
   3017       //
   3018       // Check cautiously as the friend object kind isn't yet complete.
   3019       if (New->getFriendObjectKind() != Decl::FOK_None) {
   3020         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
   3021         Diag(OldLocation, PrevDiag);
   3022       } else {
   3023         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
   3024         Diag(OldLocation, PrevDiag);
   3025         return true;
   3026       }
   3027     }
   3028 
   3029     if (OldQTypeForComparison == NewQType)
   3030       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
   3031 
   3032     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
   3033         New->isLocalExternDecl()) {
   3034       // It's OK if we couldn't merge types for a local function declaraton
   3035       // if either the old or new type is dependent. We'll merge the types
   3036       // when we instantiate the function.
   3037       return false;
   3038     }
   3039 
   3040     // Fall through for conflicting redeclarations and redefinitions.
   3041   }
   3042 
   3043   // C: Function types need to be compatible, not identical. This handles
   3044   // duplicate function decls like "void f(int); void f(enum X);" properly.
   3045   if (!getLangOpts().CPlusPlus &&
   3046       Context.typesAreCompatible(OldQType, NewQType)) {
   3047     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
   3048     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
   3049     const FunctionProtoType *OldProto = nullptr;
   3050     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
   3051         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
   3052       // The old declaration provided a function prototype, but the
   3053       // new declaration does not. Merge in the prototype.
   3054       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
   3055       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
   3056       NewQType =
   3057           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
   3058                                   OldProto->getExtProtoInfo());
   3059       New->setType(NewQType);
   3060       New->setHasInheritedPrototype();
   3061 
   3062       // Synthesize parameters with the same types.
   3063       SmallVector<ParmVarDecl*, 16> Params;
   3064       for (const auto &ParamType : OldProto->param_types()) {
   3065         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
   3066                                                  SourceLocation(), nullptr,
   3067                                                  ParamType, /*TInfo=*/nullptr,
   3068                                                  SC_None, nullptr);
   3069         Param->setScopeInfo(0, Params.size());
   3070         Param->setImplicit();
   3071         Params.push_back(Param);
   3072       }
   3073 
   3074       New->setParams(Params);
   3075     }
   3076 
   3077     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
   3078   }
   3079 
   3080   // GNU C permits a K&R definition to follow a prototype declaration
   3081   // if the declared types of the parameters in the K&R definition
   3082   // match the types in the prototype declaration, even when the
   3083   // promoted types of the parameters from the K&R definition differ
   3084   // from the types in the prototype. GCC then keeps the types from
   3085   // the prototype.
   3086   //
   3087   // If a variadic prototype is followed by a non-variadic K&R definition,
   3088   // the K&R definition becomes variadic.  This is sort of an edge case, but
   3089   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
   3090   // C99 6.9.1p8.
   3091   if (!getLangOpts().CPlusPlus &&
   3092       Old->hasPrototype() && !New->hasPrototype() &&
   3093       New->getType()->getAs<FunctionProtoType>() &&
   3094       Old->getNumParams() == New->getNumParams()) {
   3095     SmallVector<QualType, 16> ArgTypes;
   3096     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
   3097     const FunctionProtoType *OldProto
   3098       = Old->getType()->getAs<FunctionProtoType>();
   3099     const FunctionProtoType *NewProto
   3100       = New->getType()->getAs<FunctionProtoType>();
   3101 
   3102     // Determine whether this is the GNU C extension.
   3103     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
   3104                                                NewProto->getReturnType());
   3105     bool LooseCompatible = !MergedReturn.isNull();
   3106     for (unsigned Idx = 0, End = Old->getNumParams();
   3107          LooseCompatible && Idx != End; ++Idx) {
   3108       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
   3109       ParmVarDecl *NewParm = New->getParamDecl(Idx);
   3110       if (Context.typesAreCompatible(OldParm->getType(),
   3111                                      NewProto->getParamType(Idx))) {
   3112         ArgTypes.push_back(NewParm->getType());
   3113       } else if (Context.typesAreCompatible(OldParm->getType(),
   3114                                             NewParm->getType(),
   3115                                             /*CompareUnqualified=*/true)) {
   3116         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
   3117                                            NewProto->getParamType(Idx) };
   3118         Warnings.push_back(Warn);
   3119         ArgTypes.push_back(NewParm->getType());
   3120       } else
   3121         LooseCompatible = false;
   3122     }
   3123 
   3124     if (LooseCompatible) {
   3125       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
   3126         Diag(Warnings[Warn].NewParm->getLocation(),
   3127              diag::ext_param_promoted_not_compatible_with_prototype)
   3128           << Warnings[Warn].PromotedType
   3129           << Warnings[Warn].OldParm->getType();
   3130         if (Warnings[Warn].OldParm->getLocation().isValid())
   3131           Diag(Warnings[Warn].OldParm->getLocation(),
   3132                diag::note_previous_declaration);
   3133       }
   3134 
   3135       if (MergeTypeWithOld)
   3136         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
   3137                                              OldProto->getExtProtoInfo()));
   3138       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
   3139     }
   3140 
   3141     // Fall through to diagnose conflicting types.
   3142   }
   3143 
   3144   // A function that has already been declared has been redeclared or
   3145   // defined with a different type; show an appropriate diagnostic.
   3146 
   3147   // If the previous declaration was an implicitly-generated builtin
   3148   // declaration, then at the very least we should use a specialized note.
   3149   unsigned BuiltinID;
   3150   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
   3151     // If it's actually a library-defined builtin function like 'malloc'
   3152     // or 'printf', just warn about the incompatible redeclaration.
   3153     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
   3154       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
   3155       Diag(OldLocation, diag::note_previous_builtin_declaration)
   3156         << Old << Old->getType();
   3157 
   3158       // If this is a global redeclaration, just forget hereafter
   3159       // about the "builtin-ness" of the function.
   3160       //
   3161       // Doing this for local extern declarations is problematic.  If
   3162       // the builtin declaration remains visible, a second invalid
   3163       // local declaration will produce a hard error; if it doesn't
   3164       // remain visible, a single bogus local redeclaration (which is
   3165       // actually only a warning) could break all the downstream code.
   3166       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
   3167         New->getIdentifier()->revertBuiltin();
   3168 
   3169       return false;
   3170     }
   3171 
   3172     PrevDiag = diag::note_previous_builtin_declaration;
   3173   }
   3174 
   3175   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
   3176   Diag(OldLocation, PrevDiag) << Old << Old->getType();
   3177   return true;
   3178 }
   3179 
   3180 /// \brief Completes the merge of two function declarations that are
   3181 /// known to be compatible.
   3182 ///
   3183 /// This routine handles the merging of attributes and other
   3184 /// properties of function declarations from the old declaration to
   3185 /// the new declaration, once we know that New is in fact a
   3186 /// redeclaration of Old.
   3187 ///
   3188 /// \returns false
   3189 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
   3190                                         Scope *S, bool MergeTypeWithOld) {
   3191   // Merge the attributes
   3192   mergeDeclAttributes(New, Old);
   3193 
   3194   // Merge "pure" flag.
   3195   if (Old->isPure())
   3196     New->setPure();
   3197 
   3198   // Merge "used" flag.
   3199   if (Old->getMostRecentDecl()->isUsed(false))
   3200     New->setIsUsed();
   3201 
   3202   // Merge attributes from the parameters.  These can mismatch with K&R
   3203   // declarations.
   3204   if (New->getNumParams() == Old->getNumParams())
   3205       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
   3206         ParmVarDecl *NewParam = New->getParamDecl(i);
   3207         ParmVarDecl *OldParam = Old->getParamDecl(i);
   3208         mergeParamDeclAttributes(NewParam, OldParam, *this);
   3209         mergeParamDeclTypes(NewParam, OldParam, *this);
   3210       }
   3211 
   3212   if (getLangOpts().CPlusPlus)
   3213     return MergeCXXFunctionDecl(New, Old, S);
   3214 
   3215   // Merge the function types so the we get the composite types for the return
   3216   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
   3217   // was visible.
   3218   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
   3219   if (!Merged.isNull() && MergeTypeWithOld)
   3220     New->setType(Merged);
   3221 
   3222   return false;
   3223 }
   3224 
   3225 
   3226 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
   3227                                 ObjCMethodDecl *oldMethod) {
   3228 
   3229   // Merge the attributes, including deprecated/unavailable
   3230   AvailabilityMergeKind MergeKind =
   3231     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
   3232       ? AMK_ProtocolImplementation
   3233       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
   3234                                                        : AMK_Override;
   3235 
   3236   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
   3237 
   3238   // Merge attributes from the parameters.
   3239   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
   3240                                        oe = oldMethod->param_end();
   3241   for (ObjCMethodDecl::param_iterator
   3242          ni = newMethod->param_begin(), ne = newMethod->param_end();
   3243        ni != ne && oi != oe; ++ni, ++oi)
   3244     mergeParamDeclAttributes(*ni, *oi, *this);
   3245 
   3246   CheckObjCMethodOverride(newMethod, oldMethod);
   3247 }
   3248 
   3249 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
   3250 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
   3251 /// emitting diagnostics as appropriate.
   3252 ///
   3253 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
   3254 /// to here in AddInitializerToDecl. We can't check them before the initializer
   3255 /// is attached.
   3256 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
   3257                              bool MergeTypeWithOld) {
   3258   if (New->isInvalidDecl() || Old->isInvalidDecl())
   3259     return;
   3260 
   3261   QualType MergedT;
   3262   if (getLangOpts().CPlusPlus) {
   3263     if (New->getType()->isUndeducedType()) {
   3264       // We don't know what the new type is until the initializer is attached.
   3265       return;
   3266     } else if (Context.hasSameType(New->getType(), Old->getType())) {
   3267       // These could still be something that needs exception specs checked.
   3268       return MergeVarDeclExceptionSpecs(New, Old);
   3269     }
   3270     // C++ [basic.link]p10:
   3271     //   [...] the types specified by all declarations referring to a given
   3272     //   object or function shall be identical, except that declarations for an
   3273     //   array object can specify array types that differ by the presence or
   3274     //   absence of a major array bound (8.3.4).
   3275     else if (Old->getType()->isIncompleteArrayType() &&
   3276              New->getType()->isArrayType()) {
   3277       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
   3278       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
   3279       if (Context.hasSameType(OldArray->getElementType(),
   3280                               NewArray->getElementType()))
   3281         MergedT = New->getType();
   3282     } else if (Old->getType()->isArrayType() &&
   3283                New->getType()->isIncompleteArrayType()) {
   3284       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
   3285       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
   3286       if (Context.hasSameType(OldArray->getElementType(),
   3287                               NewArray->getElementType()))
   3288         MergedT = Old->getType();
   3289     } else if (New->getType()->isObjCObjectPointerType() &&
   3290                Old->getType()->isObjCObjectPointerType()) {
   3291       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
   3292                                               Old->getType());
   3293     }
   3294   } else {
   3295     // C 6.2.7p2:
   3296     //   All declarations that refer to the same object or function shall have
   3297     //   compatible type.
   3298     MergedT = Context.mergeTypes(New->getType(), Old->getType());
   3299   }
   3300   if (MergedT.isNull()) {
   3301     // It's OK if we couldn't merge types if either type is dependent, for a
   3302     // block-scope variable. In other cases (static data members of class
   3303     // templates, variable templates, ...), we require the types to be
   3304     // equivalent.
   3305     // FIXME: The C++ standard doesn't say anything about this.
   3306     if ((New->getType()->isDependentType() ||
   3307          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
   3308       // If the old type was dependent, we can't merge with it, so the new type
   3309       // becomes dependent for now. We'll reproduce the original type when we
   3310       // instantiate the TypeSourceInfo for the variable.
   3311       if (!New->getType()->isDependentType() && MergeTypeWithOld)
   3312         New->setType(Context.DependentTy);
   3313       return;
   3314     }
   3315 
   3316     // FIXME: Even if this merging succeeds, some other non-visible declaration
   3317     // of this variable might have an incompatible type. For instance:
   3318     //
   3319     //   extern int arr[];
   3320     //   void f() { extern int arr[2]; }
   3321     //   void g() { extern int arr[3]; }
   3322     //
   3323     // Neither C nor C++ requires a diagnostic for this, but we should still try
   3324     // to diagnose it.
   3325     Diag(New->getLocation(), New->isThisDeclarationADefinition()
   3326                                  ? diag::err_redefinition_different_type
   3327                                  : diag::err_redeclaration_different_type)
   3328         << New->getDeclName() << New->getType() << Old->getType();
   3329 
   3330     diag::kind PrevDiag;
   3331     SourceLocation OldLocation;
   3332     std::tie(PrevDiag, OldLocation) =
   3333         getNoteDiagForInvalidRedeclaration(Old, New);
   3334     Diag(OldLocation, PrevDiag);
   3335     return New->setInvalidDecl();
   3336   }
   3337 
   3338   // Don't actually update the type on the new declaration if the old
   3339   // declaration was an extern declaration in a different scope.
   3340   if (MergeTypeWithOld)
   3341     New->setType(MergedT);
   3342 }
   3343 
   3344 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
   3345                                   LookupResult &Previous) {
   3346   // C11 6.2.7p4:
   3347   //   For an identifier with internal or external linkage declared
   3348   //   in a scope in which a prior declaration of that identifier is
   3349   //   visible, if the prior declaration specifies internal or
   3350   //   external linkage, the type of the identifier at the later
   3351   //   declaration becomes the composite type.
   3352   //
   3353   // If the variable isn't visible, we do not merge with its type.
   3354   if (Previous.isShadowed())
   3355     return false;
   3356 
   3357   if (S.getLangOpts().CPlusPlus) {
   3358     // C++11 [dcl.array]p3:
   3359     //   If there is a preceding declaration of the entity in the same
   3360     //   scope in which the bound was specified, an omitted array bound
   3361     //   is taken to be the same as in that earlier declaration.
   3362     return NewVD->isPreviousDeclInSameBlockScope() ||
   3363            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
   3364             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
   3365   } else {
   3366     // If the old declaration was function-local, don't merge with its
   3367     // type unless we're in the same function.
   3368     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
   3369            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
   3370   }
   3371 }
   3372 
   3373 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
   3374 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
   3375 /// situation, merging decls or emitting diagnostics as appropriate.
   3376 ///
   3377 /// Tentative definition rules (C99 6.9.2p2) are checked by
   3378 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
   3379 /// definitions here, since the initializer hasn't been attached.
   3380 ///
   3381 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
   3382   // If the new decl is already invalid, don't do any other checking.
   3383   if (New->isInvalidDecl())
   3384     return;
   3385 
   3386   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
   3387     return;
   3388 
   3389   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
   3390 
   3391   // Verify the old decl was also a variable or variable template.
   3392   VarDecl *Old = nullptr;
   3393   VarTemplateDecl *OldTemplate = nullptr;
   3394   if (Previous.isSingleResult()) {
   3395     if (NewTemplate) {
   3396       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
   3397       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
   3398 
   3399       if (auto *Shadow =
   3400               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
   3401         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
   3402           return New->setInvalidDecl();
   3403     } else {
   3404       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
   3405 
   3406       if (auto *Shadow =
   3407               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
   3408         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
   3409           return New->setInvalidDecl();
   3410     }
   3411   }
   3412   if (!Old) {
   3413     Diag(New->getLocation(), diag::err_redefinition_different_kind)
   3414       << New->getDeclName();
   3415     Diag(Previous.getRepresentativeDecl()->getLocation(),
   3416          diag::note_previous_definition);
   3417     return New->setInvalidDecl();
   3418   }
   3419 
   3420   // Ensure the template parameters are compatible.
   3421   if (NewTemplate &&
   3422       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
   3423                                       OldTemplate->getTemplateParameters(),
   3424                                       /*Complain=*/true, TPL_TemplateMatch))
   3425     return New->setInvalidDecl();
   3426 
   3427   // C++ [class.mem]p1:
   3428   //   A member shall not be declared twice in the member-specification [...]
   3429   //
   3430   // Here, we need only consider static data members.
   3431   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
   3432     Diag(New->getLocation(), diag::err_duplicate_member)
   3433       << New->getIdentifier();
   3434     Diag(Old->getLocation(), diag::note_previous_declaration);
   3435     New->setInvalidDecl();
   3436   }
   3437 
   3438   mergeDeclAttributes(New, Old);
   3439   // Warn if an already-declared variable is made a weak_import in a subsequent
   3440   // declaration
   3441   if (New->hasAttr<WeakImportAttr>() &&
   3442       Old->getStorageClass() == SC_None &&
   3443       !Old->hasAttr<WeakImportAttr>()) {
   3444     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
   3445     Diag(Old->getLocation(), diag::note_previous_definition);
   3446     // Remove weak_import attribute on new declaration.
   3447     New->dropAttr<WeakImportAttr>();
   3448   }
   3449 
   3450   if (New->hasAttr<InternalLinkageAttr>() &&
   3451       !Old->hasAttr<InternalLinkageAttr>()) {
   3452     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
   3453         << New->getDeclName();
   3454     Diag(Old->getLocation(), diag::note_previous_definition);
   3455     New->dropAttr<InternalLinkageAttr>();
   3456   }
   3457 
   3458   // Merge the types.
   3459   VarDecl *MostRecent = Old->getMostRecentDecl();
   3460   if (MostRecent != Old) {
   3461     MergeVarDeclTypes(New, MostRecent,
   3462                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
   3463     if (New->isInvalidDecl())
   3464       return;
   3465   }
   3466 
   3467   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
   3468   if (New->isInvalidDecl())
   3469     return;
   3470 
   3471   diag::kind PrevDiag;
   3472   SourceLocation OldLocation;
   3473   std::tie(PrevDiag, OldLocation) =
   3474       getNoteDiagForInvalidRedeclaration(Old, New);
   3475 
   3476   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
   3477   if (New->getStorageClass() == SC_Static &&
   3478       !New->isStaticDataMember() &&
   3479       Old->hasExternalFormalLinkage()) {
   3480     if (getLangOpts().MicrosoftExt) {
   3481       Diag(New->getLocation(), diag::ext_static_non_static)
   3482           << New->getDeclName();
   3483       Diag(OldLocation, PrevDiag);
   3484     } else {
   3485       Diag(New->getLocation(), diag::err_static_non_static)
   3486           << New->getDeclName();
   3487       Diag(OldLocation, PrevDiag);
   3488       return New->setInvalidDecl();
   3489     }
   3490   }
   3491   // C99 6.2.2p4:
   3492   //   For an identifier declared with the storage-class specifier
   3493   //   extern in a scope in which a prior declaration of that
   3494   //   identifier is visible,23) if the prior declaration specifies
   3495   //   internal or external linkage, the linkage of the identifier at
   3496   //   the later declaration is the same as the linkage specified at
   3497   //   the prior declaration. If no prior declaration is visible, or
   3498   //   if the prior declaration specifies no linkage, then the
   3499   //   identifier has external linkage.
   3500   if (New->hasExternalStorage() && Old->hasLinkage())
   3501     /* Okay */;
   3502   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
   3503            !New->isStaticDataMember() &&
   3504            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
   3505     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
   3506     Diag(OldLocation, PrevDiag);
   3507     return New->setInvalidDecl();
   3508   }
   3509 
   3510   // Check if extern is followed by non-extern and vice-versa.
   3511   if (New->hasExternalStorage() &&
   3512       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
   3513     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
   3514     Diag(OldLocation, PrevDiag);
   3515     return New->setInvalidDecl();
   3516   }
   3517   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
   3518       !New->hasExternalStorage()) {
   3519     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
   3520     Diag(OldLocation, PrevDiag);
   3521     return New->setInvalidDecl();
   3522   }
   3523 
   3524   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
   3525 
   3526   // FIXME: The test for external storage here seems wrong? We still
   3527   // need to check for mismatches.
   3528   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
   3529       // Don't complain about out-of-line definitions of static members.
   3530       !(Old->getLexicalDeclContext()->isRecord() &&
   3531         !New->getLexicalDeclContext()->isRecord())) {
   3532     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
   3533     Diag(OldLocation, PrevDiag);
   3534     return New->setInvalidDecl();
   3535   }
   3536 
   3537   if (New->getTLSKind() != Old->getTLSKind()) {
   3538     if (!Old->getTLSKind()) {
   3539       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
   3540       Diag(OldLocation, PrevDiag);
   3541     } else if (!New->getTLSKind()) {
   3542       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
   3543       Diag(OldLocation, PrevDiag);
   3544     } else {
   3545       // Do not allow redeclaration to change the variable between requiring
   3546       // static and dynamic initialization.
   3547       // FIXME: GCC allows this, but uses the TLS keyword on the first
   3548       // declaration to determine the kind. Do we need to be compatible here?
   3549       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
   3550         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
   3551       Diag(OldLocation, PrevDiag);
   3552     }
   3553   }
   3554 
   3555   // C++ doesn't have tentative definitions, so go right ahead and check here.
   3556   VarDecl *Def;
   3557   if (getLangOpts().CPlusPlus &&
   3558       New->isThisDeclarationADefinition() == VarDecl::Definition &&
   3559       (Def = Old->getDefinition())) {
   3560     NamedDecl *Hidden = nullptr;
   3561     if (!hasVisibleDefinition(Def, &Hidden) &&
   3562         (New->getFormalLinkage() == InternalLinkage ||
   3563          New->getDescribedVarTemplate() ||
   3564          New->getNumTemplateParameterLists() ||
   3565          New->getDeclContext()->isDependentContext())) {
   3566       // The previous definition is hidden, and multiple definitions are
   3567       // permitted (in separate TUs). Form another definition of it.
   3568     } else {
   3569       Diag(New->getLocation(), diag::err_redefinition) << New;
   3570       Diag(Def->getLocation(), diag::note_previous_definition);
   3571       New->setInvalidDecl();
   3572       return;
   3573     }
   3574   }
   3575 
   3576   if (haveIncompatibleLanguageLinkages(Old, New)) {
   3577     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
   3578     Diag(OldLocation, PrevDiag);
   3579     New->setInvalidDecl();
   3580     return;
   3581   }
   3582 
   3583   // Merge "used" flag.
   3584   if (Old->getMostRecentDecl()->isUsed(false))
   3585     New->setIsUsed();
   3586 
   3587   // Keep a chain of previous declarations.
   3588   New->setPreviousDecl(Old);
   3589   if (NewTemplate)
   3590     NewTemplate->setPreviousDecl(OldTemplate);
   3591 
   3592   // Inherit access appropriately.
   3593   New->setAccess(Old->getAccess());
   3594   if (NewTemplate)
   3595     NewTemplate->setAccess(New->getAccess());
   3596 }
   3597 
   3598 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
   3599 /// no declarator (e.g. "struct foo;") is parsed.
   3600 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
   3601                                        DeclSpec &DS) {
   3602   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
   3603 }
   3604 
   3605 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
   3606 // disambiguate entities defined in different scopes.
   3607 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
   3608 // compatibility.
   3609 // We will pick our mangling number depending on which version of MSVC is being
   3610 // targeted.
   3611 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
   3612   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
   3613              ? S->getMSCurManglingNumber()
   3614              : S->getMSLastManglingNumber();
   3615 }
   3616 
   3617 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
   3618   if (!Context.getLangOpts().CPlusPlus)
   3619     return;
   3620 
   3621   if (isa<CXXRecordDecl>(Tag->getParent())) {
   3622     // If this tag is the direct child of a class, number it if
   3623     // it is anonymous.
   3624     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
   3625       return;
   3626     MangleNumberingContext &MCtx =
   3627         Context.getManglingNumberContext(Tag->getParent());
   3628     Context.setManglingNumber(
   3629         Tag, MCtx.getManglingNumber(
   3630                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
   3631     return;
   3632   }
   3633 
   3634   // If this tag isn't a direct child of a class, number it if it is local.
   3635   Decl *ManglingContextDecl;
   3636   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
   3637           Tag->getDeclContext(), ManglingContextDecl)) {
   3638     Context.setManglingNumber(
   3639         Tag, MCtx->getManglingNumber(
   3640                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
   3641   }
   3642 }
   3643 
   3644 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
   3645                                         TypedefNameDecl *NewTD) {
   3646   if (TagFromDeclSpec->isInvalidDecl())
   3647     return;
   3648 
   3649   // Do nothing if the tag already has a name for linkage purposes.
   3650   if (TagFromDeclSpec->hasNameForLinkage())
   3651     return;
   3652 
   3653   // A well-formed anonymous tag must always be a TUK_Definition.
   3654   assert(TagFromDeclSpec->isThisDeclarationADefinition());
   3655 
   3656   // The type must match the tag exactly;  no qualifiers allowed.
   3657   if (!Context.hasSameType(NewTD->getUnderlyingType(),
   3658                            Context.getTagDeclType(TagFromDeclSpec))) {
   3659     if (getLangOpts().CPlusPlus)
   3660       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
   3661     return;
   3662   }
   3663 
   3664   // If we've already computed linkage for the anonymous tag, then
   3665   // adding a typedef name for the anonymous decl can change that
   3666   // linkage, which might be a serious problem.  Diagnose this as
   3667   // unsupported and ignore the typedef name.  TODO: we should
   3668   // pursue this as a language defect and establish a formal rule
   3669   // for how to handle it.
   3670   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
   3671     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
   3672 
   3673     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
   3674     tagLoc = getLocForEndOfToken(tagLoc);
   3675 
   3676     llvm::SmallString<40> textToInsert;
   3677     textToInsert += ' ';
   3678     textToInsert += NewTD->getIdentifier()->getName();
   3679     Diag(tagLoc, diag::note_typedef_changes_linkage)
   3680         << FixItHint::CreateInsertion(tagLoc, textToInsert);
   3681     return;
   3682   }
   3683 
   3684   // Otherwise, set this is the anon-decl typedef for the tag.
   3685   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
   3686 }
   3687 
   3688 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
   3689   switch (T) {
   3690   case DeclSpec::TST_class:
   3691     return 0;
   3692   case DeclSpec::TST_struct:
   3693     return 1;
   3694   case DeclSpec::TST_interface:
   3695     return 2;
   3696   case DeclSpec::TST_union:
   3697     return 3;
   3698   case DeclSpec::TST_enum:
   3699     return 4;
   3700   default:
   3701     llvm_unreachable("unexpected type specifier");
   3702   }
   3703 }
   3704 
   3705 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
   3706 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
   3707 /// parameters to cope with template friend declarations.
   3708 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
   3709                                        DeclSpec &DS,
   3710                                        MultiTemplateParamsArg TemplateParams,
   3711                                        bool IsExplicitInstantiation) {
   3712   Decl *TagD = nullptr;
   3713   TagDecl *Tag = nullptr;
   3714   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
   3715       DS.getTypeSpecType() == DeclSpec::TST_struct ||
   3716       DS.getTypeSpecType() == DeclSpec::TST_interface ||
   3717       DS.getTypeSpecType() == DeclSpec::TST_union ||
   3718       DS.getTypeSpecType() == DeclSpec::TST_enum) {
   3719     TagD = DS.getRepAsDecl();
   3720 
   3721     if (!TagD) // We probably had an error
   3722       return nullptr;
   3723 
   3724     // Note that the above type specs guarantee that the
   3725     // type rep is a Decl, whereas in many of the others
   3726     // it's a Type.
   3727     if (isa<TagDecl>(TagD))
   3728       Tag = cast<TagDecl>(TagD);
   3729     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
   3730       Tag = CTD->getTemplatedDecl();
   3731   }
   3732 
   3733   if (Tag) {
   3734     handleTagNumbering(Tag, S);
   3735     Tag->setFreeStanding();
   3736     if (Tag->isInvalidDecl())
   3737       return Tag;
   3738   }
   3739 
   3740   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
   3741     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
   3742     // or incomplete types shall not be restrict-qualified."
   3743     if (TypeQuals & DeclSpec::TQ_restrict)
   3744       Diag(DS.getRestrictSpecLoc(),
   3745            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
   3746            << DS.getSourceRange();
   3747   }
   3748 
   3749   if (DS.isConstexprSpecified()) {
   3750     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
   3751     // and definitions of functions and variables.
   3752     if (Tag)
   3753       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
   3754           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
   3755     else
   3756       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
   3757     // Don't emit warnings after this error.
   3758     return TagD;
   3759   }
   3760 
   3761   if (DS.isConceptSpecified()) {
   3762     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
   3763     // either a function concept and its definition or a variable concept and
   3764     // its initializer.
   3765     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
   3766     return TagD;
   3767   }
   3768 
   3769   DiagnoseFunctionSpecifiers(DS);
   3770 
   3771   if (DS.isFriendSpecified()) {
   3772     // If we're dealing with a decl but not a TagDecl, assume that
   3773     // whatever routines created it handled the friendship aspect.
   3774     if (TagD && !Tag)
   3775       return nullptr;
   3776     return ActOnFriendTypeDecl(S, DS, TemplateParams);
   3777   }
   3778 
   3779   const CXXScopeSpec &SS = DS.getTypeSpecScope();
   3780   bool IsExplicitSpecialization =
   3781     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
   3782   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
   3783       !IsExplicitInstantiation && !IsExplicitSpecialization &&
   3784       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
   3785     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
   3786     // nested-name-specifier unless it is an explicit instantiation
   3787     // or an explicit specialization.
   3788     //
   3789     // FIXME: We allow class template partial specializations here too, per the
   3790     // obvious intent of DR1819.
   3791     //
   3792     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
   3793     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
   3794         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
   3795     return nullptr;
   3796   }
   3797 
   3798   // Track whether this decl-specifier declares anything.
   3799   bool DeclaresAnything = true;
   3800 
   3801   // Handle anonymous struct definitions.
   3802   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
   3803     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
   3804         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
   3805       if (getLangOpts().CPlusPlus ||
   3806           Record->getDeclContext()->isRecord())
   3807         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
   3808                                            Context.getPrintingPolicy());
   3809 
   3810       DeclaresAnything = false;
   3811     }
   3812   }
   3813 
   3814   // C11 6.7.2.1p2:
   3815   //   A struct-declaration that does not declare an anonymous structure or
   3816   //   anonymous union shall contain a struct-declarator-list.
   3817   //
   3818   // This rule also existed in C89 and C99; the grammar for struct-declaration
   3819   // did not permit a struct-declaration without a struct-declarator-list.
   3820   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
   3821       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
   3822     // Check for Microsoft C extension: anonymous struct/union member.
   3823     // Handle 2 kinds of anonymous struct/union:
   3824     //   struct STRUCT;
   3825     //   union UNION;
   3826     // and
   3827     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
   3828     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
   3829     if ((Tag && Tag->getDeclName()) ||
   3830         DS.getTypeSpecType() == DeclSpec::TST_typename) {
   3831       RecordDecl *Record = nullptr;
   3832       if (Tag)
   3833         Record = dyn_cast<RecordDecl>(Tag);
   3834       else if (const RecordType *RT =
   3835                    DS.getRepAsType().get()->getAsStructureType())
   3836         Record = RT->getDecl();
   3837       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
   3838         Record = UT->getDecl();
   3839 
   3840       if (Record && getLangOpts().MicrosoftExt) {
   3841         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
   3842           << Record->isUnion() << DS.getSourceRange();
   3843         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
   3844       }
   3845 
   3846       DeclaresAnything = false;
   3847     }
   3848   }
   3849 
   3850   // Skip all the checks below if we have a type error.
   3851   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
   3852       (TagD && TagD->isInvalidDecl()))
   3853     return TagD;
   3854 
   3855   if (getLangOpts().CPlusPlus &&
   3856       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
   3857     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
   3858       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
   3859           !Enum->getIdentifier() && !Enum->isInvalidDecl())
   3860         DeclaresAnything = false;
   3861 
   3862   if (!DS.isMissingDeclaratorOk()) {
   3863     // Customize diagnostic for a typedef missing a name.
   3864     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
   3865       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
   3866         << DS.getSourceRange();
   3867     else
   3868       DeclaresAnything = false;
   3869   }
   3870 
   3871   if (DS.isModulePrivateSpecified() &&
   3872       Tag && Tag->getDeclContext()->isFunctionOrMethod())
   3873     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
   3874       << Tag->getTagKind()
   3875       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
   3876 
   3877   ActOnDocumentableDecl(TagD);
   3878 
   3879   // C 6.7/2:
   3880   //   A declaration [...] shall declare at least a declarator [...], a tag,
   3881   //   or the members of an enumeration.
   3882   // C++ [dcl.dcl]p3:
   3883   //   [If there are no declarators], and except for the declaration of an
   3884   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
   3885   //   names into the program, or shall redeclare a name introduced by a
   3886   //   previous declaration.
   3887   if (!DeclaresAnything) {
   3888     // In C, we allow this as a (popular) extension / bug. Don't bother
   3889     // producing further diagnostics for redundant qualifiers after this.
   3890     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
   3891     return TagD;
   3892   }
   3893 
   3894   // C++ [dcl.stc]p1:
   3895   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
   3896   //   init-declarator-list of the declaration shall not be empty.
   3897   // C++ [dcl.fct.spec]p1:
   3898   //   If a cv-qualifier appears in a decl-specifier-seq, the
   3899   //   init-declarator-list of the declaration shall not be empty.
   3900   //
   3901   // Spurious qualifiers here appear to be valid in C.
   3902   unsigned DiagID = diag::warn_standalone_specifier;
   3903   if (getLangOpts().CPlusPlus)
   3904     DiagID = diag::ext_standalone_specifier;
   3905 
   3906   // Note that a linkage-specification sets a storage class, but
   3907   // 'extern "C" struct foo;' is actually valid and not theoretically
   3908   // useless.
   3909   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
   3910     if (SCS == DeclSpec::SCS_mutable)
   3911       // Since mutable is not a viable storage class specifier in C, there is
   3912       // no reason to treat it as an extension. Instead, diagnose as an error.
   3913       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
   3914     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
   3915       Diag(DS.getStorageClassSpecLoc(), DiagID)
   3916         << DeclSpec::getSpecifierName(SCS);
   3917   }
   3918 
   3919   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
   3920     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
   3921       << DeclSpec::getSpecifierName(TSCS);
   3922   if (DS.getTypeQualifiers()) {
   3923     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
   3924       Diag(DS.getConstSpecLoc(), DiagID) << "const";
   3925     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
   3926       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
   3927     // Restrict is covered above.
   3928     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
   3929       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
   3930   }
   3931 
   3932   // Warn about ignored type attributes, for example:
   3933   // __attribute__((aligned)) struct A;
   3934   // Attributes should be placed after tag to apply to type declaration.
   3935   if (!DS.getAttributes().empty()) {
   3936     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
   3937     if (TypeSpecType == DeclSpec::TST_class ||
   3938         TypeSpecType == DeclSpec::TST_struct ||
   3939         TypeSpecType == DeclSpec::TST_interface ||
   3940         TypeSpecType == DeclSpec::TST_union ||
   3941         TypeSpecType == DeclSpec::TST_enum) {
   3942       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
   3943            attrs = attrs->getNext())
   3944         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
   3945             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
   3946     }
   3947   }
   3948 
   3949   return TagD;
   3950 }
   3951 
   3952 /// We are trying to inject an anonymous member into the given scope;
   3953 /// check if there's an existing declaration that can't be overloaded.
   3954 ///
   3955 /// \return true if this is a forbidden redeclaration
   3956 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
   3957                                          Scope *S,
   3958                                          DeclContext *Owner,
   3959                                          DeclarationName Name,
   3960                                          SourceLocation NameLoc,
   3961                                          bool IsUnion) {
   3962   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
   3963                  Sema::ForRedeclaration);
   3964   if (!SemaRef.LookupName(R, S)) return false;
   3965 
   3966   if (R.getAsSingle<TagDecl>())
   3967     return false;
   3968 
   3969   // Pick a representative declaration.
   3970   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
   3971   assert(PrevDecl && "Expected a non-null Decl");
   3972 
   3973   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
   3974     return false;
   3975 
   3976   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
   3977     << IsUnion << Name;
   3978   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
   3979 
   3980   return true;
   3981 }
   3982 
   3983 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
   3984 /// anonymous struct or union AnonRecord into the owning context Owner
   3985 /// and scope S. This routine will be invoked just after we realize
   3986 /// that an unnamed union or struct is actually an anonymous union or
   3987 /// struct, e.g.,
   3988 ///
   3989 /// @code
   3990 /// union {
   3991 ///   int i;
   3992 ///   float f;
   3993 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
   3994 ///    // f into the surrounding scope.x
   3995 /// @endcode
   3996 ///
   3997 /// This routine is recursive, injecting the names of nested anonymous
   3998 /// structs/unions into the owning context and scope as well.
   3999 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
   4000                                          DeclContext *Owner,
   4001                                          RecordDecl *AnonRecord,
   4002                                          AccessSpecifier AS,
   4003                                          SmallVectorImpl<NamedDecl *> &Chaining,
   4004                                          bool MSAnonStruct) {
   4005   bool Invalid = false;
   4006 
   4007   // Look every FieldDecl and IndirectFieldDecl with a name.
   4008   for (auto *D : AnonRecord->decls()) {
   4009     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
   4010         cast<NamedDecl>(D)->getDeclName()) {
   4011       ValueDecl *VD = cast<ValueDecl>(D);
   4012       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
   4013                                        VD->getLocation(),
   4014                                        AnonRecord->isUnion())) {
   4015         // C++ [class.union]p2:
   4016         //   The names of the members of an anonymous union shall be
   4017         //   distinct from the names of any other entity in the
   4018         //   scope in which the anonymous union is declared.
   4019         Invalid = true;
   4020       } else {
   4021         // C++ [class.union]p2:
   4022         //   For the purpose of name lookup, after the anonymous union
   4023         //   definition, the members of the anonymous union are
   4024         //   considered to have been defined in the scope in which the
   4025         //   anonymous union is declared.
   4026         unsigned OldChainingSize = Chaining.size();
   4027         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
   4028           Chaining.append(IF->chain_begin(), IF->chain_end());
   4029         else
   4030           Chaining.push_back(VD);
   4031 
   4032         assert(Chaining.size() >= 2);
   4033         NamedDecl **NamedChain =
   4034           new (SemaRef.Context)NamedDecl*[Chaining.size()];
   4035         for (unsigned i = 0; i < Chaining.size(); i++)
   4036           NamedChain[i] = Chaining[i];
   4037 
   4038         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
   4039             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
   4040             VD->getType(), NamedChain, Chaining.size());
   4041 
   4042         for (const auto *Attr : VD->attrs())
   4043           IndirectField->addAttr(Attr->clone(SemaRef.Context));
   4044 
   4045         IndirectField->setAccess(AS);
   4046         IndirectField->setImplicit();
   4047         SemaRef.PushOnScopeChains(IndirectField, S);
   4048 
   4049         // That includes picking up the appropriate access specifier.
   4050         if (AS != AS_none) IndirectField->setAccess(AS);
   4051 
   4052         Chaining.resize(OldChainingSize);
   4053       }
   4054     }
   4055   }
   4056 
   4057   return Invalid;
   4058 }
   4059 
   4060 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
   4061 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
   4062 /// illegal input values are mapped to SC_None.
   4063 static StorageClass
   4064 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
   4065   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
   4066   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
   4067          "Parser allowed 'typedef' as storage class VarDecl.");
   4068   switch (StorageClassSpec) {
   4069   case DeclSpec::SCS_unspecified:    return SC_None;
   4070   case DeclSpec::SCS_extern:
   4071     if (DS.isExternInLinkageSpec())
   4072       return SC_None;
   4073     return SC_Extern;
   4074   case DeclSpec::SCS_static:         return SC_Static;
   4075   case DeclSpec::SCS_auto:           return SC_Auto;
   4076   case DeclSpec::SCS_register:       return SC_Register;
   4077   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
   4078     // Illegal SCSs map to None: error reporting is up to the caller.
   4079   case DeclSpec::SCS_mutable:        // Fall through.
   4080   case DeclSpec::SCS_typedef:        return SC_None;
   4081   }
   4082   llvm_unreachable("unknown storage class specifier");
   4083 }
   4084 
   4085 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
   4086   assert(Record->hasInClassInitializer());
   4087 
   4088   for (const auto *I : Record->decls()) {
   4089     const auto *FD = dyn_cast<FieldDecl>(I);
   4090     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
   4091       FD = IFD->getAnonField();
   4092     if (FD && FD->hasInClassInitializer())
   4093       return FD->getLocation();
   4094   }
   4095 
   4096   llvm_unreachable("couldn't find in-class initializer");
   4097 }
   4098 
   4099 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
   4100                                       SourceLocation DefaultInitLoc) {
   4101   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
   4102     return;
   4103 
   4104   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
   4105   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
   4106 }
   4107 
   4108 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
   4109                                       CXXRecordDecl *AnonUnion) {
   4110   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
   4111     return;
   4112 
   4113   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
   4114 }
   4115 
   4116 /// BuildAnonymousStructOrUnion - Handle the declaration of an
   4117 /// anonymous structure or union. Anonymous unions are a C++ feature
   4118 /// (C++ [class.union]) and a C11 feature; anonymous structures
   4119 /// are a C11 feature and GNU C++ extension.
   4120 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
   4121                                         AccessSpecifier AS,
   4122                                         RecordDecl *Record,
   4123                                         const PrintingPolicy &Policy) {
   4124   DeclContext *Owner = Record->getDeclContext();
   4125 
   4126   // Diagnose whether this anonymous struct/union is an extension.
   4127   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
   4128     Diag(Record->getLocation(), diag::ext_anonymous_union);
   4129   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
   4130     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
   4131   else if (!Record->isUnion() && !getLangOpts().C11)
   4132     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
   4133 
   4134   // C and C++ require different kinds of checks for anonymous
   4135   // structs/unions.
   4136   bool Invalid = false;
   4137   if (getLangOpts().CPlusPlus) {
   4138     const char *PrevSpec = nullptr;
   4139     unsigned DiagID;
   4140     if (Record->isUnion()) {
   4141       // C++ [class.union]p6:
   4142       //   Anonymous unions declared in a named namespace or in the
   4143       //   global namespace shall be declared static.
   4144       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
   4145           (isa<TranslationUnitDecl>(Owner) ||
   4146            (isa<NamespaceDecl>(Owner) &&
   4147             cast<NamespaceDecl>(Owner)->getDeclName()))) {
   4148         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
   4149           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
   4150 
   4151         // Recover by adding 'static'.
   4152         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
   4153                                PrevSpec, DiagID, Policy);
   4154       }
   4155       // C++ [class.union]p6:
   4156       //   A storage class is not allowed in a declaration of an
   4157       //   anonymous union in a class scope.
   4158       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
   4159                isa<RecordDecl>(Owner)) {
   4160         Diag(DS.getStorageClassSpecLoc(),
   4161              diag::err_anonymous_union_with_storage_spec)
   4162           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
   4163 
   4164         // Recover by removing the storage specifier.
   4165         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
   4166                                SourceLocation(),
   4167                                PrevSpec, DiagID, Context.getPrintingPolicy());
   4168       }
   4169     }
   4170 
   4171     // Ignore const/volatile/restrict qualifiers.
   4172     if (DS.getTypeQualifiers()) {
   4173       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
   4174         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
   4175           << Record->isUnion() << "const"
   4176           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
   4177       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
   4178         Diag(DS.getVolatileSpecLoc(),
   4179              diag::ext_anonymous_struct_union_qualified)
   4180           << Record->isUnion() << "volatile"
   4181           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
   4182       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
   4183         Diag(DS.getRestrictSpecLoc(),
   4184              diag::ext_anonymous_struct_union_qualified)
   4185           << Record->isUnion() << "restrict"
   4186           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
   4187       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
   4188         Diag(DS.getAtomicSpecLoc(),
   4189              diag::ext_anonymous_struct_union_qualified)
   4190           << Record->isUnion() << "_Atomic"
   4191           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
   4192 
   4193       DS.ClearTypeQualifiers();
   4194     }
   4195 
   4196     // C++ [class.union]p2:
   4197     //   The member-specification of an anonymous union shall only
   4198     //   define non-static data members. [Note: nested types and
   4199     //   functions cannot be declared within an anonymous union. ]
   4200     for (auto *Mem : Record->decls()) {
   4201       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
   4202         // C++ [class.union]p3:
   4203         //   An anonymous union shall not have private or protected
   4204         //   members (clause 11).
   4205         assert(FD->getAccess() != AS_none);
   4206         if (FD->getAccess() != AS_public) {
   4207           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
   4208             << Record->isUnion() << (FD->getAccess() == AS_protected);
   4209           Invalid = true;
   4210         }
   4211 
   4212         // C++ [class.union]p1
   4213         //   An object of a class with a non-trivial constructor, a non-trivial
   4214         //   copy constructor, a non-trivial destructor, or a non-trivial copy
   4215         //   assignment operator cannot be a member of a union, nor can an
   4216         //   array of such objects.
   4217         if (CheckNontrivialField(FD))
   4218           Invalid = true;
   4219       } else if (Mem->isImplicit()) {
   4220         // Any implicit members are fine.
   4221       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
   4222         // This is a type that showed up in an
   4223         // elaborated-type-specifier inside the anonymous struct or
   4224         // union, but which actually declares a type outside of the
   4225         // anonymous struct or union. It's okay.
   4226       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
   4227         if (!MemRecord->isAnonymousStructOrUnion() &&
   4228             MemRecord->getDeclName()) {
   4229           // Visual C++ allows type definition in anonymous struct or union.
   4230           if (getLangOpts().MicrosoftExt)
   4231             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
   4232               << Record->isUnion();
   4233           else {
   4234             // This is a nested type declaration.
   4235             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
   4236               << Record->isUnion();
   4237             Invalid = true;
   4238           }
   4239         } else {
   4240           // This is an anonymous type definition within another anonymous type.
   4241           // This is a popular extension, provided by Plan9, MSVC and GCC, but
   4242           // not part of standard C++.
   4243           Diag(MemRecord->getLocation(),
   4244                diag::ext_anonymous_record_with_anonymous_type)
   4245             << Record->isUnion();
   4246         }
   4247       } else if (isa<AccessSpecDecl>(Mem)) {
   4248         // Any access specifier is fine.
   4249       } else if (isa<StaticAssertDecl>(Mem)) {
   4250         // In C++1z, static_assert declarations are also fine.
   4251       } else {
   4252         // We have something that isn't a non-static data
   4253         // member. Complain about it.
   4254         unsigned DK = diag::err_anonymous_record_bad_member;
   4255         if (isa<TypeDecl>(Mem))
   4256           DK = diag::err_anonymous_record_with_type;
   4257         else if (isa<FunctionDecl>(Mem))
   4258           DK = diag::err_anonymous_record_with_function;
   4259         else if (isa<VarDecl>(Mem))
   4260           DK = diag::err_anonymous_record_with_static;
   4261 
   4262         // Visual C++ allows type definition in anonymous struct or union.
   4263         if (getLangOpts().MicrosoftExt &&
   4264             DK == diag::err_anonymous_record_with_type)
   4265           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
   4266             << Record->isUnion();
   4267         else {
   4268           Diag(Mem->getLocation(), DK) << Record->isUnion();
   4269           Invalid = true;
   4270         }
   4271       }
   4272     }
   4273 
   4274     // C++11 [class.union]p8 (DR1460):
   4275     //   At most one variant member of a union may have a
   4276     //   brace-or-equal-initializer.
   4277     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
   4278         Owner->isRecord())
   4279       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
   4280                                 cast<CXXRecordDecl>(Record));
   4281   }
   4282 
   4283   if (!Record->isUnion() && !Owner->isRecord()) {
   4284     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
   4285       << getLangOpts().CPlusPlus;
   4286     Invalid = true;
   4287   }
   4288 
   4289   // Mock up a declarator.
   4290   Declarator Dc(DS, Declarator::MemberContext);
   4291   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
   4292   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
   4293 
   4294   // Create a declaration for this anonymous struct/union.
   4295   NamedDecl *Anon = nullptr;
   4296   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
   4297     Anon = FieldDecl::Create(Context, OwningClass,
   4298                              DS.getLocStart(),
   4299                              Record->getLocation(),
   4300                              /*IdentifierInfo=*/nullptr,
   4301                              Context.getTypeDeclType(Record),
   4302                              TInfo,
   4303                              /*BitWidth=*/nullptr, /*Mutable=*/false,
   4304                              /*InitStyle=*/ICIS_NoInit);
   4305     Anon->setAccess(AS);
   4306     if (getLangOpts().CPlusPlus)
   4307       FieldCollector->Add(cast<FieldDecl>(Anon));
   4308   } else {
   4309     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
   4310     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
   4311     if (SCSpec == DeclSpec::SCS_mutable) {
   4312       // mutable can only appear on non-static class members, so it's always
   4313       // an error here
   4314       Diag(Record->getLocation(), diag::err_mutable_nonmember);
   4315       Invalid = true;
   4316       SC = SC_None;
   4317     }
   4318 
   4319     Anon = VarDecl::Create(Context, Owner,
   4320                            DS.getLocStart(),
   4321                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
   4322                            Context.getTypeDeclType(Record),
   4323                            TInfo, SC);
   4324 
   4325     // Default-initialize the implicit variable. This initialization will be
   4326     // trivial in almost all cases, except if a union member has an in-class
   4327     // initializer:
   4328     //   union { int n = 0; };
   4329     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
   4330   }
   4331   Anon->setImplicit();
   4332 
   4333   // Mark this as an anonymous struct/union type.
   4334   Record->setAnonymousStructOrUnion(true);
   4335 
   4336   // Add the anonymous struct/union object to the current
   4337   // context. We'll be referencing this object when we refer to one of
   4338   // its members.
   4339   Owner->addDecl(Anon);
   4340 
   4341   // Inject the members of the anonymous struct/union into the owning
   4342   // context and into the identifier resolver chain for name lookup
   4343   // purposes.
   4344   SmallVector<NamedDecl*, 2> Chain;
   4345   Chain.push_back(Anon);
   4346 
   4347   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
   4348                                           Chain, false))
   4349     Invalid = true;
   4350 
   4351   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
   4352     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
   4353       Decl *ManglingContextDecl;
   4354       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
   4355               NewVD->getDeclContext(), ManglingContextDecl)) {
   4356         Context.setManglingNumber(
   4357             NewVD, MCtx->getManglingNumber(
   4358                        NewVD, getMSManglingNumber(getLangOpts(), S)));
   4359         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
   4360       }
   4361     }
   4362   }
   4363 
   4364   if (Invalid)
   4365     Anon->setInvalidDecl();
   4366 
   4367   return Anon;
   4368 }
   4369 
   4370 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
   4371 /// Microsoft C anonymous structure.
   4372 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
   4373 /// Example:
   4374 ///
   4375 /// struct A { int a; };
   4376 /// struct B { struct A; int b; };
   4377 ///
   4378 /// void foo() {
   4379 ///   B var;
   4380 ///   var.a = 3;
   4381 /// }
   4382 ///
   4383 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
   4384                                            RecordDecl *Record) {
   4385   assert(Record && "expected a record!");
   4386 
   4387   // Mock up a declarator.
   4388   Declarator Dc(DS, Declarator::TypeNameContext);
   4389   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
   4390   assert(TInfo && "couldn't build declarator info for anonymous struct");
   4391 
   4392   auto *ParentDecl = cast<RecordDecl>(CurContext);
   4393   QualType RecTy = Context.getTypeDeclType(Record);
   4394 
   4395   // Create a declaration for this anonymous struct.
   4396   NamedDecl *Anon = FieldDecl::Create(Context,
   4397                              ParentDecl,
   4398                              DS.getLocStart(),
   4399                              DS.getLocStart(),
   4400                              /*IdentifierInfo=*/nullptr,
   4401                              RecTy,
   4402                              TInfo,
   4403                              /*BitWidth=*/nullptr, /*Mutable=*/false,
   4404                              /*InitStyle=*/ICIS_NoInit);
   4405   Anon->setImplicit();
   4406 
   4407   // Add the anonymous struct object to the current context.
   4408   CurContext->addDecl(Anon);
   4409 
   4410   // Inject the members of the anonymous struct into the current
   4411   // context and into the identifier resolver chain for name lookup
   4412   // purposes.
   4413   SmallVector<NamedDecl*, 2> Chain;
   4414   Chain.push_back(Anon);
   4415 
   4416   RecordDecl *RecordDef = Record->getDefinition();
   4417   if (RequireCompleteType(Anon->getLocation(), RecTy,
   4418                           diag::err_field_incomplete) ||
   4419       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
   4420                                           AS_none, Chain, true)) {
   4421     Anon->setInvalidDecl();
   4422     ParentDecl->setInvalidDecl();
   4423   }
   4424 
   4425   return Anon;
   4426 }
   4427 
   4428 /// GetNameForDeclarator - Determine the full declaration name for the
   4429 /// given Declarator.
   4430 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
   4431   return GetNameFromUnqualifiedId(D.getName());
   4432 }
   4433 
   4434 /// \brief Retrieves the declaration name from a parsed unqualified-id.
   4435 DeclarationNameInfo
   4436 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
   4437   DeclarationNameInfo NameInfo;
   4438   NameInfo.setLoc(Name.StartLocation);
   4439 
   4440   switch (Name.getKind()) {
   4441 
   4442   case UnqualifiedId::IK_ImplicitSelfParam:
   4443   case UnqualifiedId::IK_Identifier:
   4444     NameInfo.setName(Name.Identifier);
   4445     NameInfo.setLoc(Name.StartLocation);
   4446     return NameInfo;
   4447 
   4448   case UnqualifiedId::IK_OperatorFunctionId:
   4449     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
   4450                                            Name.OperatorFunctionId.Operator));
   4451     NameInfo.setLoc(Name.StartLocation);
   4452     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
   4453       = Name.OperatorFunctionId.SymbolLocations[0];
   4454     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
   4455       = Name.EndLocation.getRawEncoding();
   4456     return NameInfo;
   4457 
   4458   case UnqualifiedId::IK_LiteralOperatorId:
   4459     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
   4460                                                            Name.Identifier));
   4461     NameInfo.setLoc(Name.StartLocation);
   4462     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
   4463     return NameInfo;
   4464 
   4465   case UnqualifiedId::IK_ConversionFunctionId: {
   4466     TypeSourceInfo *TInfo;
   4467     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
   4468     if (Ty.isNull())
   4469       return DeclarationNameInfo();
   4470     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
   4471                                                Context.getCanonicalType(Ty)));
   4472     NameInfo.setLoc(Name.StartLocation);
   4473     NameInfo.setNamedTypeInfo(TInfo);
   4474     return NameInfo;
   4475   }
   4476 
   4477   case UnqualifiedId::IK_ConstructorName: {
   4478     TypeSourceInfo *TInfo;
   4479     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
   4480     if (Ty.isNull())
   4481       return DeclarationNameInfo();
   4482     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
   4483                                               Context.getCanonicalType(Ty)));
   4484     NameInfo.setLoc(Name.StartLocation);
   4485     NameInfo.setNamedTypeInfo(TInfo);
   4486     return NameInfo;
   4487   }
   4488 
   4489   case UnqualifiedId::IK_ConstructorTemplateId: {
   4490     // In well-formed code, we can only have a constructor
   4491     // template-id that refers to the current context, so go there
   4492     // to find the actual type being constructed.
   4493     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
   4494     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
   4495       return DeclarationNameInfo();
   4496 
   4497     // Determine the type of the class being constructed.
   4498     QualType CurClassType = Context.getTypeDeclType(CurClass);
   4499 
   4500     // FIXME: Check two things: that the template-id names the same type as
   4501     // CurClassType, and that the template-id does not occur when the name
   4502     // was qualified.
   4503 
   4504     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
   4505                                     Context.getCanonicalType(CurClassType)));
   4506     NameInfo.setLoc(Name.StartLocation);
   4507     // FIXME: should we retrieve TypeSourceInfo?
   4508     NameInfo.setNamedTypeInfo(nullptr);
   4509     return NameInfo;
   4510   }
   4511 
   4512   case UnqualifiedId::IK_DestructorName: {
   4513     TypeSourceInfo *TInfo;
   4514     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
   4515     if (Ty.isNull())
   4516       return DeclarationNameInfo();
   4517     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
   4518                                               Context.getCanonicalType(Ty)));
   4519     NameInfo.setLoc(Name.StartLocation);
   4520     NameInfo.setNamedTypeInfo(TInfo);
   4521     return NameInfo;
   4522   }
   4523 
   4524   case UnqualifiedId::IK_TemplateId: {
   4525     TemplateName TName = Name.TemplateId->Template.get();
   4526     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
   4527     return Context.getNameForTemplate(TName, TNameLoc);
   4528   }
   4529 
   4530   } // switch (Name.getKind())
   4531 
   4532   llvm_unreachable("Unknown name kind");
   4533 }
   4534 
   4535 static QualType getCoreType(QualType Ty) {
   4536   do {
   4537     if (Ty->isPointerType() || Ty->isReferenceType())
   4538       Ty = Ty->getPointeeType();
   4539     else if (Ty->isArrayType())
   4540       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
   4541     else
   4542       return Ty.withoutLocalFastQualifiers();
   4543   } while (true);
   4544 }
   4545 
   4546 /// hasSimilarParameters - Determine whether the C++ functions Declaration
   4547 /// and Definition have "nearly" matching parameters. This heuristic is
   4548 /// used to improve diagnostics in the case where an out-of-line function
   4549 /// definition doesn't match any declaration within the class or namespace.
   4550 /// Also sets Params to the list of indices to the parameters that differ
   4551 /// between the declaration and the definition. If hasSimilarParameters
   4552 /// returns true and Params is empty, then all of the parameters match.
   4553 static bool hasSimilarParameters(ASTContext &Context,
   4554                                      FunctionDecl *Declaration,
   4555                                      FunctionDecl *Definition,
   4556                                      SmallVectorImpl<unsigned> &Params) {
   4557   Params.clear();
   4558   if (Declaration->param_size() != Definition->param_size())
   4559     return false;
   4560   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
   4561     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
   4562     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
   4563 
   4564     // The parameter types are identical
   4565     if (Context.hasSameType(DefParamTy, DeclParamTy))
   4566       continue;
   4567 
   4568     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
   4569     QualType DefParamBaseTy = getCoreType(DefParamTy);
   4570     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
   4571     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
   4572 
   4573     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
   4574         (DeclTyName && DeclTyName == DefTyName))
   4575       Params.push_back(Idx);
   4576     else  // The two parameters aren't even close
   4577       return false;
   4578   }
   4579 
   4580   return true;
   4581 }
   4582 
   4583 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
   4584 /// declarator needs to be rebuilt in the current instantiation.
   4585 /// Any bits of declarator which appear before the name are valid for
   4586 /// consideration here.  That's specifically the type in the decl spec
   4587 /// and the base type in any member-pointer chunks.
   4588 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
   4589                                                     DeclarationName Name) {
   4590   // The types we specifically need to rebuild are:
   4591   //   - typenames, typeofs, and decltypes
   4592   //   - types which will become injected class names
   4593   // Of course, we also need to rebuild any type referencing such a
   4594   // type.  It's safest to just say "dependent", but we call out a
   4595   // few cases here.
   4596 
   4597   DeclSpec &DS = D.getMutableDeclSpec();
   4598   switch (DS.getTypeSpecType()) {
   4599   case DeclSpec::TST_typename:
   4600   case DeclSpec::TST_typeofType:
   4601   case DeclSpec::TST_underlyingType:
   4602   case DeclSpec::TST_atomic: {
   4603     // Grab the type from the parser.
   4604     TypeSourceInfo *TSI = nullptr;
   4605     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
   4606     if (T.isNull() || !T->isDependentType()) break;
   4607 
   4608     // Make sure there's a type source info.  This isn't really much
   4609     // of a waste; most dependent types should have type source info
   4610     // attached already.
   4611     if (!TSI)
   4612       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
   4613 
   4614     // Rebuild the type in the current instantiation.
   4615     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
   4616     if (!TSI) return true;
   4617 
   4618     // Store the new type back in the decl spec.
   4619     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
   4620     DS.UpdateTypeRep(LocType);
   4621     break;
   4622   }
   4623 
   4624   case DeclSpec::TST_decltype:
   4625   case DeclSpec::TST_typeofExpr: {
   4626     Expr *E = DS.getRepAsExpr();
   4627     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
   4628     if (Result.isInvalid()) return true;
   4629     DS.UpdateExprRep(Result.get());
   4630     break;
   4631   }
   4632 
   4633   default:
   4634     // Nothing to do for these decl specs.
   4635     break;
   4636   }
   4637 
   4638   // It doesn't matter what order we do this in.
   4639   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
   4640     DeclaratorChunk &Chunk = D.getTypeObject(I);
   4641 
   4642     // The only type information in the declarator which can come
   4643     // before the declaration name is the base type of a member
   4644     // pointer.
   4645     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
   4646       continue;
   4647 
   4648     // Rebuild the scope specifier in-place.
   4649     CXXScopeSpec &SS = Chunk.Mem.Scope();
   4650     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
   4651       return true;
   4652   }
   4653 
   4654   return false;
   4655 }
   4656 
   4657 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
   4658   D.setFunctionDefinitionKind(FDK_Declaration);
   4659   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
   4660 
   4661   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
   4662       Dcl && Dcl->getDeclContext()->isFileContext())
   4663     Dcl->setTopLevelDeclInObjCContainer();
   4664 
   4665   return Dcl;
   4666 }
   4667 
   4668 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
   4669 ///   If T is the name of a class, then each of the following shall have a
   4670 ///   name different from T:
   4671 ///     - every static data member of class T;
   4672 ///     - every member function of class T
   4673 ///     - every member of class T that is itself a type;
   4674 /// \returns true if the declaration name violates these rules.
   4675 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
   4676                                    DeclarationNameInfo NameInfo) {
   4677   DeclarationName Name = NameInfo.getName();
   4678 
   4679   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
   4680     if (Record->getIdentifier() && Record->getDeclName() == Name) {
   4681       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
   4682       return true;
   4683     }
   4684 
   4685   return false;
   4686 }
   4687 
   4688 /// \brief Diagnose a declaration whose declarator-id has the given
   4689 /// nested-name-specifier.
   4690 ///
   4691 /// \param SS The nested-name-specifier of the declarator-id.
   4692 ///
   4693 /// \param DC The declaration context to which the nested-name-specifier
   4694 /// resolves.
   4695 ///
   4696 /// \param Name The name of the entity being declared.
   4697 ///
   4698 /// \param Loc The location of the name of the entity being declared.
   4699 ///
   4700 /// \returns true if we cannot safely recover from this error, false otherwise.
   4701 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
   4702                                         DeclarationName Name,
   4703                                         SourceLocation Loc) {
   4704   DeclContext *Cur = CurContext;
   4705   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
   4706     Cur = Cur->getParent();
   4707 
   4708   // If the user provided a superfluous scope specifier that refers back to the
   4709   // class in which the entity is already declared, diagnose and ignore it.
   4710   //
   4711   // class X {
   4712   //   void X::f();
   4713   // };
   4714   //
   4715   // Note, it was once ill-formed to give redundant qualification in all
   4716   // contexts, but that rule was removed by DR482.
   4717   if (Cur->Equals(DC)) {
   4718     if (Cur->isRecord()) {
   4719       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
   4720                                       : diag::err_member_extra_qualification)
   4721         << Name << FixItHint::CreateRemoval(SS.getRange());
   4722       SS.clear();
   4723     } else {
   4724       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
   4725     }
   4726     return false;
   4727   }
   4728 
   4729   // Check whether the qualifying scope encloses the scope of the original
   4730   // declaration.
   4731   if (!Cur->Encloses(DC)) {
   4732     if (Cur->isRecord())
   4733       Diag(Loc, diag::err_member_qualification)
   4734         << Name << SS.getRange();
   4735     else if (isa<TranslationUnitDecl>(DC))
   4736       Diag(Loc, diag::err_invalid_declarator_global_scope)
   4737         << Name << SS.getRange();
   4738     else if (isa<FunctionDecl>(Cur))
   4739       Diag(Loc, diag::err_invalid_declarator_in_function)
   4740         << Name << SS.getRange();
   4741     else if (isa<BlockDecl>(Cur))
   4742       Diag(Loc, diag::err_invalid_declarator_in_block)
   4743         << Name << SS.getRange();
   4744     else
   4745       Diag(Loc, diag::err_invalid_declarator_scope)
   4746       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
   4747 
   4748     return true;
   4749   }
   4750 
   4751   if (Cur->isRecord()) {
   4752     // Cannot qualify members within a class.
   4753     Diag(Loc, diag::err_member_qualification)
   4754       << Name << SS.getRange();
   4755     SS.clear();
   4756 
   4757     // C++ constructors and destructors with incorrect scopes can break
   4758     // our AST invariants by having the wrong underlying types. If
   4759     // that's the case, then drop this declaration entirely.
   4760     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
   4761          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
   4762         !Context.hasSameType(Name.getCXXNameType(),
   4763                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
   4764       return true;
   4765 
   4766     return false;
   4767   }
   4768 
   4769   // C++11 [dcl.meaning]p1:
   4770   //   [...] "The nested-name-specifier of the qualified declarator-id shall
   4771   //   not begin with a decltype-specifer"
   4772   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
   4773   while (SpecLoc.getPrefix())
   4774     SpecLoc = SpecLoc.getPrefix();
   4775   if (dyn_cast_or_null<DecltypeType>(
   4776         SpecLoc.getNestedNameSpecifier()->getAsType()))
   4777     Diag(Loc, diag::err_decltype_in_declarator)
   4778       << SpecLoc.getTypeLoc().getSourceRange();
   4779 
   4780   return false;
   4781 }
   4782 
   4783 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
   4784                                   MultiTemplateParamsArg TemplateParamLists) {
   4785   // TODO: consider using NameInfo for diagnostic.
   4786   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
   4787   DeclarationName Name = NameInfo.getName();
   4788 
   4789   // All of these full declarators require an identifier.  If it doesn't have
   4790   // one, the ParsedFreeStandingDeclSpec action should be used.
   4791   if (!Name) {
   4792     if (!D.isInvalidType())  // Reject this if we think it is valid.
   4793       Diag(D.getDeclSpec().getLocStart(),
   4794            diag::err_declarator_need_ident)
   4795         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
   4796     return nullptr;
   4797   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
   4798     return nullptr;
   4799 
   4800   // The scope passed in may not be a decl scope.  Zip up the scope tree until
   4801   // we find one that is.
   4802   while ((S->getFlags() & Scope::DeclScope) == 0 ||
   4803          (S->getFlags() & Scope::TemplateParamScope) != 0)
   4804     S = S->getParent();
   4805 
   4806   DeclContext *DC = CurContext;
   4807   if (D.getCXXScopeSpec().isInvalid())
   4808     D.setInvalidType();
   4809   else if (D.getCXXScopeSpec().isSet()) {
   4810     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
   4811                                         UPPC_DeclarationQualifier))
   4812       return nullptr;
   4813 
   4814     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
   4815     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
   4816     if (!DC || isa<EnumDecl>(DC)) {
   4817       // If we could not compute the declaration context, it's because the
   4818       // declaration context is dependent but does not refer to a class,
   4819       // class template, or class template partial specialization. Complain
   4820       // and return early, to avoid the coming semantic disaster.
   4821       Diag(D.getIdentifierLoc(),
   4822            diag::err_template_qualified_declarator_no_match)
   4823         << D.getCXXScopeSpec().getScopeRep()
   4824         << D.getCXXScopeSpec().getRange();
   4825       return nullptr;
   4826     }
   4827     bool IsDependentContext = DC->isDependentContext();
   4828 
   4829     if (!IsDependentContext &&
   4830         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
   4831       return nullptr;
   4832 
   4833     // If a class is incomplete, do not parse entities inside it.
   4834     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
   4835       Diag(D.getIdentifierLoc(),
   4836            diag::err_member_def_undefined_record)
   4837         << Name << DC << D.getCXXScopeSpec().getRange();
   4838       return nullptr;
   4839     }
   4840     if (!D.getDeclSpec().isFriendSpecified()) {
   4841       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
   4842                                       Name, D.getIdentifierLoc())) {
   4843         if (DC->isRecord())
   4844           return nullptr;
   4845 
   4846         D.setInvalidType();
   4847       }
   4848     }
   4849 
   4850     // Check whether we need to rebuild the type of the given
   4851     // declaration in the current instantiation.
   4852     if (EnteringContext && IsDependentContext &&
   4853         TemplateParamLists.size() != 0) {
   4854       ContextRAII SavedContext(*this, DC);
   4855       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
   4856         D.setInvalidType();
   4857     }
   4858   }
   4859 
   4860   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   4861   QualType R = TInfo->getType();
   4862 
   4863   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
   4864     // If this is a typedef, we'll end up spewing multiple diagnostics.
   4865     // Just return early; it's safer. If this is a function, let the
   4866     // "constructor cannot have a return type" diagnostic handle it.
   4867     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
   4868       return nullptr;
   4869 
   4870   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
   4871                                       UPPC_DeclarationType))
   4872     D.setInvalidType();
   4873 
   4874   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
   4875                         ForRedeclaration);
   4876 
   4877   // See if this is a redefinition of a variable in the same scope.
   4878   if (!D.getCXXScopeSpec().isSet()) {
   4879     bool IsLinkageLookup = false;
   4880     bool CreateBuiltins = false;
   4881 
   4882     // If the declaration we're planning to build will be a function
   4883     // or object with linkage, then look for another declaration with
   4884     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
   4885     //
   4886     // If the declaration we're planning to build will be declared with
   4887     // external linkage in the translation unit, create any builtin with
   4888     // the same name.
   4889     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
   4890       /* Do nothing*/;
   4891     else if (CurContext->isFunctionOrMethod() &&
   4892              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
   4893               R->isFunctionType())) {
   4894       IsLinkageLookup = true;
   4895       CreateBuiltins =
   4896           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
   4897     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
   4898                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
   4899       CreateBuiltins = true;
   4900 
   4901     if (IsLinkageLookup)
   4902       Previous.clear(LookupRedeclarationWithLinkage);
   4903 
   4904     LookupName(Previous, S, CreateBuiltins);
   4905   } else { // Something like "int foo::x;"
   4906     LookupQualifiedName(Previous, DC);
   4907 
   4908     // C++ [dcl.meaning]p1:
   4909     //   When the declarator-id is qualified, the declaration shall refer to a
   4910     //  previously declared member of the class or namespace to which the
   4911     //  qualifier refers (or, in the case of a namespace, of an element of the
   4912     //  inline namespace set of that namespace (7.3.1)) or to a specialization
   4913     //  thereof; [...]
   4914     //
   4915     // Note that we already checked the context above, and that we do not have
   4916     // enough information to make sure that Previous contains the declaration
   4917     // we want to match. For example, given:
   4918     //
   4919     //   class X {
   4920     //     void f();
   4921     //     void f(float);
   4922     //   };
   4923     //
   4924     //   void X::f(int) { } // ill-formed
   4925     //
   4926     // In this case, Previous will point to the overload set
   4927     // containing the two f's declared in X, but neither of them
   4928     // matches.
   4929 
   4930     // C++ [dcl.meaning]p1:
   4931     //   [...] the member shall not merely have been introduced by a
   4932     //   using-declaration in the scope of the class or namespace nominated by
   4933     //   the nested-name-specifier of the declarator-id.
   4934     RemoveUsingDecls(Previous);
   4935   }
   4936 
   4937   if (Previous.isSingleResult() &&
   4938       Previous.getFoundDecl()->isTemplateParameter()) {
   4939     // Maybe we will complain about the shadowed template parameter.
   4940     if (!D.isInvalidType())
   4941       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
   4942                                       Previous.getFoundDecl());
   4943 
   4944     // Just pretend that we didn't see the previous declaration.
   4945     Previous.clear();
   4946   }
   4947 
   4948   // In C++, the previous declaration we find might be a tag type
   4949   // (class or enum). In this case, the new declaration will hide the
   4950   // tag type. Note that this does does not apply if we're declaring a
   4951   // typedef (C++ [dcl.typedef]p4).
   4952   if (Previous.isSingleTagDecl() &&
   4953       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
   4954     Previous.clear();
   4955 
   4956   // Check that there are no default arguments other than in the parameters
   4957   // of a function declaration (C++ only).
   4958   if (getLangOpts().CPlusPlus)
   4959     CheckExtraCXXDefaultArguments(D);
   4960 
   4961   if (D.getDeclSpec().isConceptSpecified()) {
   4962     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
   4963     // applied only to the definition of a function template or variable
   4964     // template, declared in namespace scope
   4965     if (!TemplateParamLists.size()) {
   4966       Diag(D.getDeclSpec().getConceptSpecLoc(),
   4967            diag:: err_concept_wrong_decl_kind);
   4968       return nullptr;
   4969     }
   4970 
   4971     if (!DC->getRedeclContext()->isFileContext()) {
   4972       Diag(D.getIdentifierLoc(),
   4973            diag::err_concept_decls_may_only_appear_in_namespace_scope);
   4974       return nullptr;
   4975     }
   4976   }
   4977 
   4978   NamedDecl *New;
   4979 
   4980   bool AddToScope = true;
   4981   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
   4982     if (TemplateParamLists.size()) {
   4983       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
   4984       return nullptr;
   4985     }
   4986 
   4987     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
   4988   } else if (R->isFunctionType()) {
   4989     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
   4990                                   TemplateParamLists,
   4991                                   AddToScope);
   4992   } else {
   4993     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
   4994                                   AddToScope);
   4995   }
   4996 
   4997   if (!New)
   4998     return nullptr;
   4999 
   5000   // If this has an identifier and is not an invalid redeclaration or
   5001   // function template specialization, add it to the scope stack.
   5002   if (New->getDeclName() && AddToScope &&
   5003        !(D.isRedeclaration() && New->isInvalidDecl())) {
   5004     // Only make a locally-scoped extern declaration visible if it is the first
   5005     // declaration of this entity. Qualified lookup for such an entity should
   5006     // only find this declaration if there is no visible declaration of it.
   5007     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
   5008     PushOnScopeChains(New, S, AddToContext);
   5009     if (!AddToContext)
   5010       CurContext->addHiddenDecl(New);
   5011   }
   5012 
   5013   return New;
   5014 }
   5015 
   5016 /// Helper method to turn variable array types into constant array
   5017 /// types in certain situations which would otherwise be errors (for
   5018 /// GCC compatibility).
   5019 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
   5020                                                     ASTContext &Context,
   5021                                                     bool &SizeIsNegative,
   5022                                                     llvm::APSInt &Oversized) {
   5023   // This method tries to turn a variable array into a constant
   5024   // array even when the size isn't an ICE.  This is necessary
   5025   // for compatibility with code that depends on gcc's buggy
   5026   // constant expression folding, like struct {char x[(int)(char*)2];}
   5027   SizeIsNegative = false;
   5028   Oversized = 0;
   5029 
   5030   if (T->isDependentType())
   5031     return QualType();
   5032 
   5033   QualifierCollector Qs;
   5034   const Type *Ty = Qs.strip(T);
   5035 
   5036   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
   5037     QualType Pointee = PTy->getPointeeType();
   5038     QualType FixedType =
   5039         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
   5040                                             Oversized);
   5041     if (FixedType.isNull()) return FixedType;
   5042     FixedType = Context.getPointerType(FixedType);
   5043     return Qs.apply(Context, FixedType);
   5044   }
   5045   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
   5046     QualType Inner = PTy->getInnerType();
   5047     QualType FixedType =
   5048         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
   5049                                             Oversized);
   5050     if (FixedType.isNull()) return FixedType;
   5051     FixedType = Context.getParenType(FixedType);
   5052     return Qs.apply(Context, FixedType);
   5053   }
   5054 
   5055   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
   5056   if (!VLATy)
   5057     return QualType();
   5058   // FIXME: We should probably handle this case
   5059   if (VLATy->getElementType()->isVariablyModifiedType())
   5060     return QualType();
   5061 
   5062   llvm::APSInt Res;
   5063   if (!VLATy->getSizeExpr() ||
   5064       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
   5065     return QualType();
   5066 
   5067   // Check whether the array size is negative.
   5068   if (Res.isSigned() && Res.isNegative()) {
   5069     SizeIsNegative = true;
   5070     return QualType();
   5071   }
   5072 
   5073   // Check whether the array is too large to be addressed.
   5074   unsigned ActiveSizeBits
   5075     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
   5076                                               Res);
   5077   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
   5078     Oversized = Res;
   5079     return QualType();
   5080   }
   5081 
   5082   return Context.getConstantArrayType(VLATy->getElementType(),
   5083                                       Res, ArrayType::Normal, 0);
   5084 }
   5085 
   5086 static void
   5087 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
   5088   SrcTL = SrcTL.getUnqualifiedLoc();
   5089   DstTL = DstTL.getUnqualifiedLoc();
   5090   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
   5091     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
   5092     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
   5093                                       DstPTL.getPointeeLoc());
   5094     DstPTL.setStarLoc(SrcPTL.getStarLoc());
   5095     return;
   5096   }
   5097   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
   5098     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
   5099     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
   5100                                       DstPTL.getInnerLoc());
   5101     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
   5102     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
   5103     return;
   5104   }
   5105   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
   5106   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
   5107   TypeLoc SrcElemTL = SrcATL.getElementLoc();
   5108   TypeLoc DstElemTL = DstATL.getElementLoc();
   5109   DstElemTL.initializeFullCopy(SrcElemTL);
   5110   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
   5111   DstATL.setSizeExpr(SrcATL.getSizeExpr());
   5112   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
   5113 }
   5114 
   5115 /// Helper method to turn variable array types into constant array
   5116 /// types in certain situations which would otherwise be errors (for
   5117 /// GCC compatibility).
   5118 static TypeSourceInfo*
   5119 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
   5120                                               ASTContext &Context,
   5121                                               bool &SizeIsNegative,
   5122                                               llvm::APSInt &Oversized) {
   5123   QualType FixedTy
   5124     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
   5125                                           SizeIsNegative, Oversized);
   5126   if (FixedTy.isNull())
   5127     return nullptr;
   5128   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
   5129   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
   5130                                     FixedTInfo->getTypeLoc());
   5131   return FixedTInfo;
   5132 }
   5133 
   5134 /// \brief Register the given locally-scoped extern "C" declaration so
   5135 /// that it can be found later for redeclarations. We include any extern "C"
   5136 /// declaration that is not visible in the translation unit here, not just
   5137 /// function-scope declarations.
   5138 void
   5139 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
   5140   if (!getLangOpts().CPlusPlus &&
   5141       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
   5142     // Don't need to track declarations in the TU in C.
   5143     return;
   5144 
   5145   // Note that we have a locally-scoped external with this name.
   5146   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
   5147 }
   5148 
   5149 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
   5150   // FIXME: We can have multiple results via __attribute__((overloadable)).
   5151   auto Result = Context.getExternCContextDecl()->lookup(Name);
   5152   return Result.empty() ? nullptr : *Result.begin();
   5153 }
   5154 
   5155 /// \brief Diagnose function specifiers on a declaration of an identifier that
   5156 /// does not identify a function.
   5157 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
   5158   // FIXME: We should probably indicate the identifier in question to avoid
   5159   // confusion for constructs like "inline int a(), b;"
   5160   if (DS.isInlineSpecified())
   5161     Diag(DS.getInlineSpecLoc(),
   5162          diag::err_inline_non_function);
   5163 
   5164   if (DS.isVirtualSpecified())
   5165     Diag(DS.getVirtualSpecLoc(),
   5166          diag::err_virtual_non_function);
   5167 
   5168   if (DS.isExplicitSpecified())
   5169     Diag(DS.getExplicitSpecLoc(),
   5170          diag::err_explicit_non_function);
   5171 
   5172   if (DS.isNoreturnSpecified())
   5173     Diag(DS.getNoreturnSpecLoc(),
   5174          diag::err_noreturn_non_function);
   5175 }
   5176 
   5177 NamedDecl*
   5178 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
   5179                              TypeSourceInfo *TInfo, LookupResult &Previous) {
   5180   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
   5181   if (D.getCXXScopeSpec().isSet()) {
   5182     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
   5183       << D.getCXXScopeSpec().getRange();
   5184     D.setInvalidType();
   5185     // Pretend we didn't see the scope specifier.
   5186     DC = CurContext;
   5187     Previous.clear();
   5188   }
   5189 
   5190   DiagnoseFunctionSpecifiers(D.getDeclSpec());
   5191 
   5192   if (D.getDeclSpec().isConstexprSpecified())
   5193     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
   5194       << 1;
   5195   if (D.getDeclSpec().isConceptSpecified())
   5196     Diag(D.getDeclSpec().getConceptSpecLoc(),
   5197          diag::err_concept_wrong_decl_kind);
   5198 
   5199   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
   5200     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
   5201       << D.getName().getSourceRange();
   5202     return nullptr;
   5203   }
   5204 
   5205   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
   5206   if (!NewTD) return nullptr;
   5207 
   5208   // Handle attributes prior to checking for duplicates in MergeVarDecl
   5209   ProcessDeclAttributes(S, NewTD, D);
   5210 
   5211   CheckTypedefForVariablyModifiedType(S, NewTD);
   5212 
   5213   bool Redeclaration = D.isRedeclaration();
   5214   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
   5215   D.setRedeclaration(Redeclaration);
   5216   return ND;
   5217 }
   5218 
   5219 void
   5220 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
   5221   // C99 6.7.7p2: If a typedef name specifies a variably modified type
   5222   // then it shall have block scope.
   5223   // Note that variably modified types must be fixed before merging the decl so
   5224   // that redeclarations will match.
   5225   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
   5226   QualType T = TInfo->getType();
   5227   if (T->isVariablyModifiedType()) {
   5228     getCurFunction()->setHasBranchProtectedScope();
   5229 
   5230     if (S->getFnParent() == nullptr) {
   5231       bool SizeIsNegative;
   5232       llvm::APSInt Oversized;
   5233       TypeSourceInfo *FixedTInfo =
   5234         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
   5235                                                       SizeIsNegative,
   5236                                                       Oversized);
   5237       if (FixedTInfo) {
   5238         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
   5239         NewTD->setTypeSourceInfo(FixedTInfo);
   5240       } else {
   5241         if (SizeIsNegative)
   5242           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
   5243         else if (T->isVariableArrayType())
   5244           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
   5245         else if (Oversized.getBoolValue())
   5246           Diag(NewTD->getLocation(), diag::err_array_too_large)
   5247             << Oversized.toString(10);
   5248         else
   5249           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
   5250         NewTD->setInvalidDecl();
   5251       }
   5252     }
   5253   }
   5254 }
   5255 
   5256 
   5257 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
   5258 /// declares a typedef-name, either using the 'typedef' type specifier or via
   5259 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
   5260 NamedDecl*
   5261 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
   5262                            LookupResult &Previous, bool &Redeclaration) {
   5263   // Merge the decl with the existing one if appropriate. If the decl is
   5264   // in an outer scope, it isn't the same thing.
   5265   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
   5266                        /*AllowInlineNamespace*/false);
   5267   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
   5268   if (!Previous.empty()) {
   5269     Redeclaration = true;
   5270     MergeTypedefNameDecl(S, NewTD, Previous);
   5271   }
   5272 
   5273   // If this is the C FILE type, notify the AST context.
   5274   if (IdentifierInfo *II = NewTD->getIdentifier())
   5275     if (!NewTD->isInvalidDecl() &&
   5276         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
   5277       if (II->isStr("FILE"))
   5278         Context.setFILEDecl(NewTD);
   5279       else if (II->isStr("jmp_buf"))
   5280         Context.setjmp_bufDecl(NewTD);
   5281       else if (II->isStr("sigjmp_buf"))
   5282         Context.setsigjmp_bufDecl(NewTD);
   5283       else if (II->isStr("ucontext_t"))
   5284         Context.setucontext_tDecl(NewTD);
   5285     }
   5286 
   5287   return NewTD;
   5288 }
   5289 
   5290 /// \brief Determines whether the given declaration is an out-of-scope
   5291 /// previous declaration.
   5292 ///
   5293 /// This routine should be invoked when name lookup has found a
   5294 /// previous declaration (PrevDecl) that is not in the scope where a
   5295 /// new declaration by the same name is being introduced. If the new
   5296 /// declaration occurs in a local scope, previous declarations with
   5297 /// linkage may still be considered previous declarations (C99
   5298 /// 6.2.2p4-5, C++ [basic.link]p6).
   5299 ///
   5300 /// \param PrevDecl the previous declaration found by name
   5301 /// lookup
   5302 ///
   5303 /// \param DC the context in which the new declaration is being
   5304 /// declared.
   5305 ///
   5306 /// \returns true if PrevDecl is an out-of-scope previous declaration
   5307 /// for a new delcaration with the same name.
   5308 static bool
   5309 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
   5310                                 ASTContext &Context) {
   5311   if (!PrevDecl)
   5312     return false;
   5313 
   5314   if (!PrevDecl->hasLinkage())
   5315     return false;
   5316 
   5317   if (Context.getLangOpts().CPlusPlus) {
   5318     // C++ [basic.link]p6:
   5319     //   If there is a visible declaration of an entity with linkage
   5320     //   having the same name and type, ignoring entities declared
   5321     //   outside the innermost enclosing namespace scope, the block
   5322     //   scope declaration declares that same entity and receives the
   5323     //   linkage of the previous declaration.
   5324     DeclContext *OuterContext = DC->getRedeclContext();
   5325     if (!OuterContext->isFunctionOrMethod())
   5326       // This rule only applies to block-scope declarations.
   5327       return false;
   5328 
   5329     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
   5330     if (PrevOuterContext->isRecord())
   5331       // We found a member function: ignore it.
   5332       return false;
   5333 
   5334     // Find the innermost enclosing namespace for the new and
   5335     // previous declarations.
   5336     OuterContext = OuterContext->getEnclosingNamespaceContext();
   5337     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
   5338 
   5339     // The previous declaration is in a different namespace, so it
   5340     // isn't the same function.
   5341     if (!OuterContext->Equals(PrevOuterContext))
   5342       return false;
   5343   }
   5344 
   5345   return true;
   5346 }
   5347 
   5348 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
   5349   CXXScopeSpec &SS = D.getCXXScopeSpec();
   5350   if (!SS.isSet()) return;
   5351   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
   5352 }
   5353 
   5354 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
   5355   QualType type = decl->getType();
   5356   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
   5357   if (lifetime == Qualifiers::OCL_Autoreleasing) {
   5358     // Various kinds of declaration aren't allowed to be __autoreleasing.
   5359     unsigned kind = -1U;
   5360     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
   5361       if (var->hasAttr<BlocksAttr>())
   5362         kind = 0; // __block
   5363       else if (!var->hasLocalStorage())
   5364         kind = 1; // global
   5365     } else if (isa<ObjCIvarDecl>(decl)) {
   5366       kind = 3; // ivar
   5367     } else if (isa<FieldDecl>(decl)) {
   5368       kind = 2; // field
   5369     }
   5370 
   5371     if (kind != -1U) {
   5372       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
   5373         << kind;
   5374     }
   5375   } else if (lifetime == Qualifiers::OCL_None) {
   5376     // Try to infer lifetime.
   5377     if (!type->isObjCLifetimeType())
   5378       return false;
   5379 
   5380     lifetime = type->getObjCARCImplicitLifetime();
   5381     type = Context.getLifetimeQualifiedType(type, lifetime);
   5382     decl->setType(type);
   5383   }
   5384 
   5385   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
   5386     // Thread-local variables cannot have lifetime.
   5387     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
   5388         var->getTLSKind()) {
   5389       Diag(var->getLocation(), diag::err_arc_thread_ownership)
   5390         << var->getType();
   5391       return true;
   5392     }
   5393   }
   5394 
   5395   return false;
   5396 }
   5397 
   5398 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
   5399   // Ensure that an auto decl is deduced otherwise the checks below might cache
   5400   // the wrong linkage.
   5401   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
   5402 
   5403   // 'weak' only applies to declarations with external linkage.
   5404   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
   5405     if (!ND.isExternallyVisible()) {
   5406       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
   5407       ND.dropAttr<WeakAttr>();
   5408     }
   5409   }
   5410   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
   5411     if (ND.isExternallyVisible()) {
   5412       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
   5413       ND.dropAttr<WeakRefAttr>();
   5414       ND.dropAttr<AliasAttr>();
   5415     }
   5416   }
   5417 
   5418   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
   5419     if (VD->hasInit()) {
   5420       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
   5421         assert(VD->isThisDeclarationADefinition() &&
   5422                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
   5423         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
   5424         VD->dropAttr<AliasAttr>();
   5425       }
   5426     }
   5427   }
   5428 
   5429   // 'selectany' only applies to externally visible variable declarations.
   5430   // It does not apply to functions.
   5431   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
   5432     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
   5433       S.Diag(Attr->getLocation(),
   5434              diag::err_attribute_selectany_non_extern_data);
   5435       ND.dropAttr<SelectAnyAttr>();
   5436     }
   5437   }
   5438 
   5439   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
   5440     // dll attributes require external linkage. Static locals may have external
   5441     // linkage but still cannot be explicitly imported or exported.
   5442     auto *VD = dyn_cast<VarDecl>(&ND);
   5443     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
   5444       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
   5445         << &ND << Attr;
   5446       ND.setInvalidDecl();
   5447     }
   5448   }
   5449 
   5450   // Virtual functions cannot be marked as 'notail'.
   5451   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
   5452     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
   5453       if (MD->isVirtual()) {
   5454         S.Diag(ND.getLocation(),
   5455                diag::err_invalid_attribute_on_virtual_function)
   5456             << Attr;
   5457         ND.dropAttr<NotTailCalledAttr>();
   5458       }
   5459 }
   5460 
   5461 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
   5462                                            NamedDecl *NewDecl,
   5463                                            bool IsSpecialization) {
   5464   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
   5465     OldDecl = OldTD->getTemplatedDecl();
   5466   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
   5467     NewDecl = NewTD->getTemplatedDecl();
   5468 
   5469   if (!OldDecl || !NewDecl)
   5470     return;
   5471 
   5472   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
   5473   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
   5474   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
   5475   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
   5476 
   5477   // dllimport and dllexport are inheritable attributes so we have to exclude
   5478   // inherited attribute instances.
   5479   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
   5480                     (NewExportAttr && !NewExportAttr->isInherited());
   5481 
   5482   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
   5483   // the only exception being explicit specializations.
   5484   // Implicitly generated declarations are also excluded for now because there
   5485   // is no other way to switch these to use dllimport or dllexport.
   5486   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
   5487 
   5488   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
   5489     // Allow with a warning for free functions and global variables.
   5490     bool JustWarn = false;
   5491     if (!OldDecl->isCXXClassMember()) {
   5492       auto *VD = dyn_cast<VarDecl>(OldDecl);
   5493       if (VD && !VD->getDescribedVarTemplate())
   5494         JustWarn = true;
   5495       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
   5496       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
   5497         JustWarn = true;
   5498     }
   5499 
   5500     // We cannot change a declaration that's been used because IR has already
   5501     // been emitted. Dllimported functions will still work though (modulo
   5502     // address equality) as they can use the thunk.
   5503     if (OldDecl->isUsed())
   5504       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
   5505         JustWarn = false;
   5506 
   5507     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
   5508                                : diag::err_attribute_dll_redeclaration;
   5509     S.Diag(NewDecl->getLocation(), DiagID)
   5510         << NewDecl
   5511         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
   5512     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
   5513     if (!JustWarn) {
   5514       NewDecl->setInvalidDecl();
   5515       return;
   5516     }
   5517   }
   5518 
   5519   // A redeclaration is not allowed to drop a dllimport attribute, the only
   5520   // exceptions being inline function definitions, local extern declarations,
   5521   // and qualified friend declarations.
   5522   // NB: MSVC converts such a declaration to dllexport.
   5523   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
   5524   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
   5525     // Ignore static data because out-of-line definitions are diagnosed
   5526     // separately.
   5527     IsStaticDataMember = VD->isStaticDataMember();
   5528   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
   5529     IsInline = FD->isInlined();
   5530     IsQualifiedFriend = FD->getQualifier() &&
   5531                         FD->getFriendObjectKind() == Decl::FOK_Declared;
   5532   }
   5533 
   5534   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
   5535       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
   5536     S.Diag(NewDecl->getLocation(),
   5537            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
   5538       << NewDecl << OldImportAttr;
   5539     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
   5540     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
   5541     OldDecl->dropAttr<DLLImportAttr>();
   5542     NewDecl->dropAttr<DLLImportAttr>();
   5543   } else if (IsInline && OldImportAttr &&
   5544              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
   5545     // In MinGW, seeing a function declared inline drops the dllimport attribute.
   5546     OldDecl->dropAttr<DLLImportAttr>();
   5547     NewDecl->dropAttr<DLLImportAttr>();
   5548     S.Diag(NewDecl->getLocation(),
   5549            diag::warn_dllimport_dropped_from_inline_function)
   5550         << NewDecl << OldImportAttr;
   5551   }
   5552 }
   5553 
   5554 /// Given that we are within the definition of the given function,
   5555 /// will that definition behave like C99's 'inline', where the
   5556 /// definition is discarded except for optimization purposes?
   5557 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
   5558   // Try to avoid calling GetGVALinkageForFunction.
   5559 
   5560   // All cases of this require the 'inline' keyword.
   5561   if (!FD->isInlined()) return false;
   5562 
   5563   // This is only possible in C++ with the gnu_inline attribute.
   5564   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
   5565     return false;
   5566 
   5567   // Okay, go ahead and call the relatively-more-expensive function.
   5568 
   5569 #ifndef NDEBUG
   5570   // AST quite reasonably asserts that it's working on a function
   5571   // definition.  We don't really have a way to tell it that we're
   5572   // currently defining the function, so just lie to it in +Asserts
   5573   // builds.  This is an awful hack.
   5574   FD->setLazyBody(1);
   5575 #endif
   5576 
   5577   bool isC99Inline =
   5578       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
   5579 
   5580 #ifndef NDEBUG
   5581   FD->setLazyBody(0);
   5582 #endif
   5583 
   5584   return isC99Inline;
   5585 }
   5586 
   5587 /// Determine whether a variable is extern "C" prior to attaching
   5588 /// an initializer. We can't just call isExternC() here, because that
   5589 /// will also compute and cache whether the declaration is externally
   5590 /// visible, which might change when we attach the initializer.
   5591 ///
   5592 /// This can only be used if the declaration is known to not be a
   5593 /// redeclaration of an internal linkage declaration.
   5594 ///
   5595 /// For instance:
   5596 ///
   5597 ///   auto x = []{};
   5598 ///
   5599 /// Attaching the initializer here makes this declaration not externally
   5600 /// visible, because its type has internal linkage.
   5601 ///
   5602 /// FIXME: This is a hack.
   5603 template<typename T>
   5604 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
   5605   if (S.getLangOpts().CPlusPlus) {
   5606     // In C++, the overloadable attribute negates the effects of extern "C".
   5607     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
   5608       return false;
   5609 
   5610     // So do CUDA's host/device attributes if overloading is enabled.
   5611     if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
   5612         (D->template hasAttr<CUDADeviceAttr>() ||
   5613          D->template hasAttr<CUDAHostAttr>()))
   5614       return false;
   5615   }
   5616   return D->isExternC();
   5617 }
   5618 
   5619 static bool shouldConsiderLinkage(const VarDecl *VD) {
   5620   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
   5621   if (DC->isFunctionOrMethod())
   5622     return VD->hasExternalStorage();
   5623   if (DC->isFileContext())
   5624     return true;
   5625   if (DC->isRecord())
   5626     return false;
   5627   llvm_unreachable("Unexpected context");
   5628 }
   5629 
   5630 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
   5631   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
   5632   if (DC->isFileContext() || DC->isFunctionOrMethod())
   5633     return true;
   5634   if (DC->isRecord())
   5635     return false;
   5636   llvm_unreachable("Unexpected context");
   5637 }
   5638 
   5639 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
   5640                           AttributeList::Kind Kind) {
   5641   for (const AttributeList *L = AttrList; L; L = L->getNext())
   5642     if (L->getKind() == Kind)
   5643       return true;
   5644   return false;
   5645 }
   5646 
   5647 static bool hasParsedAttr(Scope *S, const Declarator &PD,
   5648                           AttributeList::Kind Kind) {
   5649   // Check decl attributes on the DeclSpec.
   5650   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
   5651     return true;
   5652 
   5653   // Walk the declarator structure, checking decl attributes that were in a type
   5654   // position to the decl itself.
   5655   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
   5656     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
   5657       return true;
   5658   }
   5659 
   5660   // Finally, check attributes on the decl itself.
   5661   return hasParsedAttr(S, PD.getAttributes(), Kind);
   5662 }
   5663 
   5664 /// Adjust the \c DeclContext for a function or variable that might be a
   5665 /// function-local external declaration.
   5666 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
   5667   if (!DC->isFunctionOrMethod())
   5668     return false;
   5669 
   5670   // If this is a local extern function or variable declared within a function
   5671   // template, don't add it into the enclosing namespace scope until it is
   5672   // instantiated; it might have a dependent type right now.
   5673   if (DC->isDependentContext())
   5674     return true;
   5675 
   5676   // C++11 [basic.link]p7:
   5677   //   When a block scope declaration of an entity with linkage is not found to
   5678   //   refer to some other declaration, then that entity is a member of the
   5679   //   innermost enclosing namespace.
   5680   //
   5681   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
   5682   // semantically-enclosing namespace, not a lexically-enclosing one.
   5683   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
   5684     DC = DC->getParent();
   5685   return true;
   5686 }
   5687 
   5688 /// \brief Returns true if given declaration has external C language linkage.
   5689 static bool isDeclExternC(const Decl *D) {
   5690   if (const auto *FD = dyn_cast<FunctionDecl>(D))
   5691     return FD->isExternC();
   5692   if (const auto *VD = dyn_cast<VarDecl>(D))
   5693     return VD->isExternC();
   5694 
   5695   llvm_unreachable("Unknown type of decl!");
   5696 }
   5697 
   5698 NamedDecl *
   5699 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
   5700                               TypeSourceInfo *TInfo, LookupResult &Previous,
   5701                               MultiTemplateParamsArg TemplateParamLists,
   5702                               bool &AddToScope) {
   5703   QualType R = TInfo->getType();
   5704   DeclarationName Name = GetNameForDeclarator(D).getName();
   5705 
   5706   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
   5707   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
   5708 
   5709   // dllimport globals without explicit storage class are treated as extern. We
   5710   // have to change the storage class this early to get the right DeclContext.
   5711   if (SC == SC_None && !DC->isRecord() &&
   5712       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
   5713       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
   5714     SC = SC_Extern;
   5715 
   5716   DeclContext *OriginalDC = DC;
   5717   bool IsLocalExternDecl = SC == SC_Extern &&
   5718                            adjustContextForLocalExternDecl(DC);
   5719 
   5720   if (getLangOpts().OpenCL) {
   5721     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
   5722     QualType NR = R;
   5723     while (NR->isPointerType()) {
   5724       if (NR->isFunctionPointerType()) {
   5725         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
   5726         D.setInvalidType();
   5727         break;
   5728       }
   5729       NR = NR->getPointeeType();
   5730     }
   5731 
   5732     if (!getOpenCLOptions().cl_khr_fp16) {
   5733       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
   5734       // half array type (unless the cl_khr_fp16 extension is enabled).
   5735       if (Context.getBaseElementType(R)->isHalfType()) {
   5736         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
   5737         D.setInvalidType();
   5738       }
   5739     }
   5740   }
   5741 
   5742   if (SCSpec == DeclSpec::SCS_mutable) {
   5743     // mutable can only appear on non-static class members, so it's always
   5744     // an error here
   5745     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
   5746     D.setInvalidType();
   5747     SC = SC_None;
   5748   }
   5749 
   5750   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
   5751       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
   5752                               D.getDeclSpec().getStorageClassSpecLoc())) {
   5753     // In C++11, the 'register' storage class specifier is deprecated.
   5754     // Suppress the warning in system macros, it's used in macros in some
   5755     // popular C system headers, such as in glibc's htonl() macro.
   5756     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
   5757          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
   5758                                    : diag::warn_deprecated_register)
   5759       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
   5760   }
   5761 
   5762   IdentifierInfo *II = Name.getAsIdentifierInfo();
   5763   if (!II) {
   5764     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
   5765       << Name;
   5766     return nullptr;
   5767   }
   5768 
   5769   DiagnoseFunctionSpecifiers(D.getDeclSpec());
   5770 
   5771   if (!DC->isRecord() && S->getFnParent() == nullptr) {
   5772     // C99 6.9p2: The storage-class specifiers auto and register shall not
   5773     // appear in the declaration specifiers in an external declaration.
   5774     // Global Register+Asm is a GNU extension we support.
   5775     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
   5776       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
   5777       D.setInvalidType();
   5778     }
   5779   }
   5780 
   5781   if (getLangOpts().OpenCL) {
   5782     // OpenCL v1.2 s6.9.b p4:
   5783     // The sampler type cannot be used with the __local and __global address
   5784     // space qualifiers.
   5785     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
   5786       R.getAddressSpace() == LangAS::opencl_global)) {
   5787       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
   5788     }
   5789 
   5790     // OpenCL 1.2 spec, p6.9 r:
   5791     // The event type cannot be used to declare a program scope variable.
   5792     // The event type cannot be used with the __local, __constant and __global
   5793     // address space qualifiers.
   5794     if (R->isEventT()) {
   5795       if (S->getParent() == nullptr) {
   5796         Diag(D.getLocStart(), diag::err_event_t_global_var);
   5797         D.setInvalidType();
   5798       }
   5799 
   5800       if (R.getAddressSpace()) {
   5801         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
   5802         D.setInvalidType();
   5803       }
   5804     }
   5805   }
   5806 
   5807   bool IsExplicitSpecialization = false;
   5808   bool IsVariableTemplateSpecialization = false;
   5809   bool IsPartialSpecialization = false;
   5810   bool IsVariableTemplate = false;
   5811   VarDecl *NewVD = nullptr;
   5812   VarTemplateDecl *NewTemplate = nullptr;
   5813   TemplateParameterList *TemplateParams = nullptr;
   5814   if (!getLangOpts().CPlusPlus) {
   5815     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
   5816                             D.getIdentifierLoc(), II,
   5817                             R, TInfo, SC);
   5818 
   5819     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
   5820       ParsingInitForAutoVars.insert(NewVD);
   5821 
   5822     if (D.isInvalidType())
   5823       NewVD->setInvalidDecl();
   5824   } else {
   5825     bool Invalid = false;
   5826 
   5827     if (DC->isRecord() && !CurContext->isRecord()) {
   5828       // This is an out-of-line definition of a static data member.
   5829       switch (SC) {
   5830       case SC_None:
   5831         break;
   5832       case SC_Static:
   5833         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
   5834              diag::err_static_out_of_line)
   5835           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
   5836         break;
   5837       case SC_Auto:
   5838       case SC_Register:
   5839       case SC_Extern:
   5840         // [dcl.stc] p2: The auto or register specifiers shall be applied only
   5841         // to names of variables declared in a block or to function parameters.
   5842         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
   5843         // of class members
   5844 
   5845         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
   5846              diag::err_storage_class_for_static_member)
   5847           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
   5848         break;
   5849       case SC_PrivateExtern:
   5850         llvm_unreachable("C storage class in c++!");
   5851       }
   5852     }
   5853 
   5854     if (SC == SC_Static && CurContext->isRecord()) {
   5855       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
   5856         if (RD->isLocalClass())
   5857           Diag(D.getIdentifierLoc(),
   5858                diag::err_static_data_member_not_allowed_in_local_class)
   5859             << Name << RD->getDeclName();
   5860 
   5861         // C++98 [class.union]p1: If a union contains a static data member,
   5862         // the program is ill-formed. C++11 drops this restriction.
   5863         if (RD->isUnion())
   5864           Diag(D.getIdentifierLoc(),
   5865                getLangOpts().CPlusPlus11
   5866                  ? diag::warn_cxx98_compat_static_data_member_in_union
   5867                  : diag::ext_static_data_member_in_union) << Name;
   5868         // We conservatively disallow static data members in anonymous structs.
   5869         else if (!RD->getDeclName())
   5870           Diag(D.getIdentifierLoc(),
   5871                diag::err_static_data_member_not_allowed_in_anon_struct)
   5872             << Name << RD->isUnion();
   5873       }
   5874     }
   5875 
   5876     // Match up the template parameter lists with the scope specifier, then
   5877     // determine whether we have a template or a template specialization.
   5878     TemplateParams = MatchTemplateParametersToScopeSpecifier(
   5879         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
   5880         D.getCXXScopeSpec(),
   5881         D.getName().getKind() == UnqualifiedId::IK_TemplateId
   5882             ? D.getName().TemplateId
   5883             : nullptr,
   5884         TemplateParamLists,
   5885         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
   5886 
   5887     if (TemplateParams) {
   5888       if (!TemplateParams->size() &&
   5889           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
   5890         // There is an extraneous 'template<>' for this variable. Complain
   5891         // about it, but allow the declaration of the variable.
   5892         Diag(TemplateParams->getTemplateLoc(),
   5893              diag::err_template_variable_noparams)
   5894           << II
   5895           << SourceRange(TemplateParams->getTemplateLoc(),
   5896                          TemplateParams->getRAngleLoc());
   5897         TemplateParams = nullptr;
   5898       } else {
   5899         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
   5900           // This is an explicit specialization or a partial specialization.
   5901           // FIXME: Check that we can declare a specialization here.
   5902           IsVariableTemplateSpecialization = true;
   5903           IsPartialSpecialization = TemplateParams->size() > 0;
   5904         } else { // if (TemplateParams->size() > 0)
   5905           // This is a template declaration.
   5906           IsVariableTemplate = true;
   5907 
   5908           // Check that we can declare a template here.
   5909           if (CheckTemplateDeclScope(S, TemplateParams))
   5910             return nullptr;
   5911 
   5912           // Only C++1y supports variable templates (N3651).
   5913           Diag(D.getIdentifierLoc(),
   5914                getLangOpts().CPlusPlus14
   5915                    ? diag::warn_cxx11_compat_variable_template
   5916                    : diag::ext_variable_template);
   5917         }
   5918       }
   5919     } else {
   5920       assert(
   5921           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
   5922           "should have a 'template<>' for this decl");
   5923     }
   5924 
   5925     if (IsVariableTemplateSpecialization) {
   5926       SourceLocation TemplateKWLoc =
   5927           TemplateParamLists.size() > 0
   5928               ? TemplateParamLists[0]->getTemplateLoc()
   5929               : SourceLocation();
   5930       DeclResult Res = ActOnVarTemplateSpecialization(
   5931           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
   5932           IsPartialSpecialization);
   5933       if (Res.isInvalid())
   5934         return nullptr;
   5935       NewVD = cast<VarDecl>(Res.get());
   5936       AddToScope = false;
   5937     } else
   5938       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
   5939                               D.getIdentifierLoc(), II, R, TInfo, SC);
   5940 
   5941     // If this is supposed to be a variable template, create it as such.
   5942     if (IsVariableTemplate) {
   5943       NewTemplate =
   5944           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
   5945                                   TemplateParams, NewVD);
   5946       NewVD->setDescribedVarTemplate(NewTemplate);
   5947     }
   5948 
   5949     // If this decl has an auto type in need of deduction, make a note of the
   5950     // Decl so we can diagnose uses of it in its own initializer.
   5951     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
   5952       ParsingInitForAutoVars.insert(NewVD);
   5953 
   5954     if (D.isInvalidType() || Invalid) {
   5955       NewVD->setInvalidDecl();
   5956       if (NewTemplate)
   5957         NewTemplate->setInvalidDecl();
   5958     }
   5959 
   5960     SetNestedNameSpecifier(NewVD, D);
   5961 
   5962     // If we have any template parameter lists that don't directly belong to
   5963     // the variable (matching the scope specifier), store them.
   5964     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
   5965     if (TemplateParamLists.size() > VDTemplateParamLists)
   5966       NewVD->setTemplateParameterListsInfo(
   5967           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
   5968 
   5969     if (D.getDeclSpec().isConstexprSpecified())
   5970       NewVD->setConstexpr(true);
   5971 
   5972     if (D.getDeclSpec().isConceptSpecified()) {
   5973       NewVD->setConcept(true);
   5974 
   5975       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
   5976       // be declared with the thread_local, inline, friend, or constexpr
   5977       // specifiers, [...]
   5978       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
   5979         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
   5980              diag::err_concept_decl_invalid_specifiers)
   5981             << 0 << 0;
   5982         NewVD->setInvalidDecl(true);
   5983       }
   5984 
   5985       if (D.getDeclSpec().isConstexprSpecified()) {
   5986         Diag(D.getDeclSpec().getConstexprSpecLoc(),
   5987              diag::err_concept_decl_invalid_specifiers)
   5988             << 0 << 3;
   5989         NewVD->setInvalidDecl(true);
   5990       }
   5991     }
   5992   }
   5993 
   5994   // Set the lexical context. If the declarator has a C++ scope specifier, the
   5995   // lexical context will be different from the semantic context.
   5996   NewVD->setLexicalDeclContext(CurContext);
   5997   if (NewTemplate)
   5998     NewTemplate->setLexicalDeclContext(CurContext);
   5999 
   6000   if (IsLocalExternDecl)
   6001     NewVD->setLocalExternDecl();
   6002 
   6003   bool EmitTLSUnsupportedError = false;
   6004   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
   6005     // C++11 [dcl.stc]p4:
   6006     //   When thread_local is applied to a variable of block scope the
   6007     //   storage-class-specifier static is implied if it does not appear
   6008     //   explicitly.
   6009     // Core issue: 'static' is not implied if the variable is declared
   6010     //   'extern'.
   6011     if (NewVD->hasLocalStorage() &&
   6012         (SCSpec != DeclSpec::SCS_unspecified ||
   6013          TSCS != DeclSpec::TSCS_thread_local ||
   6014          !DC->isFunctionOrMethod()))
   6015       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
   6016            diag::err_thread_non_global)
   6017         << DeclSpec::getSpecifierName(TSCS);
   6018     else if (!Context.getTargetInfo().isTLSSupported()) {
   6019       if (getLangOpts().CUDA) {
   6020         // Postpone error emission until we've collected attributes required to
   6021         // figure out whether it's a host or device variable and whether the
   6022         // error should be ignored.
   6023         EmitTLSUnsupportedError = true;
   6024         // We still need to mark the variable as TLS so it shows up in AST with
   6025         // proper storage class for other tools to use even if we're not going
   6026         // to emit any code for it.
   6027         NewVD->setTSCSpec(TSCS);
   6028       } else
   6029         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
   6030              diag::err_thread_unsupported);
   6031     } else
   6032       NewVD->setTSCSpec(TSCS);
   6033   }
   6034 
   6035   // C99 6.7.4p3
   6036   //   An inline definition of a function with external linkage shall
   6037   //   not contain a definition of a modifiable object with static or
   6038   //   thread storage duration...
   6039   // We only apply this when the function is required to be defined
   6040   // elsewhere, i.e. when the function is not 'extern inline'.  Note
   6041   // that a local variable with thread storage duration still has to
   6042   // be marked 'static'.  Also note that it's possible to get these
   6043   // semantics in C++ using __attribute__((gnu_inline)).
   6044   if (SC == SC_Static && S->getFnParent() != nullptr &&
   6045       !NewVD->getType().isConstQualified()) {
   6046     FunctionDecl *CurFD = getCurFunctionDecl();
   6047     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
   6048       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
   6049            diag::warn_static_local_in_extern_inline);
   6050       MaybeSuggestAddingStaticToDecl(CurFD);
   6051     }
   6052   }
   6053 
   6054   if (D.getDeclSpec().isModulePrivateSpecified()) {
   6055     if (IsVariableTemplateSpecialization)
   6056       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
   6057           << (IsPartialSpecialization ? 1 : 0)
   6058           << FixItHint::CreateRemoval(
   6059                  D.getDeclSpec().getModulePrivateSpecLoc());
   6060     else if (IsExplicitSpecialization)
   6061       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
   6062         << 2
   6063         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
   6064     else if (NewVD->hasLocalStorage())
   6065       Diag(NewVD->getLocation(), diag::err_module_private_local)
   6066         << 0 << NewVD->getDeclName()
   6067         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
   6068         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
   6069     else {
   6070       NewVD->setModulePrivate();
   6071       if (NewTemplate)
   6072         NewTemplate->setModulePrivate();
   6073     }
   6074   }
   6075 
   6076   // Handle attributes prior to checking for duplicates in MergeVarDecl
   6077   ProcessDeclAttributes(S, NewVD, D);
   6078 
   6079   if (getLangOpts().CUDA) {
   6080     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
   6081       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
   6082            diag::err_thread_unsupported);
   6083     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
   6084     // storage [duration]."
   6085     if (SC == SC_None && S->getFnParent() != nullptr &&
   6086         (NewVD->hasAttr<CUDASharedAttr>() ||
   6087          NewVD->hasAttr<CUDAConstantAttr>())) {
   6088       NewVD->setStorageClass(SC_Static);
   6089     }
   6090   }
   6091 
   6092   // Ensure that dllimport globals without explicit storage class are treated as
   6093   // extern. The storage class is set above using parsed attributes. Now we can
   6094   // check the VarDecl itself.
   6095   assert(!NewVD->hasAttr<DLLImportAttr>() ||
   6096          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
   6097          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
   6098 
   6099   // In auto-retain/release, infer strong retension for variables of
   6100   // retainable type.
   6101   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
   6102     NewVD->setInvalidDecl();
   6103 
   6104   // Handle GNU asm-label extension (encoded as an attribute).
   6105   if (Expr *E = (Expr*)D.getAsmLabel()) {
   6106     // The parser guarantees this is a string.
   6107     StringLiteral *SE = cast<StringLiteral>(E);
   6108     StringRef Label = SE->getString();
   6109     if (S->getFnParent() != nullptr) {
   6110       switch (SC) {
   6111       case SC_None:
   6112       case SC_Auto:
   6113         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
   6114         break;
   6115       case SC_Register:
   6116         // Local Named register
   6117         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
   6118             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
   6119           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
   6120         break;
   6121       case SC_Static:
   6122       case SC_Extern:
   6123       case SC_PrivateExtern:
   6124         break;
   6125       }
   6126     } else if (SC == SC_Register) {
   6127       // Global Named register
   6128       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
   6129         const auto &TI = Context.getTargetInfo();
   6130         bool HasSizeMismatch;
   6131 
   6132         if (!TI.isValidGCCRegisterName(Label))
   6133           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
   6134         else if (!TI.validateGlobalRegisterVariable(Label,
   6135                                                     Context.getTypeSize(R),
   6136                                                     HasSizeMismatch))
   6137           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
   6138         else if (HasSizeMismatch)
   6139           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
   6140       }
   6141 
   6142       if (!R->isIntegralType(Context) && !R->isPointerType()) {
   6143         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
   6144         NewVD->setInvalidDecl(true);
   6145       }
   6146     }
   6147 
   6148     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
   6149                                                 Context, Label, 0));
   6150   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
   6151     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
   6152       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
   6153     if (I != ExtnameUndeclaredIdentifiers.end()) {
   6154       if (isDeclExternC(NewVD)) {
   6155         NewVD->addAttr(I->second);
   6156         ExtnameUndeclaredIdentifiers.erase(I);
   6157       } else
   6158         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
   6159             << /*Variable*/1 << NewVD;
   6160     }
   6161   }
   6162 
   6163   // Diagnose shadowed variables before filtering for scope.
   6164   if (D.getCXXScopeSpec().isEmpty())
   6165     CheckShadow(S, NewVD, Previous);
   6166 
   6167   // Don't consider existing declarations that are in a different
   6168   // scope and are out-of-semantic-context declarations (if the new
   6169   // declaration has linkage).
   6170   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
   6171                        D.getCXXScopeSpec().isNotEmpty() ||
   6172                        IsExplicitSpecialization ||
   6173                        IsVariableTemplateSpecialization);
   6174 
   6175   // Check whether the previous declaration is in the same block scope. This
   6176   // affects whether we merge types with it, per C++11 [dcl.array]p3.
   6177   if (getLangOpts().CPlusPlus &&
   6178       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
   6179     NewVD->setPreviousDeclInSameBlockScope(
   6180         Previous.isSingleResult() && !Previous.isShadowed() &&
   6181         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
   6182 
   6183   if (!getLangOpts().CPlusPlus) {
   6184     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
   6185   } else {
   6186     // If this is an explicit specialization of a static data member, check it.
   6187     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
   6188         CheckMemberSpecialization(NewVD, Previous))
   6189       NewVD->setInvalidDecl();
   6190 
   6191     // Merge the decl with the existing one if appropriate.
   6192     if (!Previous.empty()) {
   6193       if (Previous.isSingleResult() &&
   6194           isa<FieldDecl>(Previous.getFoundDecl()) &&
   6195           D.getCXXScopeSpec().isSet()) {
   6196         // The user tried to define a non-static data member
   6197         // out-of-line (C++ [dcl.meaning]p1).
   6198         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
   6199           << D.getCXXScopeSpec().getRange();
   6200         Previous.clear();
   6201         NewVD->setInvalidDecl();
   6202       }
   6203     } else if (D.getCXXScopeSpec().isSet()) {
   6204       // No previous declaration in the qualifying scope.
   6205       Diag(D.getIdentifierLoc(), diag::err_no_member)
   6206         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
   6207         << D.getCXXScopeSpec().getRange();
   6208       NewVD->setInvalidDecl();
   6209     }
   6210 
   6211     if (!IsVariableTemplateSpecialization)
   6212       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
   6213 
   6214     if (NewTemplate) {
   6215       VarTemplateDecl *PrevVarTemplate =
   6216           NewVD->getPreviousDecl()
   6217               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
   6218               : nullptr;
   6219 
   6220       // Check the template parameter list of this declaration, possibly
   6221       // merging in the template parameter list from the previous variable
   6222       // template declaration.
   6223       if (CheckTemplateParameterList(
   6224               TemplateParams,
   6225               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
   6226                               : nullptr,
   6227               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
   6228                DC->isDependentContext())
   6229                   ? TPC_ClassTemplateMember
   6230                   : TPC_VarTemplate))
   6231         NewVD->setInvalidDecl();
   6232 
   6233       // If we are providing an explicit specialization of a static variable
   6234       // template, make a note of that.
   6235       if (PrevVarTemplate &&
   6236           PrevVarTemplate->getInstantiatedFromMemberTemplate())
   6237         PrevVarTemplate->setMemberSpecialization();
   6238     }
   6239   }
   6240 
   6241   ProcessPragmaWeak(S, NewVD);
   6242 
   6243   // If this is the first declaration of an extern C variable, update
   6244   // the map of such variables.
   6245   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
   6246       isIncompleteDeclExternC(*this, NewVD))
   6247     RegisterLocallyScopedExternCDecl(NewVD, S);
   6248 
   6249   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
   6250     Decl *ManglingContextDecl;
   6251     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
   6252             NewVD->getDeclContext(), ManglingContextDecl)) {
   6253       Context.setManglingNumber(
   6254           NewVD, MCtx->getManglingNumber(
   6255                      NewVD, getMSManglingNumber(getLangOpts(), S)));
   6256       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
   6257     }
   6258   }
   6259 
   6260   // Special handling of variable named 'main'.
   6261   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
   6262       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
   6263       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
   6264 
   6265     // C++ [basic.start.main]p3
   6266     // A program that declares a variable main at global scope is ill-formed.
   6267     if (getLangOpts().CPlusPlus)
   6268       Diag(D.getLocStart(), diag::err_main_global_variable);
   6269 
   6270     // In C, and external-linkage variable named main results in undefined
   6271     // behavior.
   6272     else if (NewVD->hasExternalFormalLinkage())
   6273       Diag(D.getLocStart(), diag::warn_main_redefined);
   6274   }
   6275 
   6276   if (D.isRedeclaration() && !Previous.empty()) {
   6277     checkDLLAttributeRedeclaration(
   6278         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
   6279         IsExplicitSpecialization);
   6280   }
   6281 
   6282   if (NewTemplate) {
   6283     if (NewVD->isInvalidDecl())
   6284       NewTemplate->setInvalidDecl();
   6285     ActOnDocumentableDecl(NewTemplate);
   6286     return NewTemplate;
   6287   }
   6288 
   6289   return NewVD;
   6290 }
   6291 
   6292 /// \brief Diagnose variable or built-in function shadowing.  Implements
   6293 /// -Wshadow.
   6294 ///
   6295 /// This method is called whenever a VarDecl is added to a "useful"
   6296 /// scope.
   6297 ///
   6298 /// \param S the scope in which the shadowing name is being declared
   6299 /// \param R the lookup of the name
   6300 ///
   6301 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
   6302   // Return if warning is ignored.
   6303   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
   6304     return;
   6305 
   6306   // Don't diagnose declarations at file scope.
   6307   if (D->hasGlobalStorage())
   6308     return;
   6309 
   6310   DeclContext *NewDC = D->getDeclContext();
   6311 
   6312   // Only diagnose if we're shadowing an unambiguous field or variable.
   6313   if (R.getResultKind() != LookupResult::Found)
   6314     return;
   6315 
   6316   NamedDecl* ShadowedDecl = R.getFoundDecl();
   6317   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
   6318     return;
   6319 
   6320   // Fields are not shadowed by variables in C++ static methods.
   6321   if (isa<FieldDecl>(ShadowedDecl))
   6322     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
   6323       if (MD->isStatic())
   6324         return;
   6325 
   6326   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
   6327     if (shadowedVar->isExternC()) {
   6328       // For shadowing external vars, make sure that we point to the global
   6329       // declaration, not a locally scoped extern declaration.
   6330       for (auto I : shadowedVar->redecls())
   6331         if (I->isFileVarDecl()) {
   6332           ShadowedDecl = I;
   6333           break;
   6334         }
   6335     }
   6336 
   6337   DeclContext *OldDC = ShadowedDecl->getDeclContext();
   6338 
   6339   // Only warn about certain kinds of shadowing for class members.
   6340   if (NewDC && NewDC->isRecord()) {
   6341     // In particular, don't warn about shadowing non-class members.
   6342     if (!OldDC->isRecord())
   6343       return;
   6344 
   6345     // TODO: should we warn about static data members shadowing
   6346     // static data members from base classes?
   6347 
   6348     // TODO: don't diagnose for inaccessible shadowed members.
   6349     // This is hard to do perfectly because we might friend the
   6350     // shadowing context, but that's just a false negative.
   6351   }
   6352 
   6353   // Determine what kind of declaration we're shadowing.
   6354   unsigned Kind;
   6355   if (isa<RecordDecl>(OldDC)) {
   6356     if (isa<FieldDecl>(ShadowedDecl))
   6357       Kind = 3; // field
   6358     else
   6359       Kind = 2; // static data member
   6360   } else if (OldDC->isFileContext())
   6361     Kind = 1; // global
   6362   else
   6363     Kind = 0; // local
   6364 
   6365   DeclarationName Name = R.getLookupName();
   6366 
   6367   // Emit warning and note.
   6368   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
   6369     return;
   6370   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
   6371   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
   6372 }
   6373 
   6374 /// \brief Check -Wshadow without the advantage of a previous lookup.
   6375 void Sema::CheckShadow(Scope *S, VarDecl *D) {
   6376   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
   6377     return;
   6378 
   6379   LookupResult R(*this, D->getDeclName(), D->getLocation(),
   6380                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
   6381   LookupName(R, S);
   6382   CheckShadow(S, D, R);
   6383 }
   6384 
   6385 /// Check for conflict between this global or extern "C" declaration and
   6386 /// previous global or extern "C" declarations. This is only used in C++.
   6387 template<typename T>
   6388 static bool checkGlobalOrExternCConflict(
   6389     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
   6390   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
   6391   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
   6392 
   6393   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
   6394     // The common case: this global doesn't conflict with any extern "C"
   6395     // declaration.
   6396     return false;
   6397   }
   6398 
   6399   if (Prev) {
   6400     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
   6401       // Both the old and new declarations have C language linkage. This is a
   6402       // redeclaration.
   6403       Previous.clear();
   6404       Previous.addDecl(Prev);
   6405       return true;
   6406     }
   6407 
   6408     // This is a global, non-extern "C" declaration, and there is a previous
   6409     // non-global extern "C" declaration. Diagnose if this is a variable
   6410     // declaration.
   6411     if (!isa<VarDecl>(ND))
   6412       return false;
   6413   } else {
   6414     // The declaration is extern "C". Check for any declaration in the
   6415     // translation unit which might conflict.
   6416     if (IsGlobal) {
   6417       // We have already performed the lookup into the translation unit.
   6418       IsGlobal = false;
   6419       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
   6420            I != E; ++I) {
   6421         if (isa<VarDecl>(*I)) {
   6422           Prev = *I;
   6423           break;
   6424         }
   6425       }
   6426     } else {
   6427       DeclContext::lookup_result R =
   6428           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
   6429       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
   6430            I != E; ++I) {
   6431         if (isa<VarDecl>(*I)) {
   6432           Prev = *I;
   6433           break;
   6434         }
   6435         // FIXME: If we have any other entity with this name in global scope,
   6436         // the declaration is ill-formed, but that is a defect: it breaks the
   6437         // 'stat' hack, for instance. Only variables can have mangled name
   6438         // clashes with extern "C" declarations, so only they deserve a
   6439         // diagnostic.
   6440       }
   6441     }
   6442 
   6443     if (!Prev)
   6444       return false;
   6445   }
   6446 
   6447   // Use the first declaration's location to ensure we point at something which
   6448   // is lexically inside an extern "C" linkage-spec.
   6449   assert(Prev && "should have found a previous declaration to diagnose");
   6450   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
   6451     Prev = FD->getFirstDecl();
   6452   else
   6453     Prev = cast<VarDecl>(Prev)->getFirstDecl();
   6454 
   6455   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
   6456     << IsGlobal << ND;
   6457   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
   6458     << IsGlobal;
   6459   return false;
   6460 }
   6461 
   6462 /// Apply special rules for handling extern "C" declarations. Returns \c true
   6463 /// if we have found that this is a redeclaration of some prior entity.
   6464 ///
   6465 /// Per C++ [dcl.link]p6:
   6466 ///   Two declarations [for a function or variable] with C language linkage
   6467 ///   with the same name that appear in different scopes refer to the same
   6468 ///   [entity]. An entity with C language linkage shall not be declared with
   6469 ///   the same name as an entity in global scope.
   6470 template<typename T>
   6471 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
   6472                                                   LookupResult &Previous) {
   6473   if (!S.getLangOpts().CPlusPlus) {
   6474     // In C, when declaring a global variable, look for a corresponding 'extern'
   6475     // variable declared in function scope. We don't need this in C++, because
   6476     // we find local extern decls in the surrounding file-scope DeclContext.
   6477     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
   6478       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
   6479         Previous.clear();
   6480         Previous.addDecl(Prev);
   6481         return true;
   6482       }
   6483     }
   6484     return false;
   6485   }
   6486 
   6487   // A declaration in the translation unit can conflict with an extern "C"
   6488   // declaration.
   6489   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
   6490     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
   6491 
   6492   // An extern "C" declaration can conflict with a declaration in the
   6493   // translation unit or can be a redeclaration of an extern "C" declaration
   6494   // in another scope.
   6495   if (isIncompleteDeclExternC(S,ND))
   6496     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
   6497 
   6498   // Neither global nor extern "C": nothing to do.
   6499   return false;
   6500 }
   6501 
   6502 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
   6503   // If the decl is already known invalid, don't check it.
   6504   if (NewVD->isInvalidDecl())
   6505     return;
   6506 
   6507   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
   6508   QualType T = TInfo->getType();
   6509 
   6510   // Defer checking an 'auto' type until its initializer is attached.
   6511   if (T->isUndeducedType())
   6512     return;
   6513 
   6514   if (NewVD->hasAttrs())
   6515     CheckAlignasUnderalignment(NewVD);
   6516 
   6517   if (T->isObjCObjectType()) {
   6518     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
   6519       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
   6520     T = Context.getObjCObjectPointerType(T);
   6521     NewVD->setType(T);
   6522   }
   6523 
   6524   // Emit an error if an address space was applied to decl with local storage.
   6525   // This includes arrays of objects with address space qualifiers, but not
   6526   // automatic variables that point to other address spaces.
   6527   // ISO/IEC TR 18037 S5.1.2
   6528   if (!getLangOpts().OpenCL
   6529       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
   6530     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
   6531     NewVD->setInvalidDecl();
   6532     return;
   6533   }
   6534 
   6535   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
   6536   // scope.
   6537   if (getLangOpts().OpenCLVersion == 120 &&
   6538       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
   6539       NewVD->isStaticLocal()) {
   6540     Diag(NewVD->getLocation(), diag::err_static_function_scope);
   6541     NewVD->setInvalidDecl();
   6542     return;
   6543   }
   6544 
   6545   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
   6546   // __constant address space.
   6547   // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
   6548   // variables inside a function can also be declared in the global
   6549   // address space.
   6550   if (getLangOpts().OpenCL) {
   6551     if (NewVD->isFileVarDecl()) {
   6552       if (!T->isSamplerT() &&
   6553           !(T.getAddressSpace() == LangAS::opencl_constant ||
   6554             (T.getAddressSpace() == LangAS::opencl_global &&
   6555              getLangOpts().OpenCLVersion == 200))) {
   6556         if (getLangOpts().OpenCLVersion == 200)
   6557           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
   6558               << "global or constant";
   6559         else
   6560           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
   6561               << "constant";
   6562         NewVD->setInvalidDecl();
   6563         return;
   6564       }
   6565     } else {
   6566       // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
   6567       // variables inside a function can also be declared in the global
   6568       // address space.
   6569       if (NewVD->isStaticLocal() &&
   6570           !(T.getAddressSpace() == LangAS::opencl_constant ||
   6571             (T.getAddressSpace() == LangAS::opencl_global &&
   6572              getLangOpts().OpenCLVersion == 200))) {
   6573         if (getLangOpts().OpenCLVersion == 200)
   6574           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
   6575               << "global or constant";
   6576         else
   6577           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
   6578               << "constant";
   6579         NewVD->setInvalidDecl();
   6580         return;
   6581       }
   6582       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
   6583       // in functions.
   6584       if (T.getAddressSpace() == LangAS::opencl_constant ||
   6585           T.getAddressSpace() == LangAS::opencl_local) {
   6586         FunctionDecl *FD = getCurFunctionDecl();
   6587         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
   6588           if (T.getAddressSpace() == LangAS::opencl_constant)
   6589             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
   6590                 << "constant";
   6591           else
   6592             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
   6593                 << "local";
   6594           NewVD->setInvalidDecl();
   6595           return;
   6596         }
   6597       }
   6598     }
   6599   }
   6600 
   6601   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
   6602       && !NewVD->hasAttr<BlocksAttr>()) {
   6603     if (getLangOpts().getGC() != LangOptions::NonGC)
   6604       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
   6605     else {
   6606       assert(!getLangOpts().ObjCAutoRefCount);
   6607       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
   6608     }
   6609   }
   6610 
   6611   bool isVM = T->isVariablyModifiedType();
   6612   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
   6613       NewVD->hasAttr<BlocksAttr>())
   6614     getCurFunction()->setHasBranchProtectedScope();
   6615 
   6616   if ((isVM && NewVD->hasLinkage()) ||
   6617       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
   6618     bool SizeIsNegative;
   6619     llvm::APSInt Oversized;
   6620     TypeSourceInfo *FixedTInfo =
   6621       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
   6622                                                     SizeIsNegative, Oversized);
   6623     if (!FixedTInfo && T->isVariableArrayType()) {
   6624       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
   6625       // FIXME: This won't give the correct result for
   6626       // int a[10][n];
   6627       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
   6628 
   6629       if (NewVD->isFileVarDecl())
   6630         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
   6631         << SizeRange;
   6632       else if (NewVD->isStaticLocal())
   6633         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
   6634         << SizeRange;
   6635       else
   6636         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
   6637         << SizeRange;
   6638       NewVD->setInvalidDecl();
   6639       return;
   6640     }
   6641 
   6642     if (!FixedTInfo) {
   6643       if (NewVD->isFileVarDecl())
   6644         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
   6645       else
   6646         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
   6647       NewVD->setInvalidDecl();
   6648       return;
   6649     }
   6650 
   6651     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
   6652     NewVD->setType(FixedTInfo->getType());
   6653     NewVD->setTypeSourceInfo(FixedTInfo);
   6654   }
   6655 
   6656   if (T->isVoidType()) {
   6657     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
   6658     //                    of objects and functions.
   6659     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
   6660       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
   6661         << T;
   6662       NewVD->setInvalidDecl();
   6663       return;
   6664     }
   6665   }
   6666 
   6667   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
   6668     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
   6669     NewVD->setInvalidDecl();
   6670     return;
   6671   }
   6672 
   6673   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
   6674     Diag(NewVD->getLocation(), diag::err_block_on_vm);
   6675     NewVD->setInvalidDecl();
   6676     return;
   6677   }
   6678 
   6679   if (NewVD->isConstexpr() && !T->isDependentType() &&
   6680       RequireLiteralType(NewVD->getLocation(), T,
   6681                          diag::err_constexpr_var_non_literal)) {
   6682     NewVD->setInvalidDecl();
   6683     return;
   6684   }
   6685 }
   6686 
   6687 /// \brief Perform semantic checking on a newly-created variable
   6688 /// declaration.
   6689 ///
   6690 /// This routine performs all of the type-checking required for a
   6691 /// variable declaration once it has been built. It is used both to
   6692 /// check variables after they have been parsed and their declarators
   6693 /// have been translated into a declaration, and to check variables
   6694 /// that have been instantiated from a template.
   6695 ///
   6696 /// Sets NewVD->isInvalidDecl() if an error was encountered.
   6697 ///
   6698 /// Returns true if the variable declaration is a redeclaration.
   6699 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
   6700   CheckVariableDeclarationType(NewVD);
   6701 
   6702   // If the decl is already known invalid, don't check it.
   6703   if (NewVD->isInvalidDecl())
   6704     return false;
   6705 
   6706   // If we did not find anything by this name, look for a non-visible
   6707   // extern "C" declaration with the same name.
   6708   if (Previous.empty() &&
   6709       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
   6710     Previous.setShadowed();
   6711 
   6712   if (!Previous.empty()) {
   6713     MergeVarDecl(NewVD, Previous);
   6714     return true;
   6715   }
   6716   return false;
   6717 }
   6718 
   6719 namespace {
   6720 struct FindOverriddenMethod {
   6721   Sema *S;
   6722   CXXMethodDecl *Method;
   6723 
   6724   /// Member lookup function that determines whether a given C++
   6725   /// method overrides a method in a base class, to be used with
   6726   /// CXXRecordDecl::lookupInBases().
   6727   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
   6728     RecordDecl *BaseRecord =
   6729         Specifier->getType()->getAs<RecordType>()->getDecl();
   6730 
   6731     DeclarationName Name = Method->getDeclName();
   6732 
   6733     // FIXME: Do we care about other names here too?
   6734     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
   6735       // We really want to find the base class destructor here.
   6736       QualType T = S->Context.getTypeDeclType(BaseRecord);
   6737       CanQualType CT = S->Context.getCanonicalType(T);
   6738 
   6739       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
   6740     }
   6741 
   6742     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
   6743          Path.Decls = Path.Decls.slice(1)) {
   6744       NamedDecl *D = Path.Decls.front();
   6745       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
   6746         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
   6747           return true;
   6748       }
   6749     }
   6750 
   6751     return false;
   6752   }
   6753 };
   6754 
   6755 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
   6756 } // end anonymous namespace
   6757 
   6758 /// \brief Report an error regarding overriding, along with any relevant
   6759 /// overriden methods.
   6760 ///
   6761 /// \param DiagID the primary error to report.
   6762 /// \param MD the overriding method.
   6763 /// \param OEK which overrides to include as notes.
   6764 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
   6765                             OverrideErrorKind OEK = OEK_All) {
   6766   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
   6767   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
   6768                                       E = MD->end_overridden_methods();
   6769        I != E; ++I) {
   6770     // This check (& the OEK parameter) could be replaced by a predicate, but
   6771     // without lambdas that would be overkill. This is still nicer than writing
   6772     // out the diag loop 3 times.
   6773     if ((OEK == OEK_All) ||
   6774         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
   6775         (OEK == OEK_Deleted && (*I)->isDeleted()))
   6776       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
   6777   }
   6778 }
   6779 
   6780 /// AddOverriddenMethods - See if a method overrides any in the base classes,
   6781 /// and if so, check that it's a valid override and remember it.
   6782 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
   6783   // Look for methods in base classes that this method might override.
   6784   CXXBasePaths Paths;
   6785   FindOverriddenMethod FOM;
   6786   FOM.Method = MD;
   6787   FOM.S = this;
   6788   bool hasDeletedOverridenMethods = false;
   6789   bool hasNonDeletedOverridenMethods = false;
   6790   bool AddedAny = false;
   6791   if (DC->lookupInBases(FOM, Paths)) {
   6792     for (auto *I : Paths.found_decls()) {
   6793       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
   6794         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
   6795         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
   6796             !CheckOverridingFunctionAttributes(MD, OldMD) &&
   6797             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
   6798             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
   6799           hasDeletedOverridenMethods |= OldMD->isDeleted();
   6800           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
   6801           AddedAny = true;
   6802         }
   6803       }
   6804     }
   6805   }
   6806 
   6807   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
   6808     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
   6809   }
   6810   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
   6811     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
   6812   }
   6813 
   6814   return AddedAny;
   6815 }
   6816 
   6817 namespace {
   6818   // Struct for holding all of the extra arguments needed by
   6819   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
   6820   struct ActOnFDArgs {
   6821     Scope *S;
   6822     Declarator &D;
   6823     MultiTemplateParamsArg TemplateParamLists;
   6824     bool AddToScope;
   6825   };
   6826 }
   6827 
   6828 namespace {
   6829 
   6830 // Callback to only accept typo corrections that have a non-zero edit distance.
   6831 // Also only accept corrections that have the same parent decl.
   6832 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
   6833  public:
   6834   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
   6835                             CXXRecordDecl *Parent)
   6836       : Context(Context), OriginalFD(TypoFD),
   6837         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
   6838 
   6839   bool ValidateCandidate(const TypoCorrection &candidate) override {
   6840     if (candidate.getEditDistance() == 0)
   6841       return false;
   6842 
   6843     SmallVector<unsigned, 1> MismatchedParams;
   6844     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
   6845                                           CDeclEnd = candidate.end();
   6846          CDecl != CDeclEnd; ++CDecl) {
   6847       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
   6848 
   6849       if (FD && !FD->hasBody() &&
   6850           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
   6851         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
   6852           CXXRecordDecl *Parent = MD->getParent();
   6853           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
   6854             return true;
   6855         } else if (!ExpectedParent) {
   6856           return true;
   6857         }
   6858       }
   6859     }
   6860 
   6861     return false;
   6862   }
   6863 
   6864  private:
   6865   ASTContext &Context;
   6866   FunctionDecl *OriginalFD;
   6867   CXXRecordDecl *ExpectedParent;
   6868 };
   6869 
   6870 }
   6871 
   6872 /// \brief Generate diagnostics for an invalid function redeclaration.
   6873 ///
   6874 /// This routine handles generating the diagnostic messages for an invalid
   6875 /// function redeclaration, including finding possible similar declarations
   6876 /// or performing typo correction if there are no previous declarations with
   6877 /// the same name.
   6878 ///
   6879 /// Returns a NamedDecl iff typo correction was performed and substituting in
   6880 /// the new declaration name does not cause new errors.
   6881 static NamedDecl *DiagnoseInvalidRedeclaration(
   6882     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
   6883     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
   6884   DeclarationName Name = NewFD->getDeclName();
   6885   DeclContext *NewDC = NewFD->getDeclContext();
   6886   SmallVector<unsigned, 1> MismatchedParams;
   6887   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
   6888   TypoCorrection Correction;
   6889   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
   6890   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
   6891                                    : diag::err_member_decl_does_not_match;
   6892   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
   6893                     IsLocalFriend ? Sema::LookupLocalFriendName
   6894                                   : Sema::LookupOrdinaryName,
   6895                     Sema::ForRedeclaration);
   6896 
   6897   NewFD->setInvalidDecl();
   6898   if (IsLocalFriend)
   6899     SemaRef.LookupName(Prev, S);
   6900   else
   6901     SemaRef.LookupQualifiedName(Prev, NewDC);
   6902   assert(!Prev.isAmbiguous() &&
   6903          "Cannot have an ambiguity in previous-declaration lookup");
   6904   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
   6905   if (!Prev.empty()) {
   6906     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
   6907          Func != FuncEnd; ++Func) {
   6908       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
   6909       if (FD &&
   6910           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
   6911         // Add 1 to the index so that 0 can mean the mismatch didn't
   6912         // involve a parameter
   6913         unsigned ParamNum =
   6914             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
   6915         NearMatches.push_back(std::make_pair(FD, ParamNum));
   6916       }
   6917     }
   6918   // If the qualified name lookup yielded nothing, try typo correction
   6919   } else if ((Correction = SemaRef.CorrectTypo(
   6920                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
   6921                   &ExtraArgs.D.getCXXScopeSpec(),
   6922                   llvm::make_unique<DifferentNameValidatorCCC>(
   6923                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
   6924                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
   6925     // Set up everything for the call to ActOnFunctionDeclarator
   6926     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
   6927                               ExtraArgs.D.getIdentifierLoc());
   6928     Previous.clear();
   6929     Previous.setLookupName(Correction.getCorrection());
   6930     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
   6931                                     CDeclEnd = Correction.end();
   6932          CDecl != CDeclEnd; ++CDecl) {
   6933       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
   6934       if (FD && !FD->hasBody() &&
   6935           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
   6936         Previous.addDecl(FD);
   6937       }
   6938     }
   6939     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
   6940 
   6941     NamedDecl *Result;
   6942     // Retry building the function declaration with the new previous
   6943     // declarations, and with errors suppressed.
   6944     {
   6945       // Trap errors.
   6946       Sema::SFINAETrap Trap(SemaRef);
   6947 
   6948       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
   6949       // pieces need to verify the typo-corrected C++ declaration and hopefully
   6950       // eliminate the need for the parameter pack ExtraArgs.
   6951       Result = SemaRef.ActOnFunctionDeclarator(
   6952           ExtraArgs.S, ExtraArgs.D,
   6953           Correction.getCorrectionDecl()->getDeclContext(),
   6954           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
   6955           ExtraArgs.AddToScope);
   6956 
   6957       if (Trap.hasErrorOccurred())
   6958         Result = nullptr;
   6959     }
   6960 
   6961     if (Result) {
   6962       // Determine which correction we picked.
   6963       Decl *Canonical = Result->getCanonicalDecl();
   6964       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
   6965            I != E; ++I)
   6966         if ((*I)->getCanonicalDecl() == Canonical)
   6967           Correction.setCorrectionDecl(*I);
   6968 
   6969       SemaRef.diagnoseTypo(
   6970           Correction,
   6971           SemaRef.PDiag(IsLocalFriend
   6972                           ? diag::err_no_matching_local_friend_suggest
   6973                           : diag::err_member_decl_does_not_match_suggest)
   6974             << Name << NewDC << IsDefinition);
   6975       return Result;
   6976     }
   6977 
   6978     // Pretend the typo correction never occurred
   6979     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
   6980                               ExtraArgs.D.getIdentifierLoc());
   6981     ExtraArgs.D.setRedeclaration(wasRedeclaration);
   6982     Previous.clear();
   6983     Previous.setLookupName(Name);
   6984   }
   6985 
   6986   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
   6987       << Name << NewDC << IsDefinition << NewFD->getLocation();
   6988 
   6989   bool NewFDisConst = false;
   6990   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
   6991     NewFDisConst = NewMD->isConst();
   6992 
   6993   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
   6994        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
   6995        NearMatch != NearMatchEnd; ++NearMatch) {
   6996     FunctionDecl *FD = NearMatch->first;
   6997     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
   6998     bool FDisConst = MD && MD->isConst();
   6999     bool IsMember = MD || !IsLocalFriend;
   7000 
   7001     // FIXME: These notes are poorly worded for the local friend case.
   7002     if (unsigned Idx = NearMatch->second) {
   7003       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
   7004       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
   7005       if (Loc.isInvalid()) Loc = FD->getLocation();
   7006       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
   7007                                  : diag::note_local_decl_close_param_match)
   7008         << Idx << FDParam->getType()
   7009         << NewFD->getParamDecl(Idx - 1)->getType();
   7010     } else if (FDisConst != NewFDisConst) {
   7011       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
   7012           << NewFDisConst << FD->getSourceRange().getEnd();
   7013     } else
   7014       SemaRef.Diag(FD->getLocation(),
   7015                    IsMember ? diag::note_member_def_close_match
   7016                             : diag::note_local_decl_close_match);
   7017   }
   7018   return nullptr;
   7019 }
   7020 
   7021 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
   7022   switch (D.getDeclSpec().getStorageClassSpec()) {
   7023   default: llvm_unreachable("Unknown storage class!");
   7024   case DeclSpec::SCS_auto:
   7025   case DeclSpec::SCS_register:
   7026   case DeclSpec::SCS_mutable:
   7027     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
   7028                  diag::err_typecheck_sclass_func);
   7029     D.setInvalidType();
   7030     break;
   7031   case DeclSpec::SCS_unspecified: break;
   7032   case DeclSpec::SCS_extern:
   7033     if (D.getDeclSpec().isExternInLinkageSpec())
   7034       return SC_None;
   7035     return SC_Extern;
   7036   case DeclSpec::SCS_static: {
   7037     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
   7038       // C99 6.7.1p5:
   7039       //   The declaration of an identifier for a function that has
   7040       //   block scope shall have no explicit storage-class specifier
   7041       //   other than extern
   7042       // See also (C++ [dcl.stc]p4).
   7043       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
   7044                    diag::err_static_block_func);
   7045       break;
   7046     } else
   7047       return SC_Static;
   7048   }
   7049   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
   7050   }
   7051 
   7052   // No explicit storage class has already been returned
   7053   return SC_None;
   7054 }
   7055 
   7056 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
   7057                                            DeclContext *DC, QualType &R,
   7058                                            TypeSourceInfo *TInfo,
   7059                                            StorageClass SC,
   7060                                            bool &IsVirtualOkay) {
   7061   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
   7062   DeclarationName Name = NameInfo.getName();
   7063 
   7064   FunctionDecl *NewFD = nullptr;
   7065   bool isInline = D.getDeclSpec().isInlineSpecified();
   7066 
   7067   if (!SemaRef.getLangOpts().CPlusPlus) {
   7068     // Determine whether the function was written with a
   7069     // prototype. This true when:
   7070     //   - there is a prototype in the declarator, or
   7071     //   - the type R of the function is some kind of typedef or other reference
   7072     //     to a type name (which eventually refers to a function type).
   7073     bool HasPrototype =
   7074       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
   7075       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
   7076 
   7077     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
   7078                                  D.getLocStart(), NameInfo, R,
   7079                                  TInfo, SC, isInline,
   7080                                  HasPrototype, false);
   7081     if (D.isInvalidType())
   7082       NewFD->setInvalidDecl();
   7083 
   7084     return NewFD;
   7085   }
   7086 
   7087   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
   7088   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
   7089 
   7090   // Check that the return type is not an abstract class type.
   7091   // For record types, this is done by the AbstractClassUsageDiagnoser once
   7092   // the class has been completely parsed.
   7093   if (!DC->isRecord() &&
   7094       SemaRef.RequireNonAbstractType(
   7095           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
   7096           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
   7097     D.setInvalidType();
   7098 
   7099   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
   7100     // This is a C++ constructor declaration.
   7101     assert(DC->isRecord() &&
   7102            "Constructors can only be declared in a member context");
   7103 
   7104     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
   7105     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
   7106                                       D.getLocStart(), NameInfo,
   7107                                       R, TInfo, isExplicit, isInline,
   7108                                       /*isImplicitlyDeclared=*/false,
   7109                                       isConstexpr);
   7110 
   7111   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
   7112     // This is a C++ destructor declaration.
   7113     if (DC->isRecord()) {
   7114       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
   7115       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
   7116       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
   7117                                         SemaRef.Context, Record,
   7118                                         D.getLocStart(),
   7119                                         NameInfo, R, TInfo, isInline,
   7120                                         /*isImplicitlyDeclared=*/false);
   7121 
   7122       // If the class is complete, then we now create the implicit exception
   7123       // specification. If the class is incomplete or dependent, we can't do
   7124       // it yet.
   7125       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
   7126           Record->getDefinition() && !Record->isBeingDefined() &&
   7127           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
   7128         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
   7129       }
   7130 
   7131       IsVirtualOkay = true;
   7132       return NewDD;
   7133 
   7134     } else {
   7135       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
   7136       D.setInvalidType();
   7137 
   7138       // Create a FunctionDecl to satisfy the function definition parsing
   7139       // code path.
   7140       return FunctionDecl::Create(SemaRef.Context, DC,
   7141                                   D.getLocStart(),
   7142                                   D.getIdentifierLoc(), Name, R, TInfo,
   7143                                   SC, isInline,
   7144                                   /*hasPrototype=*/true, isConstexpr);
   7145     }
   7146 
   7147   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
   7148     if (!DC->isRecord()) {
   7149       SemaRef.Diag(D.getIdentifierLoc(),
   7150            diag::err_conv_function_not_member);
   7151       return nullptr;
   7152     }
   7153 
   7154     SemaRef.CheckConversionDeclarator(D, R, SC);
   7155     IsVirtualOkay = true;
   7156     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
   7157                                      D.getLocStart(), NameInfo,
   7158                                      R, TInfo, isInline, isExplicit,
   7159                                      isConstexpr, SourceLocation());
   7160 
   7161   } else if (DC->isRecord()) {
   7162     // If the name of the function is the same as the name of the record,
   7163     // then this must be an invalid constructor that has a return type.
   7164     // (The parser checks for a return type and makes the declarator a
   7165     // constructor if it has no return type).
   7166     if (Name.getAsIdentifierInfo() &&
   7167         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
   7168       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
   7169         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
   7170         << SourceRange(D.getIdentifierLoc());
   7171       return nullptr;
   7172     }
   7173 
   7174     // This is a C++ method declaration.
   7175     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
   7176                                                cast<CXXRecordDecl>(DC),
   7177                                                D.getLocStart(), NameInfo, R,
   7178                                                TInfo, SC, isInline,
   7179                                                isConstexpr, SourceLocation());
   7180     IsVirtualOkay = !Ret->isStatic();
   7181     return Ret;
   7182   } else {
   7183     bool isFriend =
   7184         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
   7185     if (!isFriend && SemaRef.CurContext->isRecord())
   7186       return nullptr;
   7187 
   7188     // Determine whether the function was written with a
   7189     // prototype. This true when:
   7190     //   - we're in C++ (where every function has a prototype),
   7191     return FunctionDecl::Create(SemaRef.Context, DC,
   7192                                 D.getLocStart(),
   7193                                 NameInfo, R, TInfo, SC, isInline,
   7194                                 true/*HasPrototype*/, isConstexpr);
   7195   }
   7196 }
   7197 
   7198 enum OpenCLParamType {
   7199   ValidKernelParam,
   7200   PtrPtrKernelParam,
   7201   PtrKernelParam,
   7202   PrivatePtrKernelParam,
   7203   InvalidKernelParam,
   7204   RecordKernelParam
   7205 };
   7206 
   7207 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
   7208   if (PT->isPointerType()) {
   7209     QualType PointeeType = PT->getPointeeType();
   7210     if (PointeeType->isPointerType())
   7211       return PtrPtrKernelParam;
   7212     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
   7213                                               : PtrKernelParam;
   7214   }
   7215 
   7216   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
   7217   // be used as builtin types.
   7218 
   7219   if (PT->isImageType())
   7220     return PtrKernelParam;
   7221 
   7222   if (PT->isBooleanType())
   7223     return InvalidKernelParam;
   7224 
   7225   if (PT->isEventT())
   7226     return InvalidKernelParam;
   7227 
   7228   if (PT->isHalfType())
   7229     return InvalidKernelParam;
   7230 
   7231   if (PT->isRecordType())
   7232     return RecordKernelParam;
   7233 
   7234   return ValidKernelParam;
   7235 }
   7236 
   7237 static void checkIsValidOpenCLKernelParameter(
   7238   Sema &S,
   7239   Declarator &D,
   7240   ParmVarDecl *Param,
   7241   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
   7242   QualType PT = Param->getType();
   7243 
   7244   // Cache the valid types we encounter to avoid rechecking structs that are
   7245   // used again
   7246   if (ValidTypes.count(PT.getTypePtr()))
   7247     return;
   7248 
   7249   switch (getOpenCLKernelParameterType(PT)) {
   7250   case PtrPtrKernelParam:
   7251     // OpenCL v1.2 s6.9.a:
   7252     // A kernel function argument cannot be declared as a
   7253     // pointer to a pointer type.
   7254     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
   7255     D.setInvalidType();
   7256     return;
   7257 
   7258   case PrivatePtrKernelParam:
   7259     // OpenCL v1.2 s6.9.a:
   7260     // A kernel function argument cannot be declared as a
   7261     // pointer to the private address space.
   7262     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
   7263     D.setInvalidType();
   7264     return;
   7265 
   7266     // OpenCL v1.2 s6.9.k:
   7267     // Arguments to kernel functions in a program cannot be declared with the
   7268     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
   7269     // uintptr_t or a struct and/or union that contain fields declared to be
   7270     // one of these built-in scalar types.
   7271 
   7272   case InvalidKernelParam:
   7273     // OpenCL v1.2 s6.8 n:
   7274     // A kernel function argument cannot be declared
   7275     // of event_t type.
   7276     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
   7277     D.setInvalidType();
   7278     return;
   7279 
   7280   case PtrKernelParam:
   7281   case ValidKernelParam:
   7282     ValidTypes.insert(PT.getTypePtr());
   7283     return;
   7284 
   7285   case RecordKernelParam:
   7286     break;
   7287   }
   7288 
   7289   // Track nested structs we will inspect
   7290   SmallVector<const Decl *, 4> VisitStack;
   7291 
   7292   // Track where we are in the nested structs. Items will migrate from
   7293   // VisitStack to HistoryStack as we do the DFS for bad field.
   7294   SmallVector<const FieldDecl *, 4> HistoryStack;
   7295   HistoryStack.push_back(nullptr);
   7296 
   7297   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
   7298   VisitStack.push_back(PD);
   7299 
   7300   assert(VisitStack.back() && "First decl null?");
   7301 
   7302   do {
   7303     const Decl *Next = VisitStack.pop_back_val();
   7304     if (!Next) {
   7305       assert(!HistoryStack.empty());
   7306       // Found a marker, we have gone up a level
   7307       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
   7308         ValidTypes.insert(Hist->getType().getTypePtr());
   7309 
   7310       continue;
   7311     }
   7312 
   7313     // Adds everything except the original parameter declaration (which is not a
   7314     // field itself) to the history stack.
   7315     const RecordDecl *RD;
   7316     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
   7317       HistoryStack.push_back(Field);
   7318       RD = Field->getType()->castAs<RecordType>()->getDecl();
   7319     } else {
   7320       RD = cast<RecordDecl>(Next);
   7321     }
   7322 
   7323     // Add a null marker so we know when we've gone back up a level
   7324     VisitStack.push_back(nullptr);
   7325 
   7326     for (const auto *FD : RD->fields()) {
   7327       QualType QT = FD->getType();
   7328 
   7329       if (ValidTypes.count(QT.getTypePtr()))
   7330         continue;
   7331 
   7332       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
   7333       if (ParamType == ValidKernelParam)
   7334         continue;
   7335 
   7336       if (ParamType == RecordKernelParam) {
   7337         VisitStack.push_back(FD);
   7338         continue;
   7339       }
   7340 
   7341       // OpenCL v1.2 s6.9.p:
   7342       // Arguments to kernel functions that are declared to be a struct or union
   7343       // do not allow OpenCL objects to be passed as elements of the struct or
   7344       // union.
   7345       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
   7346           ParamType == PrivatePtrKernelParam) {
   7347         S.Diag(Param->getLocation(),
   7348                diag::err_record_with_pointers_kernel_param)
   7349           << PT->isUnionType()
   7350           << PT;
   7351       } else {
   7352         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
   7353       }
   7354 
   7355       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
   7356         << PD->getDeclName();
   7357 
   7358       // We have an error, now let's go back up through history and show where
   7359       // the offending field came from
   7360       for (ArrayRef<const FieldDecl *>::const_iterator
   7361                I = HistoryStack.begin() + 1,
   7362                E = HistoryStack.end();
   7363            I != E; ++I) {
   7364         const FieldDecl *OuterField = *I;
   7365         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
   7366           << OuterField->getType();
   7367       }
   7368 
   7369       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
   7370         << QT->isPointerType()
   7371         << QT;
   7372       D.setInvalidType();
   7373       return;
   7374     }
   7375   } while (!VisitStack.empty());
   7376 }
   7377 
   7378 NamedDecl*
   7379 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
   7380                               TypeSourceInfo *TInfo, LookupResult &Previous,
   7381                               MultiTemplateParamsArg TemplateParamLists,
   7382                               bool &AddToScope) {
   7383   QualType R = TInfo->getType();
   7384 
   7385   assert(R.getTypePtr()->isFunctionType());
   7386 
   7387   // TODO: consider using NameInfo for diagnostic.
   7388   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
   7389   DeclarationName Name = NameInfo.getName();
   7390   StorageClass SC = getFunctionStorageClass(*this, D);
   7391 
   7392   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
   7393     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
   7394          diag::err_invalid_thread)
   7395       << DeclSpec::getSpecifierName(TSCS);
   7396 
   7397   if (D.isFirstDeclarationOfMember())
   7398     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
   7399                            D.getIdentifierLoc());
   7400 
   7401   bool isFriend = false;
   7402   FunctionTemplateDecl *FunctionTemplate = nullptr;
   7403   bool isExplicitSpecialization = false;
   7404   bool isFunctionTemplateSpecialization = false;
   7405 
   7406   bool isDependentClassScopeExplicitSpecialization = false;
   7407   bool HasExplicitTemplateArgs = false;
   7408   TemplateArgumentListInfo TemplateArgs;
   7409 
   7410   bool isVirtualOkay = false;
   7411 
   7412   DeclContext *OriginalDC = DC;
   7413   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
   7414 
   7415   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
   7416                                               isVirtualOkay);
   7417   if (!NewFD) return nullptr;
   7418 
   7419   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
   7420     NewFD->setTopLevelDeclInObjCContainer();
   7421 
   7422   // Set the lexical context. If this is a function-scope declaration, or has a
   7423   // C++ scope specifier, or is the object of a friend declaration, the lexical
   7424   // context will be different from the semantic context.
   7425   NewFD->setLexicalDeclContext(CurContext);
   7426 
   7427   if (IsLocalExternDecl)
   7428     NewFD->setLocalExternDecl();
   7429 
   7430   if (getLangOpts().CPlusPlus) {
   7431     bool isInline = D.getDeclSpec().isInlineSpecified();
   7432     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
   7433     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
   7434     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
   7435     bool isConcept = D.getDeclSpec().isConceptSpecified();
   7436     isFriend = D.getDeclSpec().isFriendSpecified();
   7437     if (isFriend && !isInline && D.isFunctionDefinition()) {
   7438       // C++ [class.friend]p5
   7439       //   A function can be defined in a friend declaration of a
   7440       //   class . . . . Such a function is implicitly inline.
   7441       NewFD->setImplicitlyInline();
   7442     }
   7443 
   7444     // If this is a method defined in an __interface, and is not a constructor
   7445     // or an overloaded operator, then set the pure flag (isVirtual will already
   7446     // return true).
   7447     if (const CXXRecordDecl *Parent =
   7448           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
   7449       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
   7450         NewFD->setPure(true);
   7451 
   7452       // C++ [class.union]p2
   7453       //   A union can have member functions, but not virtual functions.
   7454       if (isVirtual && Parent->isUnion())
   7455         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
   7456     }
   7457 
   7458     SetNestedNameSpecifier(NewFD, D);
   7459     isExplicitSpecialization = false;
   7460     isFunctionTemplateSpecialization = false;
   7461     if (D.isInvalidType())
   7462       NewFD->setInvalidDecl();
   7463 
   7464     // Match up the template parameter lists with the scope specifier, then
   7465     // determine whether we have a template or a template specialization.
   7466     bool Invalid = false;
   7467     if (TemplateParameterList *TemplateParams =
   7468             MatchTemplateParametersToScopeSpecifier(
   7469                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
   7470                 D.getCXXScopeSpec(),
   7471                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
   7472                     ? D.getName().TemplateId
   7473                     : nullptr,
   7474                 TemplateParamLists, isFriend, isExplicitSpecialization,
   7475                 Invalid)) {
   7476       if (TemplateParams->size() > 0) {
   7477         // This is a function template
   7478 
   7479         // Check that we can declare a template here.
   7480         if (CheckTemplateDeclScope(S, TemplateParams))
   7481           NewFD->setInvalidDecl();
   7482 
   7483         // A destructor cannot be a template.
   7484         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
   7485           Diag(NewFD->getLocation(), diag::err_destructor_template);
   7486           NewFD->setInvalidDecl();
   7487         }
   7488 
   7489         // If we're adding a template to a dependent context, we may need to
   7490         // rebuilding some of the types used within the template parameter list,
   7491         // now that we know what the current instantiation is.
   7492         if (DC->isDependentContext()) {
   7493           ContextRAII SavedContext(*this, DC);
   7494           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
   7495             Invalid = true;
   7496         }
   7497 
   7498 
   7499         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
   7500                                                         NewFD->getLocation(),
   7501                                                         Name, TemplateParams,
   7502                                                         NewFD);
   7503         FunctionTemplate->setLexicalDeclContext(CurContext);
   7504         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
   7505 
   7506         // For source fidelity, store the other template param lists.
   7507         if (TemplateParamLists.size() > 1) {
   7508           NewFD->setTemplateParameterListsInfo(Context,
   7509                                                TemplateParamLists.drop_back(1));
   7510         }
   7511       } else {
   7512         // This is a function template specialization.
   7513         isFunctionTemplateSpecialization = true;
   7514         // For source fidelity, store all the template param lists.
   7515         if (TemplateParamLists.size() > 0)
   7516           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
   7517 
   7518         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
   7519         if (isFriend) {
   7520           // We want to remove the "template<>", found here.
   7521           SourceRange RemoveRange = TemplateParams->getSourceRange();
   7522 
   7523           // If we remove the template<> and the name is not a
   7524           // template-id, we're actually silently creating a problem:
   7525           // the friend declaration will refer to an untemplated decl,
   7526           // and clearly the user wants a template specialization.  So
   7527           // we need to insert '<>' after the name.
   7528           SourceLocation InsertLoc;
   7529           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
   7530             InsertLoc = D.getName().getSourceRange().getEnd();
   7531             InsertLoc = getLocForEndOfToken(InsertLoc);
   7532           }
   7533 
   7534           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
   7535             << Name << RemoveRange
   7536             << FixItHint::CreateRemoval(RemoveRange)
   7537             << FixItHint::CreateInsertion(InsertLoc, "<>");
   7538         }
   7539       }
   7540     }
   7541     else {
   7542       // All template param lists were matched against the scope specifier:
   7543       // this is NOT (an explicit specialization of) a template.
   7544       if (TemplateParamLists.size() > 0)
   7545         // For source fidelity, store all the template param lists.
   7546         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
   7547     }
   7548 
   7549     if (Invalid) {
   7550       NewFD->setInvalidDecl();
   7551       if (FunctionTemplate)
   7552         FunctionTemplate->setInvalidDecl();
   7553     }
   7554 
   7555     // C++ [dcl.fct.spec]p5:
   7556     //   The virtual specifier shall only be used in declarations of
   7557     //   nonstatic class member functions that appear within a
   7558     //   member-specification of a class declaration; see 10.3.
   7559     //
   7560     if (isVirtual && !NewFD->isInvalidDecl()) {
   7561       if (!isVirtualOkay) {
   7562         Diag(D.getDeclSpec().getVirtualSpecLoc(),
   7563              diag::err_virtual_non_function);
   7564       } else if (!CurContext->isRecord()) {
   7565         // 'virtual' was specified outside of the class.
   7566         Diag(D.getDeclSpec().getVirtualSpecLoc(),
   7567              diag::err_virtual_out_of_class)
   7568           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
   7569       } else if (NewFD->getDescribedFunctionTemplate()) {
   7570         // C++ [temp.mem]p3:
   7571         //  A member function template shall not be virtual.
   7572         Diag(D.getDeclSpec().getVirtualSpecLoc(),
   7573              diag::err_virtual_member_function_template)
   7574           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
   7575       } else {
   7576         // Okay: Add virtual to the method.
   7577         NewFD->setVirtualAsWritten(true);
   7578       }
   7579 
   7580       if (getLangOpts().CPlusPlus14 &&
   7581           NewFD->getReturnType()->isUndeducedType())
   7582         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
   7583     }
   7584 
   7585     if (getLangOpts().CPlusPlus14 &&
   7586         (NewFD->isDependentContext() ||
   7587          (isFriend && CurContext->isDependentContext())) &&
   7588         NewFD->getReturnType()->isUndeducedType()) {
   7589       // If the function template is referenced directly (for instance, as a
   7590       // member of the current instantiation), pretend it has a dependent type.
   7591       // This is not really justified by the standard, but is the only sane
   7592       // thing to do.
   7593       // FIXME: For a friend function, we have not marked the function as being
   7594       // a friend yet, so 'isDependentContext' on the FD doesn't work.
   7595       const FunctionProtoType *FPT =
   7596           NewFD->getType()->castAs<FunctionProtoType>();
   7597       QualType Result =
   7598           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
   7599       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
   7600                                              FPT->getExtProtoInfo()));
   7601     }
   7602 
   7603     // C++ [dcl.fct.spec]p3:
   7604     //  The inline specifier shall not appear on a block scope function
   7605     //  declaration.
   7606     if (isInline && !NewFD->isInvalidDecl()) {
   7607       if (CurContext->isFunctionOrMethod()) {
   7608         // 'inline' is not allowed on block scope function declaration.
   7609         Diag(D.getDeclSpec().getInlineSpecLoc(),
   7610              diag::err_inline_declaration_block_scope) << Name
   7611           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
   7612       }
   7613     }
   7614 
   7615     // C++ [dcl.fct.spec]p6:
   7616     //  The explicit specifier shall be used only in the declaration of a
   7617     //  constructor or conversion function within its class definition;
   7618     //  see 12.3.1 and 12.3.2.
   7619     if (isExplicit && !NewFD->isInvalidDecl()) {
   7620       if (!CurContext->isRecord()) {
   7621         // 'explicit' was specified outside of the class.
   7622         Diag(D.getDeclSpec().getExplicitSpecLoc(),
   7623              diag::err_explicit_out_of_class)
   7624           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
   7625       } else if (!isa<CXXConstructorDecl>(NewFD) &&
   7626                  !isa<CXXConversionDecl>(NewFD)) {
   7627         // 'explicit' was specified on a function that wasn't a constructor
   7628         // or conversion function.
   7629         Diag(D.getDeclSpec().getExplicitSpecLoc(),
   7630              diag::err_explicit_non_ctor_or_conv_function)
   7631           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
   7632       }
   7633     }
   7634 
   7635     if (isConstexpr) {
   7636       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
   7637       // are implicitly inline.
   7638       NewFD->setImplicitlyInline();
   7639 
   7640       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
   7641       // be either constructors or to return a literal type. Therefore,
   7642       // destructors cannot be declared constexpr.
   7643       if (isa<CXXDestructorDecl>(NewFD))
   7644         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
   7645     }
   7646 
   7647     if (isConcept) {
   7648       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
   7649       // applied only to the definition of a function template [...]
   7650       if (!D.isFunctionDefinition()) {
   7651         Diag(D.getDeclSpec().getConceptSpecLoc(),
   7652              diag::err_function_concept_not_defined);
   7653         NewFD->setInvalidDecl();
   7654       }
   7655 
   7656       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
   7657       // have no exception-specification and is treated as if it were specified
   7658       // with noexcept(true) (15.4). [...]
   7659       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
   7660         if (FPT->hasExceptionSpec()) {
   7661           SourceRange Range;
   7662           if (D.isFunctionDeclarator())
   7663             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
   7664           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
   7665               << FixItHint::CreateRemoval(Range);
   7666           NewFD->setInvalidDecl();
   7667         } else {
   7668           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
   7669         }
   7670 
   7671         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
   7672         // following restrictions:
   7673         // - The declaration's parameter list shall be equivalent to an empty
   7674         //   parameter list.
   7675         if (FPT->getNumParams() > 0 || FPT->isVariadic())
   7676           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
   7677       }
   7678 
   7679       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
   7680       // implicity defined to be a constexpr declaration (implicitly inline)
   7681       NewFD->setImplicitlyInline();
   7682 
   7683       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
   7684       // be declared with the thread_local, inline, friend, or constexpr
   7685       // specifiers, [...]
   7686       if (isInline) {
   7687         Diag(D.getDeclSpec().getInlineSpecLoc(),
   7688              diag::err_concept_decl_invalid_specifiers)
   7689             << 1 << 1;
   7690         NewFD->setInvalidDecl(true);
   7691       }
   7692 
   7693       if (isFriend) {
   7694         Diag(D.getDeclSpec().getFriendSpecLoc(),
   7695              diag::err_concept_decl_invalid_specifiers)
   7696             << 1 << 2;
   7697         NewFD->setInvalidDecl(true);
   7698       }
   7699 
   7700       if (isConstexpr) {
   7701         Diag(D.getDeclSpec().getConstexprSpecLoc(),
   7702              diag::err_concept_decl_invalid_specifiers)
   7703             << 1 << 3;
   7704         NewFD->setInvalidDecl(true);
   7705       }
   7706     }
   7707 
   7708     // If __module_private__ was specified, mark the function accordingly.
   7709     if (D.getDeclSpec().isModulePrivateSpecified()) {
   7710       if (isFunctionTemplateSpecialization) {
   7711         SourceLocation ModulePrivateLoc
   7712           = D.getDeclSpec().getModulePrivateSpecLoc();
   7713         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
   7714           << 0
   7715           << FixItHint::CreateRemoval(ModulePrivateLoc);
   7716       } else {
   7717         NewFD->setModulePrivate();
   7718         if (FunctionTemplate)
   7719           FunctionTemplate->setModulePrivate();
   7720       }
   7721     }
   7722 
   7723     if (isFriend) {
   7724       if (FunctionTemplate) {
   7725         FunctionTemplate->setObjectOfFriendDecl();
   7726         FunctionTemplate->setAccess(AS_public);
   7727       }
   7728       NewFD->setObjectOfFriendDecl();
   7729       NewFD->setAccess(AS_public);
   7730     }
   7731 
   7732     // If a function is defined as defaulted or deleted, mark it as such now.
   7733     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
   7734     // definition kind to FDK_Definition.
   7735     switch (D.getFunctionDefinitionKind()) {
   7736       case FDK_Declaration:
   7737       case FDK_Definition:
   7738         break;
   7739 
   7740       case FDK_Defaulted:
   7741         NewFD->setDefaulted();
   7742         break;
   7743 
   7744       case FDK_Deleted:
   7745         NewFD->setDeletedAsWritten();
   7746         break;
   7747     }
   7748 
   7749     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
   7750         D.isFunctionDefinition()) {
   7751       // C++ [class.mfct]p2:
   7752       //   A member function may be defined (8.4) in its class definition, in
   7753       //   which case it is an inline member function (7.1.2)
   7754       NewFD->setImplicitlyInline();
   7755     }
   7756 
   7757     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
   7758         !CurContext->isRecord()) {
   7759       // C++ [class.static]p1:
   7760       //   A data or function member of a class may be declared static
   7761       //   in a class definition, in which case it is a static member of
   7762       //   the class.
   7763 
   7764       // Complain about the 'static' specifier if it's on an out-of-line
   7765       // member function definition.
   7766       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
   7767            diag::err_static_out_of_line)
   7768         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
   7769     }
   7770 
   7771     // C++11 [except.spec]p15:
   7772     //   A deallocation function with no exception-specification is treated
   7773     //   as if it were specified with noexcept(true).
   7774     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
   7775     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
   7776          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
   7777         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
   7778       NewFD->setType(Context.getFunctionType(
   7779           FPT->getReturnType(), FPT->getParamTypes(),
   7780           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
   7781   }
   7782 
   7783   // Filter out previous declarations that don't match the scope.
   7784   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
   7785                        D.getCXXScopeSpec().isNotEmpty() ||
   7786                        isExplicitSpecialization ||
   7787                        isFunctionTemplateSpecialization);
   7788 
   7789   // Handle GNU asm-label extension (encoded as an attribute).
   7790   if (Expr *E = (Expr*) D.getAsmLabel()) {
   7791     // The parser guarantees this is a string.
   7792     StringLiteral *SE = cast<StringLiteral>(E);
   7793     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
   7794                                                 SE->getString(), 0));
   7795   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
   7796     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
   7797       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
   7798     if (I != ExtnameUndeclaredIdentifiers.end()) {
   7799       if (isDeclExternC(NewFD)) {
   7800         NewFD->addAttr(I->second);
   7801         ExtnameUndeclaredIdentifiers.erase(I);
   7802       } else
   7803         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
   7804             << /*Variable*/0 << NewFD;
   7805     }
   7806   }
   7807 
   7808   // Copy the parameter declarations from the declarator D to the function
   7809   // declaration NewFD, if they are available.  First scavenge them into Params.
   7810   SmallVector<ParmVarDecl*, 16> Params;
   7811   if (D.isFunctionDeclarator()) {
   7812     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
   7813 
   7814     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
   7815     // function that takes no arguments, not a function that takes a
   7816     // single void argument.
   7817     // We let through "const void" here because Sema::GetTypeForDeclarator
   7818     // already checks for that case.
   7819     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
   7820       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
   7821         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
   7822         assert(Param->getDeclContext() != NewFD && "Was set before ?");
   7823         Param->setDeclContext(NewFD);
   7824         Params.push_back(Param);
   7825 
   7826         if (Param->isInvalidDecl())
   7827           NewFD->setInvalidDecl();
   7828       }
   7829     }
   7830 
   7831   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
   7832     // When we're declaring a function with a typedef, typeof, etc as in the
   7833     // following example, we'll need to synthesize (unnamed)
   7834     // parameters for use in the declaration.
   7835     //
   7836     // @code
   7837     // typedef void fn(int);
   7838     // fn f;
   7839     // @endcode
   7840 
   7841     // Synthesize a parameter for each argument type.
   7842     for (const auto &AI : FT->param_types()) {
   7843       ParmVarDecl *Param =
   7844           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
   7845       Param->setScopeInfo(0, Params.size());
   7846       Params.push_back(Param);
   7847     }
   7848   } else {
   7849     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
   7850            "Should not need args for typedef of non-prototype fn");
   7851   }
   7852 
   7853   // Finally, we know we have the right number of parameters, install them.
   7854   NewFD->setParams(Params);
   7855 
   7856   // Find all anonymous symbols defined during the declaration of this function
   7857   // and add to NewFD. This lets us track decls such 'enum Y' in:
   7858   //
   7859   //   void f(enum Y {AA} x) {}
   7860   //
   7861   // which would otherwise incorrectly end up in the translation unit scope.
   7862   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
   7863   DeclsInPrototypeScope.clear();
   7864 
   7865   if (D.getDeclSpec().isNoreturnSpecified())
   7866     NewFD->addAttr(
   7867         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
   7868                                        Context, 0));
   7869 
   7870   // Functions returning a variably modified type violate C99 6.7.5.2p2
   7871   // because all functions have linkage.
   7872   if (!NewFD->isInvalidDecl() &&
   7873       NewFD->getReturnType()->isVariablyModifiedType()) {
   7874     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
   7875     NewFD->setInvalidDecl();
   7876   }
   7877 
   7878   // Apply an implicit SectionAttr if #pragma code_seg is active.
   7879   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
   7880       !NewFD->hasAttr<SectionAttr>()) {
   7881     NewFD->addAttr(
   7882         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
   7883                                     CodeSegStack.CurrentValue->getString(),
   7884                                     CodeSegStack.CurrentPragmaLocation));
   7885     if (UnifySection(CodeSegStack.CurrentValue->getString(),
   7886                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
   7887                          ASTContext::PSF_Read,
   7888                      NewFD))
   7889       NewFD->dropAttr<SectionAttr>();
   7890   }
   7891 
   7892   // Handle attributes.
   7893   ProcessDeclAttributes(S, NewFD, D);
   7894 
   7895   if (getLangOpts().OpenCL) {
   7896     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
   7897     // type declaration will generate a compilation error.
   7898     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
   7899     if (AddressSpace == LangAS::opencl_local ||
   7900         AddressSpace == LangAS::opencl_global ||
   7901         AddressSpace == LangAS::opencl_constant) {
   7902       Diag(NewFD->getLocation(),
   7903            diag::err_opencl_return_value_with_address_space);
   7904       NewFD->setInvalidDecl();
   7905     }
   7906   }
   7907 
   7908   if (!getLangOpts().CPlusPlus) {
   7909     // Perform semantic checking on the function declaration.
   7910     bool isExplicitSpecialization=false;
   7911     if (!NewFD->isInvalidDecl() && NewFD->isMain())
   7912       CheckMain(NewFD, D.getDeclSpec());
   7913 
   7914     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
   7915       CheckMSVCRTEntryPoint(NewFD);
   7916 
   7917     if (!NewFD->isInvalidDecl())
   7918       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
   7919                                                   isExplicitSpecialization));
   7920     else if (!Previous.empty())
   7921       // Recover gracefully from an invalid redeclaration.
   7922       D.setRedeclaration(true);
   7923     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
   7924             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
   7925            "previous declaration set still overloaded");
   7926 
   7927     // Diagnose no-prototype function declarations with calling conventions that
   7928     // don't support variadic calls. Only do this in C and do it after merging
   7929     // possibly prototyped redeclarations.
   7930     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
   7931     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
   7932       CallingConv CC = FT->getExtInfo().getCC();
   7933       if (!supportsVariadicCall(CC)) {
   7934         // Windows system headers sometimes accidentally use stdcall without
   7935         // (void) parameters, so we relax this to a warning.
   7936         int DiagID =
   7937             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
   7938         Diag(NewFD->getLocation(), DiagID)
   7939             << FunctionType::getNameForCallConv(CC);
   7940       }
   7941     }
   7942   } else {
   7943     // C++11 [replacement.functions]p3:
   7944     //  The program's definitions shall not be specified as inline.
   7945     //
   7946     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
   7947     //
   7948     // Suppress the diagnostic if the function is __attribute__((used)), since
   7949     // that forces an external definition to be emitted.
   7950     if (D.getDeclSpec().isInlineSpecified() &&
   7951         NewFD->isReplaceableGlobalAllocationFunction() &&
   7952         !NewFD->hasAttr<UsedAttr>())
   7953       Diag(D.getDeclSpec().getInlineSpecLoc(),
   7954            diag::ext_operator_new_delete_declared_inline)
   7955         << NewFD->getDeclName();
   7956 
   7957     // If the declarator is a template-id, translate the parser's template
   7958     // argument list into our AST format.
   7959     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
   7960       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
   7961       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
   7962       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
   7963       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
   7964                                          TemplateId->NumArgs);
   7965       translateTemplateArguments(TemplateArgsPtr,
   7966                                  TemplateArgs);
   7967 
   7968       HasExplicitTemplateArgs = true;
   7969 
   7970       if (NewFD->isInvalidDecl()) {
   7971         HasExplicitTemplateArgs = false;
   7972       } else if (FunctionTemplate) {
   7973         // Function template with explicit template arguments.
   7974         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
   7975           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
   7976 
   7977         HasExplicitTemplateArgs = false;
   7978       } else {
   7979         assert((isFunctionTemplateSpecialization ||
   7980                 D.getDeclSpec().isFriendSpecified()) &&
   7981                "should have a 'template<>' for this decl");
   7982         // "friend void foo<>(int);" is an implicit specialization decl.
   7983         isFunctionTemplateSpecialization = true;
   7984       }
   7985     } else if (isFriend && isFunctionTemplateSpecialization) {
   7986       // This combination is only possible in a recovery case;  the user
   7987       // wrote something like:
   7988       //   template <> friend void foo(int);
   7989       // which we're recovering from as if the user had written:
   7990       //   friend void foo<>(int);
   7991       // Go ahead and fake up a template id.
   7992       HasExplicitTemplateArgs = true;
   7993       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
   7994       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
   7995     }
   7996 
   7997     // If it's a friend (and only if it's a friend), it's possible
   7998     // that either the specialized function type or the specialized
   7999     // template is dependent, and therefore matching will fail.  In
   8000     // this case, don't check the specialization yet.
   8001     bool InstantiationDependent = false;
   8002     if (isFunctionTemplateSpecialization && isFriend &&
   8003         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
   8004          TemplateSpecializationType::anyDependentTemplateArguments(
   8005             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
   8006             InstantiationDependent))) {
   8007       assert(HasExplicitTemplateArgs &&
   8008              "friend function specialization without template args");
   8009       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
   8010                                                        Previous))
   8011         NewFD->setInvalidDecl();
   8012     } else if (isFunctionTemplateSpecialization) {
   8013       if (CurContext->isDependentContext() && CurContext->isRecord()
   8014           && !isFriend) {
   8015         isDependentClassScopeExplicitSpecialization = true;
   8016         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
   8017           diag::ext_function_specialization_in_class :
   8018           diag::err_function_specialization_in_class)
   8019           << NewFD->getDeclName();
   8020       } else if (CheckFunctionTemplateSpecialization(NewFD,
   8021                                   (HasExplicitTemplateArgs ? &TemplateArgs
   8022                                                            : nullptr),
   8023                                                      Previous))
   8024         NewFD->setInvalidDecl();
   8025 
   8026       // C++ [dcl.stc]p1:
   8027       //   A storage-class-specifier shall not be specified in an explicit
   8028       //   specialization (14.7.3)
   8029       FunctionTemplateSpecializationInfo *Info =
   8030           NewFD->getTemplateSpecializationInfo();
   8031       if (Info && SC != SC_None) {
   8032         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
   8033           Diag(NewFD->getLocation(),
   8034                diag::err_explicit_specialization_inconsistent_storage_class)
   8035             << SC
   8036             << FixItHint::CreateRemoval(
   8037                                       D.getDeclSpec().getStorageClassSpecLoc());
   8038 
   8039         else
   8040           Diag(NewFD->getLocation(),
   8041                diag::ext_explicit_specialization_storage_class)
   8042             << FixItHint::CreateRemoval(
   8043                                       D.getDeclSpec().getStorageClassSpecLoc());
   8044       }
   8045 
   8046     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
   8047       if (CheckMemberSpecialization(NewFD, Previous))
   8048           NewFD->setInvalidDecl();
   8049     }
   8050 
   8051     // Perform semantic checking on the function declaration.
   8052     if (!isDependentClassScopeExplicitSpecialization) {
   8053       if (!NewFD->isInvalidDecl() && NewFD->isMain())
   8054         CheckMain(NewFD, D.getDeclSpec());
   8055 
   8056       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
   8057         CheckMSVCRTEntryPoint(NewFD);
   8058 
   8059       if (!NewFD->isInvalidDecl())
   8060         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
   8061                                                     isExplicitSpecialization));
   8062       else if (!Previous.empty())
   8063         // Recover gracefully from an invalid redeclaration.
   8064         D.setRedeclaration(true);
   8065     }
   8066 
   8067     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
   8068             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
   8069            "previous declaration set still overloaded");
   8070 
   8071     NamedDecl *PrincipalDecl = (FunctionTemplate
   8072                                 ? cast<NamedDecl>(FunctionTemplate)
   8073                                 : NewFD);
   8074 
   8075     if (isFriend && D.isRedeclaration()) {
   8076       AccessSpecifier Access = AS_public;
   8077       if (!NewFD->isInvalidDecl())
   8078         Access = NewFD->getPreviousDecl()->getAccess();
   8079 
   8080       NewFD->setAccess(Access);
   8081       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
   8082     }
   8083 
   8084     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
   8085         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
   8086       PrincipalDecl->setNonMemberOperator();
   8087 
   8088     // If we have a function template, check the template parameter
   8089     // list. This will check and merge default template arguments.
   8090     if (FunctionTemplate) {
   8091       FunctionTemplateDecl *PrevTemplate =
   8092                                      FunctionTemplate->getPreviousDecl();
   8093       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
   8094                        PrevTemplate ? PrevTemplate->getTemplateParameters()
   8095                                     : nullptr,
   8096                             D.getDeclSpec().isFriendSpecified()
   8097                               ? (D.isFunctionDefinition()
   8098                                    ? TPC_FriendFunctionTemplateDefinition
   8099                                    : TPC_FriendFunctionTemplate)
   8100                               : (D.getCXXScopeSpec().isSet() &&
   8101                                  DC && DC->isRecord() &&
   8102                                  DC->isDependentContext())
   8103                                   ? TPC_ClassTemplateMember
   8104                                   : TPC_FunctionTemplate);
   8105     }
   8106 
   8107     if (NewFD->isInvalidDecl()) {
   8108       // Ignore all the rest of this.
   8109     } else if (!D.isRedeclaration()) {
   8110       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
   8111                                        AddToScope };
   8112       // Fake up an access specifier if it's supposed to be a class member.
   8113       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
   8114         NewFD->setAccess(AS_public);
   8115 
   8116       // Qualified decls generally require a previous declaration.
   8117       if (D.getCXXScopeSpec().isSet()) {
   8118         // ...with the major exception of templated-scope or
   8119         // dependent-scope friend declarations.
   8120 
   8121         // TODO: we currently also suppress this check in dependent
   8122         // contexts because (1) the parameter depth will be off when
   8123         // matching friend templates and (2) we might actually be
   8124         // selecting a friend based on a dependent factor.  But there
   8125         // are situations where these conditions don't apply and we
   8126         // can actually do this check immediately.
   8127         if (isFriend &&
   8128             (TemplateParamLists.size() ||
   8129              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
   8130              CurContext->isDependentContext())) {
   8131           // ignore these
   8132         } else {
   8133           // The user tried to provide an out-of-line definition for a
   8134           // function that is a member of a class or namespace, but there
   8135           // was no such member function declared (C++ [class.mfct]p2,
   8136           // C++ [namespace.memdef]p2). For example:
   8137           //
   8138           // class X {
   8139           //   void f() const;
   8140           // };
   8141           //
   8142           // void X::f() { } // ill-formed
   8143           //
   8144           // Complain about this problem, and attempt to suggest close
   8145           // matches (e.g., those that differ only in cv-qualifiers and
   8146           // whether the parameter types are references).
   8147 
   8148           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
   8149                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
   8150             AddToScope = ExtraArgs.AddToScope;
   8151             return Result;
   8152           }
   8153         }
   8154 
   8155         // Unqualified local friend declarations are required to resolve
   8156         // to something.
   8157       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
   8158         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
   8159                 *this, Previous, NewFD, ExtraArgs, true, S)) {
   8160           AddToScope = ExtraArgs.AddToScope;
   8161           return Result;
   8162         }
   8163       }
   8164 
   8165     } else if (!D.isFunctionDefinition() &&
   8166                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
   8167                !isFriend && !isFunctionTemplateSpecialization &&
   8168                !isExplicitSpecialization) {
   8169       // An out-of-line member function declaration must also be a
   8170       // definition (C++ [class.mfct]p2).
   8171       // Note that this is not the case for explicit specializations of
   8172       // function templates or member functions of class templates, per
   8173       // C++ [temp.expl.spec]p2. We also allow these declarations as an
   8174       // extension for compatibility with old SWIG code which likes to
   8175       // generate them.
   8176       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
   8177         << D.getCXXScopeSpec().getRange();
   8178     }
   8179   }
   8180 
   8181   ProcessPragmaWeak(S, NewFD);
   8182   checkAttributesAfterMerging(*this, *NewFD);
   8183 
   8184   AddKnownFunctionAttributes(NewFD);
   8185 
   8186   if (NewFD->hasAttr<OverloadableAttr>() &&
   8187       !NewFD->getType()->getAs<FunctionProtoType>()) {
   8188     Diag(NewFD->getLocation(),
   8189          diag::err_attribute_overloadable_no_prototype)
   8190       << NewFD;
   8191 
   8192     // Turn this into a variadic function with no parameters.
   8193     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
   8194     FunctionProtoType::ExtProtoInfo EPI(
   8195         Context.getDefaultCallingConvention(true, false));
   8196     EPI.Variadic = true;
   8197     EPI.ExtInfo = FT->getExtInfo();
   8198 
   8199     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
   8200     NewFD->setType(R);
   8201   }
   8202 
   8203   // If there's a #pragma GCC visibility in scope, and this isn't a class
   8204   // member, set the visibility of this function.
   8205   if (!DC->isRecord() && NewFD->isExternallyVisible())
   8206     AddPushedVisibilityAttribute(NewFD);
   8207 
   8208   // If there's a #pragma clang arc_cf_code_audited in scope, consider
   8209   // marking the function.
   8210   AddCFAuditedAttribute(NewFD);
   8211 
   8212   // If this is a function definition, check if we have to apply optnone due to
   8213   // a pragma.
   8214   if(D.isFunctionDefinition())
   8215     AddRangeBasedOptnone(NewFD);
   8216 
   8217   // If this is the first declaration of an extern C variable, update
   8218   // the map of such variables.
   8219   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
   8220       isIncompleteDeclExternC(*this, NewFD))
   8221     RegisterLocallyScopedExternCDecl(NewFD, S);
   8222 
   8223   // Set this FunctionDecl's range up to the right paren.
   8224   NewFD->setRangeEnd(D.getSourceRange().getEnd());
   8225 
   8226   if (D.isRedeclaration() && !Previous.empty()) {
   8227     checkDLLAttributeRedeclaration(
   8228         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
   8229         isExplicitSpecialization || isFunctionTemplateSpecialization);
   8230   }
   8231 
   8232   if (getLangOpts().CPlusPlus) {
   8233     if (FunctionTemplate) {
   8234       if (NewFD->isInvalidDecl())
   8235         FunctionTemplate->setInvalidDecl();
   8236       return FunctionTemplate;
   8237     }
   8238   }
   8239 
   8240   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
   8241     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
   8242     if ((getLangOpts().OpenCLVersion >= 120)
   8243         && (SC == SC_Static)) {
   8244       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
   8245       D.setInvalidType();
   8246     }
   8247 
   8248     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
   8249     if (!NewFD->getReturnType()->isVoidType()) {
   8250       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
   8251       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
   8252           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
   8253                                 : FixItHint());
   8254       D.setInvalidType();
   8255     }
   8256 
   8257     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
   8258     for (auto Param : NewFD->params())
   8259       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
   8260   }
   8261 
   8262   MarkUnusedFileScopedDecl(NewFD);
   8263 
   8264   if (getLangOpts().CUDA)
   8265     if (IdentifierInfo *II = NewFD->getIdentifier())
   8266       if (!NewFD->isInvalidDecl() &&
   8267           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
   8268         if (II->isStr("cudaConfigureCall")) {
   8269           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
   8270             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
   8271 
   8272           Context.setcudaConfigureCallDecl(NewFD);
   8273         }
   8274       }
   8275 
   8276   // Here we have an function template explicit specialization at class scope.
   8277   // The actually specialization will be postponed to template instatiation
   8278   // time via the ClassScopeFunctionSpecializationDecl node.
   8279   if (isDependentClassScopeExplicitSpecialization) {
   8280     ClassScopeFunctionSpecializationDecl *NewSpec =
   8281                          ClassScopeFunctionSpecializationDecl::Create(
   8282                                 Context, CurContext, SourceLocation(),
   8283                                 cast<CXXMethodDecl>(NewFD),
   8284                                 HasExplicitTemplateArgs, TemplateArgs);
   8285     CurContext->addDecl(NewSpec);
   8286     AddToScope = false;
   8287   }
   8288 
   8289   return NewFD;
   8290 }
   8291 
   8292 /// \brief Perform semantic checking of a new function declaration.
   8293 ///
   8294 /// Performs semantic analysis of the new function declaration
   8295 /// NewFD. This routine performs all semantic checking that does not
   8296 /// require the actual declarator involved in the declaration, and is
   8297 /// used both for the declaration of functions as they are parsed
   8298 /// (called via ActOnDeclarator) and for the declaration of functions
   8299 /// that have been instantiated via C++ template instantiation (called
   8300 /// via InstantiateDecl).
   8301 ///
   8302 /// \param IsExplicitSpecialization whether this new function declaration is
   8303 /// an explicit specialization of the previous declaration.
   8304 ///
   8305 /// This sets NewFD->isInvalidDecl() to true if there was an error.
   8306 ///
   8307 /// \returns true if the function declaration is a redeclaration.
   8308 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
   8309                                     LookupResult &Previous,
   8310                                     bool IsExplicitSpecialization) {
   8311   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
   8312          "Variably modified return types are not handled here");
   8313 
   8314   // Determine whether the type of this function should be merged with
   8315   // a previous visible declaration. This never happens for functions in C++,
   8316   // and always happens in C if the previous declaration was visible.
   8317   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
   8318                                !Previous.isShadowed();
   8319 
   8320   bool Redeclaration = false;
   8321   NamedDecl *OldDecl = nullptr;
   8322 
   8323   // Merge or overload the declaration with an existing declaration of
   8324   // the same name, if appropriate.
   8325   if (!Previous.empty()) {
   8326     // Determine whether NewFD is an overload of PrevDecl or
   8327     // a declaration that requires merging. If it's an overload,
   8328     // there's no more work to do here; we'll just add the new
   8329     // function to the scope.
   8330     if (!AllowOverloadingOfFunction(Previous, Context)) {
   8331       NamedDecl *Candidate = Previous.getRepresentativeDecl();
   8332       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
   8333         Redeclaration = true;
   8334         OldDecl = Candidate;
   8335       }
   8336     } else {
   8337       switch (CheckOverload(S, NewFD, Previous, OldDecl,
   8338                             /*NewIsUsingDecl*/ false)) {
   8339       case Ovl_Match:
   8340         Redeclaration = true;
   8341         break;
   8342 
   8343       case Ovl_NonFunction:
   8344         Redeclaration = true;
   8345         break;
   8346 
   8347       case Ovl_Overload:
   8348         Redeclaration = false;
   8349         break;
   8350       }
   8351 
   8352       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
   8353         // If a function name is overloadable in C, then every function
   8354         // with that name must be marked "overloadable".
   8355         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
   8356           << Redeclaration << NewFD;
   8357         NamedDecl *OverloadedDecl = nullptr;
   8358         if (Redeclaration)
   8359           OverloadedDecl = OldDecl;
   8360         else if (!Previous.empty())
   8361           OverloadedDecl = Previous.getRepresentativeDecl();
   8362         if (OverloadedDecl)
   8363           Diag(OverloadedDecl->getLocation(),
   8364                diag::note_attribute_overloadable_prev_overload);
   8365         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
   8366       }
   8367     }
   8368   }
   8369 
   8370   // Check for a previous extern "C" declaration with this name.
   8371   if (!Redeclaration &&
   8372       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
   8373     if (!Previous.empty()) {
   8374       // This is an extern "C" declaration with the same name as a previous
   8375       // declaration, and thus redeclares that entity...
   8376       Redeclaration = true;
   8377       OldDecl = Previous.getFoundDecl();
   8378       MergeTypeWithPrevious = false;
   8379 
   8380       // ... except in the presence of __attribute__((overloadable)).
   8381       if (OldDecl->hasAttr<OverloadableAttr>()) {
   8382         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
   8383           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
   8384             << Redeclaration << NewFD;
   8385           Diag(Previous.getFoundDecl()->getLocation(),
   8386                diag::note_attribute_overloadable_prev_overload);
   8387           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
   8388         }
   8389         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
   8390           Redeclaration = false;
   8391           OldDecl = nullptr;
   8392         }
   8393       }
   8394     }
   8395   }
   8396 
   8397   // C++11 [dcl.constexpr]p8:
   8398   //   A constexpr specifier for a non-static member function that is not
   8399   //   a constructor declares that member function to be const.
   8400   //
   8401   // This needs to be delayed until we know whether this is an out-of-line
   8402   // definition of a static member function.
   8403   //
   8404   // This rule is not present in C++1y, so we produce a backwards
   8405   // compatibility warning whenever it happens in C++11.
   8406   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
   8407   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
   8408       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
   8409       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
   8410     CXXMethodDecl *OldMD = nullptr;
   8411     if (OldDecl)
   8412       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
   8413     if (!OldMD || !OldMD->isStatic()) {
   8414       const FunctionProtoType *FPT =
   8415         MD->getType()->castAs<FunctionProtoType>();
   8416       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
   8417       EPI.TypeQuals |= Qualifiers::Const;
   8418       MD->setType(Context.getFunctionType(FPT->getReturnType(),
   8419                                           FPT->getParamTypes(), EPI));
   8420 
   8421       // Warn that we did this, if we're not performing template instantiation.
   8422       // In that case, we'll have warned already when the template was defined.
   8423       if (ActiveTemplateInstantiations.empty()) {
   8424         SourceLocation AddConstLoc;
   8425         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
   8426                 .IgnoreParens().getAs<FunctionTypeLoc>())
   8427           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
   8428 
   8429         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
   8430           << FixItHint::CreateInsertion(AddConstLoc, " const");
   8431       }
   8432     }
   8433   }
   8434 
   8435   if (Redeclaration) {
   8436     // NewFD and OldDecl represent declarations that need to be
   8437     // merged.
   8438     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
   8439       NewFD->setInvalidDecl();
   8440       return Redeclaration;
   8441     }
   8442 
   8443     Previous.clear();
   8444     Previous.addDecl(OldDecl);
   8445 
   8446     if (FunctionTemplateDecl *OldTemplateDecl
   8447                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
   8448       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
   8449       FunctionTemplateDecl *NewTemplateDecl
   8450         = NewFD->getDescribedFunctionTemplate();
   8451       assert(NewTemplateDecl && "Template/non-template mismatch");
   8452       if (CXXMethodDecl *Method
   8453             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
   8454         Method->setAccess(OldTemplateDecl->getAccess());
   8455         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
   8456       }
   8457 
   8458       // If this is an explicit specialization of a member that is a function
   8459       // template, mark it as a member specialization.
   8460       if (IsExplicitSpecialization &&
   8461           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
   8462         NewTemplateDecl->setMemberSpecialization();
   8463         assert(OldTemplateDecl->isMemberSpecialization());
   8464       }
   8465 
   8466     } else {
   8467       // This needs to happen first so that 'inline' propagates.
   8468       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
   8469 
   8470       if (isa<CXXMethodDecl>(NewFD))
   8471         NewFD->setAccess(OldDecl->getAccess());
   8472     }
   8473   }
   8474 
   8475   // Semantic checking for this function declaration (in isolation).
   8476 
   8477   if (getLangOpts().CPlusPlus) {
   8478     // C++-specific checks.
   8479     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
   8480       CheckConstructor(Constructor);
   8481     } else if (CXXDestructorDecl *Destructor =
   8482                 dyn_cast<CXXDestructorDecl>(NewFD)) {
   8483       CXXRecordDecl *Record = Destructor->getParent();
   8484       QualType ClassType = Context.getTypeDeclType(Record);
   8485 
   8486       // FIXME: Shouldn't we be able to perform this check even when the class
   8487       // type is dependent? Both gcc and edg can handle that.
   8488       if (!ClassType->isDependentType()) {
   8489         DeclarationName Name
   8490           = Context.DeclarationNames.getCXXDestructorName(
   8491                                         Context.getCanonicalType(ClassType));
   8492         if (NewFD->getDeclName() != Name) {
   8493           Diag(NewFD->getLocation(), diag::err_destructor_name);
   8494           NewFD->setInvalidDecl();
   8495           return Redeclaration;
   8496         }
   8497       }
   8498     } else if (CXXConversionDecl *Conversion
   8499                = dyn_cast<CXXConversionDecl>(NewFD)) {
   8500       ActOnConversionDeclarator(Conversion);
   8501     }
   8502 
   8503     // Find any virtual functions that this function overrides.
   8504     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
   8505       if (!Method->isFunctionTemplateSpecialization() &&
   8506           !Method->getDescribedFunctionTemplate() &&
   8507           Method->isCanonicalDecl()) {
   8508         if (AddOverriddenMethods(Method->getParent(), Method)) {
   8509           // If the function was marked as "static", we have a problem.
   8510           if (NewFD->getStorageClass() == SC_Static) {
   8511             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
   8512           }
   8513         }
   8514       }
   8515 
   8516       if (Method->isStatic())
   8517         checkThisInStaticMemberFunctionType(Method);
   8518     }
   8519 
   8520     // Extra checking for C++ overloaded operators (C++ [over.oper]).
   8521     if (NewFD->isOverloadedOperator() &&
   8522         CheckOverloadedOperatorDeclaration(NewFD)) {
   8523       NewFD->setInvalidDecl();
   8524       return Redeclaration;
   8525     }
   8526 
   8527     // Extra checking for C++0x literal operators (C++0x [over.literal]).
   8528     if (NewFD->getLiteralIdentifier() &&
   8529         CheckLiteralOperatorDeclaration(NewFD)) {
   8530       NewFD->setInvalidDecl();
   8531       return Redeclaration;
   8532     }
   8533 
   8534     // In C++, check default arguments now that we have merged decls. Unless
   8535     // the lexical context is the class, because in this case this is done
   8536     // during delayed parsing anyway.
   8537     if (!CurContext->isRecord())
   8538       CheckCXXDefaultArguments(NewFD);
   8539 
   8540     // If this function declares a builtin function, check the type of this
   8541     // declaration against the expected type for the builtin.
   8542     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
   8543       ASTContext::GetBuiltinTypeError Error;
   8544       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
   8545       QualType T = Context.GetBuiltinType(BuiltinID, Error);
   8546       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
   8547         // The type of this function differs from the type of the builtin,
   8548         // so forget about the builtin entirely.
   8549         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
   8550       }
   8551     }
   8552 
   8553     // If this function is declared as being extern "C", then check to see if
   8554     // the function returns a UDT (class, struct, or union type) that is not C
   8555     // compatible, and if it does, warn the user.
   8556     // But, issue any diagnostic on the first declaration only.
   8557     if (Previous.empty() && NewFD->isExternC()) {
   8558       QualType R = NewFD->getReturnType();
   8559       if (R->isIncompleteType() && !R->isVoidType())
   8560         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
   8561             << NewFD << R;
   8562       else if (!R.isPODType(Context) && !R->isVoidType() &&
   8563                !R->isObjCObjectPointerType())
   8564         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
   8565     }
   8566   }
   8567   return Redeclaration;
   8568 }
   8569 
   8570 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
   8571   // C++11 [basic.start.main]p3:
   8572   //   A program that [...] declares main to be inline, static or
   8573   //   constexpr is ill-formed.
   8574   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
   8575   //   appear in a declaration of main.
   8576   // static main is not an error under C99, but we should warn about it.
   8577   // We accept _Noreturn main as an extension.
   8578   if (FD->getStorageClass() == SC_Static)
   8579     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
   8580          ? diag::err_static_main : diag::warn_static_main)
   8581       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
   8582   if (FD->isInlineSpecified())
   8583     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
   8584       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
   8585   if (DS.isNoreturnSpecified()) {
   8586     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
   8587     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
   8588     Diag(NoreturnLoc, diag::ext_noreturn_main);
   8589     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
   8590       << FixItHint::CreateRemoval(NoreturnRange);
   8591   }
   8592   if (FD->isConstexpr()) {
   8593     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
   8594       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
   8595     FD->setConstexpr(false);
   8596   }
   8597 
   8598   if (getLangOpts().OpenCL) {
   8599     Diag(FD->getLocation(), diag::err_opencl_no_main)
   8600         << FD->hasAttr<OpenCLKernelAttr>();
   8601     FD->setInvalidDecl();
   8602     return;
   8603   }
   8604 
   8605   QualType T = FD->getType();
   8606   assert(T->isFunctionType() && "function decl is not of function type");
   8607   const FunctionType* FT = T->castAs<FunctionType>();
   8608 
   8609   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
   8610     // In C with GNU extensions we allow main() to have non-integer return
   8611     // type, but we should warn about the extension, and we disable the
   8612     // implicit-return-zero rule.
   8613 
   8614     // GCC in C mode accepts qualified 'int'.
   8615     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
   8616       FD->setHasImplicitReturnZero(true);
   8617     else {
   8618       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
   8619       SourceRange RTRange = FD->getReturnTypeSourceRange();
   8620       if (RTRange.isValid())
   8621         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
   8622             << FixItHint::CreateReplacement(RTRange, "int");
   8623     }
   8624   } else {
   8625     // In C and C++, main magically returns 0 if you fall off the end;
   8626     // set the flag which tells us that.
   8627     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
   8628 
   8629     // All the standards say that main() should return 'int'.
   8630     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
   8631       FD->setHasImplicitReturnZero(true);
   8632     else {
   8633       // Otherwise, this is just a flat-out error.
   8634       SourceRange RTRange = FD->getReturnTypeSourceRange();
   8635       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
   8636           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
   8637                                 : FixItHint());
   8638       FD->setInvalidDecl(true);
   8639     }
   8640   }
   8641 
   8642   // Treat protoless main() as nullary.
   8643   if (isa<FunctionNoProtoType>(FT)) return;
   8644 
   8645   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
   8646   unsigned nparams = FTP->getNumParams();
   8647   assert(FD->getNumParams() == nparams);
   8648 
   8649   bool HasExtraParameters = (nparams > 3);
   8650 
   8651   if (FTP->isVariadic()) {
   8652     Diag(FD->getLocation(), diag::ext_variadic_main);
   8653     // FIXME: if we had information about the location of the ellipsis, we
   8654     // could add a FixIt hint to remove it as a parameter.
   8655   }
   8656 
   8657   // Darwin passes an undocumented fourth argument of type char**.  If
   8658   // other platforms start sprouting these, the logic below will start
   8659   // getting shifty.
   8660   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
   8661     HasExtraParameters = false;
   8662 
   8663   if (HasExtraParameters) {
   8664     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
   8665     FD->setInvalidDecl(true);
   8666     nparams = 3;
   8667   }
   8668 
   8669   // FIXME: a lot of the following diagnostics would be improved
   8670   // if we had some location information about types.
   8671 
   8672   QualType CharPP =
   8673     Context.getPointerType(Context.getPointerType(Context.CharTy));
   8674   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
   8675 
   8676   for (unsigned i = 0; i < nparams; ++i) {
   8677     QualType AT = FTP->getParamType(i);
   8678 
   8679     bool mismatch = true;
   8680 
   8681     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
   8682       mismatch = false;
   8683     else if (Expected[i] == CharPP) {
   8684       // As an extension, the following forms are okay:
   8685       //   char const **
   8686       //   char const * const *
   8687       //   char * const *
   8688 
   8689       QualifierCollector qs;
   8690       const PointerType* PT;
   8691       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
   8692           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
   8693           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
   8694                               Context.CharTy)) {
   8695         qs.removeConst();
   8696         mismatch = !qs.empty();
   8697       }
   8698     }
   8699 
   8700     if (mismatch) {
   8701       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
   8702       // TODO: suggest replacing given type with expected type
   8703       FD->setInvalidDecl(true);
   8704     }
   8705   }
   8706 
   8707   if (nparams == 1 && !FD->isInvalidDecl()) {
   8708     Diag(FD->getLocation(), diag::warn_main_one_arg);
   8709   }
   8710 
   8711   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
   8712     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
   8713     FD->setInvalidDecl();
   8714   }
   8715 }
   8716 
   8717 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
   8718   QualType T = FD->getType();
   8719   assert(T->isFunctionType() && "function decl is not of function type");
   8720   const FunctionType *FT = T->castAs<FunctionType>();
   8721 
   8722   // Set an implicit return of 'zero' if the function can return some integral,
   8723   // enumeration, pointer or nullptr type.
   8724   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
   8725       FT->getReturnType()->isAnyPointerType() ||
   8726       FT->getReturnType()->isNullPtrType())
   8727     // DllMain is exempt because a return value of zero means it failed.
   8728     if (FD->getName() != "DllMain")
   8729       FD->setHasImplicitReturnZero(true);
   8730 
   8731   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
   8732     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
   8733     FD->setInvalidDecl();
   8734   }
   8735 }
   8736 
   8737 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
   8738   // FIXME: Need strict checking.  In C89, we need to check for
   8739   // any assignment, increment, decrement, function-calls, or
   8740   // commas outside of a sizeof.  In C99, it's the same list,
   8741   // except that the aforementioned are allowed in unevaluated
   8742   // expressions.  Everything else falls under the
   8743   // "may accept other forms of constant expressions" exception.
   8744   // (We never end up here for C++, so the constant expression
   8745   // rules there don't matter.)
   8746   const Expr *Culprit;
   8747   if (Init->isConstantInitializer(Context, false, &Culprit))
   8748     return false;
   8749   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
   8750     << Culprit->getSourceRange();
   8751   return true;
   8752 }
   8753 
   8754 namespace {
   8755   // Visits an initialization expression to see if OrigDecl is evaluated in
   8756   // its own initialization and throws a warning if it does.
   8757   class SelfReferenceChecker
   8758       : public EvaluatedExprVisitor<SelfReferenceChecker> {
   8759     Sema &S;
   8760     Decl *OrigDecl;
   8761     bool isRecordType;
   8762     bool isPODType;
   8763     bool isReferenceType;
   8764 
   8765     bool isInitList;
   8766     llvm::SmallVector<unsigned, 4> InitFieldIndex;
   8767   public:
   8768     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
   8769 
   8770     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
   8771                                                     S(S), OrigDecl(OrigDecl) {
   8772       isPODType = false;
   8773       isRecordType = false;
   8774       isReferenceType = false;
   8775       isInitList = false;
   8776       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
   8777         isPODType = VD->getType().isPODType(S.Context);
   8778         isRecordType = VD->getType()->isRecordType();
   8779         isReferenceType = VD->getType()->isReferenceType();
   8780       }
   8781     }
   8782 
   8783     // For most expressions, just call the visitor.  For initializer lists,
   8784     // track the index of the field being initialized since fields are
   8785     // initialized in order allowing use of previously initialized fields.
   8786     void CheckExpr(Expr *E) {
   8787       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
   8788       if (!InitList) {
   8789         Visit(E);
   8790         return;
   8791       }
   8792 
   8793       // Track and increment the index here.
   8794       isInitList = true;
   8795       InitFieldIndex.push_back(0);
   8796       for (auto Child : InitList->children()) {
   8797         CheckExpr(cast<Expr>(Child));
   8798         ++InitFieldIndex.back();
   8799       }
   8800       InitFieldIndex.pop_back();
   8801     }
   8802 
   8803     // Returns true if MemberExpr is checked and no futher checking is needed.
   8804     // Returns false if additional checking is required.
   8805     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
   8806       llvm::SmallVector<FieldDecl*, 4> Fields;
   8807       Expr *Base = E;
   8808       bool ReferenceField = false;
   8809 
   8810       // Get the field memebers used.
   8811       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
   8812         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
   8813         if (!FD)
   8814           return false;
   8815         Fields.push_back(FD);
   8816         if (FD->getType()->isReferenceType())
   8817           ReferenceField = true;
   8818         Base = ME->getBase()->IgnoreParenImpCasts();
   8819       }
   8820 
   8821       // Keep checking only if the base Decl is the same.
   8822       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
   8823       if (!DRE || DRE->getDecl() != OrigDecl)
   8824         return false;
   8825 
   8826       // A reference field can be bound to an unininitialized field.
   8827       if (CheckReference && !ReferenceField)
   8828         return true;
   8829 
   8830       // Convert FieldDecls to their index number.
   8831       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
   8832       for (const FieldDecl *I : llvm::reverse(Fields))
   8833         UsedFieldIndex.push_back(I->getFieldIndex());
   8834 
   8835       // See if a warning is needed by checking the first difference in index
   8836       // numbers.  If field being used has index less than the field being
   8837       // initialized, then the use is safe.
   8838       for (auto UsedIter = UsedFieldIndex.begin(),
   8839                 UsedEnd = UsedFieldIndex.end(),
   8840                 OrigIter = InitFieldIndex.begin(),
   8841                 OrigEnd = InitFieldIndex.end();
   8842            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
   8843         if (*UsedIter < *OrigIter)
   8844           return true;
   8845         if (*UsedIter > *OrigIter)
   8846           break;
   8847       }
   8848 
   8849       // TODO: Add a different warning which will print the field names.
   8850       HandleDeclRefExpr(DRE);
   8851       return true;
   8852     }
   8853 
   8854     // For most expressions, the cast is directly above the DeclRefExpr.
   8855     // For conditional operators, the cast can be outside the conditional
   8856     // operator if both expressions are DeclRefExpr's.
   8857     void HandleValue(Expr *E) {
   8858       E = E->IgnoreParens();
   8859       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
   8860         HandleDeclRefExpr(DRE);
   8861         return;
   8862       }
   8863 
   8864       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
   8865         Visit(CO->getCond());
   8866         HandleValue(CO->getTrueExpr());
   8867         HandleValue(CO->getFalseExpr());
   8868         return;
   8869       }
   8870 
   8871       if (BinaryConditionalOperator *BCO =
   8872               dyn_cast<BinaryConditionalOperator>(E)) {
   8873         Visit(BCO->getCond());
   8874         HandleValue(BCO->getFalseExpr());
   8875         return;
   8876       }
   8877 
   8878       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
   8879         HandleValue(OVE->getSourceExpr());
   8880         return;
   8881       }
   8882 
   8883       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
   8884         if (BO->getOpcode() == BO_Comma) {
   8885           Visit(BO->getLHS());
   8886           HandleValue(BO->getRHS());
   8887           return;
   8888         }
   8889       }
   8890 
   8891       if (isa<MemberExpr>(E)) {
   8892         if (isInitList) {
   8893           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
   8894                                       false /*CheckReference*/))
   8895             return;
   8896         }
   8897 
   8898         Expr *Base = E->IgnoreParenImpCasts();
   8899         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
   8900           // Check for static member variables and don't warn on them.
   8901           if (!isa<FieldDecl>(ME->getMemberDecl()))
   8902             return;
   8903           Base = ME->getBase()->IgnoreParenImpCasts();
   8904         }
   8905         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
   8906           HandleDeclRefExpr(DRE);
   8907         return;
   8908       }
   8909 
   8910       Visit(E);
   8911     }
   8912 
   8913     // Reference types not handled in HandleValue are handled here since all
   8914     // uses of references are bad, not just r-value uses.
   8915     void VisitDeclRefExpr(DeclRefExpr *E) {
   8916       if (isReferenceType)
   8917         HandleDeclRefExpr(E);
   8918     }
   8919 
   8920     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
   8921       if (E->getCastKind() == CK_LValueToRValue) {
   8922         HandleValue(E->getSubExpr());
   8923         return;
   8924       }
   8925 
   8926       Inherited::VisitImplicitCastExpr(E);
   8927     }
   8928 
   8929     void VisitMemberExpr(MemberExpr *E) {
   8930       if (isInitList) {
   8931         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
   8932           return;
   8933       }
   8934 
   8935       // Don't warn on arrays since they can be treated as pointers.
   8936       if (E->getType()->canDecayToPointerType()) return;
   8937 
   8938       // Warn when a non-static method call is followed by non-static member
   8939       // field accesses, which is followed by a DeclRefExpr.
   8940       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
   8941       bool Warn = (MD && !MD->isStatic());
   8942       Expr *Base = E->getBase()->IgnoreParenImpCasts();
   8943       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
   8944         if (!isa<FieldDecl>(ME->getMemberDecl()))
   8945           Warn = false;
   8946         Base = ME->getBase()->IgnoreParenImpCasts();
   8947       }
   8948 
   8949       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
   8950         if (Warn)
   8951           HandleDeclRefExpr(DRE);
   8952         return;
   8953       }
   8954 
   8955       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
   8956       // Visit that expression.
   8957       Visit(Base);
   8958     }
   8959 
   8960     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
   8961       Expr *Callee = E->getCallee();
   8962 
   8963       if (isa<UnresolvedLookupExpr>(Callee))
   8964         return Inherited::VisitCXXOperatorCallExpr(E);
   8965 
   8966       Visit(Callee);
   8967       for (auto Arg: E->arguments())
   8968         HandleValue(Arg->IgnoreParenImpCasts());
   8969     }
   8970 
   8971     void VisitUnaryOperator(UnaryOperator *E) {
   8972       // For POD record types, addresses of its own members are well-defined.
   8973       if (E->getOpcode() == UO_AddrOf && isRecordType &&
   8974           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
   8975         if (!isPODType)
   8976           HandleValue(E->getSubExpr());
   8977         return;
   8978       }
   8979 
   8980       if (E->isIncrementDecrementOp()) {
   8981         HandleValue(E->getSubExpr());
   8982         return;
   8983       }
   8984 
   8985       Inherited::VisitUnaryOperator(E);
   8986     }
   8987 
   8988     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
   8989 
   8990     void VisitCXXConstructExpr(CXXConstructExpr *E) {
   8991       if (E->getConstructor()->isCopyConstructor()) {
   8992         Expr *ArgExpr = E->getArg(0);
   8993         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
   8994           if (ILE->getNumInits() == 1)
   8995             ArgExpr = ILE->getInit(0);
   8996         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
   8997           if (ICE->getCastKind() == CK_NoOp)
   8998             ArgExpr = ICE->getSubExpr();
   8999         HandleValue(ArgExpr);
   9000         return;
   9001       }
   9002       Inherited::VisitCXXConstructExpr(E);
   9003     }
   9004 
   9005     void VisitCallExpr(CallExpr *E) {
   9006       // Treat std::move as a use.
   9007       if (E->getNumArgs() == 1) {
   9008         if (FunctionDecl *FD = E->getDirectCallee()) {
   9009           if (FD->isInStdNamespace() && FD->getIdentifier() &&
   9010               FD->getIdentifier()->isStr("move")) {
   9011             HandleValue(E->getArg(0));
   9012             return;
   9013           }
   9014         }
   9015       }
   9016 
   9017       Inherited::VisitCallExpr(E);
   9018     }
   9019 
   9020     void VisitBinaryOperator(BinaryOperator *E) {
   9021       if (E->isCompoundAssignmentOp()) {
   9022         HandleValue(E->getLHS());
   9023         Visit(E->getRHS());
   9024         return;
   9025       }
   9026 
   9027       Inherited::VisitBinaryOperator(E);
   9028     }
   9029 
   9030     // A custom visitor for BinaryConditionalOperator is needed because the
   9031     // regular visitor would check the condition and true expression separately
   9032     // but both point to the same place giving duplicate diagnostics.
   9033     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
   9034       Visit(E->getCond());
   9035       Visit(E->getFalseExpr());
   9036     }
   9037 
   9038     void HandleDeclRefExpr(DeclRefExpr *DRE) {
   9039       Decl* ReferenceDecl = DRE->getDecl();
   9040       if (OrigDecl != ReferenceDecl) return;
   9041       unsigned diag;
   9042       if (isReferenceType) {
   9043         diag = diag::warn_uninit_self_reference_in_reference_init;
   9044       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
   9045         diag = diag::warn_static_self_reference_in_init;
   9046       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
   9047                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
   9048                  DRE->getDecl()->getType()->isRecordType()) {
   9049         diag = diag::warn_uninit_self_reference_in_init;
   9050       } else {
   9051         // Local variables will be handled by the CFG analysis.
   9052         return;
   9053       }
   9054 
   9055       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
   9056                             S.PDiag(diag)
   9057                               << DRE->getNameInfo().getName()
   9058                               << OrigDecl->getLocation()
   9059                               << DRE->getSourceRange());
   9060     }
   9061   };
   9062 
   9063   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
   9064   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
   9065                                  bool DirectInit) {
   9066     // Parameters arguments are occassionially constructed with itself,
   9067     // for instance, in recursive functions.  Skip them.
   9068     if (isa<ParmVarDecl>(OrigDecl))
   9069       return;
   9070 
   9071     E = E->IgnoreParens();
   9072 
   9073     // Skip checking T a = a where T is not a record or reference type.
   9074     // Doing so is a way to silence uninitialized warnings.
   9075     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
   9076       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
   9077         if (ICE->getCastKind() == CK_LValueToRValue)
   9078           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
   9079             if (DRE->getDecl() == OrigDecl)
   9080               return;
   9081 
   9082     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
   9083   }
   9084 }
   9085 
   9086 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
   9087                                             DeclarationName Name, QualType Type,
   9088                                             TypeSourceInfo *TSI,
   9089                                             SourceRange Range, bool DirectInit,
   9090                                             Expr *Init) {
   9091   bool IsInitCapture = !VDecl;
   9092   assert((!VDecl || !VDecl->isInitCapture()) &&
   9093          "init captures are expected to be deduced prior to initialization");
   9094 
   9095   ArrayRef<Expr *> DeduceInits = Init;
   9096   if (DirectInit) {
   9097     if (auto *PL = dyn_cast<ParenListExpr>(Init))
   9098       DeduceInits = PL->exprs();
   9099     else if (auto *IL = dyn_cast<InitListExpr>(Init))
   9100       DeduceInits = IL->inits();
   9101   }
   9102 
   9103   // Deduction only works if we have exactly one source expression.
   9104   if (DeduceInits.empty()) {
   9105     // It isn't possible to write this directly, but it is possible to
   9106     // end up in this situation with "auto x(some_pack...);"
   9107     Diag(Init->getLocStart(), IsInitCapture
   9108                                   ? diag::err_init_capture_no_expression
   9109                                   : diag::err_auto_var_init_no_expression)
   9110         << Name << Type << Range;
   9111     return QualType();
   9112   }
   9113 
   9114   if (DeduceInits.size() > 1) {
   9115     Diag(DeduceInits[1]->getLocStart(),
   9116          IsInitCapture ? diag::err_init_capture_multiple_expressions
   9117                        : diag::err_auto_var_init_multiple_expressions)
   9118         << Name << Type << Range;
   9119     return QualType();
   9120   }
   9121 
   9122   Expr *DeduceInit = DeduceInits[0];
   9123   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
   9124     Diag(Init->getLocStart(), IsInitCapture
   9125                                   ? diag::err_init_capture_paren_braces
   9126                                   : diag::err_auto_var_init_paren_braces)
   9127         << isa<InitListExpr>(Init) << Name << Type << Range;
   9128     return QualType();
   9129   }
   9130 
   9131   // Expressions default to 'id' when we're in a debugger.
   9132   bool DefaultedAnyToId = false;
   9133   if (getLangOpts().DebuggerCastResultToId &&
   9134       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
   9135     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
   9136     if (Result.isInvalid()) {
   9137       return QualType();
   9138     }
   9139     Init = Result.get();
   9140     DefaultedAnyToId = true;
   9141   }
   9142 
   9143   QualType DeducedType;
   9144   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
   9145     if (!IsInitCapture)
   9146       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
   9147     else if (isa<InitListExpr>(Init))
   9148       Diag(Range.getBegin(),
   9149            diag::err_init_capture_deduction_failure_from_init_list)
   9150           << Name
   9151           << (DeduceInit->getType().isNull() ? TSI->getType()
   9152                                              : DeduceInit->getType())
   9153           << DeduceInit->getSourceRange();
   9154     else
   9155       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
   9156           << Name << TSI->getType()
   9157           << (DeduceInit->getType().isNull() ? TSI->getType()
   9158                                              : DeduceInit->getType())
   9159           << DeduceInit->getSourceRange();
   9160   }
   9161 
   9162   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
   9163   // 'id' instead of a specific object type prevents most of our usual
   9164   // checks.
   9165   // We only want to warn outside of template instantiations, though:
   9166   // inside a template, the 'id' could have come from a parameter.
   9167   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
   9168       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
   9169     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
   9170     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
   9171   }
   9172 
   9173   return DeducedType;
   9174 }
   9175 
   9176 /// AddInitializerToDecl - Adds the initializer Init to the
   9177 /// declaration dcl. If DirectInit is true, this is C++ direct
   9178 /// initialization rather than copy initialization.
   9179 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
   9180                                 bool DirectInit, bool TypeMayContainAuto) {
   9181   // If there is no declaration, there was an error parsing it.  Just ignore
   9182   // the initializer.
   9183   if (!RealDecl || RealDecl->isInvalidDecl()) {
   9184     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
   9185     return;
   9186   }
   9187 
   9188   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
   9189     // Pure-specifiers are handled in ActOnPureSpecifier.
   9190     Diag(Method->getLocation(), diag::err_member_function_initialization)
   9191       << Method->getDeclName() << Init->getSourceRange();
   9192     Method->setInvalidDecl();
   9193     return;
   9194   }
   9195 
   9196   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
   9197   if (!VDecl) {
   9198     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
   9199     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
   9200     RealDecl->setInvalidDecl();
   9201     return;
   9202   }
   9203 
   9204   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
   9205   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
   9206     // Attempt typo correction early so that the type of the init expression can
   9207     // be deduced based on the chosen correction if the original init contains a
   9208     // TypoExpr.
   9209     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
   9210     if (!Res.isUsable()) {
   9211       RealDecl->setInvalidDecl();
   9212       return;
   9213     }
   9214     Init = Res.get();
   9215 
   9216     QualType DeducedType = deduceVarTypeFromInitializer(
   9217         VDecl, VDecl->getDeclName(), VDecl->getType(),
   9218         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
   9219     if (DeducedType.isNull()) {
   9220       RealDecl->setInvalidDecl();
   9221       return;
   9222     }
   9223 
   9224     VDecl->setType(DeducedType);
   9225     assert(VDecl->isLinkageValid());
   9226 
   9227     // In ARC, infer lifetime.
   9228     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
   9229       VDecl->setInvalidDecl();
   9230 
   9231     // If this is a redeclaration, check that the type we just deduced matches
   9232     // the previously declared type.
   9233     if (VarDecl *Old = VDecl->getPreviousDecl()) {
   9234       // We never need to merge the type, because we cannot form an incomplete
   9235       // array of auto, nor deduce such a type.
   9236       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
   9237     }
   9238 
   9239     // Check the deduced type is valid for a variable declaration.
   9240     CheckVariableDeclarationType(VDecl);
   9241     if (VDecl->isInvalidDecl())
   9242       return;
   9243   }
   9244 
   9245   // dllimport cannot be used on variable definitions.
   9246   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
   9247     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
   9248     VDecl->setInvalidDecl();
   9249     return;
   9250   }
   9251 
   9252   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
   9253     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
   9254     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
   9255     VDecl->setInvalidDecl();
   9256     return;
   9257   }
   9258 
   9259   if (!VDecl->getType()->isDependentType()) {
   9260     // A definition must end up with a complete type, which means it must be
   9261     // complete with the restriction that an array type might be completed by
   9262     // the initializer; note that later code assumes this restriction.
   9263     QualType BaseDeclType = VDecl->getType();
   9264     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
   9265       BaseDeclType = Array->getElementType();
   9266     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
   9267                             diag::err_typecheck_decl_incomplete_type)) {
   9268       RealDecl->setInvalidDecl();
   9269       return;
   9270     }
   9271 
   9272     // The variable can not have an abstract class type.
   9273     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
   9274                                diag::err_abstract_type_in_decl,
   9275                                AbstractVariableType))
   9276       VDecl->setInvalidDecl();
   9277   }
   9278 
   9279   VarDecl *Def;
   9280   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
   9281     NamedDecl *Hidden = nullptr;
   9282     if (!hasVisibleDefinition(Def, &Hidden) &&
   9283         (VDecl->getFormalLinkage() == InternalLinkage ||
   9284          VDecl->getDescribedVarTemplate() ||
   9285          VDecl->getNumTemplateParameterLists() ||
   9286          VDecl->getDeclContext()->isDependentContext())) {
   9287       // The previous definition is hidden, and multiple definitions are
   9288       // permitted (in separate TUs). Form another definition of it.
   9289     } else {
   9290       Diag(VDecl->getLocation(), diag::err_redefinition)
   9291         << VDecl->getDeclName();
   9292       Diag(Def->getLocation(), diag::note_previous_definition);
   9293       VDecl->setInvalidDecl();
   9294       return;
   9295     }
   9296   }
   9297 
   9298   if (getLangOpts().CPlusPlus) {
   9299     // C++ [class.static.data]p4
   9300     //   If a static data member is of const integral or const
   9301     //   enumeration type, its declaration in the class definition can
   9302     //   specify a constant-initializer which shall be an integral
   9303     //   constant expression (5.19). In that case, the member can appear
   9304     //   in integral constant expressions. The member shall still be
   9305     //   defined in a namespace scope if it is used in the program and the
   9306     //   namespace scope definition shall not contain an initializer.
   9307     //
   9308     // We already performed a redefinition check above, but for static
   9309     // data members we also need to check whether there was an in-class
   9310     // declaration with an initializer.
   9311     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
   9312       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
   9313           << VDecl->getDeclName();
   9314       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
   9315            diag::note_previous_initializer)
   9316           << 0;
   9317       return;
   9318     }
   9319 
   9320     if (VDecl->hasLocalStorage())
   9321       getCurFunction()->setHasBranchProtectedScope();
   9322 
   9323     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
   9324       VDecl->setInvalidDecl();
   9325       return;
   9326     }
   9327   }
   9328 
   9329   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
   9330   // a kernel function cannot be initialized."
   9331   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
   9332     Diag(VDecl->getLocation(), diag::err_local_cant_init);
   9333     VDecl->setInvalidDecl();
   9334     return;
   9335   }
   9336 
   9337   // Get the decls type and save a reference for later, since
   9338   // CheckInitializerTypes may change it.
   9339   QualType DclT = VDecl->getType(), SavT = DclT;
   9340 
   9341   // Expressions default to 'id' when we're in a debugger
   9342   // and we are assigning it to a variable of Objective-C pointer type.
   9343   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
   9344       Init->getType() == Context.UnknownAnyTy) {
   9345     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
   9346     if (Result.isInvalid()) {
   9347       VDecl->setInvalidDecl();
   9348       return;
   9349     }
   9350     Init = Result.get();
   9351   }
   9352 
   9353   // Perform the initialization.
   9354   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
   9355   if (!VDecl->isInvalidDecl()) {
   9356     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
   9357     InitializationKind Kind =
   9358         DirectInit
   9359             ? CXXDirectInit
   9360                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
   9361                                                      Init->getLocStart(),
   9362                                                      Init->getLocEnd())
   9363                   : InitializationKind::CreateDirectList(VDecl->getLocation())
   9364             : InitializationKind::CreateCopy(VDecl->getLocation(),
   9365                                              Init->getLocStart());
   9366 
   9367     MultiExprArg Args = Init;
   9368     if (CXXDirectInit)
   9369       Args = MultiExprArg(CXXDirectInit->getExprs(),
   9370                           CXXDirectInit->getNumExprs());
   9371 
   9372     // Try to correct any TypoExprs in the initialization arguments.
   9373     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
   9374       ExprResult Res = CorrectDelayedTyposInExpr(
   9375           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
   9376             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
   9377             return Init.Failed() ? ExprError() : E;
   9378           });
   9379       if (Res.isInvalid()) {
   9380         VDecl->setInvalidDecl();
   9381       } else if (Res.get() != Args[Idx]) {
   9382         Args[Idx] = Res.get();
   9383       }
   9384     }
   9385     if (VDecl->isInvalidDecl())
   9386       return;
   9387 
   9388     InitializationSequence InitSeq(*this, Entity, Kind, Args);
   9389     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
   9390     if (Result.isInvalid()) {
   9391       VDecl->setInvalidDecl();
   9392       return;
   9393     }
   9394 
   9395     Init = Result.getAs<Expr>();
   9396   }
   9397 
   9398   // Check for self-references within variable initializers.
   9399   // Variables declared within a function/method body (except for references)
   9400   // are handled by a dataflow analysis.
   9401   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
   9402       VDecl->getType()->isReferenceType()) {
   9403     CheckSelfReference(*this, RealDecl, Init, DirectInit);
   9404   }
   9405 
   9406   // If the type changed, it means we had an incomplete type that was
   9407   // completed by the initializer. For example:
   9408   //   int ary[] = { 1, 3, 5 };
   9409   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
   9410   if (!VDecl->isInvalidDecl() && (DclT != SavT))
   9411     VDecl->setType(DclT);
   9412 
   9413   if (!VDecl->isInvalidDecl()) {
   9414     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
   9415 
   9416     if (VDecl->hasAttr<BlocksAttr>())
   9417       checkRetainCycles(VDecl, Init);
   9418 
   9419     // It is safe to assign a weak reference into a strong variable.
   9420     // Although this code can still have problems:
   9421     //   id x = self.weakProp;
   9422     //   id y = self.weakProp;
   9423     // we do not warn to warn spuriously when 'x' and 'y' are on separate
   9424     // paths through the function. This should be revisited if
   9425     // -Wrepeated-use-of-weak is made flow-sensitive.
   9426     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
   9427         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
   9428                          Init->getLocStart()))
   9429       getCurFunction()->markSafeWeakUse(Init);
   9430   }
   9431 
   9432   // The initialization is usually a full-expression.
   9433   //
   9434   // FIXME: If this is a braced initialization of an aggregate, it is not
   9435   // an expression, and each individual field initializer is a separate
   9436   // full-expression. For instance, in:
   9437   //
   9438   //   struct Temp { ~Temp(); };
   9439   //   struct S { S(Temp); };
   9440   //   struct T { S a, b; } t = { Temp(), Temp() }
   9441   //
   9442   // we should destroy the first Temp before constructing the second.
   9443   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
   9444                                           false,
   9445                                           VDecl->isConstexpr());
   9446   if (Result.isInvalid()) {
   9447     VDecl->setInvalidDecl();
   9448     return;
   9449   }
   9450   Init = Result.get();
   9451 
   9452   // Attach the initializer to the decl.
   9453   VDecl->setInit(Init);
   9454 
   9455   if (VDecl->isLocalVarDecl()) {
   9456     // C99 6.7.8p4: All the expressions in an initializer for an object that has
   9457     // static storage duration shall be constant expressions or string literals.
   9458     // C++ does not have this restriction.
   9459     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
   9460       const Expr *Culprit;
   9461       if (VDecl->getStorageClass() == SC_Static)
   9462         CheckForConstantInitializer(Init, DclT);
   9463       // C89 is stricter than C99 for non-static aggregate types.
   9464       // C89 6.5.7p3: All the expressions [...] in an initializer list
   9465       // for an object that has aggregate or union type shall be
   9466       // constant expressions.
   9467       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
   9468                isa<InitListExpr>(Init) &&
   9469                !Init->isConstantInitializer(Context, false, &Culprit))
   9470         Diag(Culprit->getExprLoc(),
   9471              diag::ext_aggregate_init_not_constant)
   9472           << Culprit->getSourceRange();
   9473     }
   9474   } else if (VDecl->isStaticDataMember() &&
   9475              VDecl->getLexicalDeclContext()->isRecord()) {
   9476     // This is an in-class initialization for a static data member, e.g.,
   9477     //
   9478     // struct S {
   9479     //   static const int value = 17;
   9480     // };
   9481 
   9482     // C++ [class.mem]p4:
   9483     //   A member-declarator can contain a constant-initializer only
   9484     //   if it declares a static member (9.4) of const integral or
   9485     //   const enumeration type, see 9.4.2.
   9486     //
   9487     // C++11 [class.static.data]p3:
   9488     //   If a non-volatile const static data member is of integral or
   9489     //   enumeration type, its declaration in the class definition can
   9490     //   specify a brace-or-equal-initializer in which every initalizer-clause
   9491     //   that is an assignment-expression is a constant expression. A static
   9492     //   data member of literal type can be declared in the class definition
   9493     //   with the constexpr specifier; if so, its declaration shall specify a
   9494     //   brace-or-equal-initializer in which every initializer-clause that is
   9495     //   an assignment-expression is a constant expression.
   9496 
   9497     // Do nothing on dependent types.
   9498     if (DclT->isDependentType()) {
   9499 
   9500     // Allow any 'static constexpr' members, whether or not they are of literal
   9501     // type. We separately check that every constexpr variable is of literal
   9502     // type.
   9503     } else if (VDecl->isConstexpr()) {
   9504 
   9505     // Require constness.
   9506     } else if (!DclT.isConstQualified()) {
   9507       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
   9508         << Init->getSourceRange();
   9509       VDecl->setInvalidDecl();
   9510 
   9511     // We allow integer constant expressions in all cases.
   9512     } else if (DclT->isIntegralOrEnumerationType()) {
   9513       // Check whether the expression is a constant expression.
   9514       SourceLocation Loc;
   9515       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
   9516         // In C++11, a non-constexpr const static data member with an
   9517         // in-class initializer cannot be volatile.
   9518         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
   9519       else if (Init->isValueDependent())
   9520         ; // Nothing to check.
   9521       else if (Init->isIntegerConstantExpr(Context, &Loc))
   9522         ; // Ok, it's an ICE!
   9523       else if (Init->isEvaluatable(Context)) {
   9524         // If we can constant fold the initializer through heroics, accept it,
   9525         // but report this as a use of an extension for -pedantic.
   9526         Diag(Loc, diag::ext_in_class_initializer_non_constant)
   9527           << Init->getSourceRange();
   9528       } else {
   9529         // Otherwise, this is some crazy unknown case.  Report the issue at the
   9530         // location provided by the isIntegerConstantExpr failed check.
   9531         Diag(Loc, diag::err_in_class_initializer_non_constant)
   9532           << Init->getSourceRange();
   9533         VDecl->setInvalidDecl();
   9534       }
   9535 
   9536     // We allow foldable floating-point constants as an extension.
   9537     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
   9538       // In C++98, this is a GNU extension. In C++11, it is not, but we support
   9539       // it anyway and provide a fixit to add the 'constexpr'.
   9540       if (getLangOpts().CPlusPlus11) {
   9541         Diag(VDecl->getLocation(),
   9542              diag::ext_in_class_initializer_float_type_cxx11)
   9543             << DclT << Init->getSourceRange();
   9544         Diag(VDecl->getLocStart(),
   9545              diag::note_in_class_initializer_float_type_cxx11)
   9546             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
   9547       } else {
   9548         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
   9549           << DclT << Init->getSourceRange();
   9550 
   9551         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
   9552           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
   9553             << Init->getSourceRange();
   9554           VDecl->setInvalidDecl();
   9555         }
   9556       }
   9557 
   9558     // Suggest adding 'constexpr' in C++11 for literal types.
   9559     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
   9560       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
   9561         << DclT << Init->getSourceRange()
   9562         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
   9563       VDecl->setConstexpr(true);
   9564 
   9565     } else {
   9566       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
   9567         << DclT << Init->getSourceRange();
   9568       VDecl->setInvalidDecl();
   9569     }
   9570   } else if (VDecl->isFileVarDecl()) {
   9571     if (VDecl->getStorageClass() == SC_Extern &&
   9572         (!getLangOpts().CPlusPlus ||
   9573          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
   9574            VDecl->isExternC())) &&
   9575         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
   9576       Diag(VDecl->getLocation(), diag::warn_extern_init);
   9577 
   9578     // C99 6.7.8p4. All file scoped initializers need to be constant.
   9579     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
   9580       CheckForConstantInitializer(Init, DclT);
   9581   }
   9582 
   9583   // We will represent direct-initialization similarly to copy-initialization:
   9584   //    int x(1);  -as-> int x = 1;
   9585   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
   9586   //
   9587   // Clients that want to distinguish between the two forms, can check for
   9588   // direct initializer using VarDecl::getInitStyle().
   9589   // A major benefit is that clients that don't particularly care about which
   9590   // exactly form was it (like the CodeGen) can handle both cases without
   9591   // special case code.
   9592 
   9593   // C++ 8.5p11:
   9594   // The form of initialization (using parentheses or '=') is generally
   9595   // insignificant, but does matter when the entity being initialized has a
   9596   // class type.
   9597   if (CXXDirectInit) {
   9598     assert(DirectInit && "Call-style initializer must be direct init.");
   9599     VDecl->setInitStyle(VarDecl::CallInit);
   9600   } else if (DirectInit) {
   9601     // This must be list-initialization. No other way is direct-initialization.
   9602     VDecl->setInitStyle(VarDecl::ListInit);
   9603   }
   9604 
   9605   CheckCompleteVariableDeclaration(VDecl);
   9606 }
   9607 
   9608 /// ActOnInitializerError - Given that there was an error parsing an
   9609 /// initializer for the given declaration, try to return to some form
   9610 /// of sanity.
   9611 void Sema::ActOnInitializerError(Decl *D) {
   9612   // Our main concern here is re-establishing invariants like "a
   9613   // variable's type is either dependent or complete".
   9614   if (!D || D->isInvalidDecl()) return;
   9615 
   9616   VarDecl *VD = dyn_cast<VarDecl>(D);
   9617   if (!VD) return;
   9618 
   9619   // Auto types are meaningless if we can't make sense of the initializer.
   9620   if (ParsingInitForAutoVars.count(D)) {
   9621     D->setInvalidDecl();
   9622     return;
   9623   }
   9624 
   9625   QualType Ty = VD->getType();
   9626   if (Ty->isDependentType()) return;
   9627 
   9628   // Require a complete type.
   9629   if (RequireCompleteType(VD->getLocation(),
   9630                           Context.getBaseElementType(Ty),
   9631                           diag::err_typecheck_decl_incomplete_type)) {
   9632     VD->setInvalidDecl();
   9633     return;
   9634   }
   9635 
   9636   // Require a non-abstract type.
   9637   if (RequireNonAbstractType(VD->getLocation(), Ty,
   9638                              diag::err_abstract_type_in_decl,
   9639                              AbstractVariableType)) {
   9640     VD->setInvalidDecl();
   9641     return;
   9642   }
   9643 
   9644   // Don't bother complaining about constructors or destructors,
   9645   // though.
   9646 }
   9647 
   9648 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
   9649                                   bool TypeMayContainAuto) {
   9650   // If there is no declaration, there was an error parsing it. Just ignore it.
   9651   if (!RealDecl)
   9652     return;
   9653 
   9654   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
   9655     QualType Type = Var->getType();
   9656 
   9657     // C++11 [dcl.spec.auto]p3
   9658     if (TypeMayContainAuto && Type->getContainedAutoType()) {
   9659       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
   9660         << Var->getDeclName() << Type;
   9661       Var->setInvalidDecl();
   9662       return;
   9663     }
   9664 
   9665     // C++11 [class.static.data]p3: A static data member can be declared with
   9666     // the constexpr specifier; if so, its declaration shall specify
   9667     // a brace-or-equal-initializer.
   9668     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
   9669     // the definition of a variable [...] or the declaration of a static data
   9670     // member.
   9671     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
   9672       if (Var->isStaticDataMember())
   9673         Diag(Var->getLocation(),
   9674              diag::err_constexpr_static_mem_var_requires_init)
   9675           << Var->getDeclName();
   9676       else
   9677         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
   9678       Var->setInvalidDecl();
   9679       return;
   9680     }
   9681 
   9682     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
   9683     // definition having the concept specifier is called a variable concept. A
   9684     // concept definition refers to [...] a variable concept and its initializer.
   9685     if (Var->isConcept()) {
   9686       Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
   9687       Var->setInvalidDecl();
   9688       return;
   9689     }
   9690 
   9691     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
   9692     // be initialized.
   9693     if (!Var->isInvalidDecl() &&
   9694         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
   9695         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
   9696       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
   9697       Var->setInvalidDecl();
   9698       return;
   9699     }
   9700 
   9701     switch (Var->isThisDeclarationADefinition()) {
   9702     case VarDecl::Definition:
   9703       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
   9704         break;
   9705 
   9706       // We have an out-of-line definition of a static data member
   9707       // that has an in-class initializer, so we type-check this like
   9708       // a declaration.
   9709       //
   9710       // Fall through
   9711 
   9712     case VarDecl::DeclarationOnly:
   9713       // It's only a declaration.
   9714 
   9715       // Block scope. C99 6.7p7: If an identifier for an object is
   9716       // declared with no linkage (C99 6.2.2p6), the type for the
   9717       // object shall be complete.
   9718       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
   9719           !Var->hasLinkage() && !Var->isInvalidDecl() &&
   9720           RequireCompleteType(Var->getLocation(), Type,
   9721                               diag::err_typecheck_decl_incomplete_type))
   9722         Var->setInvalidDecl();
   9723 
   9724       // Make sure that the type is not abstract.
   9725       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
   9726           RequireNonAbstractType(Var->getLocation(), Type,
   9727                                  diag::err_abstract_type_in_decl,
   9728                                  AbstractVariableType))
   9729         Var->setInvalidDecl();
   9730       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
   9731           Var->getStorageClass() == SC_PrivateExtern) {
   9732         Diag(Var->getLocation(), diag::warn_private_extern);
   9733         Diag(Var->getLocation(), diag::note_private_extern);
   9734       }
   9735 
   9736       return;
   9737 
   9738     case VarDecl::TentativeDefinition:
   9739       // File scope. C99 6.9.2p2: A declaration of an identifier for an
   9740       // object that has file scope without an initializer, and without a
   9741       // storage-class specifier or with the storage-class specifier "static",
   9742       // constitutes a tentative definition. Note: A tentative definition with
   9743       // external linkage is valid (C99 6.2.2p5).
   9744       if (!Var->isInvalidDecl()) {
   9745         if (const IncompleteArrayType *ArrayT
   9746                                     = Context.getAsIncompleteArrayType(Type)) {
   9747           if (RequireCompleteType(Var->getLocation(),
   9748                                   ArrayT->getElementType(),
   9749                                   diag::err_illegal_decl_array_incomplete_type))
   9750             Var->setInvalidDecl();
   9751         } else if (Var->getStorageClass() == SC_Static) {
   9752           // C99 6.9.2p3: If the declaration of an identifier for an object is
   9753           // a tentative definition and has internal linkage (C99 6.2.2p3), the
   9754           // declared type shall not be an incomplete type.
   9755           // NOTE: code such as the following
   9756           //     static struct s;
   9757           //     struct s { int a; };
   9758           // is accepted by gcc. Hence here we issue a warning instead of
   9759           // an error and we do not invalidate the static declaration.
   9760           // NOTE: to avoid multiple warnings, only check the first declaration.
   9761           if (Var->isFirstDecl())
   9762             RequireCompleteType(Var->getLocation(), Type,
   9763                                 diag::ext_typecheck_decl_incomplete_type);
   9764         }
   9765       }
   9766 
   9767       // Record the tentative definition; we're done.
   9768       if (!Var->isInvalidDecl())
   9769         TentativeDefinitions.push_back(Var);
   9770       return;
   9771     }
   9772 
   9773     // Provide a specific diagnostic for uninitialized variable
   9774     // definitions with incomplete array type.
   9775     if (Type->isIncompleteArrayType()) {
   9776       Diag(Var->getLocation(),
   9777            diag::err_typecheck_incomplete_array_needs_initializer);
   9778       Var->setInvalidDecl();
   9779       return;
   9780     }
   9781 
   9782     // Provide a specific diagnostic for uninitialized variable
   9783     // definitions with reference type.
   9784     if (Type->isReferenceType()) {
   9785       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
   9786         << Var->getDeclName()
   9787         << SourceRange(Var->getLocation(), Var->getLocation());
   9788       Var->setInvalidDecl();
   9789       return;
   9790     }
   9791 
   9792     // Do not attempt to type-check the default initializer for a
   9793     // variable with dependent type.
   9794     if (Type->isDependentType())
   9795       return;
   9796 
   9797     if (Var->isInvalidDecl())
   9798       return;
   9799 
   9800     if (!Var->hasAttr<AliasAttr>()) {
   9801       if (RequireCompleteType(Var->getLocation(),
   9802                               Context.getBaseElementType(Type),
   9803                               diag::err_typecheck_decl_incomplete_type)) {
   9804         Var->setInvalidDecl();
   9805         return;
   9806       }
   9807     } else {
   9808       return;
   9809     }
   9810 
   9811     // The variable can not have an abstract class type.
   9812     if (RequireNonAbstractType(Var->getLocation(), Type,
   9813                                diag::err_abstract_type_in_decl,
   9814                                AbstractVariableType)) {
   9815       Var->setInvalidDecl();
   9816       return;
   9817     }
   9818 
   9819     // Check for jumps past the implicit initializer.  C++0x
   9820     // clarifies that this applies to a "variable with automatic
   9821     // storage duration", not a "local variable".
   9822     // C++11 [stmt.dcl]p3
   9823     //   A program that jumps from a point where a variable with automatic
   9824     //   storage duration is not in scope to a point where it is in scope is
   9825     //   ill-formed unless the variable has scalar type, class type with a
   9826     //   trivial default constructor and a trivial destructor, a cv-qualified
   9827     //   version of one of these types, or an array of one of the preceding
   9828     //   types and is declared without an initializer.
   9829     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
   9830       if (const RecordType *Record
   9831             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
   9832         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
   9833         // Mark the function for further checking even if the looser rules of
   9834         // C++11 do not require such checks, so that we can diagnose
   9835         // incompatibilities with C++98.
   9836         if (!CXXRecord->isPOD())
   9837           getCurFunction()->setHasBranchProtectedScope();
   9838       }
   9839     }
   9840 
   9841     // C++03 [dcl.init]p9:
   9842     //   If no initializer is specified for an object, and the
   9843     //   object is of (possibly cv-qualified) non-POD class type (or
   9844     //   array thereof), the object shall be default-initialized; if
   9845     //   the object is of const-qualified type, the underlying class
   9846     //   type shall have a user-declared default
   9847     //   constructor. Otherwise, if no initializer is specified for
   9848     //   a non- static object, the object and its subobjects, if
   9849     //   any, have an indeterminate initial value); if the object
   9850     //   or any of its subobjects are of const-qualified type, the
   9851     //   program is ill-formed.
   9852     // C++0x [dcl.init]p11:
   9853     //   If no initializer is specified for an object, the object is
   9854     //   default-initialized; [...].
   9855     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
   9856     InitializationKind Kind
   9857       = InitializationKind::CreateDefault(Var->getLocation());
   9858 
   9859     InitializationSequence InitSeq(*this, Entity, Kind, None);
   9860     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
   9861     if (Init.isInvalid())
   9862       Var->setInvalidDecl();
   9863     else if (Init.get()) {
   9864       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
   9865       // This is important for template substitution.
   9866       Var->setInitStyle(VarDecl::CallInit);
   9867     }
   9868 
   9869     CheckCompleteVariableDeclaration(Var);
   9870   }
   9871 }
   9872 
   9873 void Sema::ActOnCXXForRangeDecl(Decl *D) {
   9874   VarDecl *VD = dyn_cast<VarDecl>(D);
   9875   if (!VD) {
   9876     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
   9877     D->setInvalidDecl();
   9878     return;
   9879   }
   9880 
   9881   VD->setCXXForRangeDecl(true);
   9882 
   9883   // for-range-declaration cannot be given a storage class specifier.
   9884   int Error = -1;
   9885   switch (VD->getStorageClass()) {
   9886   case SC_None:
   9887     break;
   9888   case SC_Extern:
   9889     Error = 0;
   9890     break;
   9891   case SC_Static:
   9892     Error = 1;
   9893     break;
   9894   case SC_PrivateExtern:
   9895     Error = 2;
   9896     break;
   9897   case SC_Auto:
   9898     Error = 3;
   9899     break;
   9900   case SC_Register:
   9901     Error = 4;
   9902     break;
   9903   }
   9904   if (Error != -1) {
   9905     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
   9906       << VD->getDeclName() << Error;
   9907     D->setInvalidDecl();
   9908   }
   9909 }
   9910 
   9911 StmtResult
   9912 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
   9913                                  IdentifierInfo *Ident,
   9914                                  ParsedAttributes &Attrs,
   9915                                  SourceLocation AttrEnd) {
   9916   // C++1y [stmt.iter]p1:
   9917   //   A range-based for statement of the form
   9918   //      for ( for-range-identifier : for-range-initializer ) statement
   9919   //   is equivalent to
   9920   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
   9921   DeclSpec DS(Attrs.getPool().getFactory());
   9922 
   9923   const char *PrevSpec;
   9924   unsigned DiagID;
   9925   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
   9926                      getPrintingPolicy());
   9927 
   9928   Declarator D(DS, Declarator::ForContext);
   9929   D.SetIdentifier(Ident, IdentLoc);
   9930   D.takeAttributes(Attrs, AttrEnd);
   9931 
   9932   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
   9933   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
   9934                 EmptyAttrs, IdentLoc);
   9935   Decl *Var = ActOnDeclarator(S, D);
   9936   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
   9937   FinalizeDeclaration(Var);
   9938   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
   9939                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
   9940 }
   9941 
   9942 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
   9943   if (var->isInvalidDecl()) return;
   9944 
   9945   // In Objective-C, don't allow jumps past the implicit initialization of a
   9946   // local retaining variable.
   9947   if (getLangOpts().ObjC1 &&
   9948       var->hasLocalStorage()) {
   9949     switch (var->getType().getObjCLifetime()) {
   9950     case Qualifiers::OCL_None:
   9951     case Qualifiers::OCL_ExplicitNone:
   9952     case Qualifiers::OCL_Autoreleasing:
   9953       break;
   9954 
   9955     case Qualifiers::OCL_Weak:
   9956     case Qualifiers::OCL_Strong:
   9957       getCurFunction()->setHasBranchProtectedScope();
   9958       break;
   9959     }
   9960   }
   9961 
   9962   // Warn about externally-visible variables being defined without a
   9963   // prior declaration.  We only want to do this for global
   9964   // declarations, but we also specifically need to avoid doing it for
   9965   // class members because the linkage of an anonymous class can
   9966   // change if it's later given a typedef name.
   9967   if (var->isThisDeclarationADefinition() &&
   9968       var->getDeclContext()->getRedeclContext()->isFileContext() &&
   9969       var->isExternallyVisible() && var->hasLinkage() &&
   9970       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
   9971                                   var->getLocation())) {
   9972     // Find a previous declaration that's not a definition.
   9973     VarDecl *prev = var->getPreviousDecl();
   9974     while (prev && prev->isThisDeclarationADefinition())
   9975       prev = prev->getPreviousDecl();
   9976 
   9977     if (!prev)
   9978       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
   9979   }
   9980 
   9981   if (var->getTLSKind() == VarDecl::TLS_Static) {
   9982     const Expr *Culprit;
   9983     if (var->getType().isDestructedType()) {
   9984       // GNU C++98 edits for __thread, [basic.start.term]p3:
   9985       //   The type of an object with thread storage duration shall not
   9986       //   have a non-trivial destructor.
   9987       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
   9988       if (getLangOpts().CPlusPlus11)
   9989         Diag(var->getLocation(), diag::note_use_thread_local);
   9990     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
   9991                !var->getInit()->isConstantInitializer(
   9992                    Context, var->getType()->isReferenceType(), &Culprit)) {
   9993       // GNU C++98 edits for __thread, [basic.start.init]p4:
   9994       //   An object of thread storage duration shall not require dynamic
   9995       //   initialization.
   9996       // FIXME: Need strict checking here.
   9997       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
   9998         << Culprit->getSourceRange();
   9999       if (getLangOpts().CPlusPlus11)
   10000         Diag(var->getLocation(), diag::note_use_thread_local);
   10001     }
   10002 
   10003   }
   10004 
   10005   // Apply section attributes and pragmas to global variables.
   10006   bool GlobalStorage = var->hasGlobalStorage();
   10007   if (GlobalStorage && var->isThisDeclarationADefinition() &&
   10008       ActiveTemplateInstantiations.empty()) {
   10009     PragmaStack<StringLiteral *> *Stack = nullptr;
   10010     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
   10011     if (var->getType().isConstQualified())
   10012       Stack = &ConstSegStack;
   10013     else if (!var->getInit()) {
   10014       Stack = &BSSSegStack;
   10015       SectionFlags |= ASTContext::PSF_Write;
   10016     } else {
   10017       Stack = &DataSegStack;
   10018       SectionFlags |= ASTContext::PSF_Write;
   10019     }
   10020     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
   10021       var->addAttr(SectionAttr::CreateImplicit(
   10022           Context, SectionAttr::Declspec_allocate,
   10023           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
   10024     }
   10025     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
   10026       if (UnifySection(SA->getName(), SectionFlags, var))
   10027         var->dropAttr<SectionAttr>();
   10028 
   10029     // Apply the init_seg attribute if this has an initializer.  If the
   10030     // initializer turns out to not be dynamic, we'll end up ignoring this
   10031     // attribute.
   10032     if (CurInitSeg && var->getInit())
   10033       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
   10034                                                CurInitSegLoc));
   10035   }
   10036 
   10037   // All the following checks are C++ only.
   10038   if (!getLangOpts().CPlusPlus) return;
   10039 
   10040   QualType type = var->getType();
   10041   if (type->isDependentType()) return;
   10042 
   10043   // __block variables might require us to capture a copy-initializer.
   10044   if (var->hasAttr<BlocksAttr>()) {
   10045     // It's currently invalid to ever have a __block variable with an
   10046     // array type; should we diagnose that here?
   10047 
   10048     // Regardless, we don't want to ignore array nesting when
   10049     // constructing this copy.
   10050     if (type->isStructureOrClassType()) {
   10051       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
   10052       SourceLocation poi = var->getLocation();
   10053       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
   10054       ExprResult result
   10055         = PerformMoveOrCopyInitialization(
   10056             InitializedEntity::InitializeBlock(poi, type, false),
   10057             var, var->getType(), varRef, /*AllowNRVO=*/true);
   10058       if (!result.isInvalid()) {
   10059         result = MaybeCreateExprWithCleanups(result);
   10060         Expr *init = result.getAs<Expr>();
   10061         Context.setBlockVarCopyInits(var, init);
   10062       }
   10063     }
   10064   }
   10065 
   10066   Expr *Init = var->getInit();
   10067   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
   10068   QualType baseType = Context.getBaseElementType(type);
   10069 
   10070   if (!var->getDeclContext()->isDependentContext() &&
   10071       Init && !Init->isValueDependent()) {
   10072     if (IsGlobal && !var->isConstexpr() &&
   10073         !getDiagnostics().isIgnored(diag::warn_global_constructor,
   10074                                     var->getLocation())) {
   10075       // Warn about globals which don't have a constant initializer.  Don't
   10076       // warn about globals with a non-trivial destructor because we already
   10077       // warned about them.
   10078       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
   10079       if (!(RD && !RD->hasTrivialDestructor()) &&
   10080           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
   10081         Diag(var->getLocation(), diag::warn_global_constructor)
   10082           << Init->getSourceRange();
   10083     }
   10084 
   10085     if (var->isConstexpr()) {
   10086       SmallVector<PartialDiagnosticAt, 8> Notes;
   10087       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
   10088         SourceLocation DiagLoc = var->getLocation();
   10089         // If the note doesn't add any useful information other than a source
   10090         // location, fold it into the primary diagnostic.
   10091         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
   10092               diag::note_invalid_subexpr_in_const_expr) {
   10093           DiagLoc = Notes[0].first;
   10094           Notes.clear();
   10095         }
   10096         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
   10097           << var << Init->getSourceRange();
   10098         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
   10099           Diag(Notes[I].first, Notes[I].second);
   10100       }
   10101     } else if (var->isUsableInConstantExpressions(Context)) {
   10102       // Check whether the initializer of a const variable of integral or
   10103       // enumeration type is an ICE now, since we can't tell whether it was
   10104       // initialized by a constant expression if we check later.
   10105       var->checkInitIsICE();
   10106     }
   10107   }
   10108 
   10109   // Require the destructor.
   10110   if (const RecordType *recordType = baseType->getAs<RecordType>())
   10111     FinalizeVarWithDestructor(var, recordType);
   10112 }
   10113 
   10114 /// \brief Determines if a variable's alignment is dependent.
   10115 static bool hasDependentAlignment(VarDecl *VD) {
   10116   if (VD->getType()->isDependentType())
   10117     return true;
   10118   for (auto *I : VD->specific_attrs<AlignedAttr>())
   10119     if (I->isAlignmentDependent())
   10120       return true;
   10121   return false;
   10122 }
   10123 
   10124 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
   10125 /// any semantic actions necessary after any initializer has been attached.
   10126 void
   10127 Sema::FinalizeDeclaration(Decl *ThisDecl) {
   10128   // Note that we are no longer parsing the initializer for this declaration.
   10129   ParsingInitForAutoVars.erase(ThisDecl);
   10130 
   10131   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
   10132   if (!VD)
   10133     return;
   10134 
   10135   checkAttributesAfterMerging(*this, *VD);
   10136 
   10137   // Perform TLS alignment check here after attributes attached to the variable
   10138   // which may affect the alignment have been processed. Only perform the check
   10139   // if the target has a maximum TLS alignment (zero means no constraints).
   10140   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
   10141     // Protect the check so that it's not performed on dependent types and
   10142     // dependent alignments (we can't determine the alignment in that case).
   10143     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
   10144       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
   10145       if (Context.getDeclAlign(VD) > MaxAlignChars) {
   10146         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
   10147           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
   10148           << (unsigned)MaxAlignChars.getQuantity();
   10149       }
   10150     }
   10151   }
   10152 
   10153   // Static locals inherit dll attributes from their function.
   10154   if (VD->isStaticLocal()) {
   10155     if (FunctionDecl *FD =
   10156             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
   10157       if (Attr *A = getDLLAttr(FD)) {
   10158         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
   10159         NewAttr->setInherited(true);
   10160         VD->addAttr(NewAttr);
   10161       }
   10162     }
   10163   }
   10164 
   10165   // Grab the dllimport or dllexport attribute off of the VarDecl.
   10166   const InheritableAttr *DLLAttr = getDLLAttr(VD);
   10167 
   10168   // Imported static data members cannot be defined out-of-line.
   10169   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
   10170     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
   10171         VD->isThisDeclarationADefinition()) {
   10172       // We allow definitions of dllimport class template static data members
   10173       // with a warning.
   10174       CXXRecordDecl *Context =
   10175         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
   10176       bool IsClassTemplateMember =
   10177           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
   10178           Context->getDescribedClassTemplate();
   10179 
   10180       Diag(VD->getLocation(),
   10181            IsClassTemplateMember
   10182                ? diag::warn_attribute_dllimport_static_field_definition
   10183                : diag::err_attribute_dllimport_static_field_definition);
   10184       Diag(IA->getLocation(), diag::note_attribute);
   10185       if (!IsClassTemplateMember)
   10186         VD->setInvalidDecl();
   10187     }
   10188   }
   10189 
   10190   // dllimport/dllexport variables cannot be thread local, their TLS index
   10191   // isn't exported with the variable.
   10192   if (DLLAttr && VD->getTLSKind()) {
   10193     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
   10194     if (F && getDLLAttr(F)) {
   10195       assert(VD->isStaticLocal());
   10196       // But if this is a static local in a dlimport/dllexport function, the
   10197       // function will never be inlined, which means the var would never be
   10198       // imported, so having it marked import/export is safe.
   10199     } else {
   10200       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
   10201                                                                     << DLLAttr;
   10202       VD->setInvalidDecl();
   10203     }
   10204   }
   10205 
   10206   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
   10207     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
   10208       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
   10209       VD->dropAttr<UsedAttr>();
   10210     }
   10211   }
   10212 
   10213   const DeclContext *DC = VD->getDeclContext();
   10214   // If there's a #pragma GCC visibility in scope, and this isn't a class
   10215   // member, set the visibility of this variable.
   10216   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
   10217     AddPushedVisibilityAttribute(VD);
   10218 
   10219   // FIXME: Warn on unused templates.
   10220   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
   10221       !isa<VarTemplatePartialSpecializationDecl>(VD))
   10222     MarkUnusedFileScopedDecl(VD);
   10223 
   10224   // Now we have parsed the initializer and can update the table of magic
   10225   // tag values.
   10226   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
   10227       !VD->getType()->isIntegralOrEnumerationType())
   10228     return;
   10229 
   10230   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
   10231     const Expr *MagicValueExpr = VD->getInit();
   10232     if (!MagicValueExpr) {
   10233       continue;
   10234     }
   10235     llvm::APSInt MagicValueInt;
   10236     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
   10237       Diag(I->getRange().getBegin(),
   10238            diag::err_type_tag_for_datatype_not_ice)
   10239         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
   10240       continue;
   10241     }
   10242     if (MagicValueInt.getActiveBits() > 64) {
   10243       Diag(I->getRange().getBegin(),
   10244            diag::err_type_tag_for_datatype_too_large)
   10245         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
   10246       continue;
   10247     }
   10248     uint64_t MagicValue = MagicValueInt.getZExtValue();
   10249     RegisterTypeTagForDatatype(I->getArgumentKind(),
   10250                                MagicValue,
   10251                                I->getMatchingCType(),
   10252                                I->getLayoutCompatible(),
   10253                                I->getMustBeNull());
   10254   }
   10255 }
   10256 
   10257 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
   10258                                                    ArrayRef<Decl *> Group) {
   10259   SmallVector<Decl*, 8> Decls;
   10260 
   10261   if (DS.isTypeSpecOwned())
   10262     Decls.push_back(DS.getRepAsDecl());
   10263 
   10264   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
   10265   for (unsigned i = 0, e = Group.size(); i != e; ++i)
   10266     if (Decl *D = Group[i]) {
   10267       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
   10268         if (!FirstDeclaratorInGroup)
   10269           FirstDeclaratorInGroup = DD;
   10270       Decls.push_back(D);
   10271     }
   10272 
   10273   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
   10274     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
   10275       handleTagNumbering(Tag, S);
   10276       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
   10277           getLangOpts().CPlusPlus)
   10278         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
   10279     }
   10280   }
   10281 
   10282   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
   10283 }
   10284 
   10285 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
   10286 /// group, performing any necessary semantic checking.
   10287 Sema::DeclGroupPtrTy
   10288 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
   10289                            bool TypeMayContainAuto) {
   10290   // C++0x [dcl.spec.auto]p7:
   10291   //   If the type deduced for the template parameter U is not the same in each
   10292   //   deduction, the program is ill-formed.
   10293   // FIXME: When initializer-list support is added, a distinction is needed
   10294   // between the deduced type U and the deduced type which 'auto' stands for.
   10295   //   auto a = 0, b = { 1, 2, 3 };
   10296   // is legal because the deduced type U is 'int' in both cases.
   10297   if (TypeMayContainAuto && Group.size() > 1) {
   10298     QualType Deduced;
   10299     CanQualType DeducedCanon;
   10300     VarDecl *DeducedDecl = nullptr;
   10301     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
   10302       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
   10303         AutoType *AT = D->getType()->getContainedAutoType();
   10304         // Don't reissue diagnostics when instantiating a template.
   10305         if (AT && D->isInvalidDecl())
   10306           break;
   10307         QualType U = AT ? AT->getDeducedType() : QualType();
   10308         if (!U.isNull()) {
   10309           CanQualType UCanon = Context.getCanonicalType(U);
   10310           if (Deduced.isNull()) {
   10311             Deduced = U;
   10312             DeducedCanon = UCanon;
   10313             DeducedDecl = D;
   10314           } else if (DeducedCanon != UCanon) {
   10315             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
   10316                  diag::err_auto_different_deductions)
   10317               << (unsigned)AT->getKeyword()
   10318               << Deduced << DeducedDecl->getDeclName()
   10319               << U << D->getDeclName()
   10320               << DeducedDecl->getInit()->getSourceRange()
   10321               << D->getInit()->getSourceRange();
   10322             D->setInvalidDecl();
   10323             break;
   10324           }
   10325         }
   10326       }
   10327     }
   10328   }
   10329 
   10330   ActOnDocumentableDecls(Group);
   10331 
   10332   return DeclGroupPtrTy::make(
   10333       DeclGroupRef::Create(Context, Group.data(), Group.size()));
   10334 }
   10335 
   10336 void Sema::ActOnDocumentableDecl(Decl *D) {
   10337   ActOnDocumentableDecls(D);
   10338 }
   10339 
   10340 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
   10341   // Don't parse the comment if Doxygen diagnostics are ignored.
   10342   if (Group.empty() || !Group[0])
   10343     return;
   10344 
   10345   if (Diags.isIgnored(diag::warn_doc_param_not_found,
   10346                       Group[0]->getLocation()) &&
   10347       Diags.isIgnored(diag::warn_unknown_comment_command_name,
   10348                       Group[0]->getLocation()))
   10349     return;
   10350 
   10351   if (Group.size() >= 2) {
   10352     // This is a decl group.  Normally it will contain only declarations
   10353     // produced from declarator list.  But in case we have any definitions or
   10354     // additional declaration references:
   10355     //   'typedef struct S {} S;'
   10356     //   'typedef struct S *S;'
   10357     //   'struct S *pS;'
   10358     // FinalizeDeclaratorGroup adds these as separate declarations.
   10359     Decl *MaybeTagDecl = Group[0];
   10360     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
   10361       Group = Group.slice(1);
   10362     }
   10363   }
   10364 
   10365   // See if there are any new comments that are not attached to a decl.
   10366   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
   10367   if (!Comments.empty() &&
   10368       !Comments.back()->isAttached()) {
   10369     // There is at least one comment that not attached to a decl.
   10370     // Maybe it should be attached to one of these decls?
   10371     //
   10372     // Note that this way we pick up not only comments that precede the
   10373     // declaration, but also comments that *follow* the declaration -- thanks to
   10374     // the lookahead in the lexer: we've consumed the semicolon and looked
   10375     // ahead through comments.
   10376     for (unsigned i = 0, e = Group.size(); i != e; ++i)
   10377       Context.getCommentForDecl(Group[i], &PP);
   10378   }
   10379 }
   10380 
   10381 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
   10382 /// to introduce parameters into function prototype scope.
   10383 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
   10384   const DeclSpec &DS = D.getDeclSpec();
   10385 
   10386   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
   10387 
   10388   // C++03 [dcl.stc]p2 also permits 'auto'.
   10389   StorageClass SC = SC_None;
   10390   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
   10391     SC = SC_Register;
   10392   } else if (getLangOpts().CPlusPlus &&
   10393              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
   10394     SC = SC_Auto;
   10395   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
   10396     Diag(DS.getStorageClassSpecLoc(),
   10397          diag::err_invalid_storage_class_in_func_decl);
   10398     D.getMutableDeclSpec().ClearStorageClassSpecs();
   10399   }
   10400 
   10401   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
   10402     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
   10403       << DeclSpec::getSpecifierName(TSCS);
   10404   if (DS.isConstexprSpecified())
   10405     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
   10406       << 0;
   10407   if (DS.isConceptSpecified())
   10408     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
   10409 
   10410   DiagnoseFunctionSpecifiers(DS);
   10411 
   10412   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   10413   QualType parmDeclType = TInfo->getType();
   10414 
   10415   if (getLangOpts().CPlusPlus) {
   10416     // Check that there are no default arguments inside the type of this
   10417     // parameter.
   10418     CheckExtraCXXDefaultArguments(D);
   10419 
   10420     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
   10421     if (D.getCXXScopeSpec().isSet()) {
   10422       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
   10423         << D.getCXXScopeSpec().getRange();
   10424       D.getCXXScopeSpec().clear();
   10425     }
   10426   }
   10427 
   10428   // Ensure we have a valid name
   10429   IdentifierInfo *II = nullptr;
   10430   if (D.hasName()) {
   10431     II = D.getIdentifier();
   10432     if (!II) {
   10433       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
   10434         << GetNameForDeclarator(D).getName();
   10435       D.setInvalidType(true);
   10436     }
   10437   }
   10438 
   10439   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
   10440   if (II) {
   10441     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
   10442                    ForRedeclaration);
   10443     LookupName(R, S);
   10444     if (R.isSingleResult()) {
   10445       NamedDecl *PrevDecl = R.getFoundDecl();
   10446       if (PrevDecl->isTemplateParameter()) {
   10447         // Maybe we will complain about the shadowed template parameter.
   10448         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
   10449         // Just pretend that we didn't see the previous declaration.
   10450         PrevDecl = nullptr;
   10451       } else if (S->isDeclScope(PrevDecl)) {
   10452         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
   10453         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
   10454 
   10455         // Recover by removing the name
   10456         II = nullptr;
   10457         D.SetIdentifier(nullptr, D.getIdentifierLoc());
   10458         D.setInvalidType(true);
   10459       }
   10460     }
   10461   }
   10462 
   10463   // Temporarily put parameter variables in the translation unit, not
   10464   // the enclosing context.  This prevents them from accidentally
   10465   // looking like class members in C++.
   10466   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
   10467                                     D.getLocStart(),
   10468                                     D.getIdentifierLoc(), II,
   10469                                     parmDeclType, TInfo,
   10470                                     SC);
   10471 
   10472   if (D.isInvalidType())
   10473     New->setInvalidDecl();
   10474 
   10475   assert(S->isFunctionPrototypeScope());
   10476   assert(S->getFunctionPrototypeDepth() >= 1);
   10477   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
   10478                     S->getNextFunctionPrototypeIndex());
   10479 
   10480   // Add the parameter declaration into this scope.
   10481   S->AddDecl(New);
   10482   if (II)
   10483     IdResolver.AddDecl(New);
   10484 
   10485   ProcessDeclAttributes(S, New, D);
   10486 
   10487   if (D.getDeclSpec().isModulePrivateSpecified())
   10488     Diag(New->getLocation(), diag::err_module_private_local)
   10489       << 1 << New->getDeclName()
   10490       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
   10491       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
   10492 
   10493   if (New->hasAttr<BlocksAttr>()) {
   10494     Diag(New->getLocation(), diag::err_block_on_nonlocal);
   10495   }
   10496   return New;
   10497 }
   10498 
   10499 /// \brief Synthesizes a variable for a parameter arising from a
   10500 /// typedef.
   10501 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
   10502                                               SourceLocation Loc,
   10503                                               QualType T) {
   10504   /* FIXME: setting StartLoc == Loc.
   10505      Would it be worth to modify callers so as to provide proper source
   10506      location for the unnamed parameters, embedding the parameter's type? */
   10507   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
   10508                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
   10509                                            SC_None, nullptr);
   10510   Param->setImplicit();
   10511   return Param;
   10512 }
   10513 
   10514 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
   10515                                     ParmVarDecl * const *ParamEnd) {
   10516   // Don't diagnose unused-parameter errors in template instantiations; we
   10517   // will already have done so in the template itself.
   10518   if (!ActiveTemplateInstantiations.empty())
   10519     return;
   10520 
   10521   for (; Param != ParamEnd; ++Param) {
   10522     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
   10523         !(*Param)->hasAttr<UnusedAttr>()) {
   10524       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
   10525         << (*Param)->getDeclName();
   10526     }
   10527   }
   10528 }
   10529 
   10530 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
   10531                                                   ParmVarDecl * const *ParamEnd,
   10532                                                   QualType ReturnTy,
   10533                                                   NamedDecl *D) {
   10534   if (LangOpts.NumLargeByValueCopy == 0) // No check.
   10535     return;
   10536 
   10537   // Warn if the return value is pass-by-value and larger than the specified
   10538   // threshold.
   10539   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
   10540     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
   10541     if (Size > LangOpts.NumLargeByValueCopy)
   10542       Diag(D->getLocation(), diag::warn_return_value_size)
   10543           << D->getDeclName() << Size;
   10544   }
   10545 
   10546   // Warn if any parameter is pass-by-value and larger than the specified
   10547   // threshold.
   10548   for (; Param != ParamEnd; ++Param) {
   10549     QualType T = (*Param)->getType();
   10550     if (T->isDependentType() || !T.isPODType(Context))
   10551       continue;
   10552     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
   10553     if (Size > LangOpts.NumLargeByValueCopy)
   10554       Diag((*Param)->getLocation(), diag::warn_parameter_size)
   10555           << (*Param)->getDeclName() << Size;
   10556   }
   10557 }
   10558 
   10559 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
   10560                                   SourceLocation NameLoc, IdentifierInfo *Name,
   10561                                   QualType T, TypeSourceInfo *TSInfo,
   10562                                   StorageClass SC) {
   10563   // In ARC, infer a lifetime qualifier for appropriate parameter types.
   10564   if (getLangOpts().ObjCAutoRefCount &&
   10565       T.getObjCLifetime() == Qualifiers::OCL_None &&
   10566       T->isObjCLifetimeType()) {
   10567 
   10568     Qualifiers::ObjCLifetime lifetime;
   10569 
   10570     // Special cases for arrays:
   10571     //   - if it's const, use __unsafe_unretained
   10572     //   - otherwise, it's an error
   10573     if (T->isArrayType()) {
   10574       if (!T.isConstQualified()) {
   10575         DelayedDiagnostics.add(
   10576             sema::DelayedDiagnostic::makeForbiddenType(
   10577             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
   10578       }
   10579       lifetime = Qualifiers::OCL_ExplicitNone;
   10580     } else {
   10581       lifetime = T->getObjCARCImplicitLifetime();
   10582     }
   10583     T = Context.getLifetimeQualifiedType(T, lifetime);
   10584   }
   10585 
   10586   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
   10587                                          Context.getAdjustedParameterType(T),
   10588                                          TSInfo, SC, nullptr);
   10589 
   10590   // Parameters can not be abstract class types.
   10591   // For record types, this is done by the AbstractClassUsageDiagnoser once
   10592   // the class has been completely parsed.
   10593   if (!CurContext->isRecord() &&
   10594       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
   10595                              AbstractParamType))
   10596     New->setInvalidDecl();
   10597 
   10598   // Parameter declarators cannot be interface types. All ObjC objects are
   10599   // passed by reference.
   10600   if (T->isObjCObjectType()) {
   10601     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
   10602     Diag(NameLoc,
   10603          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
   10604       << FixItHint::CreateInsertion(TypeEndLoc, "*");
   10605     T = Context.getObjCObjectPointerType(T);
   10606     New->setType(T);
   10607   }
   10608 
   10609   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
   10610   // duration shall not be qualified by an address-space qualifier."
   10611   // Since all parameters have automatic store duration, they can not have
   10612   // an address space.
   10613   if (T.getAddressSpace() != 0) {
   10614     // OpenCL allows function arguments declared to be an array of a type
   10615     // to be qualified with an address space.
   10616     if (!(getLangOpts().OpenCL && T->isArrayType())) {
   10617       Diag(NameLoc, diag::err_arg_with_address_space);
   10618       New->setInvalidDecl();
   10619     }
   10620   }
   10621 
   10622   return New;
   10623 }
   10624 
   10625 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
   10626                                            SourceLocation LocAfterDecls) {
   10627   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
   10628 
   10629   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
   10630   // for a K&R function.
   10631   if (!FTI.hasPrototype) {
   10632     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
   10633       --i;
   10634       if (FTI.Params[i].Param == nullptr) {
   10635         SmallString<256> Code;
   10636         llvm::raw_svector_ostream(Code)
   10637             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
   10638         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
   10639             << FTI.Params[i].Ident
   10640             << FixItHint::CreateInsertion(LocAfterDecls, Code);
   10641 
   10642         // Implicitly declare the argument as type 'int' for lack of a better
   10643         // type.
   10644         AttributeFactory attrs;
   10645         DeclSpec DS(attrs);
   10646         const char* PrevSpec; // unused
   10647         unsigned DiagID; // unused
   10648         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
   10649                            DiagID, Context.getPrintingPolicy());
   10650         // Use the identifier location for the type source range.
   10651         DS.SetRangeStart(FTI.Params[i].IdentLoc);
   10652         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
   10653         Declarator ParamD(DS, Declarator::KNRTypeListContext);
   10654         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
   10655         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
   10656       }
   10657     }
   10658   }
   10659 }
   10660 
   10661 Decl *
   10662 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
   10663                               MultiTemplateParamsArg TemplateParameterLists,
   10664                               SkipBodyInfo *SkipBody) {
   10665   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
   10666   assert(D.isFunctionDeclarator() && "Not a function declarator!");
   10667   Scope *ParentScope = FnBodyScope->getParent();
   10668 
   10669   D.setFunctionDefinitionKind(FDK_Definition);
   10670   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
   10671   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
   10672 }
   10673 
   10674 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
   10675   Consumer.HandleInlineMethodDefinition(D);
   10676 }
   10677 
   10678 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
   10679                              const FunctionDecl*& PossibleZeroParamPrototype) {
   10680   // Don't warn about invalid declarations.
   10681   if (FD->isInvalidDecl())
   10682     return false;
   10683 
   10684   // Or declarations that aren't global.
   10685   if (!FD->isGlobal())
   10686     return false;
   10687 
   10688   // Don't warn about C++ member functions.
   10689   if (isa<CXXMethodDecl>(FD))
   10690     return false;
   10691 
   10692   // Don't warn about 'main'.
   10693   if (FD->isMain())
   10694     return false;
   10695 
   10696   // Don't warn about inline functions.
   10697   if (FD->isInlined())
   10698     return false;
   10699 
   10700   // Don't warn about function templates.
   10701   if (FD->getDescribedFunctionTemplate())
   10702     return false;
   10703 
   10704   // Don't warn about function template specializations.
   10705   if (FD->isFunctionTemplateSpecialization())
   10706     return false;
   10707 
   10708   // Don't warn for OpenCL kernels.
   10709   if (FD->hasAttr<OpenCLKernelAttr>())
   10710     return false;
   10711 
   10712   // Don't warn on explicitly deleted functions.
   10713   if (FD->isDeleted())
   10714     return false;
   10715 
   10716   bool MissingPrototype = true;
   10717   for (const FunctionDecl *Prev = FD->getPreviousDecl();
   10718        Prev; Prev = Prev->getPreviousDecl()) {
   10719     // Ignore any declarations that occur in function or method
   10720     // scope, because they aren't visible from the header.
   10721     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
   10722       continue;
   10723 
   10724     MissingPrototype = !Prev->getType()->isFunctionProtoType();
   10725     if (FD->getNumParams() == 0)
   10726       PossibleZeroParamPrototype = Prev;
   10727     break;
   10728   }
   10729 
   10730   return MissingPrototype;
   10731 }
   10732 
   10733 void
   10734 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
   10735                                    const FunctionDecl *EffectiveDefinition,
   10736                                    SkipBodyInfo *SkipBody) {
   10737   // Don't complain if we're in GNU89 mode and the previous definition
   10738   // was an extern inline function.
   10739   const FunctionDecl *Definition = EffectiveDefinition;
   10740   if (!Definition)
   10741     if (!FD->isDefined(Definition))
   10742       return;
   10743 
   10744   if (canRedefineFunction(Definition, getLangOpts()))
   10745     return;
   10746 
   10747   // If we don't have a visible definition of the function, and it's inline or
   10748   // a template, skip the new definition.
   10749   if (SkipBody && !hasVisibleDefinition(Definition) &&
   10750       (Definition->getFormalLinkage() == InternalLinkage ||
   10751        Definition->isInlined() ||
   10752        Definition->getDescribedFunctionTemplate() ||
   10753        Definition->getNumTemplateParameterLists())) {
   10754     SkipBody->ShouldSkip = true;
   10755     if (auto *TD = Definition->getDescribedFunctionTemplate())
   10756       makeMergedDefinitionVisible(TD, FD->getLocation());
   10757     else
   10758       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
   10759                                   FD->getLocation());
   10760     return;
   10761   }
   10762 
   10763   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
   10764       Definition->getStorageClass() == SC_Extern)
   10765     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
   10766         << FD->getDeclName() << getLangOpts().CPlusPlus;
   10767   else
   10768     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
   10769 
   10770   Diag(Definition->getLocation(), diag::note_previous_definition);
   10771   FD->setInvalidDecl();
   10772 }
   10773 
   10774 
   10775 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
   10776                                    Sema &S) {
   10777   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
   10778 
   10779   LambdaScopeInfo *LSI = S.PushLambdaScope();
   10780   LSI->CallOperator = CallOperator;
   10781   LSI->Lambda = LambdaClass;
   10782   LSI->ReturnType = CallOperator->getReturnType();
   10783   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
   10784 
   10785   if (LCD == LCD_None)
   10786     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
   10787   else if (LCD == LCD_ByCopy)
   10788     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
   10789   else if (LCD == LCD_ByRef)
   10790     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
   10791   DeclarationNameInfo DNI = CallOperator->getNameInfo();
   10792 
   10793   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
   10794   LSI->Mutable = !CallOperator->isConst();
   10795 
   10796   // Add the captures to the LSI so they can be noted as already
   10797   // captured within tryCaptureVar.
   10798   auto I = LambdaClass->field_begin();
   10799   for (const auto &C : LambdaClass->captures()) {
   10800     if (C.capturesVariable()) {
   10801       VarDecl *VD = C.getCapturedVar();
   10802       if (VD->isInitCapture())
   10803         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
   10804       QualType CaptureType = VD->getType();
   10805       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
   10806       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
   10807           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
   10808           /*EllipsisLoc*/C.isPackExpansion()
   10809                          ? C.getEllipsisLoc() : SourceLocation(),
   10810           CaptureType, /*Expr*/ nullptr);
   10811 
   10812     } else if (C.capturesThis()) {
   10813       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
   10814                               S.getCurrentThisType(), /*Expr*/ nullptr);
   10815     } else {
   10816       LSI->addVLATypeCapture(C.getLocation(), I->getType());
   10817     }
   10818     ++I;
   10819   }
   10820 }
   10821 
   10822 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
   10823                                     SkipBodyInfo *SkipBody) {
   10824   // Clear the last template instantiation error context.
   10825   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
   10826 
   10827   if (!D)
   10828     return D;
   10829   FunctionDecl *FD = nullptr;
   10830 
   10831   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
   10832     FD = FunTmpl->getTemplatedDecl();
   10833   else
   10834     FD = cast<FunctionDecl>(D);
   10835 
   10836   // See if this is a redefinition.
   10837   if (!FD->isLateTemplateParsed()) {
   10838     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
   10839 
   10840     // If we're skipping the body, we're done. Don't enter the scope.
   10841     if (SkipBody && SkipBody->ShouldSkip)
   10842       return D;
   10843   }
   10844 
   10845   // If we are instantiating a generic lambda call operator, push
   10846   // a LambdaScopeInfo onto the function stack.  But use the information
   10847   // that's already been calculated (ActOnLambdaExpr) to prime the current
   10848   // LambdaScopeInfo.
   10849   // When the template operator is being specialized, the LambdaScopeInfo,
   10850   // has to be properly restored so that tryCaptureVariable doesn't try
   10851   // and capture any new variables. In addition when calculating potential
   10852   // captures during transformation of nested lambdas, it is necessary to
   10853   // have the LSI properly restored.
   10854   if (isGenericLambdaCallOperatorSpecialization(FD)) {
   10855     assert(ActiveTemplateInstantiations.size() &&
   10856       "There should be an active template instantiation on the stack "
   10857       "when instantiating a generic lambda!");
   10858     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
   10859   }
   10860   else
   10861     // Enter a new function scope
   10862     PushFunctionScope();
   10863 
   10864   // Builtin functions cannot be defined.
   10865   if (unsigned BuiltinID = FD->getBuiltinID()) {
   10866     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
   10867         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
   10868       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
   10869       FD->setInvalidDecl();
   10870     }
   10871   }
   10872 
   10873   // The return type of a function definition must be complete
   10874   // (C99 6.9.1p3, C++ [dcl.fct]p6).
   10875   QualType ResultType = FD->getReturnType();
   10876   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
   10877       !FD->isInvalidDecl() &&
   10878       RequireCompleteType(FD->getLocation(), ResultType,
   10879                           diag::err_func_def_incomplete_result))
   10880     FD->setInvalidDecl();
   10881 
   10882   if (FnBodyScope)
   10883     PushDeclContext(FnBodyScope, FD);
   10884 
   10885   // Check the validity of our function parameters
   10886   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
   10887                            /*CheckParameterNames=*/true);
   10888 
   10889   // Introduce our parameters into the function scope
   10890   for (auto Param : FD->params()) {
   10891     Param->setOwningFunction(FD);
   10892 
   10893     // If this has an identifier, add it to the scope stack.
   10894     if (Param->getIdentifier() && FnBodyScope) {
   10895       CheckShadow(FnBodyScope, Param);
   10896 
   10897       PushOnScopeChains(Param, FnBodyScope);
   10898     }
   10899   }
   10900 
   10901   // If we had any tags defined in the function prototype,
   10902   // introduce them into the function scope.
   10903   if (FnBodyScope) {
   10904     for (ArrayRef<NamedDecl *>::iterator
   10905              I = FD->getDeclsInPrototypeScope().begin(),
   10906              E = FD->getDeclsInPrototypeScope().end();
   10907          I != E; ++I) {
   10908       NamedDecl *D = *I;
   10909 
   10910       // Some of these decls (like enums) may have been pinned to the
   10911       // translation unit for lack of a real context earlier. If so, remove
   10912       // from the translation unit and reattach to the current context.
   10913       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
   10914         // Is the decl actually in the context?
   10915         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
   10916           if (DI == D) {
   10917             Context.getTranslationUnitDecl()->removeDecl(D);
   10918             break;
   10919           }
   10920         }
   10921         // Either way, reassign the lexical decl context to our FunctionDecl.
   10922         D->setLexicalDeclContext(CurContext);
   10923       }
   10924 
   10925       // If the decl has a non-null name, make accessible in the current scope.
   10926       if (!D->getName().empty())
   10927         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
   10928 
   10929       // Similarly, dive into enums and fish their constants out, making them
   10930       // accessible in this scope.
   10931       if (auto *ED = dyn_cast<EnumDecl>(D)) {
   10932         for (auto *EI : ED->enumerators())
   10933           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
   10934       }
   10935     }
   10936   }
   10937 
   10938   // Ensure that the function's exception specification is instantiated.
   10939   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
   10940     ResolveExceptionSpec(D->getLocation(), FPT);
   10941 
   10942   // dllimport cannot be applied to non-inline function definitions.
   10943   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
   10944       !FD->isTemplateInstantiation()) {
   10945     assert(!FD->hasAttr<DLLExportAttr>());
   10946     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
   10947     FD->setInvalidDecl();
   10948     return D;
   10949   }
   10950   // We want to attach documentation to original Decl (which might be
   10951   // a function template).
   10952   ActOnDocumentableDecl(D);
   10953   if (getCurLexicalContext()->isObjCContainer() &&
   10954       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
   10955       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
   10956     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
   10957 
   10958   return D;
   10959 }
   10960 
   10961 /// \brief Given the set of return statements within a function body,
   10962 /// compute the variables that are subject to the named return value
   10963 /// optimization.
   10964 ///
   10965 /// Each of the variables that is subject to the named return value
   10966 /// optimization will be marked as NRVO variables in the AST, and any
   10967 /// return statement that has a marked NRVO variable as its NRVO candidate can
   10968 /// use the named return value optimization.
   10969 ///
   10970 /// This function applies a very simplistic algorithm for NRVO: if every return
   10971 /// statement in the scope of a variable has the same NRVO candidate, that
   10972 /// candidate is an NRVO variable.
   10973 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
   10974   ReturnStmt **Returns = Scope->Returns.data();
   10975 
   10976   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
   10977     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
   10978       if (!NRVOCandidate->isNRVOVariable())
   10979         Returns[I]->setNRVOCandidate(nullptr);
   10980     }
   10981   }
   10982 }
   10983 
   10984 bool Sema::canDelayFunctionBody(const Declarator &D) {
   10985   // We can't delay parsing the body of a constexpr function template (yet).
   10986   if (D.getDeclSpec().isConstexprSpecified())
   10987     return false;
   10988 
   10989   // We can't delay parsing the body of a function template with a deduced
   10990   // return type (yet).
   10991   if (D.getDeclSpec().containsPlaceholderType()) {
   10992     // If the placeholder introduces a non-deduced trailing return type,
   10993     // we can still delay parsing it.
   10994     if (D.getNumTypeObjects()) {
   10995       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
   10996       if (Outer.Kind == DeclaratorChunk::Function &&
   10997           Outer.Fun.hasTrailingReturnType()) {
   10998         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
   10999         return Ty.isNull() || !Ty->isUndeducedType();
   11000       }
   11001     }
   11002     return false;
   11003   }
   11004 
   11005   return true;
   11006 }
   11007 
   11008 bool Sema::canSkipFunctionBody(Decl *D) {
   11009   // We cannot skip the body of a function (or function template) which is
   11010   // constexpr, since we may need to evaluate its body in order to parse the
   11011   // rest of the file.
   11012   // We cannot skip the body of a function with an undeduced return type,
   11013   // because any callers of that function need to know the type.
   11014   if (const FunctionDecl *FD = D->getAsFunction())
   11015     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
   11016       return false;
   11017   return Consumer.shouldSkipFunctionBody(D);
   11018 }
   11019 
   11020 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
   11021   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
   11022     FD->setHasSkippedBody();
   11023   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
   11024     MD->setHasSkippedBody();
   11025   return ActOnFinishFunctionBody(Decl, nullptr);
   11026 }
   11027 
   11028 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
   11029   return ActOnFinishFunctionBody(D, BodyArg, false);
   11030 }
   11031 
   11032 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
   11033                                     bool IsInstantiation) {
   11034   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
   11035 
   11036   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
   11037   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
   11038 
   11039   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
   11040     CheckCompletedCoroutineBody(FD, Body);
   11041 
   11042   if (FD) {
   11043     FD->setBody(Body);
   11044 
   11045     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
   11046         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
   11047       // If the function has a deduced result type but contains no 'return'
   11048       // statements, the result type as written must be exactly 'auto', and
   11049       // the deduced result type is 'void'.
   11050       if (!FD->getReturnType()->getAs<AutoType>()) {
   11051         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
   11052             << FD->getReturnType();
   11053         FD->setInvalidDecl();
   11054       } else {
   11055         // Substitute 'void' for the 'auto' in the type.
   11056         TypeLoc ResultType = getReturnTypeLoc(FD);
   11057         Context.adjustDeducedFunctionResultType(
   11058             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
   11059       }
   11060     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
   11061       auto *LSI = getCurLambda();
   11062       if (LSI->HasImplicitReturnType) {
   11063         deduceClosureReturnType(*LSI);
   11064 
   11065         // C++11 [expr.prim.lambda]p4:
   11066         //   [...] if there are no return statements in the compound-statement
   11067         //   [the deduced type is] the type void
   11068         QualType RetType =
   11069             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
   11070 
   11071         // Update the return type to the deduced type.
   11072         const FunctionProtoType *Proto =
   11073             FD->getType()->getAs<FunctionProtoType>();
   11074         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
   11075                                             Proto->getExtProtoInfo()));
   11076       }
   11077     }
   11078 
   11079     // The only way to be included in UndefinedButUsed is if there is an
   11080     // ODR use before the definition. Avoid the expensive map lookup if this
   11081     // is the first declaration.
   11082     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
   11083       if (!FD->isExternallyVisible())
   11084         UndefinedButUsed.erase(FD);
   11085       else if (FD->isInlined() &&
   11086                !LangOpts.GNUInline &&
   11087                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
   11088         UndefinedButUsed.erase(FD);
   11089     }
   11090 
   11091     // If the function implicitly returns zero (like 'main') or is naked,
   11092     // don't complain about missing return statements.
   11093     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
   11094       WP.disableCheckFallThrough();
   11095 
   11096     // MSVC permits the use of pure specifier (=0) on function definition,
   11097     // defined at class scope, warn about this non-standard construct.
   11098     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
   11099       Diag(FD->getLocation(), diag::ext_pure_function_definition);
   11100 
   11101     if (!FD->isInvalidDecl()) {
   11102       // Don't diagnose unused parameters of defaulted or deleted functions.
   11103       if (!FD->isDeleted() && !FD->isDefaulted())
   11104         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
   11105       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
   11106                                              FD->getReturnType(), FD);
   11107 
   11108       // If this is a structor, we need a vtable.
   11109       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
   11110         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
   11111       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
   11112         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
   11113 
   11114       // Try to apply the named return value optimization. We have to check
   11115       // if we can do this here because lambdas keep return statements around
   11116       // to deduce an implicit return type.
   11117       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
   11118           !FD->isDependentContext())
   11119         computeNRVO(Body, getCurFunction());
   11120     }
   11121 
   11122     // GNU warning -Wmissing-prototypes:
   11123     //   Warn if a global function is defined without a previous
   11124     //   prototype declaration. This warning is issued even if the
   11125     //   definition itself provides a prototype. The aim is to detect
   11126     //   global functions that fail to be declared in header files.
   11127     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
   11128     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
   11129       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
   11130 
   11131       if (PossibleZeroParamPrototype) {
   11132         // We found a declaration that is not a prototype,
   11133         // but that could be a zero-parameter prototype
   11134         if (TypeSourceInfo *TI =
   11135                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
   11136           TypeLoc TL = TI->getTypeLoc();
   11137           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
   11138             Diag(PossibleZeroParamPrototype->getLocation(),
   11139                  diag::note_declaration_not_a_prototype)
   11140                 << PossibleZeroParamPrototype
   11141                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
   11142         }
   11143       }
   11144     }
   11145 
   11146     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
   11147       const CXXMethodDecl *KeyFunction;
   11148       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
   11149           MD->isVirtual() &&
   11150           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
   11151           MD == KeyFunction->getCanonicalDecl()) {
   11152         // Update the key-function state if necessary for this ABI.
   11153         if (FD->isInlined() &&
   11154             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
   11155           Context.setNonKeyFunction(MD);
   11156 
   11157           // If the newly-chosen key function is already defined, then we
   11158           // need to mark the vtable as used retroactively.
   11159           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
   11160           const FunctionDecl *Definition;
   11161           if (KeyFunction && KeyFunction->isDefined(Definition))
   11162             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
   11163         } else {
   11164           // We just defined they key function; mark the vtable as used.
   11165           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
   11166         }
   11167       }
   11168     }
   11169 
   11170     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
   11171            "Function parsing confused");
   11172   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
   11173     assert(MD == getCurMethodDecl() && "Method parsing confused");
   11174     MD->setBody(Body);
   11175     if (!MD->isInvalidDecl()) {
   11176       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
   11177       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
   11178                                              MD->getReturnType(), MD);
   11179 
   11180       if (Body)
   11181         computeNRVO(Body, getCurFunction());
   11182     }
   11183     if (getCurFunction()->ObjCShouldCallSuper) {
   11184       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
   11185         << MD->getSelector().getAsString();
   11186       getCurFunction()->ObjCShouldCallSuper = false;
   11187     }
   11188     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
   11189       const ObjCMethodDecl *InitMethod = nullptr;
   11190       bool isDesignated =
   11191           MD->isDesignatedInitializerForTheInterface(&InitMethod);
   11192       assert(isDesignated && InitMethod);
   11193       (void)isDesignated;
   11194 
   11195       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
   11196         auto IFace = MD->getClassInterface();
   11197         if (!IFace)
   11198           return false;
   11199         auto SuperD = IFace->getSuperClass();
   11200         if (!SuperD)
   11201           return false;
   11202         return SuperD->getIdentifier() ==
   11203             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
   11204       };
   11205       // Don't issue this warning for unavailable inits or direct subclasses
   11206       // of NSObject.
   11207       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
   11208         Diag(MD->getLocation(),
   11209              diag::warn_objc_designated_init_missing_super_call);
   11210         Diag(InitMethod->getLocation(),
   11211              diag::note_objc_designated_init_marked_here);
   11212       }
   11213       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
   11214     }
   11215     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
   11216       // Don't issue this warning for unavaialable inits.
   11217       if (!MD->isUnavailable())
   11218         Diag(MD->getLocation(),
   11219              diag::warn_objc_secondary_init_missing_init_call);
   11220       getCurFunction()->ObjCWarnForNoInitDelegation = false;
   11221     }
   11222   } else {
   11223     return nullptr;
   11224   }
   11225 
   11226   assert(!getCurFunction()->ObjCShouldCallSuper &&
   11227          "This should only be set for ObjC methods, which should have been "
   11228          "handled in the block above.");
   11229 
   11230   // Verify and clean out per-function state.
   11231   if (Body && (!FD || !FD->isDefaulted())) {
   11232     // C++ constructors that have function-try-blocks can't have return
   11233     // statements in the handlers of that block. (C++ [except.handle]p14)
   11234     // Verify this.
   11235     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
   11236       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
   11237 
   11238     // Verify that gotos and switch cases don't jump into scopes illegally.
   11239     if (getCurFunction()->NeedsScopeChecking() &&
   11240         !PP.isCodeCompletionEnabled())
   11241       DiagnoseInvalidJumps(Body);
   11242 
   11243     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
   11244       if (!Destructor->getParent()->isDependentType())
   11245         CheckDestructor(Destructor);
   11246 
   11247       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
   11248                                              Destructor->getParent());
   11249     }
   11250 
   11251     // If any errors have occurred, clear out any temporaries that may have
   11252     // been leftover. This ensures that these temporaries won't be picked up for
   11253     // deletion in some later function.
   11254     if (getDiagnostics().hasErrorOccurred() ||
   11255         getDiagnostics().getSuppressAllDiagnostics()) {
   11256       DiscardCleanupsInEvaluationContext();
   11257     }
   11258     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
   11259         !isa<FunctionTemplateDecl>(dcl)) {
   11260       // Since the body is valid, issue any analysis-based warnings that are
   11261       // enabled.
   11262       ActivePolicy = &WP;
   11263     }
   11264 
   11265     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
   11266         (!CheckConstexprFunctionDecl(FD) ||
   11267          !CheckConstexprFunctionBody(FD, Body)))
   11268       FD->setInvalidDecl();
   11269 
   11270     if (FD && FD->hasAttr<NakedAttr>()) {
   11271       for (const Stmt *S : Body->children()) {
   11272         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
   11273           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
   11274           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
   11275           FD->setInvalidDecl();
   11276           break;
   11277         }
   11278       }
   11279     }
   11280 
   11281     assert(ExprCleanupObjects.size() ==
   11282                ExprEvalContexts.back().NumCleanupObjects &&
   11283            "Leftover temporaries in function");
   11284     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
   11285     assert(MaybeODRUseExprs.empty() &&
   11286            "Leftover expressions for odr-use checking");
   11287   }
   11288 
   11289   if (!IsInstantiation)
   11290     PopDeclContext();
   11291 
   11292   PopFunctionScopeInfo(ActivePolicy, dcl);
   11293   // If any errors have occurred, clear out any temporaries that may have
   11294   // been leftover. This ensures that these temporaries won't be picked up for
   11295   // deletion in some later function.
   11296   if (getDiagnostics().hasErrorOccurred()) {
   11297     DiscardCleanupsInEvaluationContext();
   11298   }
   11299 
   11300   return dcl;
   11301 }
   11302 
   11303 
   11304 /// When we finish delayed parsing of an attribute, we must attach it to the
   11305 /// relevant Decl.
   11306 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
   11307                                        ParsedAttributes &Attrs) {
   11308   // Always attach attributes to the underlying decl.
   11309   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
   11310     D = TD->getTemplatedDecl();
   11311   ProcessDeclAttributeList(S, D, Attrs.getList());
   11312 
   11313   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
   11314     if (Method->isStatic())
   11315       checkThisInStaticMemberFunctionAttributes(Method);
   11316 }
   11317 
   11318 
   11319 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
   11320 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
   11321 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
   11322                                           IdentifierInfo &II, Scope *S) {
   11323   // Before we produce a declaration for an implicitly defined
   11324   // function, see whether there was a locally-scoped declaration of
   11325   // this name as a function or variable. If so, use that
   11326   // (non-visible) declaration, and complain about it.
   11327   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
   11328     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
   11329     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
   11330     return ExternCPrev;
   11331   }
   11332 
   11333   // Extension in C99.  Legal in C90, but warn about it.
   11334   unsigned diag_id;
   11335   if (II.getName().startswith("__builtin_"))
   11336     diag_id = diag::warn_builtin_unknown;
   11337   else if (getLangOpts().C99)
   11338     diag_id = diag::ext_implicit_function_decl;
   11339   else
   11340     diag_id = diag::warn_implicit_function_decl;
   11341   Diag(Loc, diag_id) << &II;
   11342 
   11343   // Because typo correction is expensive, only do it if the implicit
   11344   // function declaration is going to be treated as an error.
   11345   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
   11346     TypoCorrection Corrected;
   11347     if (S &&
   11348         (Corrected = CorrectTypo(
   11349              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
   11350              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
   11351       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
   11352                    /*ErrorRecovery*/false);
   11353   }
   11354 
   11355   // Set a Declarator for the implicit definition: int foo();
   11356   const char *Dummy;
   11357   AttributeFactory attrFactory;
   11358   DeclSpec DS(attrFactory);
   11359   unsigned DiagID;
   11360   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
   11361                                   Context.getPrintingPolicy());
   11362   (void)Error; // Silence warning.
   11363   assert(!Error && "Error setting up implicit decl!");
   11364   SourceLocation NoLoc;
   11365   Declarator D(DS, Declarator::BlockContext);
   11366   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
   11367                                              /*IsAmbiguous=*/false,
   11368                                              /*LParenLoc=*/NoLoc,
   11369                                              /*Params=*/nullptr,
   11370                                              /*NumParams=*/0,
   11371                                              /*EllipsisLoc=*/NoLoc,
   11372                                              /*RParenLoc=*/NoLoc,
   11373                                              /*TypeQuals=*/0,
   11374                                              /*RefQualifierIsLvalueRef=*/true,
   11375                                              /*RefQualifierLoc=*/NoLoc,
   11376                                              /*ConstQualifierLoc=*/NoLoc,
   11377                                              /*VolatileQualifierLoc=*/NoLoc,
   11378                                              /*RestrictQualifierLoc=*/NoLoc,
   11379                                              /*MutableLoc=*/NoLoc,
   11380                                              EST_None,
   11381                                              /*ESpecRange=*/SourceRange(),
   11382                                              /*Exceptions=*/nullptr,
   11383                                              /*ExceptionRanges=*/nullptr,
   11384                                              /*NumExceptions=*/0,
   11385                                              /*NoexceptExpr=*/nullptr,
   11386                                              /*ExceptionSpecTokens=*/nullptr,
   11387                                              Loc, Loc, D),
   11388                 DS.getAttributes(),
   11389                 SourceLocation());
   11390   D.SetIdentifier(&II, Loc);
   11391 
   11392   // Insert this function into translation-unit scope.
   11393 
   11394   DeclContext *PrevDC = CurContext;
   11395   CurContext = Context.getTranslationUnitDecl();
   11396 
   11397   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
   11398   FD->setImplicit();
   11399 
   11400   CurContext = PrevDC;
   11401 
   11402   AddKnownFunctionAttributes(FD);
   11403 
   11404   return FD;
   11405 }
   11406 
   11407 /// \brief Adds any function attributes that we know a priori based on
   11408 /// the declaration of this function.
   11409 ///
   11410 /// These attributes can apply both to implicitly-declared builtins
   11411 /// (like __builtin___printf_chk) or to library-declared functions
   11412 /// like NSLog or printf.
   11413 ///
   11414 /// We need to check for duplicate attributes both here and where user-written
   11415 /// attributes are applied to declarations.
   11416 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
   11417   if (FD->isInvalidDecl())
   11418     return;
   11419 
   11420   // If this is a built-in function, map its builtin attributes to
   11421   // actual attributes.
   11422   if (unsigned BuiltinID = FD->getBuiltinID()) {
   11423     // Handle printf-formatting attributes.
   11424     unsigned FormatIdx;
   11425     bool HasVAListArg;
   11426     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
   11427       if (!FD->hasAttr<FormatAttr>()) {
   11428         const char *fmt = "printf";
   11429         unsigned int NumParams = FD->getNumParams();
   11430         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
   11431             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
   11432           fmt = "NSString";
   11433         FD->addAttr(FormatAttr::CreateImplicit(Context,
   11434                                                &Context.Idents.get(fmt),
   11435                                                FormatIdx+1,
   11436                                                HasVAListArg ? 0 : FormatIdx+2,
   11437                                                FD->getLocation()));
   11438       }
   11439     }
   11440     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
   11441                                              HasVAListArg)) {
   11442      if (!FD->hasAttr<FormatAttr>())
   11443        FD->addAttr(FormatAttr::CreateImplicit(Context,
   11444                                               &Context.Idents.get("scanf"),
   11445                                               FormatIdx+1,
   11446                                               HasVAListArg ? 0 : FormatIdx+2,
   11447                                               FD->getLocation()));
   11448     }
   11449 
   11450     // Mark const if we don't care about errno and that is the only
   11451     // thing preventing the function from being const. This allows
   11452     // IRgen to use LLVM intrinsics for such functions.
   11453     if (!getLangOpts().MathErrno &&
   11454         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
   11455       if (!FD->hasAttr<ConstAttr>())
   11456         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
   11457     }
   11458 
   11459     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
   11460         !FD->hasAttr<ReturnsTwiceAttr>())
   11461       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
   11462                                          FD->getLocation()));
   11463     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
   11464       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
   11465     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
   11466       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
   11467     if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
   11468         Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
   11469         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
   11470       // Assign appropriate attribute depending on CUDA compilation
   11471       // mode and the target builtin belongs to. E.g. during host
   11472       // compilation, aux builtins are __device__, the rest are __host__.
   11473       if (getLangOpts().CUDAIsDevice !=
   11474           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
   11475         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
   11476       else
   11477         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
   11478     }
   11479   }
   11480 
   11481   IdentifierInfo *Name = FD->getIdentifier();
   11482   if (!Name)
   11483     return;
   11484   if ((!getLangOpts().CPlusPlus &&
   11485        FD->getDeclContext()->isTranslationUnit()) ||
   11486       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
   11487        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
   11488        LinkageSpecDecl::lang_c)) {
   11489     // Okay: this could be a libc/libm/Objective-C function we know
   11490     // about.
   11491   } else
   11492     return;
   11493 
   11494   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
   11495     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
   11496     // target-specific builtins, perhaps?
   11497     if (!FD->hasAttr<FormatAttr>())
   11498       FD->addAttr(FormatAttr::CreateImplicit(Context,
   11499                                              &Context.Idents.get("printf"), 2,
   11500                                              Name->isStr("vasprintf") ? 0 : 3,
   11501                                              FD->getLocation()));
   11502   }
   11503 
   11504   if (Name->isStr("__CFStringMakeConstantString")) {
   11505     // We already have a __builtin___CFStringMakeConstantString,
   11506     // but builds that use -fno-constant-cfstrings don't go through that.
   11507     if (!FD->hasAttr<FormatArgAttr>())
   11508       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
   11509                                                 FD->getLocation()));
   11510   }
   11511 }
   11512 
   11513 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
   11514                                     TypeSourceInfo *TInfo) {
   11515   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
   11516   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
   11517 
   11518   if (!TInfo) {
   11519     assert(D.isInvalidType() && "no declarator info for valid type");
   11520     TInfo = Context.getTrivialTypeSourceInfo(T);
   11521   }
   11522 
   11523   // Scope manipulation handled by caller.
   11524   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
   11525                                            D.getLocStart(),
   11526                                            D.getIdentifierLoc(),
   11527                                            D.getIdentifier(),
   11528                                            TInfo);
   11529 
   11530   // Bail out immediately if we have an invalid declaration.
   11531   if (D.isInvalidType()) {
   11532     NewTD->setInvalidDecl();
   11533     return NewTD;
   11534   }
   11535 
   11536   if (D.getDeclSpec().isModulePrivateSpecified()) {
   11537     if (CurContext->isFunctionOrMethod())
   11538       Diag(NewTD->getLocation(), diag::err_module_private_local)
   11539         << 2 << NewTD->getDeclName()
   11540         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
   11541         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
   11542     else
   11543       NewTD->setModulePrivate();
   11544   }
   11545 
   11546   // C++ [dcl.typedef]p8:
   11547   //   If the typedef declaration defines an unnamed class (or
   11548   //   enum), the first typedef-name declared by the declaration
   11549   //   to be that class type (or enum type) is used to denote the
   11550   //   class type (or enum type) for linkage purposes only.
   11551   // We need to check whether the type was declared in the declaration.
   11552   switch (D.getDeclSpec().getTypeSpecType()) {
   11553   case TST_enum:
   11554   case TST_struct:
   11555   case TST_interface:
   11556   case TST_union:
   11557   case TST_class: {
   11558     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
   11559     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
   11560     break;
   11561   }
   11562 
   11563   default:
   11564     break;
   11565   }
   11566 
   11567   return NewTD;
   11568 }
   11569 
   11570 
   11571 /// \brief Check that this is a valid underlying type for an enum declaration.
   11572 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
   11573   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
   11574   QualType T = TI->getType();
   11575 
   11576   if (T->isDependentType())
   11577     return false;
   11578 
   11579   if (const BuiltinType *BT = T->getAs<BuiltinType>())
   11580     if (BT->isInteger())
   11581       return false;
   11582 
   11583   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
   11584   return true;
   11585 }
   11586 
   11587 /// Check whether this is a valid redeclaration of a previous enumeration.
   11588 /// \return true if the redeclaration was invalid.
   11589 bool Sema::CheckEnumRedeclaration(
   11590     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
   11591     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
   11592   bool IsFixed = !EnumUnderlyingTy.isNull();
   11593 
   11594   if (IsScoped != Prev->isScoped()) {
   11595     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
   11596       << Prev->isScoped();
   11597     Diag(Prev->getLocation(), diag::note_previous_declaration);
   11598     return true;
   11599   }
   11600 
   11601   if (IsFixed && Prev->isFixed()) {
   11602     if (!EnumUnderlyingTy->isDependentType() &&
   11603         !Prev->getIntegerType()->isDependentType() &&
   11604         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
   11605                                         Prev->getIntegerType())) {
   11606       // TODO: Highlight the underlying type of the redeclaration.
   11607       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
   11608         << EnumUnderlyingTy << Prev->getIntegerType();
   11609       Diag(Prev->getLocation(), diag::note_previous_declaration)
   11610           << Prev->getIntegerTypeRange();
   11611       return true;
   11612     }
   11613   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
   11614     ;
   11615   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
   11616     ;
   11617   } else if (IsFixed != Prev->isFixed()) {
   11618     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
   11619       << Prev->isFixed();
   11620     Diag(Prev->getLocation(), diag::note_previous_declaration);
   11621     return true;
   11622   }
   11623 
   11624   return false;
   11625 }
   11626 
   11627 /// \brief Get diagnostic %select index for tag kind for
   11628 /// redeclaration diagnostic message.
   11629 /// WARNING: Indexes apply to particular diagnostics only!
   11630 ///
   11631 /// \returns diagnostic %select index.
   11632 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
   11633   switch (Tag) {
   11634   case TTK_Struct: return 0;
   11635   case TTK_Interface: return 1;
   11636   case TTK_Class:  return 2;
   11637   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
   11638   }
   11639 }
   11640 
   11641 /// \brief Determine if tag kind is a class-key compatible with
   11642 /// class for redeclaration (class, struct, or __interface).
   11643 ///
   11644 /// \returns true iff the tag kind is compatible.
   11645 static bool isClassCompatTagKind(TagTypeKind Tag)
   11646 {
   11647   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
   11648 }
   11649 
   11650 /// \brief Determine whether a tag with a given kind is acceptable
   11651 /// as a redeclaration of the given tag declaration.
   11652 ///
   11653 /// \returns true if the new tag kind is acceptable, false otherwise.
   11654 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
   11655                                         TagTypeKind NewTag, bool isDefinition,
   11656                                         SourceLocation NewTagLoc,
   11657                                         const IdentifierInfo *Name) {
   11658   // C++ [dcl.type.elab]p3:
   11659   //   The class-key or enum keyword present in the
   11660   //   elaborated-type-specifier shall agree in kind with the
   11661   //   declaration to which the name in the elaborated-type-specifier
   11662   //   refers. This rule also applies to the form of
   11663   //   elaborated-type-specifier that declares a class-name or
   11664   //   friend class since it can be construed as referring to the
   11665   //   definition of the class. Thus, in any
   11666   //   elaborated-type-specifier, the enum keyword shall be used to
   11667   //   refer to an enumeration (7.2), the union class-key shall be
   11668   //   used to refer to a union (clause 9), and either the class or
   11669   //   struct class-key shall be used to refer to a class (clause 9)
   11670   //   declared using the class or struct class-key.
   11671   TagTypeKind OldTag = Previous->getTagKind();
   11672   if (!isDefinition || !isClassCompatTagKind(NewTag))
   11673     if (OldTag == NewTag)
   11674       return true;
   11675 
   11676   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
   11677     // Warn about the struct/class tag mismatch.
   11678     bool isTemplate = false;
   11679     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
   11680       isTemplate = Record->getDescribedClassTemplate();
   11681 
   11682     if (!ActiveTemplateInstantiations.empty()) {
   11683       // In a template instantiation, do not offer fix-its for tag mismatches
   11684       // since they usually mess up the template instead of fixing the problem.
   11685       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
   11686         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
   11687         << getRedeclDiagFromTagKind(OldTag);
   11688       return true;
   11689     }
   11690 
   11691     if (isDefinition) {
   11692       // On definitions, check previous tags and issue a fix-it for each
   11693       // one that doesn't match the current tag.
   11694       if (Previous->getDefinition()) {
   11695         // Don't suggest fix-its for redefinitions.
   11696         return true;
   11697       }
   11698 
   11699       bool previousMismatch = false;
   11700       for (auto I : Previous->redecls()) {
   11701         if (I->getTagKind() != NewTag) {
   11702           if (!previousMismatch) {
   11703             previousMismatch = true;
   11704             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
   11705               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
   11706               << getRedeclDiagFromTagKind(I->getTagKind());
   11707           }
   11708           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
   11709             << getRedeclDiagFromTagKind(NewTag)
   11710             << FixItHint::CreateReplacement(I->getInnerLocStart(),
   11711                  TypeWithKeyword::getTagTypeKindName(NewTag));
   11712         }
   11713       }
   11714       return true;
   11715     }
   11716 
   11717     // Check for a previous definition.  If current tag and definition
   11718     // are same type, do nothing.  If no definition, but disagree with
   11719     // with previous tag type, give a warning, but no fix-it.
   11720     const TagDecl *Redecl = Previous->getDefinition() ?
   11721                             Previous->getDefinition() : Previous;
   11722     if (Redecl->getTagKind() == NewTag) {
   11723       return true;
   11724     }
   11725 
   11726     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
   11727       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
   11728       << getRedeclDiagFromTagKind(OldTag);
   11729     Diag(Redecl->getLocation(), diag::note_previous_use);
   11730 
   11731     // If there is a previous definition, suggest a fix-it.
   11732     if (Previous->getDefinition()) {
   11733         Diag(NewTagLoc, diag::note_struct_class_suggestion)
   11734           << getRedeclDiagFromTagKind(Redecl->getTagKind())
   11735           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
   11736                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
   11737     }
   11738 
   11739     return true;
   11740   }
   11741   return false;
   11742 }
   11743 
   11744 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
   11745 /// from an outer enclosing namespace or file scope inside a friend declaration.
   11746 /// This should provide the commented out code in the following snippet:
   11747 ///   namespace N {
   11748 ///     struct X;
   11749 ///     namespace M {
   11750 ///       struct Y { friend struct /*N::*/ X; };
   11751 ///     }
   11752 ///   }
   11753 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
   11754                                          SourceLocation NameLoc) {
   11755   // While the decl is in a namespace, do repeated lookup of that name and see
   11756   // if we get the same namespace back.  If we do not, continue until
   11757   // translation unit scope, at which point we have a fully qualified NNS.
   11758   SmallVector<IdentifierInfo *, 4> Namespaces;
   11759   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
   11760   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
   11761     // This tag should be declared in a namespace, which can only be enclosed by
   11762     // other namespaces.  Bail if there's an anonymous namespace in the chain.
   11763     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
   11764     if (!Namespace || Namespace->isAnonymousNamespace())
   11765       return FixItHint();
   11766     IdentifierInfo *II = Namespace->getIdentifier();
   11767     Namespaces.push_back(II);
   11768     NamedDecl *Lookup = SemaRef.LookupSingleName(
   11769         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
   11770     if (Lookup == Namespace)
   11771       break;
   11772   }
   11773 
   11774   // Once we have all the namespaces, reverse them to go outermost first, and
   11775   // build an NNS.
   11776   SmallString<64> Insertion;
   11777   llvm::raw_svector_ostream OS(Insertion);
   11778   if (DC->isTranslationUnit())
   11779     OS << "::";
   11780   std::reverse(Namespaces.begin(), Namespaces.end());
   11781   for (auto *II : Namespaces)
   11782     OS << II->getName() << "::";
   11783   return FixItHint::CreateInsertion(NameLoc, Insertion);
   11784 }
   11785 
   11786 /// \brief Determine whether a tag originally declared in context \p OldDC can
   11787 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
   11788 /// found a declaration in \p OldDC as a previous decl, perhaps through a
   11789 /// using-declaration).
   11790 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
   11791                                          DeclContext *NewDC) {
   11792   OldDC = OldDC->getRedeclContext();
   11793   NewDC = NewDC->getRedeclContext();
   11794 
   11795   if (OldDC->Equals(NewDC))
   11796     return true;
   11797 
   11798   // In MSVC mode, we allow a redeclaration if the contexts are related (either
   11799   // encloses the other).
   11800   if (S.getLangOpts().MSVCCompat &&
   11801       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
   11802     return true;
   11803 
   11804   return false;
   11805 }
   11806 
   11807 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
   11808 /// former case, Name will be non-null.  In the later case, Name will be null.
   11809 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
   11810 /// reference/declaration/definition of a tag.
   11811 ///
   11812 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
   11813 /// trailing-type-specifier) other than one in an alias-declaration.
   11814 ///
   11815 /// \param SkipBody If non-null, will be set to indicate if the caller should
   11816 /// skip the definition of this tag and treat it as if it were a declaration.
   11817 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
   11818                      SourceLocation KWLoc, CXXScopeSpec &SS,
   11819                      IdentifierInfo *Name, SourceLocation NameLoc,
   11820                      AttributeList *Attr, AccessSpecifier AS,
   11821                      SourceLocation ModulePrivateLoc,
   11822                      MultiTemplateParamsArg TemplateParameterLists,
   11823                      bool &OwnedDecl, bool &IsDependent,
   11824                      SourceLocation ScopedEnumKWLoc,
   11825                      bool ScopedEnumUsesClassTag,
   11826                      TypeResult UnderlyingType,
   11827                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
   11828   // If this is not a definition, it must have a name.
   11829   IdentifierInfo *OrigName = Name;
   11830   assert((Name != nullptr || TUK == TUK_Definition) &&
   11831          "Nameless record must be a definition!");
   11832   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
   11833 
   11834   OwnedDecl = false;
   11835   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
   11836   bool ScopedEnum = ScopedEnumKWLoc.isValid();
   11837 
   11838   // FIXME: Check explicit specializations more carefully.
   11839   bool isExplicitSpecialization = false;
   11840   bool Invalid = false;
   11841 
   11842   // We only need to do this matching if we have template parameters
   11843   // or a scope specifier, which also conveniently avoids this work
   11844   // for non-C++ cases.
   11845   if (TemplateParameterLists.size() > 0 ||
   11846       (SS.isNotEmpty() && TUK != TUK_Reference)) {
   11847     if (TemplateParameterList *TemplateParams =
   11848             MatchTemplateParametersToScopeSpecifier(
   11849                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
   11850                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
   11851       if (Kind == TTK_Enum) {
   11852         Diag(KWLoc, diag::err_enum_template);
   11853         return nullptr;
   11854       }
   11855 
   11856       if (TemplateParams->size() > 0) {
   11857         // This is a declaration or definition of a class template (which may
   11858         // be a member of another template).
   11859 
   11860         if (Invalid)
   11861           return nullptr;
   11862 
   11863         OwnedDecl = false;
   11864         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
   11865                                                SS, Name, NameLoc, Attr,
   11866                                                TemplateParams, AS,
   11867                                                ModulePrivateLoc,
   11868                                                /*FriendLoc*/SourceLocation(),
   11869                                                TemplateParameterLists.size()-1,
   11870                                                TemplateParameterLists.data(),
   11871                                                SkipBody);
   11872         return Result.get();
   11873       } else {
   11874         // The "template<>" header is extraneous.
   11875         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
   11876           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
   11877         isExplicitSpecialization = true;
   11878       }
   11879     }
   11880   }
   11881 
   11882   // Figure out the underlying type if this a enum declaration. We need to do
   11883   // this early, because it's needed to detect if this is an incompatible
   11884   // redeclaration.
   11885   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
   11886   bool EnumUnderlyingIsImplicit = false;
   11887 
   11888   if (Kind == TTK_Enum) {
   11889     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
   11890       // No underlying type explicitly specified, or we failed to parse the
   11891       // type, default to int.
   11892       EnumUnderlying = Context.IntTy.getTypePtr();
   11893     else if (UnderlyingType.get()) {
   11894       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
   11895       // integral type; any cv-qualification is ignored.
   11896       TypeSourceInfo *TI = nullptr;
   11897       GetTypeFromParser(UnderlyingType.get(), &TI);
   11898       EnumUnderlying = TI;
   11899 
   11900       if (CheckEnumUnderlyingType(TI))
   11901         // Recover by falling back to int.
   11902         EnumUnderlying = Context.IntTy.getTypePtr();
   11903 
   11904       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
   11905                                           UPPC_FixedUnderlyingType))
   11906         EnumUnderlying = Context.IntTy.getTypePtr();
   11907 
   11908     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
   11909       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
   11910         // Microsoft enums are always of int type.
   11911         EnumUnderlying = Context.IntTy.getTypePtr();
   11912         EnumUnderlyingIsImplicit = true;
   11913       }
   11914     }
   11915   }
   11916 
   11917   DeclContext *SearchDC = CurContext;
   11918   DeclContext *DC = CurContext;
   11919   bool isStdBadAlloc = false;
   11920 
   11921   RedeclarationKind Redecl = ForRedeclaration;
   11922   if (TUK == TUK_Friend || TUK == TUK_Reference)
   11923     Redecl = NotForRedeclaration;
   11924 
   11925   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
   11926   if (Name && SS.isNotEmpty()) {
   11927     // We have a nested-name tag ('struct foo::bar').
   11928 
   11929     // Check for invalid 'foo::'.
   11930     if (SS.isInvalid()) {
   11931       Name = nullptr;
   11932       goto CreateNewDecl;
   11933     }
   11934 
   11935     // If this is a friend or a reference to a class in a dependent
   11936     // context, don't try to make a decl for it.
   11937     if (TUK == TUK_Friend || TUK == TUK_Reference) {
   11938       DC = computeDeclContext(SS, false);
   11939       if (!DC) {
   11940         IsDependent = true;
   11941         return nullptr;
   11942       }
   11943     } else {
   11944       DC = computeDeclContext(SS, true);
   11945       if (!DC) {
   11946         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
   11947           << SS.getRange();
   11948         return nullptr;
   11949       }
   11950     }
   11951 
   11952     if (RequireCompleteDeclContext(SS, DC))
   11953       return nullptr;
   11954 
   11955     SearchDC = DC;
   11956     // Look-up name inside 'foo::'.
   11957     LookupQualifiedName(Previous, DC);
   11958 
   11959     if (Previous.isAmbiguous())
   11960       return nullptr;
   11961 
   11962     if (Previous.empty()) {
   11963       // Name lookup did not find anything. However, if the
   11964       // nested-name-specifier refers to the current instantiation,
   11965       // and that current instantiation has any dependent base
   11966       // classes, we might find something at instantiation time: treat
   11967       // this as a dependent elaborated-type-specifier.
   11968       // But this only makes any sense for reference-like lookups.
   11969       if (Previous.wasNotFoundInCurrentInstantiation() &&
   11970           (TUK == TUK_Reference || TUK == TUK_Friend)) {
   11971         IsDependent = true;
   11972         return nullptr;
   11973       }
   11974 
   11975       // A tag 'foo::bar' must already exist.
   11976       Diag(NameLoc, diag::err_not_tag_in_scope)
   11977         << Kind << Name << DC << SS.getRange();
   11978       Name = nullptr;
   11979       Invalid = true;
   11980       goto CreateNewDecl;
   11981     }
   11982   } else if (Name) {
   11983     // C++14 [class.mem]p14:
   11984     //   If T is the name of a class, then each of the following shall have a
   11985     //   name different from T:
   11986     //    -- every member of class T that is itself a type
   11987     if (TUK != TUK_Reference && TUK != TUK_Friend &&
   11988         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
   11989       return nullptr;
   11990 
   11991     // If this is a named struct, check to see if there was a previous forward
   11992     // declaration or definition.
   11993     // FIXME: We're looking into outer scopes here, even when we
   11994     // shouldn't be. Doing so can result in ambiguities that we
   11995     // shouldn't be diagnosing.
   11996     LookupName(Previous, S);
   11997 
   11998     // When declaring or defining a tag, ignore ambiguities introduced
   11999     // by types using'ed into this scope.
   12000     if (Previous.isAmbiguous() &&
   12001         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
   12002       LookupResult::Filter F = Previous.makeFilter();
   12003       while (F.hasNext()) {
   12004         NamedDecl *ND = F.next();
   12005         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
   12006           F.erase();
   12007       }
   12008       F.done();
   12009     }
   12010 
   12011     // C++11 [namespace.memdef]p3:
   12012     //   If the name in a friend declaration is neither qualified nor
   12013     //   a template-id and the declaration is a function or an
   12014     //   elaborated-type-specifier, the lookup to determine whether
   12015     //   the entity has been previously declared shall not consider
   12016     //   any scopes outside the innermost enclosing namespace.
   12017     //
   12018     // MSVC doesn't implement the above rule for types, so a friend tag
   12019     // declaration may be a redeclaration of a type declared in an enclosing
   12020     // scope.  They do implement this rule for friend functions.
   12021     //
   12022     // Does it matter that this should be by scope instead of by
   12023     // semantic context?
   12024     if (!Previous.empty() && TUK == TUK_Friend) {
   12025       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
   12026       LookupResult::Filter F = Previous.makeFilter();
   12027       bool FriendSawTagOutsideEnclosingNamespace = false;
   12028       while (F.hasNext()) {
   12029         NamedDecl *ND = F.next();
   12030         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
   12031         if (DC->isFileContext() &&
   12032             !EnclosingNS->Encloses(ND->getDeclContext())) {
   12033           if (getLangOpts().MSVCCompat)
   12034             FriendSawTagOutsideEnclosingNamespace = true;
   12035           else
   12036             F.erase();
   12037         }
   12038       }
   12039       F.done();
   12040 
   12041       // Diagnose this MSVC extension in the easy case where lookup would have
   12042       // unambiguously found something outside the enclosing namespace.
   12043       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
   12044         NamedDecl *ND = Previous.getFoundDecl();
   12045         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
   12046             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
   12047       }
   12048     }
   12049 
   12050     // Note:  there used to be some attempt at recovery here.
   12051     if (Previous.isAmbiguous())
   12052       return nullptr;
   12053 
   12054     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
   12055       // FIXME: This makes sure that we ignore the contexts associated
   12056       // with C structs, unions, and enums when looking for a matching
   12057       // tag declaration or definition. See the similar lookup tweak
   12058       // in Sema::LookupName; is there a better way to deal with this?
   12059       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
   12060         SearchDC = SearchDC->getParent();
   12061     }
   12062   }
   12063 
   12064   if (Previous.isSingleResult() &&
   12065       Previous.getFoundDecl()->isTemplateParameter()) {
   12066     // Maybe we will complain about the shadowed template parameter.
   12067     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
   12068     // Just pretend that we didn't see the previous declaration.
   12069     Previous.clear();
   12070   }
   12071 
   12072   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
   12073       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
   12074     // This is a declaration of or a reference to "std::bad_alloc".
   12075     isStdBadAlloc = true;
   12076 
   12077     if (Previous.empty() && StdBadAlloc) {
   12078       // std::bad_alloc has been implicitly declared (but made invisible to
   12079       // name lookup). Fill in this implicit declaration as the previous
   12080       // declaration, so that the declarations get chained appropriately.
   12081       Previous.addDecl(getStdBadAlloc());
   12082     }
   12083   }
   12084 
   12085   // If we didn't find a previous declaration, and this is a reference
   12086   // (or friend reference), move to the correct scope.  In C++, we
   12087   // also need to do a redeclaration lookup there, just in case
   12088   // there's a shadow friend decl.
   12089   if (Name && Previous.empty() &&
   12090       (TUK == TUK_Reference || TUK == TUK_Friend)) {
   12091     if (Invalid) goto CreateNewDecl;
   12092     assert(SS.isEmpty());
   12093 
   12094     if (TUK == TUK_Reference) {
   12095       // C++ [basic.scope.pdecl]p5:
   12096       //   -- for an elaborated-type-specifier of the form
   12097       //
   12098       //          class-key identifier
   12099       //
   12100       //      if the elaborated-type-specifier is used in the
   12101       //      decl-specifier-seq or parameter-declaration-clause of a
   12102       //      function defined in namespace scope, the identifier is
   12103       //      declared as a class-name in the namespace that contains
   12104       //      the declaration; otherwise, except as a friend
   12105       //      declaration, the identifier is declared in the smallest
   12106       //      non-class, non-function-prototype scope that contains the
   12107       //      declaration.
   12108       //
   12109       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
   12110       // C structs and unions.
   12111       //
   12112       // It is an error in C++ to declare (rather than define) an enum
   12113       // type, including via an elaborated type specifier.  We'll
   12114       // diagnose that later; for now, declare the enum in the same
   12115       // scope as we would have picked for any other tag type.
   12116       //
   12117       // GNU C also supports this behavior as part of its incomplete
   12118       // enum types extension, while GNU C++ does not.
   12119       //
   12120       // Find the context where we'll be declaring the tag.
   12121       // FIXME: We would like to maintain the current DeclContext as the
   12122       // lexical context,
   12123       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
   12124         SearchDC = SearchDC->getParent();
   12125 
   12126       // Find the scope where we'll be declaring the tag.
   12127       while (S->isClassScope() ||
   12128              (getLangOpts().CPlusPlus &&
   12129               S->isFunctionPrototypeScope()) ||
   12130              ((S->getFlags() & Scope::DeclScope) == 0) ||
   12131              (S->getEntity() && S->getEntity()->isTransparentContext()))
   12132         S = S->getParent();
   12133     } else {
   12134       assert(TUK == TUK_Friend);
   12135       // C++ [namespace.memdef]p3:
   12136       //   If a friend declaration in a non-local class first declares a
   12137       //   class or function, the friend class or function is a member of
   12138       //   the innermost enclosing namespace.
   12139       SearchDC = SearchDC->getEnclosingNamespaceContext();
   12140     }
   12141 
   12142     // In C++, we need to do a redeclaration lookup to properly
   12143     // diagnose some problems.
   12144     // FIXME: redeclaration lookup is also used (with and without C++) to find a
   12145     // hidden declaration so that we don't get ambiguity errors when using a
   12146     // type declared by an elaborated-type-specifier.  In C that is not correct
   12147     // and we should instead merge compatible types found by lookup.
   12148     if (getLangOpts().CPlusPlus) {
   12149       Previous.setRedeclarationKind(ForRedeclaration);
   12150       LookupQualifiedName(Previous, SearchDC);
   12151     } else {
   12152       Previous.setRedeclarationKind(ForRedeclaration);
   12153       LookupName(Previous, S);
   12154     }
   12155   }
   12156 
   12157   // If we have a known previous declaration to use, then use it.
   12158   if (Previous.empty() && SkipBody && SkipBody->Previous)
   12159     Previous.addDecl(SkipBody->Previous);
   12160 
   12161   if (!Previous.empty()) {
   12162     NamedDecl *PrevDecl = Previous.getFoundDecl();
   12163     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
   12164 
   12165     // It's okay to have a tag decl in the same scope as a typedef
   12166     // which hides a tag decl in the same scope.  Finding this
   12167     // insanity with a redeclaration lookup can only actually happen
   12168     // in C++.
   12169     //
   12170     // This is also okay for elaborated-type-specifiers, which is
   12171     // technically forbidden by the current standard but which is
   12172     // okay according to the likely resolution of an open issue;
   12173     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
   12174     if (getLangOpts().CPlusPlus) {
   12175       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
   12176         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
   12177           TagDecl *Tag = TT->getDecl();
   12178           if (Tag->getDeclName() == Name &&
   12179               Tag->getDeclContext()->getRedeclContext()
   12180                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
   12181             PrevDecl = Tag;
   12182             Previous.clear();
   12183             Previous.addDecl(Tag);
   12184             Previous.resolveKind();
   12185           }
   12186         }
   12187       }
   12188     }
   12189 
   12190     // If this is a redeclaration of a using shadow declaration, it must
   12191     // declare a tag in the same context. In MSVC mode, we allow a
   12192     // redefinition if either context is within the other.
   12193     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
   12194       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
   12195       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
   12196           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
   12197           !(OldTag && isAcceptableTagRedeclContext(
   12198                           *this, OldTag->getDeclContext(), SearchDC))) {
   12199         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
   12200         Diag(Shadow->getTargetDecl()->getLocation(),
   12201              diag::note_using_decl_target);
   12202         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
   12203             << 0;
   12204         // Recover by ignoring the old declaration.
   12205         Previous.clear();
   12206         goto CreateNewDecl;
   12207       }
   12208     }
   12209 
   12210     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
   12211       // If this is a use of a previous tag, or if the tag is already declared
   12212       // in the same scope (so that the definition/declaration completes or
   12213       // rementions the tag), reuse the decl.
   12214       if (TUK == TUK_Reference || TUK == TUK_Friend ||
   12215           isDeclInScope(DirectPrevDecl, SearchDC, S,
   12216                         SS.isNotEmpty() || isExplicitSpecialization)) {
   12217         // Make sure that this wasn't declared as an enum and now used as a
   12218         // struct or something similar.
   12219         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
   12220                                           TUK == TUK_Definition, KWLoc,
   12221                                           Name)) {
   12222           bool SafeToContinue
   12223             = (PrevTagDecl->getTagKind() != TTK_Enum &&
   12224                Kind != TTK_Enum);
   12225           if (SafeToContinue)
   12226             Diag(KWLoc, diag::err_use_with_wrong_tag)
   12227               << Name
   12228               << FixItHint::CreateReplacement(SourceRange(KWLoc),
   12229                                               PrevTagDecl->getKindName());
   12230           else
   12231             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
   12232           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
   12233 
   12234           if (SafeToContinue)
   12235             Kind = PrevTagDecl->getTagKind();
   12236           else {
   12237             // Recover by making this an anonymous redefinition.
   12238             Name = nullptr;
   12239             Previous.clear();
   12240             Invalid = true;
   12241           }
   12242         }
   12243 
   12244         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
   12245           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
   12246 
   12247           // If this is an elaborated-type-specifier for a scoped enumeration,
   12248           // the 'class' keyword is not necessary and not permitted.
   12249           if (TUK == TUK_Reference || TUK == TUK_Friend) {
   12250             if (ScopedEnum)
   12251               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
   12252                 << PrevEnum->isScoped()
   12253                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
   12254             return PrevTagDecl;
   12255           }
   12256 
   12257           QualType EnumUnderlyingTy;
   12258           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
   12259             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
   12260           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
   12261             EnumUnderlyingTy = QualType(T, 0);
   12262 
   12263           // All conflicts with previous declarations are recovered by
   12264           // returning the previous declaration, unless this is a definition,
   12265           // in which case we want the caller to bail out.
   12266           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
   12267                                      ScopedEnum, EnumUnderlyingTy,
   12268                                      EnumUnderlyingIsImplicit, PrevEnum))
   12269             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
   12270         }
   12271 
   12272         // C++11 [class.mem]p1:
   12273         //   A member shall not be declared twice in the member-specification,
   12274         //   except that a nested class or member class template can be declared
   12275         //   and then later defined.
   12276         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
   12277             S->isDeclScope(PrevDecl)) {
   12278           Diag(NameLoc, diag::ext_member_redeclared);
   12279           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
   12280         }
   12281 
   12282         if (!Invalid) {
   12283           // If this is a use, just return the declaration we found, unless
   12284           // we have attributes.
   12285 
   12286           // FIXME: In the future, return a variant or some other clue
   12287           // for the consumer of this Decl to know it doesn't own it.
   12288           // For our current ASTs this shouldn't be a problem, but will
   12289           // need to be changed with DeclGroups.
   12290           if (!Attr &&
   12291               ((TUK == TUK_Reference &&
   12292                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
   12293                || TUK == TUK_Friend))
   12294             return PrevTagDecl;
   12295 
   12296           // Diagnose attempts to redefine a tag.
   12297           if (TUK == TUK_Definition) {
   12298             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
   12299               // If we're defining a specialization and the previous definition
   12300               // is from an implicit instantiation, don't emit an error
   12301               // here; we'll catch this in the general case below.
   12302               bool IsExplicitSpecializationAfterInstantiation = false;
   12303               if (isExplicitSpecialization) {
   12304                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
   12305                   IsExplicitSpecializationAfterInstantiation =
   12306                     RD->getTemplateSpecializationKind() !=
   12307                     TSK_ExplicitSpecialization;
   12308                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
   12309                   IsExplicitSpecializationAfterInstantiation =
   12310                     ED->getTemplateSpecializationKind() !=
   12311                     TSK_ExplicitSpecialization;
   12312               }
   12313 
   12314               NamedDecl *Hidden = nullptr;
   12315               if (SkipBody && getLangOpts().CPlusPlus &&
   12316                   !hasVisibleDefinition(Def, &Hidden)) {
   12317                 // There is a definition of this tag, but it is not visible. We
   12318                 // explicitly make use of C++'s one definition rule here, and
   12319                 // assume that this definition is identical to the hidden one
   12320                 // we already have. Make the existing definition visible and
   12321                 // use it in place of this one.
   12322                 SkipBody->ShouldSkip = true;
   12323                 makeMergedDefinitionVisible(Hidden, KWLoc);
   12324                 return Def;
   12325               } else if (!IsExplicitSpecializationAfterInstantiation) {
   12326                 // A redeclaration in function prototype scope in C isn't
   12327                 // visible elsewhere, so merely issue a warning.
   12328                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
   12329                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
   12330                 else
   12331                   Diag(NameLoc, diag::err_redefinition) << Name;
   12332                 Diag(Def->getLocation(), diag::note_previous_definition);
   12333                 // If this is a redefinition, recover by making this
   12334                 // struct be anonymous, which will make any later
   12335                 // references get the previous definition.
   12336                 Name = nullptr;
   12337                 Previous.clear();
   12338                 Invalid = true;
   12339               }
   12340             } else {
   12341               // If the type is currently being defined, complain
   12342               // about a nested redefinition.
   12343               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
   12344               if (TD->isBeingDefined()) {
   12345                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
   12346                 Diag(PrevTagDecl->getLocation(),
   12347                      diag::note_previous_definition);
   12348                 Name = nullptr;
   12349                 Previous.clear();
   12350                 Invalid = true;
   12351               }
   12352             }
   12353 
   12354             // Okay, this is definition of a previously declared or referenced
   12355             // tag. We're going to create a new Decl for it.
   12356           }
   12357 
   12358           // Okay, we're going to make a redeclaration.  If this is some kind
   12359           // of reference, make sure we build the redeclaration in the same DC
   12360           // as the original, and ignore the current access specifier.
   12361           if (TUK == TUK_Friend || TUK == TUK_Reference) {
   12362             SearchDC = PrevTagDecl->getDeclContext();
   12363             AS = AS_none;
   12364           }
   12365         }
   12366         // If we get here we have (another) forward declaration or we
   12367         // have a definition.  Just create a new decl.
   12368 
   12369       } else {
   12370         // If we get here, this is a definition of a new tag type in a nested
   12371         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
   12372         // new decl/type.  We set PrevDecl to NULL so that the entities
   12373         // have distinct types.
   12374         Previous.clear();
   12375       }
   12376       // If we get here, we're going to create a new Decl. If PrevDecl
   12377       // is non-NULL, it's a definition of the tag declared by
   12378       // PrevDecl. If it's NULL, we have a new definition.
   12379 
   12380 
   12381     // Otherwise, PrevDecl is not a tag, but was found with tag
   12382     // lookup.  This is only actually possible in C++, where a few
   12383     // things like templates still live in the tag namespace.
   12384     } else {
   12385       // Use a better diagnostic if an elaborated-type-specifier
   12386       // found the wrong kind of type on the first
   12387       // (non-redeclaration) lookup.
   12388       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
   12389           !Previous.isForRedeclaration()) {
   12390         unsigned Kind = 0;
   12391         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
   12392         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
   12393         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
   12394         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
   12395         Diag(PrevDecl->getLocation(), diag::note_declared_at);
   12396         Invalid = true;
   12397 
   12398       // Otherwise, only diagnose if the declaration is in scope.
   12399       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
   12400                                 SS.isNotEmpty() || isExplicitSpecialization)) {
   12401         // do nothing
   12402 
   12403       // Diagnose implicit declarations introduced by elaborated types.
   12404       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
   12405         unsigned Kind = 0;
   12406         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
   12407         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
   12408         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
   12409         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
   12410         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
   12411         Invalid = true;
   12412 
   12413       // Otherwise it's a declaration.  Call out a particularly common
   12414       // case here.
   12415       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
   12416         unsigned Kind = 0;
   12417         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
   12418         Diag(NameLoc, diag::err_tag_definition_of_typedef)
   12419           << Name << Kind << TND->getUnderlyingType();
   12420         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
   12421         Invalid = true;
   12422 
   12423       // Otherwise, diagnose.
   12424       } else {
   12425         // The tag name clashes with something else in the target scope,
   12426         // issue an error and recover by making this tag be anonymous.
   12427         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
   12428         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   12429         Name = nullptr;
   12430         Invalid = true;
   12431       }
   12432 
   12433       // The existing declaration isn't relevant to us; we're in a
   12434       // new scope, so clear out the previous declaration.
   12435       Previous.clear();
   12436     }
   12437   }
   12438 
   12439 CreateNewDecl:
   12440 
   12441   TagDecl *PrevDecl = nullptr;
   12442   if (Previous.isSingleResult())
   12443     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
   12444 
   12445   // If there is an identifier, use the location of the identifier as the
   12446   // location of the decl, otherwise use the location of the struct/union
   12447   // keyword.
   12448   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
   12449 
   12450   // Otherwise, create a new declaration. If there is a previous
   12451   // declaration of the same entity, the two will be linked via
   12452   // PrevDecl.
   12453   TagDecl *New;
   12454 
   12455   bool IsForwardReference = false;
   12456   if (Kind == TTK_Enum) {
   12457     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
   12458     // enum X { A, B, C } D;    D should chain to X.
   12459     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
   12460                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
   12461                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
   12462     // If this is an undefined enum, warn.
   12463     if (TUK != TUK_Definition && !Invalid) {
   12464       TagDecl *Def;
   12465       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
   12466           cast<EnumDecl>(New)->isFixed()) {
   12467         // C++0x: 7.2p2: opaque-enum-declaration.
   12468         // Conflicts are diagnosed above. Do nothing.
   12469       }
   12470       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
   12471         Diag(Loc, diag::ext_forward_ref_enum_def)
   12472           << New;
   12473         Diag(Def->getLocation(), diag::note_previous_definition);
   12474       } else {
   12475         unsigned DiagID = diag::ext_forward_ref_enum;
   12476         if (getLangOpts().MSVCCompat)
   12477           DiagID = diag::ext_ms_forward_ref_enum;
   12478         else if (getLangOpts().CPlusPlus)
   12479           DiagID = diag::err_forward_ref_enum;
   12480         Diag(Loc, DiagID);
   12481 
   12482         // If this is a forward-declared reference to an enumeration, make a
   12483         // note of it; we won't actually be introducing the declaration into
   12484         // the declaration context.
   12485         if (TUK == TUK_Reference)
   12486           IsForwardReference = true;
   12487       }
   12488     }
   12489 
   12490     if (EnumUnderlying) {
   12491       EnumDecl *ED = cast<EnumDecl>(New);
   12492       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
   12493         ED->setIntegerTypeSourceInfo(TI);
   12494       else
   12495         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
   12496       ED->setPromotionType(ED->getIntegerType());
   12497     }
   12498 
   12499   } else {
   12500     // struct/union/class
   12501 
   12502     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
   12503     // struct X { int A; } D;    D should chain to X.
   12504     if (getLangOpts().CPlusPlus) {
   12505       // FIXME: Look for a way to use RecordDecl for simple structs.
   12506       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
   12507                                   cast_or_null<CXXRecordDecl>(PrevDecl));
   12508 
   12509       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
   12510         StdBadAlloc = cast<CXXRecordDecl>(New);
   12511     } else
   12512       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
   12513                                cast_or_null<RecordDecl>(PrevDecl));
   12514   }
   12515 
   12516   // C++11 [dcl.type]p3:
   12517   //   A type-specifier-seq shall not define a class or enumeration [...].
   12518   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
   12519     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
   12520       << Context.getTagDeclType(New);
   12521     Invalid = true;
   12522   }
   12523 
   12524   // Maybe add qualifier info.
   12525   if (SS.isNotEmpty()) {
   12526     if (SS.isSet()) {
   12527       // If this is either a declaration or a definition, check the
   12528       // nested-name-specifier against the current context. We don't do this
   12529       // for explicit specializations, because they have similar checking
   12530       // (with more specific diagnostics) in the call to
   12531       // CheckMemberSpecialization, below.
   12532       if (!isExplicitSpecialization &&
   12533           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
   12534           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
   12535         Invalid = true;
   12536 
   12537       New->setQualifierInfo(SS.getWithLocInContext(Context));
   12538       if (TemplateParameterLists.size() > 0) {
   12539         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
   12540       }
   12541     }
   12542     else
   12543       Invalid = true;
   12544   }
   12545 
   12546   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
   12547     // Add alignment attributes if necessary; these attributes are checked when
   12548     // the ASTContext lays out the structure.
   12549     //
   12550     // It is important for implementing the correct semantics that this
   12551     // happen here (in act on tag decl). The #pragma pack stack is
   12552     // maintained as a result of parser callbacks which can occur at
   12553     // many points during the parsing of a struct declaration (because
   12554     // the #pragma tokens are effectively skipped over during the
   12555     // parsing of the struct).
   12556     if (TUK == TUK_Definition) {
   12557       AddAlignmentAttributesForRecord(RD);
   12558       AddMsStructLayoutForRecord(RD);
   12559     }
   12560   }
   12561 
   12562   if (ModulePrivateLoc.isValid()) {
   12563     if (isExplicitSpecialization)
   12564       Diag(New->getLocation(), diag::err_module_private_specialization)
   12565         << 2
   12566         << FixItHint::CreateRemoval(ModulePrivateLoc);
   12567     // __module_private__ does not apply to local classes. However, we only
   12568     // diagnose this as an error when the declaration specifiers are
   12569     // freestanding. Here, we just ignore the __module_private__.
   12570     else if (!SearchDC->isFunctionOrMethod())
   12571       New->setModulePrivate();
   12572   }
   12573 
   12574   // If this is a specialization of a member class (of a class template),
   12575   // check the specialization.
   12576   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
   12577     Invalid = true;
   12578 
   12579   // If we're declaring or defining a tag in function prototype scope in C,
   12580   // note that this type can only be used within the function and add it to
   12581   // the list of decls to inject into the function definition scope.
   12582   if ((Name || Kind == TTK_Enum) &&
   12583       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
   12584     if (getLangOpts().CPlusPlus) {
   12585       // C++ [dcl.fct]p6:
   12586       //   Types shall not be defined in return or parameter types.
   12587       if (TUK == TUK_Definition && !IsTypeSpecifier) {
   12588         Diag(Loc, diag::err_type_defined_in_param_type)
   12589             << Name;
   12590         Invalid = true;
   12591       }
   12592     } else {
   12593       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
   12594     }
   12595     DeclsInPrototypeScope.push_back(New);
   12596   }
   12597 
   12598   if (Invalid)
   12599     New->setInvalidDecl();
   12600 
   12601   if (Attr)
   12602     ProcessDeclAttributeList(S, New, Attr);
   12603 
   12604   // Set the lexical context. If the tag has a C++ scope specifier, the
   12605   // lexical context will be different from the semantic context.
   12606   New->setLexicalDeclContext(CurContext);
   12607 
   12608   // Mark this as a friend decl if applicable.
   12609   // In Microsoft mode, a friend declaration also acts as a forward
   12610   // declaration so we always pass true to setObjectOfFriendDecl to make
   12611   // the tag name visible.
   12612   if (TUK == TUK_Friend)
   12613     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
   12614 
   12615   // Set the access specifier.
   12616   if (!Invalid && SearchDC->isRecord())
   12617     SetMemberAccessSpecifier(New, PrevDecl, AS);
   12618 
   12619   if (TUK == TUK_Definition)
   12620     New->startDefinition();
   12621 
   12622   // If this has an identifier, add it to the scope stack.
   12623   if (TUK == TUK_Friend) {
   12624     // We might be replacing an existing declaration in the lookup tables;
   12625     // if so, borrow its access specifier.
   12626     if (PrevDecl)
   12627       New->setAccess(PrevDecl->getAccess());
   12628 
   12629     DeclContext *DC = New->getDeclContext()->getRedeclContext();
   12630     DC->makeDeclVisibleInContext(New);
   12631     if (Name) // can be null along some error paths
   12632       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
   12633         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
   12634   } else if (Name) {
   12635     S = getNonFieldDeclScope(S);
   12636     PushOnScopeChains(New, S, !IsForwardReference);
   12637     if (IsForwardReference)
   12638       SearchDC->makeDeclVisibleInContext(New);
   12639 
   12640   } else {
   12641     CurContext->addDecl(New);
   12642   }
   12643 
   12644   // If this is the C FILE type, notify the AST context.
   12645   if (IdentifierInfo *II = New->getIdentifier())
   12646     if (!New->isInvalidDecl() &&
   12647         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
   12648         II->isStr("FILE"))
   12649       Context.setFILEDecl(New);
   12650 
   12651   if (PrevDecl)
   12652     mergeDeclAttributes(New, PrevDecl);
   12653 
   12654   // If there's a #pragma GCC visibility in scope, set the visibility of this
   12655   // record.
   12656   AddPushedVisibilityAttribute(New);
   12657 
   12658   OwnedDecl = true;
   12659   // In C++, don't return an invalid declaration. We can't recover well from
   12660   // the cases where we make the type anonymous.
   12661   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
   12662 }
   12663 
   12664 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
   12665   AdjustDeclIfTemplate(TagD);
   12666   TagDecl *Tag = cast<TagDecl>(TagD);
   12667 
   12668   // Enter the tag context.
   12669   PushDeclContext(S, Tag);
   12670 
   12671   ActOnDocumentableDecl(TagD);
   12672 
   12673   // If there's a #pragma GCC visibility in scope, set the visibility of this
   12674   // record.
   12675   AddPushedVisibilityAttribute(Tag);
   12676 }
   12677 
   12678 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
   12679   assert(isa<ObjCContainerDecl>(IDecl) &&
   12680          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
   12681   DeclContext *OCD = cast<DeclContext>(IDecl);
   12682   assert(getContainingDC(OCD) == CurContext &&
   12683       "The next DeclContext should be lexically contained in the current one.");
   12684   CurContext = OCD;
   12685   return IDecl;
   12686 }
   12687 
   12688 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
   12689                                            SourceLocation FinalLoc,
   12690                                            bool IsFinalSpelledSealed,
   12691                                            SourceLocation LBraceLoc) {
   12692   AdjustDeclIfTemplate(TagD);
   12693   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
   12694 
   12695   FieldCollector->StartClass();
   12696 
   12697   if (!Record->getIdentifier())
   12698     return;
   12699 
   12700   if (FinalLoc.isValid())
   12701     Record->addAttr(new (Context)
   12702                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
   12703 
   12704   // C++ [class]p2:
   12705   //   [...] The class-name is also inserted into the scope of the
   12706   //   class itself; this is known as the injected-class-name. For
   12707   //   purposes of access checking, the injected-class-name is treated
   12708   //   as if it were a public member name.
   12709   CXXRecordDecl *InjectedClassName
   12710     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
   12711                             Record->getLocStart(), Record->getLocation(),
   12712                             Record->getIdentifier(),
   12713                             /*PrevDecl=*/nullptr,
   12714                             /*DelayTypeCreation=*/true);
   12715   Context.getTypeDeclType(InjectedClassName, Record);
   12716   InjectedClassName->setImplicit();
   12717   InjectedClassName->setAccess(AS_public);
   12718   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
   12719       InjectedClassName->setDescribedClassTemplate(Template);
   12720   PushOnScopeChains(InjectedClassName, S);
   12721   assert(InjectedClassName->isInjectedClassName() &&
   12722          "Broken injected-class-name");
   12723 }
   12724 
   12725 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
   12726                                     SourceLocation RBraceLoc) {
   12727   AdjustDeclIfTemplate(TagD);
   12728   TagDecl *Tag = cast<TagDecl>(TagD);
   12729   Tag->setRBraceLoc(RBraceLoc);
   12730 
   12731   // Make sure we "complete" the definition even it is invalid.
   12732   if (Tag->isBeingDefined()) {
   12733     assert(Tag->isInvalidDecl() && "We should already have completed it");
   12734     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
   12735       RD->completeDefinition();
   12736   }
   12737 
   12738   if (isa<CXXRecordDecl>(Tag))
   12739     FieldCollector->FinishClass();
   12740 
   12741   // Exit this scope of this tag's definition.
   12742   PopDeclContext();
   12743 
   12744   if (getCurLexicalContext()->isObjCContainer() &&
   12745       Tag->getDeclContext()->isFileContext())
   12746     Tag->setTopLevelDeclInObjCContainer();
   12747 
   12748   // Notify the consumer that we've defined a tag.
   12749   if (!Tag->isInvalidDecl())
   12750     Consumer.HandleTagDeclDefinition(Tag);
   12751 }
   12752 
   12753 void Sema::ActOnObjCContainerFinishDefinition() {
   12754   // Exit this scope of this interface definition.
   12755   PopDeclContext();
   12756 }
   12757 
   12758 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
   12759   assert(DC == CurContext && "Mismatch of container contexts");
   12760   OriginalLexicalContext = DC;
   12761   ActOnObjCContainerFinishDefinition();
   12762 }
   12763 
   12764 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
   12765   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
   12766   OriginalLexicalContext = nullptr;
   12767 }
   12768 
   12769 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
   12770   AdjustDeclIfTemplate(TagD);
   12771   TagDecl *Tag = cast<TagDecl>(TagD);
   12772   Tag->setInvalidDecl();
   12773 
   12774   // Make sure we "complete" the definition even it is invalid.
   12775   if (Tag->isBeingDefined()) {
   12776     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
   12777       RD->completeDefinition();
   12778   }
   12779 
   12780   // We're undoing ActOnTagStartDefinition here, not
   12781   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
   12782   // the FieldCollector.
   12783 
   12784   PopDeclContext();
   12785 }
   12786 
   12787 // Note that FieldName may be null for anonymous bitfields.
   12788 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
   12789                                 IdentifierInfo *FieldName,
   12790                                 QualType FieldTy, bool IsMsStruct,
   12791                                 Expr *BitWidth, bool *ZeroWidth) {
   12792   // Default to true; that shouldn't confuse checks for emptiness
   12793   if (ZeroWidth)
   12794     *ZeroWidth = true;
   12795 
   12796   // C99 6.7.2.1p4 - verify the field type.
   12797   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
   12798   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
   12799     // Handle incomplete types with specific error.
   12800     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
   12801       return ExprError();
   12802     if (FieldName)
   12803       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
   12804         << FieldName << FieldTy << BitWidth->getSourceRange();
   12805     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
   12806       << FieldTy << BitWidth->getSourceRange();
   12807   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
   12808                                              UPPC_BitFieldWidth))
   12809     return ExprError();
   12810 
   12811   // If the bit-width is type- or value-dependent, don't try to check
   12812   // it now.
   12813   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
   12814     return BitWidth;
   12815 
   12816   llvm::APSInt Value;
   12817   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
   12818   if (ICE.isInvalid())
   12819     return ICE;
   12820   BitWidth = ICE.get();
   12821 
   12822   if (Value != 0 && ZeroWidth)
   12823     *ZeroWidth = false;
   12824 
   12825   // Zero-width bitfield is ok for anonymous field.
   12826   if (Value == 0 && FieldName)
   12827     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
   12828 
   12829   if (Value.isSigned() && Value.isNegative()) {
   12830     if (FieldName)
   12831       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
   12832                << FieldName << Value.toString(10);
   12833     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
   12834       << Value.toString(10);
   12835   }
   12836 
   12837   if (!FieldTy->isDependentType()) {
   12838     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
   12839     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
   12840     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
   12841 
   12842     // Over-wide bitfields are an error in C or when using the MSVC bitfield
   12843     // ABI.
   12844     bool CStdConstraintViolation =
   12845         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
   12846     bool MSBitfieldViolation =
   12847         Value.ugt(TypeStorageSize) &&
   12848         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
   12849     if (CStdConstraintViolation || MSBitfieldViolation) {
   12850       unsigned DiagWidth =
   12851           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
   12852       if (FieldName)
   12853         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
   12854                << FieldName << (unsigned)Value.getZExtValue()
   12855                << !CStdConstraintViolation << DiagWidth;
   12856 
   12857       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
   12858              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
   12859              << DiagWidth;
   12860     }
   12861 
   12862     // Warn on types where the user might conceivably expect to get all
   12863     // specified bits as value bits: that's all integral types other than
   12864     // 'bool'.
   12865     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
   12866       if (FieldName)
   12867         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
   12868             << FieldName << (unsigned)Value.getZExtValue()
   12869             << (unsigned)TypeWidth;
   12870       else
   12871         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
   12872             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
   12873     }
   12874   }
   12875 
   12876   return BitWidth;
   12877 }
   12878 
   12879 /// ActOnField - Each field of a C struct/union is passed into this in order
   12880 /// to create a FieldDecl object for it.
   12881 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
   12882                        Declarator &D, Expr *BitfieldWidth) {
   12883   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
   12884                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
   12885                                /*InitStyle=*/ICIS_NoInit, AS_public);
   12886   return Res;
   12887 }
   12888 
   12889 /// HandleField - Analyze a field of a C struct or a C++ data member.
   12890 ///
   12891 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
   12892                              SourceLocation DeclStart,
   12893                              Declarator &D, Expr *BitWidth,
   12894                              InClassInitStyle InitStyle,
   12895                              AccessSpecifier AS) {
   12896   IdentifierInfo *II = D.getIdentifier();
   12897   SourceLocation Loc = DeclStart;
   12898   if (II) Loc = D.getIdentifierLoc();
   12899 
   12900   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   12901   QualType T = TInfo->getType();
   12902   if (getLangOpts().CPlusPlus) {
   12903     CheckExtraCXXDefaultArguments(D);
   12904 
   12905     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
   12906                                         UPPC_DataMemberType)) {
   12907       D.setInvalidType();
   12908       T = Context.IntTy;
   12909       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
   12910     }
   12911   }
   12912 
   12913   // TR 18037 does not allow fields to be declared with address spaces.
   12914   if (T.getQualifiers().hasAddressSpace()) {
   12915     Diag(Loc, diag::err_field_with_address_space);
   12916     D.setInvalidType();
   12917   }
   12918 
   12919   // OpenCL 1.2 spec, s6.9 r:
   12920   // The event type cannot be used to declare a structure or union field.
   12921   if (LangOpts.OpenCL && T->isEventT()) {
   12922     Diag(Loc, diag::err_event_t_struct_field);
   12923     D.setInvalidType();
   12924   }
   12925 
   12926   DiagnoseFunctionSpecifiers(D.getDeclSpec());
   12927 
   12928   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
   12929     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
   12930          diag::err_invalid_thread)
   12931       << DeclSpec::getSpecifierName(TSCS);
   12932 
   12933   // Check to see if this name was declared as a member previously
   12934   NamedDecl *PrevDecl = nullptr;
   12935   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
   12936   LookupName(Previous, S);
   12937   switch (Previous.getResultKind()) {
   12938     case LookupResult::Found:
   12939     case LookupResult::FoundUnresolvedValue:
   12940       PrevDecl = Previous.getAsSingle<NamedDecl>();
   12941       break;
   12942 
   12943     case LookupResult::FoundOverloaded:
   12944       PrevDecl = Previous.getRepresentativeDecl();
   12945       break;
   12946 
   12947     case LookupResult::NotFound:
   12948     case LookupResult::NotFoundInCurrentInstantiation:
   12949     case LookupResult::Ambiguous:
   12950       break;
   12951   }
   12952   Previous.suppressDiagnostics();
   12953 
   12954   if (PrevDecl && PrevDecl->isTemplateParameter()) {
   12955     // Maybe we will complain about the shadowed template parameter.
   12956     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
   12957     // Just pretend that we didn't see the previous declaration.
   12958     PrevDecl = nullptr;
   12959   }
   12960 
   12961   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
   12962     PrevDecl = nullptr;
   12963 
   12964   bool Mutable
   12965     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
   12966   SourceLocation TSSL = D.getLocStart();
   12967   FieldDecl *NewFD
   12968     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
   12969                      TSSL, AS, PrevDecl, &D);
   12970 
   12971   if (NewFD->isInvalidDecl())
   12972     Record->setInvalidDecl();
   12973 
   12974   if (D.getDeclSpec().isModulePrivateSpecified())
   12975     NewFD->setModulePrivate();
   12976 
   12977   if (NewFD->isInvalidDecl() && PrevDecl) {
   12978     // Don't introduce NewFD into scope; there's already something
   12979     // with the same name in the same scope.
   12980   } else if (II) {
   12981     PushOnScopeChains(NewFD, S);
   12982   } else
   12983     Record->addDecl(NewFD);
   12984 
   12985   return NewFD;
   12986 }
   12987 
   12988 /// \brief Build a new FieldDecl and check its well-formedness.
   12989 ///
   12990 /// This routine builds a new FieldDecl given the fields name, type,
   12991 /// record, etc. \p PrevDecl should refer to any previous declaration
   12992 /// with the same name and in the same scope as the field to be
   12993 /// created.
   12994 ///
   12995 /// \returns a new FieldDecl.
   12996 ///
   12997 /// \todo The Declarator argument is a hack. It will be removed once
   12998 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
   12999                                 TypeSourceInfo *TInfo,
   13000                                 RecordDecl *Record, SourceLocation Loc,
   13001                                 bool Mutable, Expr *BitWidth,
   13002                                 InClassInitStyle InitStyle,
   13003                                 SourceLocation TSSL,
   13004                                 AccessSpecifier AS, NamedDecl *PrevDecl,
   13005                                 Declarator *D) {
   13006   IdentifierInfo *II = Name.getAsIdentifierInfo();
   13007   bool InvalidDecl = false;
   13008   if (D) InvalidDecl = D->isInvalidType();
   13009 
   13010   // If we receive a broken type, recover by assuming 'int' and
   13011   // marking this declaration as invalid.
   13012   if (T.isNull()) {
   13013     InvalidDecl = true;
   13014     T = Context.IntTy;
   13015   }
   13016 
   13017   QualType EltTy = Context.getBaseElementType(T);
   13018   if (!EltTy->isDependentType()) {
   13019     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
   13020       // Fields of incomplete type force their record to be invalid.
   13021       Record->setInvalidDecl();
   13022       InvalidDecl = true;
   13023     } else {
   13024       NamedDecl *Def;
   13025       EltTy->isIncompleteType(&Def);
   13026       if (Def && Def->isInvalidDecl()) {
   13027         Record->setInvalidDecl();
   13028         InvalidDecl = true;
   13029       }
   13030     }
   13031   }
   13032 
   13033   // OpenCL v1.2 s6.9.c: bitfields are not supported.
   13034   if (BitWidth && getLangOpts().OpenCL) {
   13035     Diag(Loc, diag::err_opencl_bitfields);
   13036     InvalidDecl = true;
   13037   }
   13038 
   13039   // C99 6.7.2.1p8: A member of a structure or union may have any type other
   13040   // than a variably modified type.
   13041   if (!InvalidDecl && T->isVariablyModifiedType()) {
   13042     bool SizeIsNegative;
   13043     llvm::APSInt Oversized;
   13044 
   13045     TypeSourceInfo *FixedTInfo =
   13046       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
   13047                                                     SizeIsNegative,
   13048                                                     Oversized);
   13049     if (FixedTInfo) {
   13050       Diag(Loc, diag::warn_illegal_constant_array_size);
   13051       TInfo = FixedTInfo;
   13052       T = FixedTInfo->getType();
   13053     } else {
   13054       if (SizeIsNegative)
   13055         Diag(Loc, diag::err_typecheck_negative_array_size);
   13056       else if (Oversized.getBoolValue())
   13057         Diag(Loc, diag::err_array_too_large)
   13058           << Oversized.toString(10);
   13059       else
   13060         Diag(Loc, diag::err_typecheck_field_variable_size);
   13061       InvalidDecl = true;
   13062     }
   13063   }
   13064 
   13065   // Fields can not have abstract class types
   13066   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
   13067                                              diag::err_abstract_type_in_decl,
   13068                                              AbstractFieldType))
   13069     InvalidDecl = true;
   13070 
   13071   bool ZeroWidth = false;
   13072   if (InvalidDecl)
   13073     BitWidth = nullptr;
   13074   // If this is declared as a bit-field, check the bit-field.
   13075   if (BitWidth) {
   13076     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
   13077                               &ZeroWidth).get();
   13078     if (!BitWidth) {
   13079       InvalidDecl = true;
   13080       BitWidth = nullptr;
   13081       ZeroWidth = false;
   13082     }
   13083   }
   13084 
   13085   // Check that 'mutable' is consistent with the type of the declaration.
   13086   if (!InvalidDecl && Mutable) {
   13087     unsigned DiagID = 0;
   13088     if (T->isReferenceType())
   13089       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
   13090                                         : diag::err_mutable_reference;
   13091     else if (T.isConstQualified())
   13092       DiagID = diag::err_mutable_const;
   13093 
   13094     if (DiagID) {
   13095       SourceLocation ErrLoc = Loc;
   13096       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
   13097         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
   13098       Diag(ErrLoc, DiagID);
   13099       if (DiagID != diag::ext_mutable_reference) {
   13100         Mutable = false;
   13101         InvalidDecl = true;
   13102       }
   13103     }
   13104   }
   13105 
   13106   // C++11 [class.union]p8 (DR1460):
   13107   //   At most one variant member of a union may have a
   13108   //   brace-or-equal-initializer.
   13109   if (InitStyle != ICIS_NoInit)
   13110     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
   13111 
   13112   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
   13113                                        BitWidth, Mutable, InitStyle);
   13114   if (InvalidDecl)
   13115     NewFD->setInvalidDecl();
   13116 
   13117   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
   13118     Diag(Loc, diag::err_duplicate_member) << II;
   13119     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
   13120     NewFD->setInvalidDecl();
   13121   }
   13122 
   13123   if (!InvalidDecl && getLangOpts().CPlusPlus) {
   13124     if (Record->isUnion()) {
   13125       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
   13126         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
   13127         if (RDecl->getDefinition()) {
   13128           // C++ [class.union]p1: An object of a class with a non-trivial
   13129           // constructor, a non-trivial copy constructor, a non-trivial
   13130           // destructor, or a non-trivial copy assignment operator
   13131           // cannot be a member of a union, nor can an array of such
   13132           // objects.
   13133           if (CheckNontrivialField(NewFD))
   13134             NewFD->setInvalidDecl();
   13135         }
   13136       }
   13137 
   13138       // C++ [class.union]p1: If a union contains a member of reference type,
   13139       // the program is ill-formed, except when compiling with MSVC extensions
   13140       // enabled.
   13141       if (EltTy->isReferenceType()) {
   13142         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
   13143                                     diag::ext_union_member_of_reference_type :
   13144                                     diag::err_union_member_of_reference_type)
   13145           << NewFD->getDeclName() << EltTy;
   13146         if (!getLangOpts().MicrosoftExt)
   13147           NewFD->setInvalidDecl();
   13148       }
   13149     }
   13150   }
   13151 
   13152   // FIXME: We need to pass in the attributes given an AST
   13153   // representation, not a parser representation.
   13154   if (D) {
   13155     // FIXME: The current scope is almost... but not entirely... correct here.
   13156     ProcessDeclAttributes(getCurScope(), NewFD, *D);
   13157 
   13158     if (NewFD->hasAttrs())
   13159       CheckAlignasUnderalignment(NewFD);
   13160   }
   13161 
   13162   // In auto-retain/release, infer strong retension for fields of
   13163   // retainable type.
   13164   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
   13165     NewFD->setInvalidDecl();
   13166 
   13167   if (T.isObjCGCWeak())
   13168     Diag(Loc, diag::warn_attribute_weak_on_field);
   13169 
   13170   NewFD->setAccess(AS);
   13171   return NewFD;
   13172 }
   13173 
   13174 bool Sema::CheckNontrivialField(FieldDecl *FD) {
   13175   assert(FD);
   13176   assert(getLangOpts().CPlusPlus && "valid check only for C++");
   13177 
   13178   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
   13179     return false;
   13180 
   13181   QualType EltTy = Context.getBaseElementType(FD->getType());
   13182   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
   13183     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
   13184     if (RDecl->getDefinition()) {
   13185       // We check for copy constructors before constructors
   13186       // because otherwise we'll never get complaints about
   13187       // copy constructors.
   13188 
   13189       CXXSpecialMember member = CXXInvalid;
   13190       // We're required to check for any non-trivial constructors. Since the
   13191       // implicit default constructor is suppressed if there are any
   13192       // user-declared constructors, we just need to check that there is a
   13193       // trivial default constructor and a trivial copy constructor. (We don't
   13194       // worry about move constructors here, since this is a C++98 check.)
   13195       if (RDecl->hasNonTrivialCopyConstructor())
   13196         member = CXXCopyConstructor;
   13197       else if (!RDecl->hasTrivialDefaultConstructor())
   13198         member = CXXDefaultConstructor;
   13199       else if (RDecl->hasNonTrivialCopyAssignment())
   13200         member = CXXCopyAssignment;
   13201       else if (RDecl->hasNonTrivialDestructor())
   13202         member = CXXDestructor;
   13203 
   13204       if (member != CXXInvalid) {
   13205         if (!getLangOpts().CPlusPlus11 &&
   13206             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
   13207           // Objective-C++ ARC: it is an error to have a non-trivial field of
   13208           // a union. However, system headers in Objective-C programs
   13209           // occasionally have Objective-C lifetime objects within unions,
   13210           // and rather than cause the program to fail, we make those
   13211           // members unavailable.
   13212           SourceLocation Loc = FD->getLocation();
   13213           if (getSourceManager().isInSystemHeader(Loc)) {
   13214             if (!FD->hasAttr<UnavailableAttr>())
   13215               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
   13216                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
   13217             return false;
   13218           }
   13219         }
   13220 
   13221         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
   13222                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
   13223                diag::err_illegal_union_or_anon_struct_member)
   13224           << FD->getParent()->isUnion() << FD->getDeclName() << member;
   13225         DiagnoseNontrivial(RDecl, member);
   13226         return !getLangOpts().CPlusPlus11;
   13227       }
   13228     }
   13229   }
   13230 
   13231   return false;
   13232 }
   13233 
   13234 /// TranslateIvarVisibility - Translate visibility from a token ID to an
   13235 ///  AST enum value.
   13236 static ObjCIvarDecl::AccessControl
   13237 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
   13238   switch (ivarVisibility) {
   13239   default: llvm_unreachable("Unknown visitibility kind");
   13240   case tok::objc_private: return ObjCIvarDecl::Private;
   13241   case tok::objc_public: return ObjCIvarDecl::Public;
   13242   case tok::objc_protected: return ObjCIvarDecl::Protected;
   13243   case tok::objc_package: return ObjCIvarDecl::Package;
   13244   }
   13245 }
   13246 
   13247 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
   13248 /// in order to create an IvarDecl object for it.
   13249 Decl *Sema::ActOnIvar(Scope *S,
   13250                                 SourceLocation DeclStart,
   13251                                 Declarator &D, Expr *BitfieldWidth,
   13252                                 tok::ObjCKeywordKind Visibility) {
   13253 
   13254   IdentifierInfo *II = D.getIdentifier();
   13255   Expr *BitWidth = (Expr*)BitfieldWidth;
   13256   SourceLocation Loc = DeclStart;
   13257   if (II) Loc = D.getIdentifierLoc();
   13258 
   13259   // FIXME: Unnamed fields can be handled in various different ways, for
   13260   // example, unnamed unions inject all members into the struct namespace!
   13261 
   13262   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   13263   QualType T = TInfo->getType();
   13264 
   13265   if (BitWidth) {
   13266     // 6.7.2.1p3, 6.7.2.1p4
   13267     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
   13268     if (!BitWidth)
   13269       D.setInvalidType();
   13270   } else {
   13271     // Not a bitfield.
   13272 
   13273     // validate II.
   13274 
   13275   }
   13276   if (T->isReferenceType()) {
   13277     Diag(Loc, diag::err_ivar_reference_type);
   13278     D.setInvalidType();
   13279   }
   13280   // C99 6.7.2.1p8: A member of a structure or union may have any type other
   13281   // than a variably modified type.
   13282   else if (T->isVariablyModifiedType()) {
   13283     Diag(Loc, diag::err_typecheck_ivar_variable_size);
   13284     D.setInvalidType();
   13285   }
   13286 
   13287   // Get the visibility (access control) for this ivar.
   13288   ObjCIvarDecl::AccessControl ac =
   13289     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
   13290                                         : ObjCIvarDecl::None;
   13291   // Must set ivar's DeclContext to its enclosing interface.
   13292   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
   13293   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
   13294     return nullptr;
   13295   ObjCContainerDecl *EnclosingContext;
   13296   if (ObjCImplementationDecl *IMPDecl =
   13297       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
   13298     if (LangOpts.ObjCRuntime.isFragile()) {
   13299     // Case of ivar declared in an implementation. Context is that of its class.
   13300       EnclosingContext = IMPDecl->getClassInterface();
   13301       assert(EnclosingContext && "Implementation has no class interface!");
   13302     }
   13303     else
   13304       EnclosingContext = EnclosingDecl;
   13305   } else {
   13306     if (ObjCCategoryDecl *CDecl =
   13307         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
   13308       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
   13309         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
   13310         return nullptr;
   13311       }
   13312     }
   13313     EnclosingContext = EnclosingDecl;
   13314   }
   13315 
   13316   // Construct the decl.
   13317   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
   13318                                              DeclStart, Loc, II, T,
   13319                                              TInfo, ac, (Expr *)BitfieldWidth);
   13320 
   13321   if (II) {
   13322     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
   13323                                            ForRedeclaration);
   13324     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
   13325         && !isa<TagDecl>(PrevDecl)) {
   13326       Diag(Loc, diag::err_duplicate_member) << II;
   13327       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
   13328       NewID->setInvalidDecl();
   13329     }
   13330   }
   13331 
   13332   // Process attributes attached to the ivar.
   13333   ProcessDeclAttributes(S, NewID, D);
   13334 
   13335   if (D.isInvalidType())
   13336     NewID->setInvalidDecl();
   13337 
   13338   // In ARC, infer 'retaining' for ivars of retainable type.
   13339   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
   13340     NewID->setInvalidDecl();
   13341 
   13342   if (D.getDeclSpec().isModulePrivateSpecified())
   13343     NewID->setModulePrivate();
   13344 
   13345   if (II) {
   13346     // FIXME: When interfaces are DeclContexts, we'll need to add
   13347     // these to the interface.
   13348     S->AddDecl(NewID);
   13349     IdResolver.AddDecl(NewID);
   13350   }
   13351 
   13352   if (LangOpts.ObjCRuntime.isNonFragile() &&
   13353       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
   13354     Diag(Loc, diag::warn_ivars_in_interface);
   13355 
   13356   return NewID;
   13357 }
   13358 
   13359 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
   13360 /// class and class extensions. For every class \@interface and class
   13361 /// extension \@interface, if the last ivar is a bitfield of any type,
   13362 /// then add an implicit `char :0` ivar to the end of that interface.
   13363 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
   13364                              SmallVectorImpl<Decl *> &AllIvarDecls) {
   13365   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
   13366     return;
   13367 
   13368   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
   13369   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
   13370 
   13371   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
   13372     return;
   13373   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
   13374   if (!ID) {
   13375     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
   13376       if (!CD->IsClassExtension())
   13377         return;
   13378     }
   13379     // No need to add this to end of @implementation.
   13380     else
   13381       return;
   13382   }
   13383   // All conditions are met. Add a new bitfield to the tail end of ivars.
   13384   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
   13385   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
   13386 
   13387   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
   13388                               DeclLoc, DeclLoc, nullptr,
   13389                               Context.CharTy,
   13390                               Context.getTrivialTypeSourceInfo(Context.CharTy,
   13391                                                                DeclLoc),
   13392                               ObjCIvarDecl::Private, BW,
   13393                               true);
   13394   AllIvarDecls.push_back(Ivar);
   13395 }
   13396 
   13397 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
   13398                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
   13399                        SourceLocation RBrac, AttributeList *Attr) {
   13400   assert(EnclosingDecl && "missing record or interface decl");
   13401 
   13402   // If this is an Objective-C @implementation or category and we have
   13403   // new fields here we should reset the layout of the interface since
   13404   // it will now change.
   13405   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
   13406     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
   13407     switch (DC->getKind()) {
   13408     default: break;
   13409     case Decl::ObjCCategory:
   13410       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
   13411       break;
   13412     case Decl::ObjCImplementation:
   13413       Context.
   13414         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
   13415       break;
   13416     }
   13417   }
   13418 
   13419   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
   13420 
   13421   // Start counting up the number of named members; make sure to include
   13422   // members of anonymous structs and unions in the total.
   13423   unsigned NumNamedMembers = 0;
   13424   if (Record) {
   13425     for (const auto *I : Record->decls()) {
   13426       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
   13427         if (IFD->getDeclName())
   13428           ++NumNamedMembers;
   13429     }
   13430   }
   13431 
   13432   // Verify that all the fields are okay.
   13433   SmallVector<FieldDecl*, 32> RecFields;
   13434 
   13435   bool ARCErrReported = false;
   13436   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
   13437        i != end; ++i) {
   13438     FieldDecl *FD = cast<FieldDecl>(*i);
   13439 
   13440     // Get the type for the field.
   13441     const Type *FDTy = FD->getType().getTypePtr();
   13442 
   13443     if (!FD->isAnonymousStructOrUnion()) {
   13444       // Remember all fields written by the user.
   13445       RecFields.push_back(FD);
   13446     }
   13447 
   13448     // If the field is already invalid for some reason, don't emit more
   13449     // diagnostics about it.
   13450     if (FD->isInvalidDecl()) {
   13451       EnclosingDecl->setInvalidDecl();
   13452       continue;
   13453     }
   13454 
   13455     // C99 6.7.2.1p2:
   13456     //   A structure or union shall not contain a member with
   13457     //   incomplete or function type (hence, a structure shall not
   13458     //   contain an instance of itself, but may contain a pointer to
   13459     //   an instance of itself), except that the last member of a
   13460     //   structure with more than one named member may have incomplete
   13461     //   array type; such a structure (and any union containing,
   13462     //   possibly recursively, a member that is such a structure)
   13463     //   shall not be a member of a structure or an element of an
   13464     //   array.
   13465     if (FDTy->isFunctionType()) {
   13466       // Field declared as a function.
   13467       Diag(FD->getLocation(), diag::err_field_declared_as_function)
   13468         << FD->getDeclName();
   13469       FD->setInvalidDecl();
   13470       EnclosingDecl->setInvalidDecl();
   13471       continue;
   13472     } else if (FDTy->isIncompleteArrayType() && Record &&
   13473                ((i + 1 == Fields.end() && !Record->isUnion()) ||
   13474                 ((getLangOpts().MicrosoftExt ||
   13475                   getLangOpts().CPlusPlus) &&
   13476                  (i + 1 == Fields.end() || Record->isUnion())))) {
   13477       // Flexible array member.
   13478       // Microsoft and g++ is more permissive regarding flexible array.
   13479       // It will accept flexible array in union and also
   13480       // as the sole element of a struct/class.
   13481       unsigned DiagID = 0;
   13482       if (Record->isUnion())
   13483         DiagID = getLangOpts().MicrosoftExt
   13484                      ? diag::ext_flexible_array_union_ms
   13485                      : getLangOpts().CPlusPlus
   13486                            ? diag::ext_flexible_array_union_gnu
   13487                            : diag::err_flexible_array_union;
   13488       else if (Fields.size() == 1)
   13489         DiagID = getLangOpts().MicrosoftExt
   13490                      ? diag::ext_flexible_array_empty_aggregate_ms
   13491                      : getLangOpts().CPlusPlus
   13492                            ? diag::ext_flexible_array_empty_aggregate_gnu
   13493                            : NumNamedMembers < 1
   13494                                  ? diag::err_flexible_array_empty_aggregate
   13495                                  : 0;
   13496 
   13497       if (DiagID)
   13498         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
   13499                                         << Record->getTagKind();
   13500       // While the layout of types that contain virtual bases is not specified
   13501       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
   13502       // virtual bases after the derived members.  This would make a flexible
   13503       // array member declared at the end of an object not adjacent to the end
   13504       // of the type.
   13505       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
   13506         if (RD->getNumVBases() != 0)
   13507           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
   13508             << FD->getDeclName() << Record->getTagKind();
   13509       if (!getLangOpts().C99)
   13510         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
   13511           << FD->getDeclName() << Record->getTagKind();
   13512 
   13513       // If the element type has a non-trivial destructor, we would not
   13514       // implicitly destroy the elements, so disallow it for now.
   13515       //
   13516       // FIXME: GCC allows this. We should probably either implicitly delete
   13517       // the destructor of the containing class, or just allow this.
   13518       QualType BaseElem = Context.getBaseElementType(FD->getType());
   13519       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
   13520         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
   13521           << FD->getDeclName() << FD->getType();
   13522         FD->setInvalidDecl();
   13523         EnclosingDecl->setInvalidDecl();
   13524         continue;
   13525       }
   13526       // Okay, we have a legal flexible array member at the end of the struct.
   13527       Record->setHasFlexibleArrayMember(true);
   13528     } else if (!FDTy->isDependentType() &&
   13529                RequireCompleteType(FD->getLocation(), FD->getType(),
   13530                                    diag::err_field_incomplete)) {
   13531       // Incomplete type
   13532       FD->setInvalidDecl();
   13533       EnclosingDecl->setInvalidDecl();
   13534       continue;
   13535     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
   13536       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
   13537         // A type which contains a flexible array member is considered to be a
   13538         // flexible array member.
   13539         Record->setHasFlexibleArrayMember(true);
   13540         if (!Record->isUnion()) {
   13541           // If this is a struct/class and this is not the last element, reject
   13542           // it.  Note that GCC supports variable sized arrays in the middle of
   13543           // structures.
   13544           if (i + 1 != Fields.end())
   13545             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
   13546               << FD->getDeclName() << FD->getType();
   13547           else {
   13548             // We support flexible arrays at the end of structs in
   13549             // other structs as an extension.
   13550             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
   13551               << FD->getDeclName();
   13552           }
   13553         }
   13554       }
   13555       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
   13556           RequireNonAbstractType(FD->getLocation(), FD->getType(),
   13557                                  diag::err_abstract_type_in_decl,
   13558                                  AbstractIvarType)) {
   13559         // Ivars can not have abstract class types
   13560         FD->setInvalidDecl();
   13561       }
   13562       if (Record && FDTTy->getDecl()->hasObjectMember())
   13563         Record->setHasObjectMember(true);
   13564       if (Record && FDTTy->getDecl()->hasVolatileMember())
   13565         Record->setHasVolatileMember(true);
   13566     } else if (FDTy->isObjCObjectType()) {
   13567       /// A field cannot be an Objective-c object
   13568       Diag(FD->getLocation(), diag::err_statically_allocated_object)
   13569         << FixItHint::CreateInsertion(FD->getLocation(), "*");
   13570       QualType T = Context.getObjCObjectPointerType(FD->getType());
   13571       FD->setType(T);
   13572     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
   13573                (!getLangOpts().CPlusPlus || Record->isUnion())) {
   13574       // It's an error in ARC if a field has lifetime.
   13575       // We don't want to report this in a system header, though,
   13576       // so we just make the field unavailable.
   13577       // FIXME: that's really not sufficient; we need to make the type
   13578       // itself invalid to, say, initialize or copy.
   13579       QualType T = FD->getType();
   13580       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
   13581       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
   13582         SourceLocation loc = FD->getLocation();
   13583         if (getSourceManager().isInSystemHeader(loc)) {
   13584           if (!FD->hasAttr<UnavailableAttr>()) {
   13585             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
   13586                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
   13587           }
   13588         } else {
   13589           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
   13590             << T->isBlockPointerType() << Record->getTagKind();
   13591         }
   13592         ARCErrReported = true;
   13593       }
   13594     } else if (getLangOpts().ObjC1 &&
   13595                getLangOpts().getGC() != LangOptions::NonGC &&
   13596                Record && !Record->hasObjectMember()) {
   13597       if (FD->getType()->isObjCObjectPointerType() ||
   13598           FD->getType().isObjCGCStrong())
   13599         Record->setHasObjectMember(true);
   13600       else if (Context.getAsArrayType(FD->getType())) {
   13601         QualType BaseType = Context.getBaseElementType(FD->getType());
   13602         if (BaseType->isRecordType() &&
   13603             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
   13604           Record->setHasObjectMember(true);
   13605         else if (BaseType->isObjCObjectPointerType() ||
   13606                  BaseType.isObjCGCStrong())
   13607                Record->setHasObjectMember(true);
   13608       }
   13609     }
   13610     if (Record && FD->getType().isVolatileQualified())
   13611       Record->setHasVolatileMember(true);
   13612     // Keep track of the number of named members.
   13613     if (FD->getIdentifier())
   13614       ++NumNamedMembers;
   13615   }
   13616 
   13617   // Okay, we successfully defined 'Record'.
   13618   if (Record) {
   13619     bool Completed = false;
   13620     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
   13621       if (!CXXRecord->isInvalidDecl()) {
   13622         // Set access bits correctly on the directly-declared conversions.
   13623         for (CXXRecordDecl::conversion_iterator
   13624                I = CXXRecord->conversion_begin(),
   13625                E = CXXRecord->conversion_end(); I != E; ++I)
   13626           I.setAccess((*I)->getAccess());
   13627 
   13628         if (!CXXRecord->isDependentType()) {
   13629           if (CXXRecord->hasUserDeclaredDestructor()) {
   13630             // Adjust user-defined destructor exception spec.
   13631             if (getLangOpts().CPlusPlus11)
   13632               AdjustDestructorExceptionSpec(CXXRecord,
   13633                                             CXXRecord->getDestructor());
   13634           }
   13635 
   13636           // Add any implicitly-declared members to this class.
   13637           AddImplicitlyDeclaredMembersToClass(CXXRecord);
   13638 
   13639           // If we have virtual base classes, we may end up finding multiple
   13640           // final overriders for a given virtual function. Check for this
   13641           // problem now.
   13642           if (CXXRecord->getNumVBases()) {
   13643             CXXFinalOverriderMap FinalOverriders;
   13644             CXXRecord->getFinalOverriders(FinalOverriders);
   13645 
   13646             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
   13647                                              MEnd = FinalOverriders.end();
   13648                  M != MEnd; ++M) {
   13649               for (OverridingMethods::iterator SO = M->second.begin(),
   13650                                             SOEnd = M->second.end();
   13651                    SO != SOEnd; ++SO) {
   13652                 assert(SO->second.size() > 0 &&
   13653                        "Virtual function without overridding functions?");
   13654                 if (SO->second.size() == 1)
   13655                   continue;
   13656 
   13657                 // C++ [class.virtual]p2:
   13658                 //   In a derived class, if a virtual member function of a base
   13659                 //   class subobject has more than one final overrider the
   13660                 //   program is ill-formed.
   13661                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
   13662                   << (const NamedDecl *)M->first << Record;
   13663                 Diag(M->first->getLocation(),
   13664                      diag::note_overridden_virtual_function);
   13665                 for (OverridingMethods::overriding_iterator
   13666                           OM = SO->second.begin(),
   13667                        OMEnd = SO->second.end();
   13668                      OM != OMEnd; ++OM)
   13669                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
   13670                     << (const NamedDecl *)M->first << OM->Method->getParent();
   13671 
   13672                 Record->setInvalidDecl();
   13673               }
   13674             }
   13675             CXXRecord->completeDefinition(&FinalOverriders);
   13676             Completed = true;
   13677           }
   13678         }
   13679       }
   13680     }
   13681 
   13682     if (!Completed)
   13683       Record->completeDefinition();
   13684 
   13685     if (Record->hasAttrs()) {
   13686       CheckAlignasUnderalignment(Record);
   13687 
   13688       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
   13689         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
   13690                                            IA->getRange(), IA->getBestCase(),
   13691                                            IA->getSemanticSpelling());
   13692     }
   13693 
   13694     // Check if the structure/union declaration is a type that can have zero
   13695     // size in C. For C this is a language extension, for C++ it may cause
   13696     // compatibility problems.
   13697     bool CheckForZeroSize;
   13698     if (!getLangOpts().CPlusPlus) {
   13699       CheckForZeroSize = true;
   13700     } else {
   13701       // For C++ filter out types that cannot be referenced in C code.
   13702       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
   13703       CheckForZeroSize =
   13704           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
   13705           !CXXRecord->isDependentType() &&
   13706           CXXRecord->isCLike();
   13707     }
   13708     if (CheckForZeroSize) {
   13709       bool ZeroSize = true;
   13710       bool IsEmpty = true;
   13711       unsigned NonBitFields = 0;
   13712       for (RecordDecl::field_iterator I = Record->field_begin(),
   13713                                       E = Record->field_end();
   13714            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
   13715         IsEmpty = false;
   13716         if (I->isUnnamedBitfield()) {
   13717           if (I->getBitWidthValue(Context) > 0)
   13718             ZeroSize = false;
   13719         } else {
   13720           ++NonBitFields;
   13721           QualType FieldType = I->getType();
   13722           if (FieldType->isIncompleteType() ||
   13723               !Context.getTypeSizeInChars(FieldType).isZero())
   13724             ZeroSize = false;
   13725         }
   13726       }
   13727 
   13728       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
   13729       // allowed in C++, but warn if its declaration is inside
   13730       // extern "C" block.
   13731       if (ZeroSize) {
   13732         Diag(RecLoc, getLangOpts().CPlusPlus ?
   13733                          diag::warn_zero_size_struct_union_in_extern_c :
   13734                          diag::warn_zero_size_struct_union_compat)
   13735           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
   13736       }
   13737 
   13738       // Structs without named members are extension in C (C99 6.7.2.1p7),
   13739       // but are accepted by GCC.
   13740       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
   13741         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
   13742                                diag::ext_no_named_members_in_struct_union)
   13743           << Record->isUnion();
   13744       }
   13745     }
   13746   } else {
   13747     ObjCIvarDecl **ClsFields =
   13748       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
   13749     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
   13750       ID->setEndOfDefinitionLoc(RBrac);
   13751       // Add ivar's to class's DeclContext.
   13752       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
   13753         ClsFields[i]->setLexicalDeclContext(ID);
   13754         ID->addDecl(ClsFields[i]);
   13755       }
   13756       // Must enforce the rule that ivars in the base classes may not be
   13757       // duplicates.
   13758       if (ID->getSuperClass())
   13759         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
   13760     } else if (ObjCImplementationDecl *IMPDecl =
   13761                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
   13762       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
   13763       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
   13764         // Ivar declared in @implementation never belongs to the implementation.
   13765         // Only it is in implementation's lexical context.
   13766         ClsFields[I]->setLexicalDeclContext(IMPDecl);
   13767       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
   13768       IMPDecl->setIvarLBraceLoc(LBrac);
   13769       IMPDecl->setIvarRBraceLoc(RBrac);
   13770     } else if (ObjCCategoryDecl *CDecl =
   13771                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
   13772       // case of ivars in class extension; all other cases have been
   13773       // reported as errors elsewhere.
   13774       // FIXME. Class extension does not have a LocEnd field.
   13775       // CDecl->setLocEnd(RBrac);
   13776       // Add ivar's to class extension's DeclContext.
   13777       // Diagnose redeclaration of private ivars.
   13778       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
   13779       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
   13780         if (IDecl) {
   13781           if (const ObjCIvarDecl *ClsIvar =
   13782               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
   13783             Diag(ClsFields[i]->getLocation(),
   13784                  diag::err_duplicate_ivar_declaration);
   13785             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
   13786             continue;
   13787           }
   13788           for (const auto *Ext : IDecl->known_extensions()) {
   13789             if (const ObjCIvarDecl *ClsExtIvar
   13790                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
   13791               Diag(ClsFields[i]->getLocation(),
   13792                    diag::err_duplicate_ivar_declaration);
   13793               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
   13794               continue;
   13795             }
   13796           }
   13797         }
   13798         ClsFields[i]->setLexicalDeclContext(CDecl);
   13799         CDecl->addDecl(ClsFields[i]);
   13800       }
   13801       CDecl->setIvarLBraceLoc(LBrac);
   13802       CDecl->setIvarRBraceLoc(RBrac);
   13803     }
   13804   }
   13805 
   13806   if (Attr)
   13807     ProcessDeclAttributeList(S, Record, Attr);
   13808 }
   13809 
   13810 /// \brief Determine whether the given integral value is representable within
   13811 /// the given type T.
   13812 static bool isRepresentableIntegerValue(ASTContext &Context,
   13813                                         llvm::APSInt &Value,
   13814                                         QualType T) {
   13815   assert(T->isIntegralType(Context) && "Integral type required!");
   13816   unsigned BitWidth = Context.getIntWidth(T);
   13817 
   13818   if (Value.isUnsigned() || Value.isNonNegative()) {
   13819     if (T->isSignedIntegerOrEnumerationType())
   13820       --BitWidth;
   13821     return Value.getActiveBits() <= BitWidth;
   13822   }
   13823   return Value.getMinSignedBits() <= BitWidth;
   13824 }
   13825 
   13826 // \brief Given an integral type, return the next larger integral type
   13827 // (or a NULL type of no such type exists).
   13828 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
   13829   // FIXME: Int128/UInt128 support, which also needs to be introduced into
   13830   // enum checking below.
   13831   assert(T->isIntegralType(Context) && "Integral type required!");
   13832   const unsigned NumTypes = 4;
   13833   QualType SignedIntegralTypes[NumTypes] = {
   13834     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
   13835   };
   13836   QualType UnsignedIntegralTypes[NumTypes] = {
   13837     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
   13838     Context.UnsignedLongLongTy
   13839   };
   13840 
   13841   unsigned BitWidth = Context.getTypeSize(T);
   13842   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
   13843                                                         : UnsignedIntegralTypes;
   13844   for (unsigned I = 0; I != NumTypes; ++I)
   13845     if (Context.getTypeSize(Types[I]) > BitWidth)
   13846       return Types[I];
   13847 
   13848   return QualType();
   13849 }
   13850 
   13851 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
   13852                                           EnumConstantDecl *LastEnumConst,
   13853                                           SourceLocation IdLoc,
   13854                                           IdentifierInfo *Id,
   13855                                           Expr *Val) {
   13856   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   13857   llvm::APSInt EnumVal(IntWidth);
   13858   QualType EltTy;
   13859 
   13860   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
   13861     Val = nullptr;
   13862 
   13863   if (Val)
   13864     Val = DefaultLvalueConversion(Val).get();
   13865 
   13866   if (Val) {
   13867     if (Enum->isDependentType() || Val->isTypeDependent())
   13868       EltTy = Context.DependentTy;
   13869     else {
   13870       SourceLocation ExpLoc;
   13871       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
   13872           !getLangOpts().MSVCCompat) {
   13873         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
   13874         // constant-expression in the enumerator-definition shall be a converted
   13875         // constant expression of the underlying type.
   13876         EltTy = Enum->getIntegerType();
   13877         ExprResult Converted =
   13878           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
   13879                                            CCEK_Enumerator);
   13880         if (Converted.isInvalid())
   13881           Val = nullptr;
   13882         else
   13883           Val = Converted.get();
   13884       } else if (!Val->isValueDependent() &&
   13885                  !(Val = VerifyIntegerConstantExpression(Val,
   13886                                                          &EnumVal).get())) {
   13887         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
   13888       } else {
   13889         if (Enum->isFixed()) {
   13890           EltTy = Enum->getIntegerType();
   13891 
   13892           // In Obj-C and Microsoft mode, require the enumeration value to be
   13893           // representable in the underlying type of the enumeration. In C++11,
   13894           // we perform a non-narrowing conversion as part of converted constant
   13895           // expression checking.
   13896           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
   13897             if (getLangOpts().MSVCCompat) {
   13898               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
   13899               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
   13900             } else
   13901               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
   13902           } else
   13903             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
   13904         } else if (getLangOpts().CPlusPlus) {
   13905           // C++11 [dcl.enum]p5:
   13906           //   If the underlying type is not fixed, the type of each enumerator
   13907           //   is the type of its initializing value:
   13908           //     - If an initializer is specified for an enumerator, the
   13909           //       initializing value has the same type as the expression.
   13910           EltTy = Val->getType();
   13911         } else {
   13912           // C99 6.7.2.2p2:
   13913           //   The expression that defines the value of an enumeration constant
   13914           //   shall be an integer constant expression that has a value
   13915           //   representable as an int.
   13916 
   13917           // Complain if the value is not representable in an int.
   13918           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
   13919             Diag(IdLoc, diag::ext_enum_value_not_int)
   13920               << EnumVal.toString(10) << Val->getSourceRange()
   13921               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
   13922           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
   13923             // Force the type of the expression to 'int'.
   13924             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
   13925           }
   13926           EltTy = Val->getType();
   13927         }
   13928       }
   13929     }
   13930   }
   13931 
   13932   if (!Val) {
   13933     if (Enum->isDependentType())
   13934       EltTy = Context.DependentTy;
   13935     else if (!LastEnumConst) {
   13936       // C++0x [dcl.enum]p5:
   13937       //   If the underlying type is not fixed, the type of each enumerator
   13938       //   is the type of its initializing value:
   13939       //     - If no initializer is specified for the first enumerator, the
   13940       //       initializing value has an unspecified integral type.
   13941       //
   13942       // GCC uses 'int' for its unspecified integral type, as does
   13943       // C99 6.7.2.2p3.
   13944       if (Enum->isFixed()) {
   13945         EltTy = Enum->getIntegerType();
   13946       }
   13947       else {
   13948         EltTy = Context.IntTy;
   13949       }
   13950     } else {
   13951       // Assign the last value + 1.
   13952       EnumVal = LastEnumConst->getInitVal();
   13953       ++EnumVal;
   13954       EltTy = LastEnumConst->getType();
   13955 
   13956       // Check for overflow on increment.
   13957       if (EnumVal < LastEnumConst->getInitVal()) {
   13958         // C++0x [dcl.enum]p5:
   13959         //   If the underlying type is not fixed, the type of each enumerator
   13960         //   is the type of its initializing value:
   13961         //
   13962         //     - Otherwise the type of the initializing value is the same as
   13963         //       the type of the initializing value of the preceding enumerator
   13964         //       unless the incremented value is not representable in that type,
   13965         //       in which case the type is an unspecified integral type
   13966         //       sufficient to contain the incremented value. If no such type
   13967         //       exists, the program is ill-formed.
   13968         QualType T = getNextLargerIntegralType(Context, EltTy);
   13969         if (T.isNull() || Enum->isFixed()) {
   13970           // There is no integral type larger enough to represent this
   13971           // value. Complain, then allow the value to wrap around.
   13972           EnumVal = LastEnumConst->getInitVal();
   13973           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
   13974           ++EnumVal;
   13975           if (Enum->isFixed())
   13976             // When the underlying type is fixed, this is ill-formed.
   13977             Diag(IdLoc, diag::err_enumerator_wrapped)
   13978               << EnumVal.toString(10)
   13979               << EltTy;
   13980           else
   13981             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
   13982               << EnumVal.toString(10);
   13983         } else {
   13984           EltTy = T;
   13985         }
   13986 
   13987         // Retrieve the last enumerator's value, extent that type to the
   13988         // type that is supposed to be large enough to represent the incremented
   13989         // value, then increment.
   13990         EnumVal = LastEnumConst->getInitVal();
   13991         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
   13992         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
   13993         ++EnumVal;
   13994 
   13995         // If we're not in C++, diagnose the overflow of enumerator values,
   13996         // which in C99 means that the enumerator value is not representable in
   13997         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
   13998         // permits enumerator values that are representable in some larger
   13999         // integral type.
   14000         if (!getLangOpts().CPlusPlus && !T.isNull())
   14001           Diag(IdLoc, diag::warn_enum_value_overflow);
   14002       } else if (!getLangOpts().CPlusPlus &&
   14003                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
   14004         // Enforce C99 6.7.2.2p2 even when we compute the next value.
   14005         Diag(IdLoc, diag::ext_enum_value_not_int)
   14006           << EnumVal.toString(10) << 1;
   14007       }
   14008     }
   14009   }
   14010 
   14011   if (!EltTy->isDependentType()) {
   14012     // Make the enumerator value match the signedness and size of the
   14013     // enumerator's type.
   14014     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
   14015     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
   14016   }
   14017 
   14018   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
   14019                                   Val, EnumVal);
   14020 }
   14021 
   14022 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
   14023                                                 SourceLocation IILoc) {
   14024   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
   14025       !getLangOpts().CPlusPlus)
   14026     return SkipBodyInfo();
   14027 
   14028   // We have an anonymous enum definition. Look up the first enumerator to
   14029   // determine if we should merge the definition with an existing one and
   14030   // skip the body.
   14031   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
   14032                                          ForRedeclaration);
   14033   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
   14034   if (!PrevECD)
   14035     return SkipBodyInfo();
   14036 
   14037   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
   14038   NamedDecl *Hidden;
   14039   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
   14040     SkipBodyInfo Skip;
   14041     Skip.Previous = Hidden;
   14042     return Skip;
   14043   }
   14044 
   14045   return SkipBodyInfo();
   14046 }
   14047 
   14048 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
   14049                               SourceLocation IdLoc, IdentifierInfo *Id,
   14050                               AttributeList *Attr,
   14051                               SourceLocation EqualLoc, Expr *Val) {
   14052   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
   14053   EnumConstantDecl *LastEnumConst =
   14054     cast_or_null<EnumConstantDecl>(lastEnumConst);
   14055 
   14056   // The scope passed in may not be a decl scope.  Zip up the scope tree until
   14057   // we find one that is.
   14058   S = getNonFieldDeclScope(S);
   14059 
   14060   // Verify that there isn't already something declared with this name in this
   14061   // scope.
   14062   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
   14063                                          ForRedeclaration);
   14064   if (PrevDecl && PrevDecl->isTemplateParameter()) {
   14065     // Maybe we will complain about the shadowed template parameter.
   14066     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
   14067     // Just pretend that we didn't see the previous declaration.
   14068     PrevDecl = nullptr;
   14069   }
   14070 
   14071   // C++ [class.mem]p15:
   14072   // If T is the name of a class, then each of the following shall have a name
   14073   // different from T:
   14074   // - every enumerator of every member of class T that is an unscoped
   14075   // enumerated type
   14076   if (!TheEnumDecl->isScoped())
   14077     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
   14078                             DeclarationNameInfo(Id, IdLoc));
   14079 
   14080   EnumConstantDecl *New =
   14081     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
   14082   if (!New)
   14083     return nullptr;
   14084 
   14085   if (PrevDecl) {
   14086     // When in C++, we may get a TagDecl with the same name; in this case the
   14087     // enum constant will 'hide' the tag.
   14088     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
   14089            "Received TagDecl when not in C++!");
   14090     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
   14091         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
   14092       if (isa<EnumConstantDecl>(PrevDecl))
   14093         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
   14094       else
   14095         Diag(IdLoc, diag::err_redefinition) << Id;
   14096       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   14097       return nullptr;
   14098     }
   14099   }
   14100 
   14101   // Process attributes.
   14102   if (Attr) ProcessDeclAttributeList(S, New, Attr);
   14103 
   14104   // Register this decl in the current scope stack.
   14105   New->setAccess(TheEnumDecl->getAccess());
   14106   PushOnScopeChains(New, S);
   14107 
   14108   ActOnDocumentableDecl(New);
   14109 
   14110   return New;
   14111 }
   14112 
   14113 // Returns true when the enum initial expression does not trigger the
   14114 // duplicate enum warning.  A few common cases are exempted as follows:
   14115 // Element2 = Element1
   14116 // Element2 = Element1 + 1
   14117 // Element2 = Element1 - 1
   14118 // Where Element2 and Element1 are from the same enum.
   14119 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
   14120   Expr *InitExpr = ECD->getInitExpr();
   14121   if (!InitExpr)
   14122     return true;
   14123   InitExpr = InitExpr->IgnoreImpCasts();
   14124 
   14125   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
   14126     if (!BO->isAdditiveOp())
   14127       return true;
   14128     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
   14129     if (!IL)
   14130       return true;
   14131     if (IL->getValue() != 1)
   14132       return true;
   14133 
   14134     InitExpr = BO->getLHS();
   14135   }
   14136 
   14137   // This checks if the elements are from the same enum.
   14138   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
   14139   if (!DRE)
   14140     return true;
   14141 
   14142   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
   14143   if (!EnumConstant)
   14144     return true;
   14145 
   14146   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
   14147       Enum)
   14148     return true;
   14149 
   14150   return false;
   14151 }
   14152 
   14153 namespace {
   14154 struct DupKey {
   14155   int64_t val;
   14156   bool isTombstoneOrEmptyKey;
   14157   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
   14158     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
   14159 };
   14160 
   14161 static DupKey GetDupKey(const llvm::APSInt& Val) {
   14162   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
   14163                 false);
   14164 }
   14165 
   14166 struct DenseMapInfoDupKey {
   14167   static DupKey getEmptyKey() { return DupKey(0, true); }
   14168   static DupKey getTombstoneKey() { return DupKey(1, true); }
   14169   static unsigned getHashValue(const DupKey Key) {
   14170     return (unsigned)(Key.val * 37);
   14171   }
   14172   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
   14173     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
   14174            LHS.val == RHS.val;
   14175   }
   14176 };
   14177 } // end anonymous namespace
   14178 
   14179 // Emits a warning when an element is implicitly set a value that
   14180 // a previous element has already been set to.
   14181 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
   14182                                         EnumDecl *Enum,
   14183                                         QualType EnumType) {
   14184   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
   14185     return;
   14186   // Avoid anonymous enums
   14187   if (!Enum->getIdentifier())
   14188     return;
   14189 
   14190   // Only check for small enums.
   14191   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
   14192     return;
   14193 
   14194   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
   14195   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
   14196 
   14197   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
   14198   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
   14199           ValueToVectorMap;
   14200 
   14201   DuplicatesVector DupVector;
   14202   ValueToVectorMap EnumMap;
   14203 
   14204   // Populate the EnumMap with all values represented by enum constants without
   14205   // an initialier.
   14206   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
   14207     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
   14208 
   14209     // Null EnumConstantDecl means a previous diagnostic has been emitted for
   14210     // this constant.  Skip this enum since it may be ill-formed.
   14211     if (!ECD) {
   14212       return;
   14213     }
   14214 
   14215     if (ECD->getInitExpr())
   14216       continue;
   14217 
   14218     DupKey Key = GetDupKey(ECD->getInitVal());
   14219     DeclOrVector &Entry = EnumMap[Key];
   14220 
   14221     // First time encountering this value.
   14222     if (Entry.isNull())
   14223       Entry = ECD;
   14224   }
   14225 
   14226   // Create vectors for any values that has duplicates.
   14227   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
   14228     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
   14229     if (!ValidDuplicateEnum(ECD, Enum))
   14230       continue;
   14231 
   14232     DupKey Key = GetDupKey(ECD->getInitVal());
   14233 
   14234     DeclOrVector& Entry = EnumMap[Key];
   14235     if (Entry.isNull())
   14236       continue;
   14237 
   14238     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
   14239       // Ensure constants are different.
   14240       if (D == ECD)
   14241         continue;
   14242 
   14243       // Create new vector and push values onto it.
   14244       ECDVector *Vec = new ECDVector();
   14245       Vec->push_back(D);
   14246       Vec->push_back(ECD);
   14247 
   14248       // Update entry to point to the duplicates vector.
   14249       Entry = Vec;
   14250 
   14251       // Store the vector somewhere we can consult later for quick emission of
   14252       // diagnostics.
   14253       DupVector.push_back(Vec);
   14254       continue;
   14255     }
   14256 
   14257     ECDVector *Vec = Entry.get<ECDVector*>();
   14258     // Make sure constants are not added more than once.
   14259     if (*Vec->begin() == ECD)
   14260       continue;
   14261 
   14262     Vec->push_back(ECD);
   14263   }
   14264 
   14265   // Emit diagnostics.
   14266   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
   14267                                   DupVectorEnd = DupVector.end();
   14268        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
   14269     ECDVector *Vec = *DupVectorIter;
   14270     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
   14271 
   14272     // Emit warning for one enum constant.
   14273     ECDVector::iterator I = Vec->begin();
   14274     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
   14275       << (*I)->getName() << (*I)->getInitVal().toString(10)
   14276       << (*I)->getSourceRange();
   14277     ++I;
   14278 
   14279     // Emit one note for each of the remaining enum constants with
   14280     // the same value.
   14281     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
   14282       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
   14283         << (*I)->getName() << (*I)->getInitVal().toString(10)
   14284         << (*I)->getSourceRange();
   14285     delete Vec;
   14286   }
   14287 }
   14288 
   14289 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
   14290                              bool AllowMask) const {
   14291   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
   14292   assert(ED->isCompleteDefinition() && "expected enum definition");
   14293 
   14294   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
   14295   llvm::APInt &FlagBits = R.first->second;
   14296 
   14297   if (R.second) {
   14298     for (auto *E : ED->enumerators()) {
   14299       const auto &EVal = E->getInitVal();
   14300       // Only single-bit enumerators introduce new flag values.
   14301       if (EVal.isPowerOf2())
   14302         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
   14303     }
   14304   }
   14305 
   14306   // A value is in a flag enum if either its bits are a subset of the enum's
   14307   // flag bits (the first condition) or we are allowing masks and the same is
   14308   // true of its complement (the second condition). When masks are allowed, we
   14309   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
   14310   //
   14311   // While it's true that any value could be used as a mask, the assumption is
   14312   // that a mask will have all of the insignificant bits set. Anything else is
   14313   // likely a logic error.
   14314   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
   14315   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
   14316 }
   14317 
   14318 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
   14319                          SourceLocation RBraceLoc, Decl *EnumDeclX,
   14320                          ArrayRef<Decl *> Elements,
   14321                          Scope *S, AttributeList *Attr) {
   14322   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
   14323   QualType EnumType = Context.getTypeDeclType(Enum);
   14324 
   14325   if (Attr)
   14326     ProcessDeclAttributeList(S, Enum, Attr);
   14327 
   14328   if (Enum->isDependentType()) {
   14329     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
   14330       EnumConstantDecl *ECD =
   14331         cast_or_null<EnumConstantDecl>(Elements[i]);
   14332       if (!ECD) continue;
   14333 
   14334       ECD->setType(EnumType);
   14335     }
   14336 
   14337     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
   14338     return;
   14339   }
   14340 
   14341   // TODO: If the result value doesn't fit in an int, it must be a long or long
   14342   // long value.  ISO C does not support this, but GCC does as an extension,
   14343   // emit a warning.
   14344   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   14345   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
   14346   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
   14347 
   14348   // Verify that all the values are okay, compute the size of the values, and
   14349   // reverse the list.
   14350   unsigned NumNegativeBits = 0;
   14351   unsigned NumPositiveBits = 0;
   14352 
   14353   // Keep track of whether all elements have type int.
   14354   bool AllElementsInt = true;
   14355 
   14356   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
   14357     EnumConstantDecl *ECD =
   14358       cast_or_null<EnumConstantDecl>(Elements[i]);
   14359     if (!ECD) continue;  // Already issued a diagnostic.
   14360 
   14361     const llvm::APSInt &InitVal = ECD->getInitVal();
   14362 
   14363     // Keep track of the size of positive and negative values.
   14364     if (InitVal.isUnsigned() || InitVal.isNonNegative())
   14365       NumPositiveBits = std::max(NumPositiveBits,
   14366                                  (unsigned)InitVal.getActiveBits());
   14367     else
   14368       NumNegativeBits = std::max(NumNegativeBits,
   14369                                  (unsigned)InitVal.getMinSignedBits());
   14370 
   14371     // Keep track of whether every enum element has type int (very commmon).
   14372     if (AllElementsInt)
   14373       AllElementsInt = ECD->getType() == Context.IntTy;
   14374   }
   14375 
   14376   // Figure out the type that should be used for this enum.
   14377   QualType BestType;
   14378   unsigned BestWidth;
   14379 
   14380   // C++0x N3000 [conv.prom]p3:
   14381   //   An rvalue of an unscoped enumeration type whose underlying
   14382   //   type is not fixed can be converted to an rvalue of the first
   14383   //   of the following types that can represent all the values of
   14384   //   the enumeration: int, unsigned int, long int, unsigned long
   14385   //   int, long long int, or unsigned long long int.
   14386   // C99 6.4.4.3p2:
   14387   //   An identifier declared as an enumeration constant has type int.
   14388   // The C99 rule is modified by a gcc extension
   14389   QualType BestPromotionType;
   14390 
   14391   bool Packed = Enum->hasAttr<PackedAttr>();
   14392   // -fshort-enums is the equivalent to specifying the packed attribute on all
   14393   // enum definitions.
   14394   if (LangOpts.ShortEnums)
   14395     Packed = true;
   14396 
   14397   if (Enum->isFixed()) {
   14398     BestType = Enum->getIntegerType();
   14399     if (BestType->isPromotableIntegerType())
   14400       BestPromotionType = Context.getPromotedIntegerType(BestType);
   14401     else
   14402       BestPromotionType = BestType;
   14403 
   14404     BestWidth = Context.getIntWidth(BestType);
   14405   }
   14406   else if (NumNegativeBits) {
   14407     // If there is a negative value, figure out the smallest integer type (of
   14408     // int/long/longlong) that fits.
   14409     // If it's packed, check also if it fits a char or a short.
   14410     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
   14411       BestType = Context.SignedCharTy;
   14412       BestWidth = CharWidth;
   14413     } else if (Packed && NumNegativeBits <= ShortWidth &&
   14414                NumPositiveBits < ShortWidth) {
   14415       BestType = Context.ShortTy;
   14416       BestWidth = ShortWidth;
   14417     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
   14418       BestType = Context.IntTy;
   14419       BestWidth = IntWidth;
   14420     } else {
   14421       BestWidth = Context.getTargetInfo().getLongWidth();
   14422 
   14423       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
   14424         BestType = Context.LongTy;
   14425       } else {
   14426         BestWidth = Context.getTargetInfo().getLongLongWidth();
   14427 
   14428         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
   14429           Diag(Enum->getLocation(), diag::ext_enum_too_large);
   14430         BestType = Context.LongLongTy;
   14431       }
   14432     }
   14433     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
   14434   } else {
   14435     // If there is no negative value, figure out the smallest type that fits
   14436     // all of the enumerator values.
   14437     // If it's packed, check also if it fits a char or a short.
   14438     if (Packed && NumPositiveBits <= CharWidth) {
   14439       BestType = Context.UnsignedCharTy;
   14440       BestPromotionType = Context.IntTy;
   14441       BestWidth = CharWidth;
   14442     } else if (Packed && NumPositiveBits <= ShortWidth) {
   14443       BestType = Context.UnsignedShortTy;
   14444       BestPromotionType = Context.IntTy;
   14445       BestWidth = ShortWidth;
   14446     } else if (NumPositiveBits <= IntWidth) {
   14447       BestType = Context.UnsignedIntTy;
   14448       BestWidth = IntWidth;
   14449       BestPromotionType
   14450         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
   14451                            ? Context.UnsignedIntTy : Context.IntTy;
   14452     } else if (NumPositiveBits <=
   14453                (BestWidth = Context.getTargetInfo().getLongWidth())) {
   14454       BestType = Context.UnsignedLongTy;
   14455       BestPromotionType
   14456         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
   14457                            ? Context.UnsignedLongTy : Context.LongTy;
   14458     } else {
   14459       BestWidth = Context.getTargetInfo().getLongLongWidth();
   14460       assert(NumPositiveBits <= BestWidth &&
   14461              "How could an initializer get larger than ULL?");
   14462       BestType = Context.UnsignedLongLongTy;
   14463       BestPromotionType
   14464         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
   14465                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
   14466     }
   14467   }
   14468 
   14469   // Loop over all of the enumerator constants, changing their types to match
   14470   // the type of the enum if needed.
   14471   for (auto *D : Elements) {
   14472     auto *ECD = cast_or_null<EnumConstantDecl>(D);
   14473     if (!ECD) continue;  // Already issued a diagnostic.
   14474 
   14475     // Standard C says the enumerators have int type, but we allow, as an
   14476     // extension, the enumerators to be larger than int size.  If each
   14477     // enumerator value fits in an int, type it as an int, otherwise type it the
   14478     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
   14479     // that X has type 'int', not 'unsigned'.
   14480 
   14481     // Determine whether the value fits into an int.
   14482     llvm::APSInt InitVal = ECD->getInitVal();
   14483 
   14484     // If it fits into an integer type, force it.  Otherwise force it to match
   14485     // the enum decl type.
   14486     QualType NewTy;
   14487     unsigned NewWidth;
   14488     bool NewSign;
   14489     if (!getLangOpts().CPlusPlus &&
   14490         !Enum->isFixed() &&
   14491         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
   14492       NewTy = Context.IntTy;
   14493       NewWidth = IntWidth;
   14494       NewSign = true;
   14495     } else if (ECD->getType() == BestType) {
   14496       // Already the right type!
   14497       if (getLangOpts().CPlusPlus)
   14498         // C++ [dcl.enum]p4: Following the closing brace of an
   14499         // enum-specifier, each enumerator has the type of its
   14500         // enumeration.
   14501         ECD->setType(EnumType);
   14502       continue;
   14503     } else {
   14504       NewTy = BestType;
   14505       NewWidth = BestWidth;
   14506       NewSign = BestType->isSignedIntegerOrEnumerationType();
   14507     }
   14508 
   14509     // Adjust the APSInt value.
   14510     InitVal = InitVal.extOrTrunc(NewWidth);
   14511     InitVal.setIsSigned(NewSign);
   14512     ECD->setInitVal(InitVal);
   14513 
   14514     // Adjust the Expr initializer and type.
   14515     if (ECD->getInitExpr() &&
   14516         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
   14517       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
   14518                                                 CK_IntegralCast,
   14519                                                 ECD->getInitExpr(),
   14520                                                 /*base paths*/ nullptr,
   14521                                                 VK_RValue));
   14522     if (getLangOpts().CPlusPlus)
   14523       // C++ [dcl.enum]p4: Following the closing brace of an
   14524       // enum-specifier, each enumerator has the type of its
   14525       // enumeration.
   14526       ECD->setType(EnumType);
   14527     else
   14528       ECD->setType(NewTy);
   14529   }
   14530 
   14531   Enum->completeDefinition(BestType, BestPromotionType,
   14532                            NumPositiveBits, NumNegativeBits);
   14533 
   14534   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
   14535 
   14536   if (Enum->hasAttr<FlagEnumAttr>()) {
   14537     for (Decl *D : Elements) {
   14538       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
   14539       if (!ECD) continue;  // Already issued a diagnostic.
   14540 
   14541       llvm::APSInt InitVal = ECD->getInitVal();
   14542       if (InitVal != 0 && !InitVal.isPowerOf2() &&
   14543           !IsValueInFlagEnum(Enum, InitVal, true))
   14544         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
   14545           << ECD << Enum;
   14546     }
   14547   }
   14548 
   14549   // Now that the enum type is defined, ensure it's not been underaligned.
   14550   if (Enum->hasAttrs())
   14551     CheckAlignasUnderalignment(Enum);
   14552 }
   14553 
   14554 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
   14555                                   SourceLocation StartLoc,
   14556                                   SourceLocation EndLoc) {
   14557   StringLiteral *AsmString = cast<StringLiteral>(expr);
   14558 
   14559   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
   14560                                                    AsmString, StartLoc,
   14561                                                    EndLoc);
   14562   CurContext->addDecl(New);
   14563   return New;
   14564 }
   14565 
   14566 static void checkModuleImportContext(Sema &S, Module *M,
   14567                                      SourceLocation ImportLoc, DeclContext *DC,
   14568                                      bool FromInclude = false) {
   14569   SourceLocation ExternCLoc;
   14570 
   14571   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
   14572     switch (LSD->getLanguage()) {
   14573     case LinkageSpecDecl::lang_c:
   14574       if (ExternCLoc.isInvalid())
   14575         ExternCLoc = LSD->getLocStart();
   14576       break;
   14577     case LinkageSpecDecl::lang_cxx:
   14578       break;
   14579     }
   14580     DC = LSD->getParent();
   14581   }
   14582 
   14583   while (isa<LinkageSpecDecl>(DC))
   14584     DC = DC->getParent();
   14585 
   14586   if (!isa<TranslationUnitDecl>(DC)) {
   14587     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
   14588                           ? diag::ext_module_import_not_at_top_level_noop
   14589                           : diag::err_module_import_not_at_top_level_fatal)
   14590         << M->getFullModuleName() << DC;
   14591     S.Diag(cast<Decl>(DC)->getLocStart(),
   14592            diag::note_module_import_not_at_top_level) << DC;
   14593   } else if (!M->IsExternC && ExternCLoc.isValid()) {
   14594     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
   14595       << M->getFullModuleName();
   14596     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
   14597   }
   14598 }
   14599 
   14600 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
   14601   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
   14602 }
   14603 
   14604 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
   14605                                    SourceLocation ImportLoc,
   14606                                    ModuleIdPath Path) {
   14607   Module *Mod =
   14608       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
   14609                                    /*IsIncludeDirective=*/false);
   14610   if (!Mod)
   14611     return true;
   14612 
   14613   VisibleModules.setVisible(Mod, ImportLoc);
   14614 
   14615   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
   14616 
   14617   // FIXME: we should support importing a submodule within a different submodule
   14618   // of the same top-level module. Until we do, make it an error rather than
   14619   // silently ignoring the import.
   14620   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
   14621     Diag(ImportLoc, diag::err_module_self_import)
   14622         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
   14623   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
   14624     Diag(ImportLoc, diag::err_module_import_in_implementation)
   14625         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
   14626 
   14627   SmallVector<SourceLocation, 2> IdentifierLocs;
   14628   Module *ModCheck = Mod;
   14629   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
   14630     // If we've run out of module parents, just drop the remaining identifiers.
   14631     // We need the length to be consistent.
   14632     if (!ModCheck)
   14633       break;
   14634     ModCheck = ModCheck->Parent;
   14635 
   14636     IdentifierLocs.push_back(Path[I].second);
   14637   }
   14638 
   14639   ImportDecl *Import = ImportDecl::Create(Context,
   14640                                           Context.getTranslationUnitDecl(),
   14641                                           AtLoc.isValid()? AtLoc : ImportLoc,
   14642                                           Mod, IdentifierLocs);
   14643   Context.getTranslationUnitDecl()->addDecl(Import);
   14644   return Import;
   14645 }
   14646 
   14647 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
   14648   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
   14649 
   14650   // Determine whether we're in the #include buffer for a module. The #includes
   14651   // in that buffer do not qualify as module imports; they're just an
   14652   // implementation detail of us building the module.
   14653   //
   14654   // FIXME: Should we even get ActOnModuleInclude calls for those?
   14655   bool IsInModuleIncludes =
   14656       TUKind == TU_Module &&
   14657       getSourceManager().isWrittenInMainFile(DirectiveLoc);
   14658 
   14659   // If this module import was due to an inclusion directive, create an
   14660   // implicit import declaration to capture it in the AST.
   14661   if (!IsInModuleIncludes) {
   14662     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
   14663     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
   14664                                                      DirectiveLoc, Mod,
   14665                                                      DirectiveLoc);
   14666     TU->addDecl(ImportD);
   14667     Consumer.HandleImplicitImportDecl(ImportD);
   14668   }
   14669 
   14670   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
   14671   VisibleModules.setVisible(Mod, DirectiveLoc);
   14672 }
   14673 
   14674 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
   14675   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
   14676 
   14677   if (getLangOpts().ModulesLocalVisibility)
   14678     VisibleModulesStack.push_back(std::move(VisibleModules));
   14679   VisibleModules.setVisible(Mod, DirectiveLoc);
   14680 }
   14681 
   14682 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
   14683   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
   14684 
   14685   if (getLangOpts().ModulesLocalVisibility) {
   14686     VisibleModules = std::move(VisibleModulesStack.back());
   14687     VisibleModulesStack.pop_back();
   14688     VisibleModules.setVisible(Mod, DirectiveLoc);
   14689   }
   14690 }
   14691 
   14692 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
   14693                                                       Module *Mod) {
   14694   // Bail if we're not allowed to implicitly import a module here.
   14695   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
   14696     return;
   14697 
   14698   // Create the implicit import declaration.
   14699   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
   14700   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
   14701                                                    Loc, Mod, Loc);
   14702   TU->addDecl(ImportD);
   14703   Consumer.HandleImplicitImportDecl(ImportD);
   14704 
   14705   // Make the module visible.
   14706   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
   14707   VisibleModules.setVisible(Mod, Loc);
   14708 }
   14709 
   14710 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
   14711                                       IdentifierInfo* AliasName,
   14712                                       SourceLocation PragmaLoc,
   14713                                       SourceLocation NameLoc,
   14714                                       SourceLocation AliasNameLoc) {
   14715   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
   14716                                          LookupOrdinaryName);
   14717   AsmLabelAttr *Attr =
   14718       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
   14719 
   14720   // If a declaration that:
   14721   // 1) declares a function or a variable
   14722   // 2) has external linkage
   14723   // already exists, add a label attribute to it.
   14724   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
   14725     if (isDeclExternC(PrevDecl))
   14726       PrevDecl->addAttr(Attr);
   14727     else
   14728       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
   14729           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
   14730   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
   14731   } else
   14732     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
   14733 }
   14734 
   14735 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
   14736                              SourceLocation PragmaLoc,
   14737                              SourceLocation NameLoc) {
   14738   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
   14739 
   14740   if (PrevDecl) {
   14741     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
   14742   } else {
   14743     (void)WeakUndeclaredIdentifiers.insert(
   14744       std::pair<IdentifierInfo*,WeakInfo>
   14745         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
   14746   }
   14747 }
   14748 
   14749 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
   14750                                 IdentifierInfo* AliasName,
   14751                                 SourceLocation PragmaLoc,
   14752                                 SourceLocation NameLoc,
   14753                                 SourceLocation AliasNameLoc) {
   14754   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
   14755                                     LookupOrdinaryName);
   14756   WeakInfo W = WeakInfo(Name, NameLoc);
   14757 
   14758   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
   14759     if (!PrevDecl->hasAttr<AliasAttr>())
   14760       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
   14761         DeclApplyPragmaWeak(TUScope, ND, W);
   14762   } else {
   14763     (void)WeakUndeclaredIdentifiers.insert(
   14764       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
   14765   }
   14766 }
   14767 
   14768 Decl *Sema::getObjCDeclContext() const {
   14769   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
   14770 }
   14771 
   14772 AvailabilityResult Sema::getCurContextAvailability() const {
   14773   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
   14774   if (!D)
   14775     return AR_Available;
   14776 
   14777   // If we are within an Objective-C method, we should consult
   14778   // both the availability of the method as well as the
   14779   // enclosing class.  If the class is (say) deprecated,
   14780   // the entire method is considered deprecated from the
   14781   // purpose of checking if the current context is deprecated.
   14782   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
   14783     AvailabilityResult R = MD->getAvailability();
   14784     if (R != AR_Available)
   14785       return R;
   14786     D = MD->getClassInterface();
   14787   }
   14788   // If we are within an Objective-c @implementation, it
   14789   // gets the same availability context as the @interface.
   14790   else if (const ObjCImplementationDecl *ID =
   14791             dyn_cast<ObjCImplementationDecl>(D)) {
   14792     D = ID->getClassInterface();
   14793   }
   14794   // Recover from user error.
   14795   return D ? D->getAvailability() : AR_Available;
   14796 }
   14797