1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaInternal.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 
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 final : public CorrectionCandidateCallback {
65  public:
66    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
67                         bool AllowTemplates = false,
68                         bool AllowNonTemplates = true)
69        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
71      WantExpressionKeywords = false;
72      WantCXXNamedCasts = false;
73      WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       if (!AllowInvalidDecl && ND->isInvalidDecl())
79         return false;
80 
81       if (getAsTypeTemplateDecl(ND))
82         return AllowTemplates;
83 
84       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
85       if (!IsType)
86         return false;
87 
88       if (AllowNonTemplates)
89         return true;
90 
91       // An injected-class-name of a class template (specialization) is valid
92       // as a template or as a non-template.
93       if (AllowTemplates) {
94         auto *RD = dyn_cast<CXXRecordDecl>(ND);
95         if (!RD || !RD->isInjectedClassName())
96           return false;
97         RD = cast<CXXRecordDecl>(RD->getDeclContext());
98         return RD->getDescribedClassTemplate() ||
99                isa<ClassTemplateSpecializationDecl>(RD);
100       }
101 
102       return false;
103     }
104 
105     return !WantClassName && candidate.isKeyword();
106   }
107 
108   std::unique_ptr<CorrectionCandidateCallback> clone() override {
109     return llvm::make_unique<TypeNameValidatorCCC>(*this);
110   }
111 
112  private:
113   bool AllowInvalidDecl;
114   bool WantClassName;
115   bool AllowTemplates;
116   bool AllowNonTemplates;
117 };
118 
119 } // end anonymous namespace
120 
121 /// Determine whether the token kind starts a simple-type-specifier.
122 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
123   switch (Kind) {
124   // FIXME: Take into account the current language when deciding whether a
125   // token kind is a valid type specifier
126   case tok::kw_short:
127   case tok::kw_long:
128   case tok::kw___int64:
129   case tok::kw___int128:
130   case tok::kw_signed:
131   case tok::kw_unsigned:
132   case tok::kw_void:
133   case tok::kw_char:
134   case tok::kw_int:
135   case tok::kw_half:
136   case tok::kw_float:
137   case tok::kw_double:
138   case tok::kw__Float16:
139   case tok::kw___float128:
140   case tok::kw_wchar_t:
141   case tok::kw_bool:
142   case tok::kw___underlying_type:
143   case tok::kw___auto_type:
144     return true;
145 
146   case tok::annot_typename:
147   case tok::kw_char16_t:
148   case tok::kw_char32_t:
149   case tok::kw_typeof:
150   case tok::annot_decltype:
151   case tok::kw_decltype:
152     return getLangOpts().CPlusPlus;
153 
154   case tok::kw_char8_t:
155     return getLangOpts().Char8;
156 
157   default:
158     break;
159   }
160 
161   return false;
162 }
163 
164 namespace {
165 enum class UnqualifiedTypeNameLookupResult {
166   NotFound,
167   FoundNonType,
168   FoundType
169 };
170 } // end anonymous namespace
171 
172 /// Tries to perform unqualified lookup of the type decls in bases for
173 /// dependent class.
174 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
175 /// type decl, \a FoundType if only type decls are found.
176 static UnqualifiedTypeNameLookupResult
177 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
178                                 SourceLocation NameLoc,
179                                 const CXXRecordDecl *RD) {
180   if (!RD->hasDefinition())
181     return UnqualifiedTypeNameLookupResult::NotFound;
182   // Look for type decls in base classes.
183   UnqualifiedTypeNameLookupResult FoundTypeDecl =
184       UnqualifiedTypeNameLookupResult::NotFound;
185   for (const auto &Base : RD->bases()) {
186     const CXXRecordDecl *BaseRD = nullptr;
187     if (auto *BaseTT = Base.getType()->getAs<TagType>())
188       BaseRD = BaseTT->getAsCXXRecordDecl();
189     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
190       // Look for type decls in dependent base classes that have known primary
191       // templates.
192       if (!TST || !TST->isDependentType())
193         continue;
194       auto *TD = TST->getTemplateName().getAsTemplateDecl();
195       if (!TD)
196         continue;
197       if (auto *BasePrimaryTemplate =
198           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
199         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
200           BaseRD = BasePrimaryTemplate;
201         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
202           if (const ClassTemplatePartialSpecializationDecl *PS =
203                   CTD->findPartialSpecialization(Base.getType()))
204             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
205               BaseRD = PS;
206         }
207       }
208     }
209     if (BaseRD) {
210       for (NamedDecl *ND : BaseRD->lookup(&II)) {
211         if (!isa<TypeDecl>(ND))
212           return UnqualifiedTypeNameLookupResult::FoundNonType;
213         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214       }
215       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
216         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
217         case UnqualifiedTypeNameLookupResult::FoundNonType:
218           return UnqualifiedTypeNameLookupResult::FoundNonType;
219         case UnqualifiedTypeNameLookupResult::FoundType:
220           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
221           break;
222         case UnqualifiedTypeNameLookupResult::NotFound:
223           break;
224         }
225       }
226     }
227   }
228 
229   return FoundTypeDecl;
230 }
231 
232 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
233                                                       const IdentifierInfo &II,
234                                                       SourceLocation NameLoc) {
235   // Lookup in the parent class template context, if any.
236   const CXXRecordDecl *RD = nullptr;
237   UnqualifiedTypeNameLookupResult FoundTypeDecl =
238       UnqualifiedTypeNameLookupResult::NotFound;
239   for (DeclContext *DC = S.CurContext;
240        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
241        DC = DC->getParent()) {
242     // Look for type decls in dependent base classes that have known primary
243     // templates.
244     RD = dyn_cast<CXXRecordDecl>(DC);
245     if (RD && RD->getDescribedClassTemplate())
246       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
247   }
248   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
249     return nullptr;
250 
251   // We found some types in dependent base classes.  Recover as if the user
252   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
253   // lookup during template instantiation.
254   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
255 
256   ASTContext &Context = S.Context;
257   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
258                                           cast<Type>(Context.getRecordType(RD)));
259   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
260 
261   CXXScopeSpec SS;
262   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
263 
264   TypeLocBuilder Builder;
265   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
266   DepTL.setNameLoc(NameLoc);
267   DepTL.setElaboratedKeywordLoc(SourceLocation());
268   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
269   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
270 }
271 
272 /// If the identifier refers to a type name within this scope,
273 /// return the declaration of that type.
274 ///
275 /// This routine performs ordinary name lookup of the identifier II
276 /// within the given scope, with optional C++ scope specifier SS, to
277 /// determine whether the name refers to a type. If so, returns an
278 /// opaque pointer (actually a QualType) corresponding to that
279 /// type. Otherwise, returns NULL.
280 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
281                              Scope *S, CXXScopeSpec *SS,
282                              bool isClassName, bool HasTrailingDot,
283                              ParsedType ObjectTypePtr,
284                              bool IsCtorOrDtorName,
285                              bool WantNontrivialTypeSourceInfo,
286                              bool IsClassTemplateDeductionContext,
287                              IdentifierInfo **CorrectedII) {
288   // FIXME: Consider allowing this outside C++1z mode as an extension.
289   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
290                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
291                               !isClassName && !HasTrailingDot;
292 
293   // Determine where we will perform name lookup.
294   DeclContext *LookupCtx = nullptr;
295   if (ObjectTypePtr) {
296     QualType ObjectType = ObjectTypePtr.get();
297     if (ObjectType->isRecordType())
298       LookupCtx = computeDeclContext(ObjectType);
299   } else if (SS && SS->isNotEmpty()) {
300     LookupCtx = computeDeclContext(*SS, false);
301 
302     if (!LookupCtx) {
303       if (isDependentScopeSpecifier(*SS)) {
304         // C++ [temp.res]p3:
305         //   A qualified-id that refers to a type and in which the
306         //   nested-name-specifier depends on a template-parameter (14.6.2)
307         //   shall be prefixed by the keyword typename to indicate that the
308         //   qualified-id denotes a type, forming an
309         //   elaborated-type-specifier (7.1.5.3).
310         //
311         // We therefore do not perform any name lookup if the result would
312         // refer to a member of an unknown specialization.
313         if (!isClassName && !IsCtorOrDtorName)
314           return nullptr;
315 
316         // We know from the grammar that this name refers to a type,
317         // so build a dependent node to describe the type.
318         if (WantNontrivialTypeSourceInfo)
319           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
320 
321         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
322         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
323                                        II, NameLoc);
324         return ParsedType::make(T);
325       }
326 
327       return nullptr;
328     }
329 
330     if (!LookupCtx->isDependentContext() &&
331         RequireCompleteDeclContext(*SS, LookupCtx))
332       return nullptr;
333   }
334 
335   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
336   // lookup for class-names.
337   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
338                                       LookupOrdinaryName;
339   LookupResult Result(*this, &II, NameLoc, Kind);
340   if (LookupCtx) {
341     // Perform "qualified" name lookup into the declaration context we
342     // computed, which is either the type of the base of a member access
343     // expression or the declaration context associated with a prior
344     // nested-name-specifier.
345     LookupQualifiedName(Result, LookupCtx);
346 
347     if (ObjectTypePtr && Result.empty()) {
348       // C++ [basic.lookup.classref]p3:
349       //   If the unqualified-id is ~type-name, the type-name is looked up
350       //   in the context of the entire postfix-expression. If the type T of
351       //   the object expression is of a class type C, the type-name is also
352       //   looked up in the scope of class C. At least one of the lookups shall
353       //   find a name that refers to (possibly cv-qualified) T.
354       LookupName(Result, S);
355     }
356   } else {
357     // Perform unqualified name lookup.
358     LookupName(Result, S);
359 
360     // For unqualified lookup in a class template in MSVC mode, look into
361     // dependent base classes where the primary class template is known.
362     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
363       if (ParsedType TypeInBase =
364               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
365         return TypeInBase;
366     }
367   }
368 
369   NamedDecl *IIDecl = nullptr;
370   switch (Result.getResultKind()) {
371   case LookupResult::NotFound:
372   case LookupResult::NotFoundInCurrentInstantiation:
373     if (CorrectedII) {
374       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
375                                AllowDeducedTemplate);
376       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
377                                               S, SS, CCC, CTK_ErrorRecovery);
378       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
379       TemplateTy Template;
380       bool MemberOfUnknownSpecialization;
381       UnqualifiedId TemplateName;
382       TemplateName.setIdentifier(NewII, NameLoc);
383       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
384       CXXScopeSpec NewSS, *NewSSPtr = SS;
385       if (SS && NNS) {
386         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
387         NewSSPtr = &NewSS;
388       }
389       if (Correction && (NNS || NewII != &II) &&
390           // Ignore a correction to a template type as the to-be-corrected
391           // identifier is not a template (typo correction for template names
392           // is handled elsewhere).
393           !(getLangOpts().CPlusPlus && NewSSPtr &&
394             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
395                            Template, MemberOfUnknownSpecialization))) {
396         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
397                                     isClassName, HasTrailingDot, ObjectTypePtr,
398                                     IsCtorOrDtorName,
399                                     WantNontrivialTypeSourceInfo,
400                                     IsClassTemplateDeductionContext);
401         if (Ty) {
402           diagnoseTypo(Correction,
403                        PDiag(diag::err_unknown_type_or_class_name_suggest)
404                          << Result.getLookupName() << isClassName);
405           if (SS && NNS)
406             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
407           *CorrectedII = NewII;
408           return Ty;
409         }
410       }
411     }
412     // If typo correction failed or was not performed, fall through
413     LLVM_FALLTHROUGH;
414   case LookupResult::FoundOverloaded:
415   case LookupResult::FoundUnresolvedValue:
416     Result.suppressDiagnostics();
417     return nullptr;
418 
419   case LookupResult::Ambiguous:
420     // Recover from type-hiding ambiguities by hiding the type.  We'll
421     // do the lookup again when looking for an object, and we can
422     // diagnose the error then.  If we don't do this, then the error
423     // about hiding the type will be immediately followed by an error
424     // that only makes sense if the identifier was treated like a type.
425     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
426       Result.suppressDiagnostics();
427       return nullptr;
428     }
429 
430     // Look to see if we have a type anywhere in the list of results.
431     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
432          Res != ResEnd; ++Res) {
433       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
434           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
435         if (!IIDecl ||
436             (*Res)->getLocation().getRawEncoding() <
437               IIDecl->getLocation().getRawEncoding())
438           IIDecl = *Res;
439       }
440     }
441 
442     if (!IIDecl) {
443       // None of the entities we found is a type, so there is no way
444       // to even assume that the result is a type. In this case, don't
445       // complain about the ambiguity. The parser will either try to
446       // perform this lookup again (e.g., as an object name), which
447       // will produce the ambiguity, or will complain that it expected
448       // a type name.
449       Result.suppressDiagnostics();
450       return nullptr;
451     }
452 
453     // We found a type within the ambiguous lookup; diagnose the
454     // ambiguity and then return that type. This might be the right
455     // answer, or it might not be, but it suppresses any attempt to
456     // perform the name lookup again.
457     break;
458 
459   case LookupResult::Found:
460     IIDecl = Result.getFoundDecl();
461     break;
462   }
463 
464   assert(IIDecl && "Didn't find decl");
465 
466   QualType T;
467   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
468     // C++ [class.qual]p2: A lookup that would find the injected-class-name
469     // instead names the constructors of the class, except when naming a class.
470     // This is ill-formed when we're not actually forming a ctor or dtor name.
471     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
472     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
473     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
474         FoundRD->isInjectedClassName() &&
475         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
476       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
477           << &II << /*Type*/1;
478 
479     DiagnoseUseOfDecl(IIDecl, NameLoc);
480 
481     T = Context.getTypeDeclType(TD);
482     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
483   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
484     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
485     if (!HasTrailingDot)
486       T = Context.getObjCInterfaceType(IDecl);
487   } else if (AllowDeducedTemplate) {
488     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
489       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
490                                                        QualType(), false);
491   }
492 
493   if (T.isNull()) {
494     // If it's not plausibly a type, suppress diagnostics.
495     Result.suppressDiagnostics();
496     return nullptr;
497   }
498 
499   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
500   // constructor or destructor name (in such a case, the scope specifier
501   // will be attached to the enclosing Expr or Decl node).
502   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
503       !isa<ObjCInterfaceDecl>(IIDecl)) {
504     if (WantNontrivialTypeSourceInfo) {
505       // Construct a type with type-source information.
506       TypeLocBuilder Builder;
507       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
508 
509       T = getElaboratedType(ETK_None, *SS, T);
510       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
511       ElabTL.setElaboratedKeywordLoc(SourceLocation());
512       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
513       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
514     } else {
515       T = getElaboratedType(ETK_None, *SS, T);
516     }
517   }
518 
519   return ParsedType::make(T);
520 }
521 
522 // Builds a fake NNS for the given decl context.
523 static NestedNameSpecifier *
524 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
525   for (;; DC = DC->getLookupParent()) {
526     DC = DC->getPrimaryContext();
527     auto *ND = dyn_cast<NamespaceDecl>(DC);
528     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
529       return NestedNameSpecifier::Create(Context, nullptr, ND);
530     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
531       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
532                                          RD->getTypeForDecl());
533     else if (isa<TranslationUnitDecl>(DC))
534       return NestedNameSpecifier::GlobalSpecifier(Context);
535   }
536   llvm_unreachable("something isn't in TU scope?");
537 }
538 
539 /// Find the parent class with dependent bases of the innermost enclosing method
540 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
541 /// up allowing unqualified dependent type names at class-level, which MSVC
542 /// correctly rejects.
543 static const CXXRecordDecl *
544 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
545   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
546     DC = DC->getPrimaryContext();
547     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
548       if (MD->getParent()->hasAnyDependentBases())
549         return MD->getParent();
550   }
551   return nullptr;
552 }
553 
554 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
555                                           SourceLocation NameLoc,
556                                           bool IsTemplateTypeArg) {
557   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
558 
559   NestedNameSpecifier *NNS = nullptr;
560   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
561     // If we weren't able to parse a default template argument, delay lookup
562     // until instantiation time by making a non-dependent DependentTypeName. We
563     // pretend we saw a NestedNameSpecifier referring to the current scope, and
564     // lookup is retried.
565     // FIXME: This hurts our diagnostic quality, since we get errors like "no
566     // type named 'Foo' in 'current_namespace'" when the user didn't write any
567     // name specifiers.
568     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
569     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
570   } else if (const CXXRecordDecl *RD =
571                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
572     // Build a DependentNameType that will perform lookup into RD at
573     // instantiation time.
574     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
575                                       RD->getTypeForDecl());
576 
577     // Diagnose that this identifier was undeclared, and retry the lookup during
578     // template instantiation.
579     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
580                                                                       << RD;
581   } else {
582     // This is not a situation that we should recover from.
583     return ParsedType();
584   }
585 
586   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
587 
588   // Build type location information.  We synthesized the qualifier, so we have
589   // to build a fake NestedNameSpecifierLoc.
590   NestedNameSpecifierLocBuilder NNSLocBuilder;
591   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
592   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
593 
594   TypeLocBuilder Builder;
595   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
596   DepTL.setNameLoc(NameLoc);
597   DepTL.setElaboratedKeywordLoc(SourceLocation());
598   DepTL.setQualifierLoc(QualifierLoc);
599   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
600 }
601 
602 /// isTagName() - This method is called *for error recovery purposes only*
603 /// to determine if the specified name is a valid tag name ("struct foo").  If
604 /// so, this returns the TST for the tag corresponding to it (TST_enum,
605 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
606 /// cases in C where the user forgot to specify the tag.
607 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
608   // Do a tag name lookup in this scope.
609   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
610   LookupName(R, S, false);
611   R.suppressDiagnostics();
612   if (R.getResultKind() == LookupResult::Found)
613     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
614       switch (TD->getTagKind()) {
615       case TTK_Struct: return DeclSpec::TST_struct;
616       case TTK_Interface: return DeclSpec::TST_interface;
617       case TTK_Union:  return DeclSpec::TST_union;
618       case TTK_Class:  return DeclSpec::TST_class;
619       case TTK_Enum:   return DeclSpec::TST_enum;
620       }
621     }
622 
623   return DeclSpec::TST_unspecified;
624 }
625 
626 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
627 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
628 /// then downgrade the missing typename error to a warning.
629 /// This is needed for MSVC compatibility; Example:
630 /// @code
631 /// template<class T> class A {
632 /// public:
633 ///   typedef int TYPE;
634 /// };
635 /// template<class T> class B : public A<T> {
636 /// public:
637 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
638 /// };
639 /// @endcode
640 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
641   if (CurContext->isRecord()) {
642     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
643       return true;
644 
645     const Type *Ty = SS->getScopeRep()->getAsType();
646 
647     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
648     for (const auto &Base : RD->bases())
649       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
650         return true;
651     return S->isFunctionPrototypeScope();
652   }
653   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
654 }
655 
656 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
657                                    SourceLocation IILoc,
658                                    Scope *S,
659                                    CXXScopeSpec *SS,
660                                    ParsedType &SuggestedType,
661                                    bool IsTemplateName) {
662   // Don't report typename errors for editor placeholders.
663   if (II->isEditorPlaceholder())
664     return;
665   // We don't have anything to suggest (yet).
666   SuggestedType = nullptr;
667 
668   // There may have been a typo in the name of the type. Look up typo
669   // results, in case we have something that we can suggest.
670   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
671                            /*AllowTemplates=*/IsTemplateName,
672                            /*AllowNonTemplates=*/!IsTemplateName);
673   if (TypoCorrection Corrected =
674           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
675                       CCC, CTK_ErrorRecovery)) {
676     // FIXME: Support error recovery for the template-name case.
677     bool CanRecover = !IsTemplateName;
678     if (Corrected.isKeyword()) {
679       // We corrected to a keyword.
680       diagnoseTypo(Corrected,
681                    PDiag(IsTemplateName ? diag::err_no_template_suggest
682                                         : diag::err_unknown_typename_suggest)
683                        << II);
684       II = Corrected.getCorrectionAsIdentifierInfo();
685     } else {
686       // We found a similarly-named type or interface; suggest that.
687       if (!SS || !SS->isSet()) {
688         diagnoseTypo(Corrected,
689                      PDiag(IsTemplateName ? diag::err_no_template_suggest
690                                           : diag::err_unknown_typename_suggest)
691                          << II, CanRecover);
692       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
693         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
694         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
695                                 II->getName().equals(CorrectedStr);
696         diagnoseTypo(Corrected,
697                      PDiag(IsTemplateName
698                                ? diag::err_no_member_template_suggest
699                                : diag::err_unknown_nested_typename_suggest)
700                          << II << DC << DroppedSpecifier << SS->getRange(),
701                      CanRecover);
702       } else {
703         llvm_unreachable("could not have corrected a typo here");
704       }
705 
706       if (!CanRecover)
707         return;
708 
709       CXXScopeSpec tmpSS;
710       if (Corrected.getCorrectionSpecifier())
711         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
712                           SourceRange(IILoc));
713       // FIXME: Support class template argument deduction here.
714       SuggestedType =
715           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
716                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
717                       /*IsCtorOrDtorName=*/false,
718                       /*WantNontrivialTypeSourceInfo=*/true);
719     }
720     return;
721   }
722 
723   if (getLangOpts().CPlusPlus && !IsTemplateName) {
724     // See if II is a class template that the user forgot to pass arguments to.
725     UnqualifiedId Name;
726     Name.setIdentifier(II, IILoc);
727     CXXScopeSpec EmptySS;
728     TemplateTy TemplateResult;
729     bool MemberOfUnknownSpecialization;
730     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
731                        Name, nullptr, true, TemplateResult,
732                        MemberOfUnknownSpecialization) == TNK_Type_template) {
733       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
734       return;
735     }
736   }
737 
738   // FIXME: Should we move the logic that tries to recover from a missing tag
739   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740 
741   if (!SS || (!SS->isSet() && !SS->isInvalid()))
742     Diag(IILoc, IsTemplateName ? diag::err_no_template
743                                : diag::err_unknown_typename)
744         << II;
745   else if (DeclContext *DC = computeDeclContext(*SS, false))
746     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747                                : diag::err_typename_nested_not_found)
748         << II << DC << SS->getRange();
749   else if (isDependentScopeSpecifier(*SS)) {
750     unsigned DiagID = diag::err_typename_missing;
751     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752       DiagID = diag::ext_typename_missing;
753 
754     Diag(SS->getRange().getBegin(), DiagID)
755       << SS->getScopeRep() << II->getName()
756       << SourceRange(SS->getRange().getBegin(), IILoc)
757       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758     SuggestedType = ActOnTypenameType(S, SourceLocation(),
759                                       *SS, *II, IILoc).get();
760   } else {
761     assert(SS && SS->isInvalid() &&
762            "Invalid scope specifier has already been diagnosed");
763   }
764 }
765 
766 /// Determine whether the given result set contains either a type name
767 /// or
768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770                        NextToken.is(tok::less);
771 
772   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774       return true;
775 
776     if (CheckTemplate && isa<TemplateDecl>(*I))
777       return true;
778   }
779 
780   return false;
781 }
782 
783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784                                     Scope *S, CXXScopeSpec &SS,
785                                     IdentifierInfo *&Name,
786                                     SourceLocation NameLoc) {
787   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788   SemaRef.LookupParsedName(R, S, &SS);
789   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790     StringRef FixItTagName;
791     switch (Tag->getTagKind()) {
792       case TTK_Class:
793         FixItTagName = "class ";
794         break;
795 
796       case TTK_Enum:
797         FixItTagName = "enum ";
798         break;
799 
800       case TTK_Struct:
801         FixItTagName = "struct ";
802         break;
803 
804       case TTK_Interface:
805         FixItTagName = "__interface ";
806         break;
807 
808       case TTK_Union:
809         FixItTagName = "union ";
810         break;
811     }
812 
813     StringRef TagName = FixItTagName.drop_back();
814     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817 
818     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819          I != IEnd; ++I)
820       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821         << Name << TagName;
822 
823     // Replace lookup results with just the tag decl.
824     Result.clear(Sema::LookupTagName);
825     SemaRef.LookupParsedName(Result, S, &SS);
826     return true;
827   }
828 
829   return false;
830 }
831 
832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
834                                   QualType T, SourceLocation NameLoc) {
835   ASTContext &Context = S.Context;
836 
837   TypeLocBuilder Builder;
838   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839 
840   T = S.getElaboratedType(ETK_None, SS, T);
841   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842   ElabTL.setElaboratedKeywordLoc(SourceLocation());
843   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845 }
846 
847 Sema::NameClassification
848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
849                    SourceLocation NameLoc, const Token &NextToken,
850                    bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
851   DeclarationNameInfo NameInfo(Name, NameLoc);
852   ObjCMethodDecl *CurMethod = getCurMethodDecl();
853 
854   if (NextToken.is(tok::coloncolon)) {
855     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
856     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
857   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858              isCurrentClassName(*Name, S, &SS)) {
859     // Per [class.qual]p2, this names the constructors of SS, not the
860     // injected-class-name. We don't have a classification for that.
861     // There's not much point caching this result, since the parser
862     // will reject it later.
863     return NameClassification::Unknown();
864   }
865 
866   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
867   LookupParsedName(Result, S, &SS, !CurMethod);
868 
869   // For unqualified lookup in a class template in MSVC mode, look into
870   // dependent base classes where the primary class template is known.
871   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872     if (ParsedType TypeInBase =
873             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
874       return TypeInBase;
875   }
876 
877   // Perform lookup for Objective-C instance variables (including automatically
878   // synthesized instance variables), if we're in an Objective-C method.
879   // FIXME: This lookup really, really needs to be folded in to the normal
880   // unqualified lookup mechanism.
881   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
882     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
883     if (E.get() || E.isInvalid())
884       return E;
885   }
886 
887   bool SecondTry = false;
888   bool IsFilteredTemplateName = false;
889 
890 Corrected:
891   switch (Result.getResultKind()) {
892   case LookupResult::NotFound:
893     // If an unqualified-id is followed by a '(', then we have a function
894     // call.
895     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896       // In C++, this is an ADL-only call.
897       // FIXME: Reference?
898       if (getLangOpts().CPlusPlus)
899         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
900 
901       // C90 6.3.2.2:
902       //   If the expression that precedes the parenthesized argument list in a
903       //   function call consists solely of an identifier, and if no
904       //   declaration is visible for this identifier, the identifier is
905       //   implicitly declared exactly as if, in the innermost block containing
906       //   the function call, the declaration
907       //
908       //     extern int identifier ();
909       //
910       //   appeared.
911       //
912       // We also allow this in C99 as an extension.
913       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
914         Result.addDecl(D);
915         Result.resolveKind();
916         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
917       }
918     }
919 
920     if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
921       // In C++20 onwards, this could be an ADL-only call to a function
922       // template, and we're required to assume that this is a template name.
923       //
924       // FIXME: Find a way to still do typo correction in this case.
925       TemplateName Template =
926           Context.getAssumedTemplateName(NameInfo.getName());
927       return NameClassification::UndeclaredTemplate(Template);
928     }
929 
930     // In C, we first see whether there is a tag type by the same name, in
931     // which case it's likely that the user just forgot to write "enum",
932     // "struct", or "union".
933     if (!getLangOpts().CPlusPlus && !SecondTry &&
934         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
935       break;
936     }
937 
938     // Perform typo correction to determine if there is another name that is
939     // close to this name.
940     if (!SecondTry && CCC) {
941       SecondTry = true;
942       if (TypoCorrection Corrected =
943               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
944                           &SS, *CCC, CTK_ErrorRecovery)) {
945         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
946         unsigned QualifiedDiag = diag::err_no_member_suggest;
947 
948         NamedDecl *FirstDecl = Corrected.getFoundDecl();
949         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
950         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
951             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
952           UnqualifiedDiag = diag::err_no_template_suggest;
953           QualifiedDiag = diag::err_no_member_template_suggest;
954         } else if (UnderlyingFirstDecl &&
955                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
956                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
957                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
958           UnqualifiedDiag = diag::err_unknown_typename_suggest;
959           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
960         }
961 
962         if (SS.isEmpty()) {
963           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
964         } else {// FIXME: is this even reachable? Test it.
965           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
966           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
967                                   Name->getName().equals(CorrectedStr);
968           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
969                                     << Name << computeDeclContext(SS, false)
970                                     << DroppedSpecifier << SS.getRange());
971         }
972 
973         // Update the name, so that the caller has the new name.
974         Name = Corrected.getCorrectionAsIdentifierInfo();
975 
976         // Typo correction corrected to a keyword.
977         if (Corrected.isKeyword())
978           return Name;
979 
980         // Also update the LookupResult...
981         // FIXME: This should probably go away at some point
982         Result.clear();
983         Result.setLookupName(Corrected.getCorrection());
984         if (FirstDecl)
985           Result.addDecl(FirstDecl);
986 
987         // If we found an Objective-C instance variable, let
988         // LookupInObjCMethod build the appropriate expression to
989         // reference the ivar.
990         // FIXME: This is a gross hack.
991         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
992           Result.clear();
993           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
994           return E;
995         }
996 
997         goto Corrected;
998       }
999     }
1000 
1001     // We failed to correct; just fall through and let the parser deal with it.
1002     Result.suppressDiagnostics();
1003     return NameClassification::Unknown();
1004 
1005   case LookupResult::NotFoundInCurrentInstantiation: {
1006     // We performed name lookup into the current instantiation, and there were
1007     // dependent bases, so we treat this result the same way as any other
1008     // dependent nested-name-specifier.
1009 
1010     // C++ [temp.res]p2:
1011     //   A name used in a template declaration or definition and that is
1012     //   dependent on a template-parameter is assumed not to name a type
1013     //   unless the applicable name lookup finds a type name or the name is
1014     //   qualified by the keyword typename.
1015     //
1016     // FIXME: If the next token is '<', we might want to ask the parser to
1017     // perform some heroics to see if we actually have a
1018     // template-argument-list, which would indicate a missing 'template'
1019     // keyword here.
1020     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1021                                       NameInfo, IsAddressOfOperand,
1022                                       /*TemplateArgs=*/nullptr);
1023   }
1024 
1025   case LookupResult::Found:
1026   case LookupResult::FoundOverloaded:
1027   case LookupResult::FoundUnresolvedValue:
1028     break;
1029 
1030   case LookupResult::Ambiguous:
1031     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1032         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1033                                       /*AllowDependent=*/false)) {
1034       // C++ [temp.local]p3:
1035       //   A lookup that finds an injected-class-name (10.2) can result in an
1036       //   ambiguity in certain cases (for example, if it is found in more than
1037       //   one base class). If all of the injected-class-names that are found
1038       //   refer to specializations of the same class template, and if the name
1039       //   is followed by a template-argument-list, the reference refers to the
1040       //   class template itself and not a specialization thereof, and is not
1041       //   ambiguous.
1042       //
1043       // This filtering can make an ambiguous result into an unambiguous one,
1044       // so try again after filtering out template names.
1045       FilterAcceptableTemplateNames(Result);
1046       if (!Result.isAmbiguous()) {
1047         IsFilteredTemplateName = true;
1048         break;
1049       }
1050     }
1051 
1052     // Diagnose the ambiguity and return an error.
1053     return NameClassification::Error();
1054   }
1055 
1056   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1057       (IsFilteredTemplateName ||
1058        hasAnyAcceptableTemplateNames(
1059            Result, /*AllowFunctionTemplates=*/true,
1060            /*AllowDependent=*/false,
1061            /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1062                getLangOpts().CPlusPlus2a))) {
1063     // C++ [temp.names]p3:
1064     //   After name lookup (3.4) finds that a name is a template-name or that
1065     //   an operator-function-id or a literal- operator-id refers to a set of
1066     //   overloaded functions any member of which is a function template if
1067     //   this is followed by a <, the < is always taken as the delimiter of a
1068     //   template-argument-list and never as the less-than operator.
1069     // C++2a [temp.names]p2:
1070     //   A name is also considered to refer to a template if it is an
1071     //   unqualified-id followed by a < and name lookup finds either one
1072     //   or more functions or finds nothing.
1073     if (!IsFilteredTemplateName)
1074       FilterAcceptableTemplateNames(Result);
1075 
1076     bool IsFunctionTemplate;
1077     bool IsVarTemplate;
1078     TemplateName Template;
1079     if (Result.end() - Result.begin() > 1) {
1080       IsFunctionTemplate = true;
1081       Template = Context.getOverloadedTemplateName(Result.begin(),
1082                                                    Result.end());
1083     } else if (!Result.empty()) {
1084       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1085           *Result.begin(), /*AllowFunctionTemplates=*/true,
1086           /*AllowDependent=*/false));
1087       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1088       IsVarTemplate = isa<VarTemplateDecl>(TD);
1089 
1090       if (SS.isSet() && !SS.isInvalid())
1091         Template =
1092             Context.getQualifiedTemplateName(SS.getScopeRep(),
1093                                              /*TemplateKeyword=*/false, TD);
1094       else
1095         Template = TemplateName(TD);
1096     } else {
1097       // All results were non-template functions. This is a function template
1098       // name.
1099       IsFunctionTemplate = true;
1100       Template = Context.getAssumedTemplateName(NameInfo.getName());
1101     }
1102 
1103     if (IsFunctionTemplate) {
1104       // Function templates always go through overload resolution, at which
1105       // point we'll perform the various checks (e.g., accessibility) we need
1106       // to based on which function we selected.
1107       Result.suppressDiagnostics();
1108 
1109       return NameClassification::FunctionTemplate(Template);
1110     }
1111 
1112     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1113                          : NameClassification::TypeTemplate(Template);
1114   }
1115 
1116   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1117   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1118     DiagnoseUseOfDecl(Type, NameLoc);
1119     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1120     QualType T = Context.getTypeDeclType(Type);
1121     if (SS.isNotEmpty())
1122       return buildNestedType(*this, SS, T, NameLoc);
1123     return ParsedType::make(T);
1124   }
1125 
1126   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1127   if (!Class) {
1128     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1129     if (ObjCCompatibleAliasDecl *Alias =
1130             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1131       Class = Alias->getClassInterface();
1132   }
1133 
1134   if (Class) {
1135     DiagnoseUseOfDecl(Class, NameLoc);
1136 
1137     if (NextToken.is(tok::period)) {
1138       // Interface. <something> is parsed as a property reference expression.
1139       // Just return "unknown" as a fall-through for now.
1140       Result.suppressDiagnostics();
1141       return NameClassification::Unknown();
1142     }
1143 
1144     QualType T = Context.getObjCInterfaceType(Class);
1145     return ParsedType::make(T);
1146   }
1147 
1148   // We can have a type template here if we're classifying a template argument.
1149   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1150       !isa<VarTemplateDecl>(FirstDecl))
1151     return NameClassification::TypeTemplate(
1152         TemplateName(cast<TemplateDecl>(FirstDecl)));
1153 
1154   // Check for a tag type hidden by a non-type decl in a few cases where it
1155   // seems likely a type is wanted instead of the non-type that was found.
1156   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1157   if ((NextToken.is(tok::identifier) ||
1158        (NextIsOp &&
1159         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1160       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1161     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1162     DiagnoseUseOfDecl(Type, NameLoc);
1163     QualType T = Context.getTypeDeclType(Type);
1164     if (SS.isNotEmpty())
1165       return buildNestedType(*this, SS, T, NameLoc);
1166     return ParsedType::make(T);
1167   }
1168 
1169   if (FirstDecl->isCXXClassMember())
1170     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1171                                            nullptr, S);
1172 
1173   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1174   return BuildDeclarationNameExpr(SS, Result, ADL);
1175 }
1176 
1177 Sema::TemplateNameKindForDiagnostics
1178 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1179   auto *TD = Name.getAsTemplateDecl();
1180   if (!TD)
1181     return TemplateNameKindForDiagnostics::DependentTemplate;
1182   if (isa<ClassTemplateDecl>(TD))
1183     return TemplateNameKindForDiagnostics::ClassTemplate;
1184   if (isa<FunctionTemplateDecl>(TD))
1185     return TemplateNameKindForDiagnostics::FunctionTemplate;
1186   if (isa<VarTemplateDecl>(TD))
1187     return TemplateNameKindForDiagnostics::VarTemplate;
1188   if (isa<TypeAliasTemplateDecl>(TD))
1189     return TemplateNameKindForDiagnostics::AliasTemplate;
1190   if (isa<TemplateTemplateParmDecl>(TD))
1191     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1192   if (isa<ConceptDecl>(TD))
1193     return TemplateNameKindForDiagnostics::Concept;
1194   return TemplateNameKindForDiagnostics::DependentTemplate;
1195 }
1196 
1197 // Determines the context to return to after temporarily entering a
1198 // context.  This depends in an unnecessarily complicated way on the
1199 // exact ordering of callbacks from the parser.
1200 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1201 
1202   // Functions defined inline within classes aren't parsed until we've
1203   // finished parsing the top-level class, so the top-level class is
1204   // the context we'll need to return to.
1205   // A Lambda call operator whose parent is a class must not be treated
1206   // as an inline member function.  A Lambda can be used legally
1207   // either as an in-class member initializer or a default argument.  These
1208   // are parsed once the class has been marked complete and so the containing
1209   // context would be the nested class (when the lambda is defined in one);
1210   // If the class is not complete, then the lambda is being used in an
1211   // ill-formed fashion (such as to specify the width of a bit-field, or
1212   // in an array-bound) - in which case we still want to return the
1213   // lexically containing DC (which could be a nested class).
1214   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1215     DC = DC->getLexicalParent();
1216 
1217     // A function not defined within a class will always return to its
1218     // lexical context.
1219     if (!isa<CXXRecordDecl>(DC))
1220       return DC;
1221 
1222     // A C++ inline method/friend is parsed *after* the topmost class
1223     // it was declared in is fully parsed ("complete");  the topmost
1224     // class is the context we need to return to.
1225     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1226       DC = RD;
1227 
1228     // Return the declaration context of the topmost class the inline method is
1229     // declared in.
1230     return DC;
1231   }
1232 
1233   return DC->getLexicalParent();
1234 }
1235 
1236 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1237   assert(getContainingDC(DC) == CurContext &&
1238       "The next DeclContext should be lexically contained in the current one.");
1239   CurContext = DC;
1240   S->setEntity(DC);
1241 }
1242 
1243 void Sema::PopDeclContext() {
1244   assert(CurContext && "DeclContext imbalance!");
1245 
1246   CurContext = getContainingDC(CurContext);
1247   assert(CurContext && "Popped translation unit!");
1248 }
1249 
1250 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1251                                                                     Decl *D) {
1252   // Unlike PushDeclContext, the context to which we return is not necessarily
1253   // the containing DC of TD, because the new context will be some pre-existing
1254   // TagDecl definition instead of a fresh one.
1255   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1256   CurContext = cast<TagDecl>(D)->getDefinition();
1257   assert(CurContext && "skipping definition of undefined tag");
1258   // Start lookups from the parent of the current context; we don't want to look
1259   // into the pre-existing complete definition.
1260   S->setEntity(CurContext->getLookupParent());
1261   return Result;
1262 }
1263 
1264 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1265   CurContext = static_cast<decltype(CurContext)>(Context);
1266 }
1267 
1268 /// EnterDeclaratorContext - Used when we must lookup names in the context
1269 /// of a declarator's nested name specifier.
1270 ///
1271 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1272   // C++0x [basic.lookup.unqual]p13:
1273   //   A name used in the definition of a static data member of class
1274   //   X (after the qualified-id of the static member) is looked up as
1275   //   if the name was used in a member function of X.
1276   // C++0x [basic.lookup.unqual]p14:
1277   //   If a variable member of a namespace is defined outside of the
1278   //   scope of its namespace then any name used in the definition of
1279   //   the variable member (after the declarator-id) is looked up as
1280   //   if the definition of the variable member occurred in its
1281   //   namespace.
1282   // Both of these imply that we should push a scope whose context
1283   // is the semantic context of the declaration.  We can't use
1284   // PushDeclContext here because that context is not necessarily
1285   // lexically contained in the current context.  Fortunately,
1286   // the containing scope should have the appropriate information.
1287 
1288   assert(!S->getEntity() && "scope already has entity");
1289 
1290 #ifndef NDEBUG
1291   Scope *Ancestor = S->getParent();
1292   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1293   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1294 #endif
1295 
1296   CurContext = DC;
1297   S->setEntity(DC);
1298 }
1299 
1300 void Sema::ExitDeclaratorContext(Scope *S) {
1301   assert(S->getEntity() == CurContext && "Context imbalance!");
1302 
1303   // Switch back to the lexical context.  The safety of this is
1304   // enforced by an assert in EnterDeclaratorContext.
1305   Scope *Ancestor = S->getParent();
1306   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1307   CurContext = Ancestor->getEntity();
1308 
1309   // We don't need to do anything with the scope, which is going to
1310   // disappear.
1311 }
1312 
1313 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1314   // We assume that the caller has already called
1315   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1316   FunctionDecl *FD = D->getAsFunction();
1317   if (!FD)
1318     return;
1319 
1320   // Same implementation as PushDeclContext, but enters the context
1321   // from the lexical parent, rather than the top-level class.
1322   assert(CurContext == FD->getLexicalParent() &&
1323     "The next DeclContext should be lexically contained in the current one.");
1324   CurContext = FD;
1325   S->setEntity(CurContext);
1326 
1327   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1328     ParmVarDecl *Param = FD->getParamDecl(P);
1329     // If the parameter has an identifier, then add it to the scope
1330     if (Param->getIdentifier()) {
1331       S->AddDecl(Param);
1332       IdResolver.AddDecl(Param);
1333     }
1334   }
1335 }
1336 
1337 void Sema::ActOnExitFunctionContext() {
1338   // Same implementation as PopDeclContext, but returns to the lexical parent,
1339   // rather than the top-level class.
1340   assert(CurContext && "DeclContext imbalance!");
1341   CurContext = CurContext->getLexicalParent();
1342   assert(CurContext && "Popped translation unit!");
1343 }
1344 
1345 /// Determine whether we allow overloading of the function
1346 /// PrevDecl with another declaration.
1347 ///
1348 /// This routine determines whether overloading is possible, not
1349 /// whether some new function is actually an overload. It will return
1350 /// true in C++ (where we can always provide overloads) or, as an
1351 /// extension, in C when the previous function is already an
1352 /// overloaded function declaration or has the "overloadable"
1353 /// attribute.
1354 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1355                                        ASTContext &Context,
1356                                        const FunctionDecl *New) {
1357   if (Context.getLangOpts().CPlusPlus)
1358     return true;
1359 
1360   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1361     return true;
1362 
1363   return Previous.getResultKind() == LookupResult::Found &&
1364          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1365           New->hasAttr<OverloadableAttr>());
1366 }
1367 
1368 /// Add this decl to the scope shadowed decl chains.
1369 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1370   // Move up the scope chain until we find the nearest enclosing
1371   // non-transparent context. The declaration will be introduced into this
1372   // scope.
1373   while (S->getEntity() && S->getEntity()->isTransparentContext())
1374     S = S->getParent();
1375 
1376   // Add scoped declarations into their context, so that they can be
1377   // found later. Declarations without a context won't be inserted
1378   // into any context.
1379   if (AddToContext)
1380     CurContext->addDecl(D);
1381 
1382   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1383   // are function-local declarations.
1384   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1385       !D->getDeclContext()->getRedeclContext()->Equals(
1386         D->getLexicalDeclContext()->getRedeclContext()) &&
1387       !D->getLexicalDeclContext()->isFunctionOrMethod())
1388     return;
1389 
1390   // Template instantiations should also not be pushed into scope.
1391   if (isa<FunctionDecl>(D) &&
1392       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1393     return;
1394 
1395   // If this replaces anything in the current scope,
1396   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1397                                IEnd = IdResolver.end();
1398   for (; I != IEnd; ++I) {
1399     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1400       S->RemoveDecl(*I);
1401       IdResolver.RemoveDecl(*I);
1402 
1403       // Should only need to replace one decl.
1404       break;
1405     }
1406   }
1407 
1408   S->AddDecl(D);
1409 
1410   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1411     // Implicitly-generated labels may end up getting generated in an order that
1412     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1413     // the label at the appropriate place in the identifier chain.
1414     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1415       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1416       if (IDC == CurContext) {
1417         if (!S->isDeclScope(*I))
1418           continue;
1419       } else if (IDC->Encloses(CurContext))
1420         break;
1421     }
1422 
1423     IdResolver.InsertDeclAfter(I, D);
1424   } else {
1425     IdResolver.AddDecl(D);
1426   }
1427 }
1428 
1429 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1430                          bool AllowInlineNamespace) {
1431   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1432 }
1433 
1434 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1435   DeclContext *TargetDC = DC->getPrimaryContext();
1436   do {
1437     if (DeclContext *ScopeDC = S->getEntity())
1438       if (ScopeDC->getPrimaryContext() == TargetDC)
1439         return S;
1440   } while ((S = S->getParent()));
1441 
1442   return nullptr;
1443 }
1444 
1445 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1446                                             DeclContext*,
1447                                             ASTContext&);
1448 
1449 /// Filters out lookup results that don't fall within the given scope
1450 /// as determined by isDeclInScope.
1451 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1452                                 bool ConsiderLinkage,
1453                                 bool AllowInlineNamespace) {
1454   LookupResult::Filter F = R.makeFilter();
1455   while (F.hasNext()) {
1456     NamedDecl *D = F.next();
1457 
1458     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1459       continue;
1460 
1461     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1462       continue;
1463 
1464     F.erase();
1465   }
1466 
1467   F.done();
1468 }
1469 
1470 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1471 /// have compatible owning modules.
1472 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1473   // FIXME: The Modules TS is not clear about how friend declarations are
1474   // to be treated. It's not meaningful to have different owning modules for
1475   // linkage in redeclarations of the same entity, so for now allow the
1476   // redeclaration and change the owning modules to match.
1477   if (New->getFriendObjectKind() &&
1478       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1479     New->setLocalOwningModule(Old->getOwningModule());
1480     makeMergedDefinitionVisible(New);
1481     return false;
1482   }
1483 
1484   Module *NewM = New->getOwningModule();
1485   Module *OldM = Old->getOwningModule();
1486 
1487   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1488     NewM = NewM->Parent;
1489   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1490     OldM = OldM->Parent;
1491 
1492   if (NewM == OldM)
1493     return false;
1494 
1495   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1496   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1497   if (NewIsModuleInterface || OldIsModuleInterface) {
1498     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1499     //   if a declaration of D [...] appears in the purview of a module, all
1500     //   other such declarations shall appear in the purview of the same module
1501     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1502       << New
1503       << NewIsModuleInterface
1504       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1505       << OldIsModuleInterface
1506       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1507     Diag(Old->getLocation(), diag::note_previous_declaration);
1508     New->setInvalidDecl();
1509     return true;
1510   }
1511 
1512   return false;
1513 }
1514 
1515 static bool isUsingDecl(NamedDecl *D) {
1516   return isa<UsingShadowDecl>(D) ||
1517          isa<UnresolvedUsingTypenameDecl>(D) ||
1518          isa<UnresolvedUsingValueDecl>(D);
1519 }
1520 
1521 /// Removes using shadow declarations from the lookup results.
1522 static void RemoveUsingDecls(LookupResult &R) {
1523   LookupResult::Filter F = R.makeFilter();
1524   while (F.hasNext())
1525     if (isUsingDecl(F.next()))
1526       F.erase();
1527 
1528   F.done();
1529 }
1530 
1531 /// Check for this common pattern:
1532 /// @code
1533 /// class S {
1534 ///   S(const S&); // DO NOT IMPLEMENT
1535 ///   void operator=(const S&); // DO NOT IMPLEMENT
1536 /// };
1537 /// @endcode
1538 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1539   // FIXME: Should check for private access too but access is set after we get
1540   // the decl here.
1541   if (D->doesThisDeclarationHaveABody())
1542     return false;
1543 
1544   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1545     return CD->isCopyConstructor();
1546   return D->isCopyAssignmentOperator();
1547 }
1548 
1549 // We need this to handle
1550 //
1551 // typedef struct {
1552 //   void *foo() { return 0; }
1553 // } A;
1554 //
1555 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1556 // for example. If 'A', foo will have external linkage. If we have '*A',
1557 // foo will have no linkage. Since we can't know until we get to the end
1558 // of the typedef, this function finds out if D might have non-external linkage.
1559 // Callers should verify at the end of the TU if it D has external linkage or
1560 // not.
1561 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1562   const DeclContext *DC = D->getDeclContext();
1563   while (!DC->isTranslationUnit()) {
1564     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1565       if (!RD->hasNameForLinkage())
1566         return true;
1567     }
1568     DC = DC->getParent();
1569   }
1570 
1571   return !D->isExternallyVisible();
1572 }
1573 
1574 // FIXME: This needs to be refactored; some other isInMainFile users want
1575 // these semantics.
1576 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1577   if (S.TUKind != TU_Complete)
1578     return false;
1579   return S.SourceMgr.isInMainFile(Loc);
1580 }
1581 
1582 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1583   assert(D);
1584 
1585   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1586     return false;
1587 
1588   // Ignore all entities declared within templates, and out-of-line definitions
1589   // of members of class templates.
1590   if (D->getDeclContext()->isDependentContext() ||
1591       D->getLexicalDeclContext()->isDependentContext())
1592     return false;
1593 
1594   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1595     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1596       return false;
1597     // A non-out-of-line declaration of a member specialization was implicitly
1598     // instantiated; it's the out-of-line declaration that we're interested in.
1599     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1600         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1601       return false;
1602 
1603     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1604       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1605         return false;
1606     } else {
1607       // 'static inline' functions are defined in headers; don't warn.
1608       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1609         return false;
1610     }
1611 
1612     if (FD->doesThisDeclarationHaveABody() &&
1613         Context.DeclMustBeEmitted(FD))
1614       return false;
1615   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1616     // Constants and utility variables are defined in headers with internal
1617     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1618     // like "inline".)
1619     if (!isMainFileLoc(*this, VD->getLocation()))
1620       return false;
1621 
1622     if (Context.DeclMustBeEmitted(VD))
1623       return false;
1624 
1625     if (VD->isStaticDataMember() &&
1626         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1627       return false;
1628     if (VD->isStaticDataMember() &&
1629         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1630         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1631       return false;
1632 
1633     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1634       return false;
1635   } else {
1636     return false;
1637   }
1638 
1639   // Only warn for unused decls internal to the translation unit.
1640   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1641   // for inline functions defined in the main source file, for instance.
1642   return mightHaveNonExternalLinkage(D);
1643 }
1644 
1645 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1646   if (!D)
1647     return;
1648 
1649   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1650     const FunctionDecl *First = FD->getFirstDecl();
1651     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1652       return; // First should already be in the vector.
1653   }
1654 
1655   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1656     const VarDecl *First = VD->getFirstDecl();
1657     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1658       return; // First should already be in the vector.
1659   }
1660 
1661   if (ShouldWarnIfUnusedFileScopedDecl(D))
1662     UnusedFileScopedDecls.push_back(D);
1663 }
1664 
1665 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1666   if (D->isInvalidDecl())
1667     return false;
1668 
1669   bool Referenced = false;
1670   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1671     // For a decomposition declaration, warn if none of the bindings are
1672     // referenced, instead of if the variable itself is referenced (which
1673     // it is, by the bindings' expressions).
1674     for (auto *BD : DD->bindings()) {
1675       if (BD->isReferenced()) {
1676         Referenced = true;
1677         break;
1678       }
1679     }
1680   } else if (!D->getDeclName()) {
1681     return false;
1682   } else if (D->isReferenced() || D->isUsed()) {
1683     Referenced = true;
1684   }
1685 
1686   if (Referenced || D->hasAttr<UnusedAttr>() ||
1687       D->hasAttr<ObjCPreciseLifetimeAttr>())
1688     return false;
1689 
1690   if (isa<LabelDecl>(D))
1691     return true;
1692 
1693   // Except for labels, we only care about unused decls that are local to
1694   // functions.
1695   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1696   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1697     // For dependent types, the diagnostic is deferred.
1698     WithinFunction =
1699         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1700   if (!WithinFunction)
1701     return false;
1702 
1703   if (isa<TypedefNameDecl>(D))
1704     return true;
1705 
1706   // White-list anything that isn't a local variable.
1707   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1708     return false;
1709 
1710   // Types of valid local variables should be complete, so this should succeed.
1711   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1712 
1713     // White-list anything with an __attribute__((unused)) type.
1714     const auto *Ty = VD->getType().getTypePtr();
1715 
1716     // Only look at the outermost level of typedef.
1717     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1718       if (TT->getDecl()->hasAttr<UnusedAttr>())
1719         return false;
1720     }
1721 
1722     // If we failed to complete the type for some reason, or if the type is
1723     // dependent, don't diagnose the variable.
1724     if (Ty->isIncompleteType() || Ty->isDependentType())
1725       return false;
1726 
1727     // Look at the element type to ensure that the warning behaviour is
1728     // consistent for both scalars and arrays.
1729     Ty = Ty->getBaseElementTypeUnsafe();
1730 
1731     if (const TagType *TT = Ty->getAs<TagType>()) {
1732       const TagDecl *Tag = TT->getDecl();
1733       if (Tag->hasAttr<UnusedAttr>())
1734         return false;
1735 
1736       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1737         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1738           return false;
1739 
1740         if (const Expr *Init = VD->getInit()) {
1741           if (const ExprWithCleanups *Cleanups =
1742                   dyn_cast<ExprWithCleanups>(Init))
1743             Init = Cleanups->getSubExpr();
1744           const CXXConstructExpr *Construct =
1745             dyn_cast<CXXConstructExpr>(Init);
1746           if (Construct && !Construct->isElidable()) {
1747             CXXConstructorDecl *CD = Construct->getConstructor();
1748             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1749                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1750               return false;
1751           }
1752         }
1753       }
1754     }
1755 
1756     // TODO: __attribute__((unused)) templates?
1757   }
1758 
1759   return true;
1760 }
1761 
1762 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1763                                      FixItHint &Hint) {
1764   if (isa<LabelDecl>(D)) {
1765     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1766         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1767         true);
1768     if (AfterColon.isInvalid())
1769       return;
1770     Hint = FixItHint::CreateRemoval(
1771         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1772   }
1773 }
1774 
1775 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1776   if (D->getTypeForDecl()->isDependentType())
1777     return;
1778 
1779   for (auto *TmpD : D->decls()) {
1780     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1781       DiagnoseUnusedDecl(T);
1782     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1783       DiagnoseUnusedNestedTypedefs(R);
1784   }
1785 }
1786 
1787 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1788 /// unless they are marked attr(unused).
1789 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1790   if (!ShouldDiagnoseUnusedDecl(D))
1791     return;
1792 
1793   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1794     // typedefs can be referenced later on, so the diagnostics are emitted
1795     // at end-of-translation-unit.
1796     UnusedLocalTypedefNameCandidates.insert(TD);
1797     return;
1798   }
1799 
1800   FixItHint Hint;
1801   GenerateFixForUnusedDecl(D, Context, Hint);
1802 
1803   unsigned DiagID;
1804   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1805     DiagID = diag::warn_unused_exception_param;
1806   else if (isa<LabelDecl>(D))
1807     DiagID = diag::warn_unused_label;
1808   else
1809     DiagID = diag::warn_unused_variable;
1810 
1811   Diag(D->getLocation(), DiagID) << D << Hint;
1812 }
1813 
1814 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1815   // Verify that we have no forward references left.  If so, there was a goto
1816   // or address of a label taken, but no definition of it.  Label fwd
1817   // definitions are indicated with a null substmt which is also not a resolved
1818   // MS inline assembly label name.
1819   bool Diagnose = false;
1820   if (L->isMSAsmLabel())
1821     Diagnose = !L->isResolvedMSAsmLabel();
1822   else
1823     Diagnose = L->getStmt() == nullptr;
1824   if (Diagnose)
1825     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1826 }
1827 
1828 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1829   S->mergeNRVOIntoParent();
1830 
1831   if (S->decl_empty()) return;
1832   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1833          "Scope shouldn't contain decls!");
1834 
1835   for (auto *TmpD : S->decls()) {
1836     assert(TmpD && "This decl didn't get pushed??");
1837 
1838     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1839     NamedDecl *D = cast<NamedDecl>(TmpD);
1840 
1841     // Diagnose unused variables in this scope.
1842     if (!S->hasUnrecoverableErrorOccurred()) {
1843       DiagnoseUnusedDecl(D);
1844       if (const auto *RD = dyn_cast<RecordDecl>(D))
1845         DiagnoseUnusedNestedTypedefs(RD);
1846     }
1847 
1848     if (!D->getDeclName()) continue;
1849 
1850     // If this was a forward reference to a label, verify it was defined.
1851     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1852       CheckPoppedLabel(LD, *this);
1853 
1854     // Remove this name from our lexical scope, and warn on it if we haven't
1855     // already.
1856     IdResolver.RemoveDecl(D);
1857     auto ShadowI = ShadowingDecls.find(D);
1858     if (ShadowI != ShadowingDecls.end()) {
1859       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1860         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1861             << D << FD << FD->getParent();
1862         Diag(FD->getLocation(), diag::note_previous_declaration);
1863       }
1864       ShadowingDecls.erase(ShadowI);
1865     }
1866   }
1867 }
1868 
1869 /// Look for an Objective-C class in the translation unit.
1870 ///
1871 /// \param Id The name of the Objective-C class we're looking for. If
1872 /// typo-correction fixes this name, the Id will be updated
1873 /// to the fixed name.
1874 ///
1875 /// \param IdLoc The location of the name in the translation unit.
1876 ///
1877 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1878 /// if there is no class with the given name.
1879 ///
1880 /// \returns The declaration of the named Objective-C class, or NULL if the
1881 /// class could not be found.
1882 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1883                                               SourceLocation IdLoc,
1884                                               bool DoTypoCorrection) {
1885   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1886   // creation from this context.
1887   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1888 
1889   if (!IDecl && DoTypoCorrection) {
1890     // Perform typo correction at the given location, but only if we
1891     // find an Objective-C class name.
1892     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1893     if (TypoCorrection C =
1894             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1895                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1896       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1897       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1898       Id = IDecl->getIdentifier();
1899     }
1900   }
1901   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1902   // This routine must always return a class definition, if any.
1903   if (Def && Def->getDefinition())
1904       Def = Def->getDefinition();
1905   return Def;
1906 }
1907 
1908 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1909 /// from S, where a non-field would be declared. This routine copes
1910 /// with the difference between C and C++ scoping rules in structs and
1911 /// unions. For example, the following code is well-formed in C but
1912 /// ill-formed in C++:
1913 /// @code
1914 /// struct S6 {
1915 ///   enum { BAR } e;
1916 /// };
1917 ///
1918 /// void test_S6() {
1919 ///   struct S6 a;
1920 ///   a.e = BAR;
1921 /// }
1922 /// @endcode
1923 /// For the declaration of BAR, this routine will return a different
1924 /// scope. The scope S will be the scope of the unnamed enumeration
1925 /// within S6. In C++, this routine will return the scope associated
1926 /// with S6, because the enumeration's scope is a transparent
1927 /// context but structures can contain non-field names. In C, this
1928 /// routine will return the translation unit scope, since the
1929 /// enumeration's scope is a transparent context and structures cannot
1930 /// contain non-field names.
1931 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1932   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1933          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1934          (S->isClassScope() && !getLangOpts().CPlusPlus))
1935     S = S->getParent();
1936   return S;
1937 }
1938 
1939 /// Looks up the declaration of "struct objc_super" and
1940 /// saves it for later use in building builtin declaration of
1941 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1942 /// pre-existing declaration exists no action takes place.
1943 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1944                                         IdentifierInfo *II) {
1945   if (!II->isStr("objc_msgSendSuper"))
1946     return;
1947   ASTContext &Context = ThisSema.Context;
1948 
1949   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1950                       SourceLocation(), Sema::LookupTagName);
1951   ThisSema.LookupName(Result, S);
1952   if (Result.getResultKind() == LookupResult::Found)
1953     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1954       Context.setObjCSuperType(Context.getTagDeclType(TD));
1955 }
1956 
1957 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1958                                ASTContext::GetBuiltinTypeError Error) {
1959   switch (Error) {
1960   case ASTContext::GE_None:
1961     return "";
1962   case ASTContext::GE_Missing_type:
1963     return BuiltinInfo.getHeaderName(ID);
1964   case ASTContext::GE_Missing_stdio:
1965     return "stdio.h";
1966   case ASTContext::GE_Missing_setjmp:
1967     return "setjmp.h";
1968   case ASTContext::GE_Missing_ucontext:
1969     return "ucontext.h";
1970   }
1971   llvm_unreachable("unhandled error kind");
1972 }
1973 
1974 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1975 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1976 /// if we're creating this built-in in anticipation of redeclaring the
1977 /// built-in.
1978 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1979                                      Scope *S, bool ForRedeclaration,
1980                                      SourceLocation Loc) {
1981   LookupPredefedObjCSuperType(*this, S, II);
1982 
1983   ASTContext::GetBuiltinTypeError Error;
1984   QualType R = Context.GetBuiltinType(ID, Error);
1985   if (Error) {
1986     if (ForRedeclaration)
1987       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1988           << getHeaderName(Context.BuiltinInfo, ID, Error)
1989           << Context.BuiltinInfo.getName(ID);
1990     return nullptr;
1991   }
1992 
1993   if (!ForRedeclaration &&
1994       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1995        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1996     Diag(Loc, diag::ext_implicit_lib_function_decl)
1997         << Context.BuiltinInfo.getName(ID) << R;
1998     if (Context.BuiltinInfo.getHeaderName(ID) &&
1999         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2000       Diag(Loc, diag::note_include_header_or_declare)
2001           << Context.BuiltinInfo.getHeaderName(ID)
2002           << Context.BuiltinInfo.getName(ID);
2003   }
2004 
2005   if (R.isNull())
2006     return nullptr;
2007 
2008   DeclContext *Parent = Context.getTranslationUnitDecl();
2009   if (getLangOpts().CPlusPlus) {
2010     LinkageSpecDecl *CLinkageDecl =
2011         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2012                                 LinkageSpecDecl::lang_c, false);
2013     CLinkageDecl->setImplicit();
2014     Parent->addDecl(CLinkageDecl);
2015     Parent = CLinkageDecl;
2016   }
2017 
2018   FunctionDecl *New = FunctionDecl::Create(Context,
2019                                            Parent,
2020                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2021                                            SC_Extern,
2022                                            false,
2023                                            R->isFunctionProtoType());
2024   New->setImplicit();
2025 
2026   // Create Decl objects for each parameter, adding them to the
2027   // FunctionDecl.
2028   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2029     SmallVector<ParmVarDecl*, 16> Params;
2030     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2031       ParmVarDecl *parm =
2032           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2033                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2034                               SC_None, nullptr);
2035       parm->setScopeInfo(0, i);
2036       Params.push_back(parm);
2037     }
2038     New->setParams(Params);
2039   }
2040 
2041   AddKnownFunctionAttributes(New);
2042   RegisterLocallyScopedExternCDecl(New, S);
2043 
2044   // TUScope is the translation-unit scope to insert this function into.
2045   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2046   // relate Scopes to DeclContexts, and probably eliminate CurContext
2047   // entirely, but we're not there yet.
2048   DeclContext *SavedContext = CurContext;
2049   CurContext = Parent;
2050   PushOnScopeChains(New, TUScope);
2051   CurContext = SavedContext;
2052   return New;
2053 }
2054 
2055 /// Typedef declarations don't have linkage, but they still denote the same
2056 /// entity if their types are the same.
2057 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2058 /// isSameEntity.
2059 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2060                                                      TypedefNameDecl *Decl,
2061                                                      LookupResult &Previous) {
2062   // This is only interesting when modules are enabled.
2063   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2064     return;
2065 
2066   // Empty sets are uninteresting.
2067   if (Previous.empty())
2068     return;
2069 
2070   LookupResult::Filter Filter = Previous.makeFilter();
2071   while (Filter.hasNext()) {
2072     NamedDecl *Old = Filter.next();
2073 
2074     // Non-hidden declarations are never ignored.
2075     if (S.isVisible(Old))
2076       continue;
2077 
2078     // Declarations of the same entity are not ignored, even if they have
2079     // different linkages.
2080     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2081       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2082                                 Decl->getUnderlyingType()))
2083         continue;
2084 
2085       // If both declarations give a tag declaration a typedef name for linkage
2086       // purposes, then they declare the same entity.
2087       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2088           Decl->getAnonDeclWithTypedefName())
2089         continue;
2090     }
2091 
2092     Filter.erase();
2093   }
2094 
2095   Filter.done();
2096 }
2097 
2098 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2099   QualType OldType;
2100   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2101     OldType = OldTypedef->getUnderlyingType();
2102   else
2103     OldType = Context.getTypeDeclType(Old);
2104   QualType NewType = New->getUnderlyingType();
2105 
2106   if (NewType->isVariablyModifiedType()) {
2107     // Must not redefine a typedef with a variably-modified type.
2108     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2109     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2110       << Kind << NewType;
2111     if (Old->getLocation().isValid())
2112       notePreviousDefinition(Old, New->getLocation());
2113     New->setInvalidDecl();
2114     return true;
2115   }
2116 
2117   if (OldType != NewType &&
2118       !OldType->isDependentType() &&
2119       !NewType->isDependentType() &&
2120       !Context.hasSameType(OldType, NewType)) {
2121     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2122     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2123       << Kind << NewType << OldType;
2124     if (Old->getLocation().isValid())
2125       notePreviousDefinition(Old, New->getLocation());
2126     New->setInvalidDecl();
2127     return true;
2128   }
2129   return false;
2130 }
2131 
2132 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2133 /// same name and scope as a previous declaration 'Old'.  Figure out
2134 /// how to resolve this situation, merging decls or emitting
2135 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2136 ///
2137 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2138                                 LookupResult &OldDecls) {
2139   // If the new decl is known invalid already, don't bother doing any
2140   // merging checks.
2141   if (New->isInvalidDecl()) return;
2142 
2143   // Allow multiple definitions for ObjC built-in typedefs.
2144   // FIXME: Verify the underlying types are equivalent!
2145   if (getLangOpts().ObjC) {
2146     const IdentifierInfo *TypeID = New->getIdentifier();
2147     switch (TypeID->getLength()) {
2148     default: break;
2149     case 2:
2150       {
2151         if (!TypeID->isStr("id"))
2152           break;
2153         QualType T = New->getUnderlyingType();
2154         if (!T->isPointerType())
2155           break;
2156         if (!T->isVoidPointerType()) {
2157           QualType PT = T->getAs<PointerType>()->getPointeeType();
2158           if (!PT->isStructureType())
2159             break;
2160         }
2161         Context.setObjCIdRedefinitionType(T);
2162         // Install the built-in type for 'id', ignoring the current definition.
2163         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2164         return;
2165       }
2166     case 5:
2167       if (!TypeID->isStr("Class"))
2168         break;
2169       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2170       // Install the built-in type for 'Class', ignoring the current definition.
2171       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2172       return;
2173     case 3:
2174       if (!TypeID->isStr("SEL"))
2175         break;
2176       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2177       // Install the built-in type for 'SEL', ignoring the current definition.
2178       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2179       return;
2180     }
2181     // Fall through - the typedef name was not a builtin type.
2182   }
2183 
2184   // Verify the old decl was also a type.
2185   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2186   if (!Old) {
2187     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2188       << New->getDeclName();
2189 
2190     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2191     if (OldD->getLocation().isValid())
2192       notePreviousDefinition(OldD, New->getLocation());
2193 
2194     return New->setInvalidDecl();
2195   }
2196 
2197   // If the old declaration is invalid, just give up here.
2198   if (Old->isInvalidDecl())
2199     return New->setInvalidDecl();
2200 
2201   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2202     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2203     auto *NewTag = New->getAnonDeclWithTypedefName();
2204     NamedDecl *Hidden = nullptr;
2205     if (OldTag && NewTag &&
2206         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2207         !hasVisibleDefinition(OldTag, &Hidden)) {
2208       // There is a definition of this tag, but it is not visible. Use it
2209       // instead of our tag.
2210       New->setTypeForDecl(OldTD->getTypeForDecl());
2211       if (OldTD->isModed())
2212         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2213                                     OldTD->getUnderlyingType());
2214       else
2215         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2216 
2217       // Make the old tag definition visible.
2218       makeMergedDefinitionVisible(Hidden);
2219 
2220       // If this was an unscoped enumeration, yank all of its enumerators
2221       // out of the scope.
2222       if (isa<EnumDecl>(NewTag)) {
2223         Scope *EnumScope = getNonFieldDeclScope(S);
2224         for (auto *D : NewTag->decls()) {
2225           auto *ED = cast<EnumConstantDecl>(D);
2226           assert(EnumScope->isDeclScope(ED));
2227           EnumScope->RemoveDecl(ED);
2228           IdResolver.RemoveDecl(ED);
2229           ED->getLexicalDeclContext()->removeDecl(ED);
2230         }
2231       }
2232     }
2233   }
2234 
2235   // If the typedef types are not identical, reject them in all languages and
2236   // with any extensions enabled.
2237   if (isIncompatibleTypedef(Old, New))
2238     return;
2239 
2240   // The types match.  Link up the redeclaration chain and merge attributes if
2241   // the old declaration was a typedef.
2242   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2243     New->setPreviousDecl(Typedef);
2244     mergeDeclAttributes(New, Old);
2245   }
2246 
2247   if (getLangOpts().MicrosoftExt)
2248     return;
2249 
2250   if (getLangOpts().CPlusPlus) {
2251     // C++ [dcl.typedef]p2:
2252     //   In a given non-class scope, a typedef specifier can be used to
2253     //   redefine the name of any type declared in that scope to refer
2254     //   to the type to which it already refers.
2255     if (!isa<CXXRecordDecl>(CurContext))
2256       return;
2257 
2258     // C++0x [dcl.typedef]p4:
2259     //   In a given class scope, a typedef specifier can be used to redefine
2260     //   any class-name declared in that scope that is not also a typedef-name
2261     //   to refer to the type to which it already refers.
2262     //
2263     // This wording came in via DR424, which was a correction to the
2264     // wording in DR56, which accidentally banned code like:
2265     //
2266     //   struct S {
2267     //     typedef struct A { } A;
2268     //   };
2269     //
2270     // in the C++03 standard. We implement the C++0x semantics, which
2271     // allow the above but disallow
2272     //
2273     //   struct S {
2274     //     typedef int I;
2275     //     typedef int I;
2276     //   };
2277     //
2278     // since that was the intent of DR56.
2279     if (!isa<TypedefNameDecl>(Old))
2280       return;
2281 
2282     Diag(New->getLocation(), diag::err_redefinition)
2283       << New->getDeclName();
2284     notePreviousDefinition(Old, New->getLocation());
2285     return New->setInvalidDecl();
2286   }
2287 
2288   // Modules always permit redefinition of typedefs, as does C11.
2289   if (getLangOpts().Modules || getLangOpts().C11)
2290     return;
2291 
2292   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2293   // is normally mapped to an error, but can be controlled with
2294   // -Wtypedef-redefinition.  If either the original or the redefinition is
2295   // in a system header, don't emit this for compatibility with GCC.
2296   if (getDiagnostics().getSuppressSystemWarnings() &&
2297       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2298       (Old->isImplicit() ||
2299        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2300        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2301     return;
2302 
2303   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2304     << New->getDeclName();
2305   notePreviousDefinition(Old, New->getLocation());
2306 }
2307 
2308 /// DeclhasAttr - returns true if decl Declaration already has the target
2309 /// attribute.
2310 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2311   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2312   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2313   for (const auto *i : D->attrs())
2314     if (i->getKind() == A->getKind()) {
2315       if (Ann) {
2316         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2317           return true;
2318         continue;
2319       }
2320       // FIXME: Don't hardcode this check
2321       if (OA && isa<OwnershipAttr>(i))
2322         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2323       return true;
2324     }
2325 
2326   return false;
2327 }
2328 
2329 static bool isAttributeTargetADefinition(Decl *D) {
2330   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2331     return VD->isThisDeclarationADefinition();
2332   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2333     return TD->isCompleteDefinition() || TD->isBeingDefined();
2334   return true;
2335 }
2336 
2337 /// Merge alignment attributes from \p Old to \p New, taking into account the
2338 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2339 ///
2340 /// \return \c true if any attributes were added to \p New.
2341 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2342   // Look for alignas attributes on Old, and pick out whichever attribute
2343   // specifies the strictest alignment requirement.
2344   AlignedAttr *OldAlignasAttr = nullptr;
2345   AlignedAttr *OldStrictestAlignAttr = nullptr;
2346   unsigned OldAlign = 0;
2347   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2348     // FIXME: We have no way of representing inherited dependent alignments
2349     // in a case like:
2350     //   template<int A, int B> struct alignas(A) X;
2351     //   template<int A, int B> struct alignas(B) X {};
2352     // For now, we just ignore any alignas attributes which are not on the
2353     // definition in such a case.
2354     if (I->isAlignmentDependent())
2355       return false;
2356 
2357     if (I->isAlignas())
2358       OldAlignasAttr = I;
2359 
2360     unsigned Align = I->getAlignment(S.Context);
2361     if (Align > OldAlign) {
2362       OldAlign = Align;
2363       OldStrictestAlignAttr = I;
2364     }
2365   }
2366 
2367   // Look for alignas attributes on New.
2368   AlignedAttr *NewAlignasAttr = nullptr;
2369   unsigned NewAlign = 0;
2370   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2371     if (I->isAlignmentDependent())
2372       return false;
2373 
2374     if (I->isAlignas())
2375       NewAlignasAttr = I;
2376 
2377     unsigned Align = I->getAlignment(S.Context);
2378     if (Align > NewAlign)
2379       NewAlign = Align;
2380   }
2381 
2382   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2383     // Both declarations have 'alignas' attributes. We require them to match.
2384     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2385     // fall short. (If two declarations both have alignas, they must both match
2386     // every definition, and so must match each other if there is a definition.)
2387 
2388     // If either declaration only contains 'alignas(0)' specifiers, then it
2389     // specifies the natural alignment for the type.
2390     if (OldAlign == 0 || NewAlign == 0) {
2391       QualType Ty;
2392       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2393         Ty = VD->getType();
2394       else
2395         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2396 
2397       if (OldAlign == 0)
2398         OldAlign = S.Context.getTypeAlign(Ty);
2399       if (NewAlign == 0)
2400         NewAlign = S.Context.getTypeAlign(Ty);
2401     }
2402 
2403     if (OldAlign != NewAlign) {
2404       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2405         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2406         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2407       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2408     }
2409   }
2410 
2411   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2412     // C++11 [dcl.align]p6:
2413     //   if any declaration of an entity has an alignment-specifier,
2414     //   every defining declaration of that entity shall specify an
2415     //   equivalent alignment.
2416     // C11 6.7.5/7:
2417     //   If the definition of an object does not have an alignment
2418     //   specifier, any other declaration of that object shall also
2419     //   have no alignment specifier.
2420     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2421       << OldAlignasAttr;
2422     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2423       << OldAlignasAttr;
2424   }
2425 
2426   bool AnyAdded = false;
2427 
2428   // Ensure we have an attribute representing the strictest alignment.
2429   if (OldAlign > NewAlign) {
2430     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2431     Clone->setInherited(true);
2432     New->addAttr(Clone);
2433     AnyAdded = true;
2434   }
2435 
2436   // Ensure we have an alignas attribute if the old declaration had one.
2437   if (OldAlignasAttr && !NewAlignasAttr &&
2438       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2439     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2440     Clone->setInherited(true);
2441     New->addAttr(Clone);
2442     AnyAdded = true;
2443   }
2444 
2445   return AnyAdded;
2446 }
2447 
2448 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2449                                const InheritableAttr *Attr,
2450                                Sema::AvailabilityMergeKind AMK) {
2451   // This function copies an attribute Attr from a previous declaration to the
2452   // new declaration D if the new declaration doesn't itself have that attribute
2453   // yet or if that attribute allows duplicates.
2454   // If you're adding a new attribute that requires logic different from
2455   // "use explicit attribute on decl if present, else use attribute from
2456   // previous decl", for example if the attribute needs to be consistent
2457   // between redeclarations, you need to call a custom merge function here.
2458   InheritableAttr *NewAttr = nullptr;
2459   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2460   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2461     NewAttr = S.mergeAvailabilityAttr(
2462         D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2463         AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2464         AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2465         AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2466   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2467     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2468                                     AttrSpellingListIndex);
2469   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2470     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2471                                         AttrSpellingListIndex);
2472   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2473     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2474                                    AttrSpellingListIndex);
2475   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2476     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2477                                    AttrSpellingListIndex);
2478   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2479     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2480                                 FA->getFormatIdx(), FA->getFirstArg(),
2481                                 AttrSpellingListIndex);
2482   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2483     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2484                                  AttrSpellingListIndex);
2485   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2486     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2487                                  AttrSpellingListIndex);
2488   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2489     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2490                                        AttrSpellingListIndex,
2491                                        IA->getSemanticSpelling());
2492   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2493     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2494                                       &S.Context.Idents.get(AA->getSpelling()),
2495                                       AttrSpellingListIndex);
2496   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2497            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2498             isa<CUDAGlobalAttr>(Attr))) {
2499     // CUDA target attributes are part of function signature for
2500     // overloading purposes and must not be merged.
2501     return false;
2502   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2503     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2504   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2505     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2506   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2507     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2508   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2509     NewAttr = S.mergeCommonAttr(D, *CommonA);
2510   else if (isa<AlignedAttr>(Attr))
2511     // AlignedAttrs are handled separately, because we need to handle all
2512     // such attributes on a declaration at the same time.
2513     NewAttr = nullptr;
2514   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2515            (AMK == Sema::AMK_Override ||
2516             AMK == Sema::AMK_ProtocolImplementation))
2517     NewAttr = nullptr;
2518   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2519     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2520                               UA->getGuid());
2521   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2522     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2523   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2524     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2525   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2526     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2527 
2528   if (NewAttr) {
2529     NewAttr->setInherited(true);
2530     D->addAttr(NewAttr);
2531     if (isa<MSInheritanceAttr>(NewAttr))
2532       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2533     return true;
2534   }
2535 
2536   return false;
2537 }
2538 
2539 static const NamedDecl *getDefinition(const Decl *D) {
2540   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2541     return TD->getDefinition();
2542   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2543     const VarDecl *Def = VD->getDefinition();
2544     if (Def)
2545       return Def;
2546     return VD->getActingDefinition();
2547   }
2548   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2549     return FD->getDefinition();
2550   return nullptr;
2551 }
2552 
2553 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2554   for (const auto *Attribute : D->attrs())
2555     if (Attribute->getKind() == Kind)
2556       return true;
2557   return false;
2558 }
2559 
2560 /// checkNewAttributesAfterDef - If we already have a definition, check that
2561 /// there are no new attributes in this declaration.
2562 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2563   if (!New->hasAttrs())
2564     return;
2565 
2566   const NamedDecl *Def = getDefinition(Old);
2567   if (!Def || Def == New)
2568     return;
2569 
2570   AttrVec &NewAttributes = New->getAttrs();
2571   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2572     const Attr *NewAttribute = NewAttributes[I];
2573 
2574     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2575       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2576         Sema::SkipBodyInfo SkipBody;
2577         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2578 
2579         // If we're skipping this definition, drop the "alias" attribute.
2580         if (SkipBody.ShouldSkip) {
2581           NewAttributes.erase(NewAttributes.begin() + I);
2582           --E;
2583           continue;
2584         }
2585       } else {
2586         VarDecl *VD = cast<VarDecl>(New);
2587         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2588                                 VarDecl::TentativeDefinition
2589                             ? diag::err_alias_after_tentative
2590                             : diag::err_redefinition;
2591         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2592         if (Diag == diag::err_redefinition)
2593           S.notePreviousDefinition(Def, VD->getLocation());
2594         else
2595           S.Diag(Def->getLocation(), diag::note_previous_definition);
2596         VD->setInvalidDecl();
2597       }
2598       ++I;
2599       continue;
2600     }
2601 
2602     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2603       // Tentative definitions are only interesting for the alias check above.
2604       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2605         ++I;
2606         continue;
2607       }
2608     }
2609 
2610     if (hasAttribute(Def, NewAttribute->getKind())) {
2611       ++I;
2612       continue; // regular attr merging will take care of validating this.
2613     }
2614 
2615     if (isa<C11NoReturnAttr>(NewAttribute)) {
2616       // C's _Noreturn is allowed to be added to a function after it is defined.
2617       ++I;
2618       continue;
2619     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2620       if (AA->isAlignas()) {
2621         // C++11 [dcl.align]p6:
2622         //   if any declaration of an entity has an alignment-specifier,
2623         //   every defining declaration of that entity shall specify an
2624         //   equivalent alignment.
2625         // C11 6.7.5/7:
2626         //   If the definition of an object does not have an alignment
2627         //   specifier, any other declaration of that object shall also
2628         //   have no alignment specifier.
2629         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2630           << AA;
2631         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2632           << AA;
2633         NewAttributes.erase(NewAttributes.begin() + I);
2634         --E;
2635         continue;
2636       }
2637     }
2638 
2639     S.Diag(NewAttribute->getLocation(),
2640            diag::warn_attribute_precede_definition);
2641     S.Diag(Def->getLocation(), diag::note_previous_definition);
2642     NewAttributes.erase(NewAttributes.begin() + I);
2643     --E;
2644   }
2645 }
2646 
2647 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2648 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2649                                AvailabilityMergeKind AMK) {
2650   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2651     UsedAttr *NewAttr = OldAttr->clone(Context);
2652     NewAttr->setInherited(true);
2653     New->addAttr(NewAttr);
2654   }
2655 
2656   if (!Old->hasAttrs() && !New->hasAttrs())
2657     return;
2658 
2659   // Attributes declared post-definition are currently ignored.
2660   checkNewAttributesAfterDef(*this, New, Old);
2661 
2662   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2663     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2664       if (OldA->getLabel() != NewA->getLabel()) {
2665         // This redeclaration changes __asm__ label.
2666         Diag(New->getLocation(), diag::err_different_asm_label);
2667         Diag(OldA->getLocation(), diag::note_previous_declaration);
2668       }
2669     } else if (Old->isUsed()) {
2670       // This redeclaration adds an __asm__ label to a declaration that has
2671       // already been ODR-used.
2672       Diag(New->getLocation(), diag::err_late_asm_label_name)
2673         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2674     }
2675   }
2676 
2677   // Re-declaration cannot add abi_tag's.
2678   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2679     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2680       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2681         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2682                       NewTag) == OldAbiTagAttr->tags_end()) {
2683           Diag(NewAbiTagAttr->getLocation(),
2684                diag::err_new_abi_tag_on_redeclaration)
2685               << NewTag;
2686           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2687         }
2688       }
2689     } else {
2690       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2691       Diag(Old->getLocation(), diag::note_previous_declaration);
2692     }
2693   }
2694 
2695   // This redeclaration adds a section attribute.
2696   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2697     if (auto *VD = dyn_cast<VarDecl>(New)) {
2698       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2699         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2700         Diag(Old->getLocation(), diag::note_previous_declaration);
2701       }
2702     }
2703   }
2704 
2705   // Redeclaration adds code-seg attribute.
2706   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2707   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2708       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2709     Diag(New->getLocation(), diag::warn_mismatched_section)
2710          << 0 /*codeseg*/;
2711     Diag(Old->getLocation(), diag::note_previous_declaration);
2712   }
2713 
2714   if (!Old->hasAttrs())
2715     return;
2716 
2717   bool foundAny = New->hasAttrs();
2718 
2719   // Ensure that any moving of objects within the allocated map is done before
2720   // we process them.
2721   if (!foundAny) New->setAttrs(AttrVec());
2722 
2723   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2724     // Ignore deprecated/unavailable/availability attributes if requested.
2725     AvailabilityMergeKind LocalAMK = AMK_None;
2726     if (isa<DeprecatedAttr>(I) ||
2727         isa<UnavailableAttr>(I) ||
2728         isa<AvailabilityAttr>(I)) {
2729       switch (AMK) {
2730       case AMK_None:
2731         continue;
2732 
2733       case AMK_Redeclaration:
2734       case AMK_Override:
2735       case AMK_ProtocolImplementation:
2736         LocalAMK = AMK;
2737         break;
2738       }
2739     }
2740 
2741     // Already handled.
2742     if (isa<UsedAttr>(I))
2743       continue;
2744 
2745     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2746       foundAny = true;
2747   }
2748 
2749   if (mergeAlignedAttrs(*this, New, Old))
2750     foundAny = true;
2751 
2752   if (!foundAny) New->dropAttrs();
2753 }
2754 
2755 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2756 /// to the new one.
2757 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2758                                      const ParmVarDecl *oldDecl,
2759                                      Sema &S) {
2760   // C++11 [dcl.attr.depend]p2:
2761   //   The first declaration of a function shall specify the
2762   //   carries_dependency attribute for its declarator-id if any declaration
2763   //   of the function specifies the carries_dependency attribute.
2764   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2765   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2766     S.Diag(CDA->getLocation(),
2767            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2768     // Find the first declaration of the parameter.
2769     // FIXME: Should we build redeclaration chains for function parameters?
2770     const FunctionDecl *FirstFD =
2771       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2772     const ParmVarDecl *FirstVD =
2773       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2774     S.Diag(FirstVD->getLocation(),
2775            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2776   }
2777 
2778   if (!oldDecl->hasAttrs())
2779     return;
2780 
2781   bool foundAny = newDecl->hasAttrs();
2782 
2783   // Ensure that any moving of objects within the allocated map is
2784   // done before we process them.
2785   if (!foundAny) newDecl->setAttrs(AttrVec());
2786 
2787   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2788     if (!DeclHasAttr(newDecl, I)) {
2789       InheritableAttr *newAttr =
2790         cast<InheritableParamAttr>(I->clone(S.Context));
2791       newAttr->setInherited(true);
2792       newDecl->addAttr(newAttr);
2793       foundAny = true;
2794     }
2795   }
2796 
2797   if (!foundAny) newDecl->dropAttrs();
2798 }
2799 
2800 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2801                                 const ParmVarDecl *OldParam,
2802                                 Sema &S) {
2803   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2804     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2805       if (*Oldnullability != *Newnullability) {
2806         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2807           << DiagNullabilityKind(
2808                *Newnullability,
2809                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2810                 != 0))
2811           << DiagNullabilityKind(
2812                *Oldnullability,
2813                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2814                 != 0));
2815         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2816       }
2817     } else {
2818       QualType NewT = NewParam->getType();
2819       NewT = S.Context.getAttributedType(
2820                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2821                          NewT, NewT);
2822       NewParam->setType(NewT);
2823     }
2824   }
2825 }
2826 
2827 namespace {
2828 
2829 /// Used in MergeFunctionDecl to keep track of function parameters in
2830 /// C.
2831 struct GNUCompatibleParamWarning {
2832   ParmVarDecl *OldParm;
2833   ParmVarDecl *NewParm;
2834   QualType PromotedType;
2835 };
2836 
2837 } // end anonymous namespace
2838 
2839 /// getSpecialMember - get the special member enum for a method.
2840 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2841   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2842     if (Ctor->isDefaultConstructor())
2843       return Sema::CXXDefaultConstructor;
2844 
2845     if (Ctor->isCopyConstructor())
2846       return Sema::CXXCopyConstructor;
2847 
2848     if (Ctor->isMoveConstructor())
2849       return Sema::CXXMoveConstructor;
2850   } else if (isa<CXXDestructorDecl>(MD)) {
2851     return Sema::CXXDestructor;
2852   } else if (MD->isCopyAssignmentOperator()) {
2853     return Sema::CXXCopyAssignment;
2854   } else if (MD->isMoveAssignmentOperator()) {
2855     return Sema::CXXMoveAssignment;
2856   }
2857 
2858   return Sema::CXXInvalid;
2859 }
2860 
2861 // Determine whether the previous declaration was a definition, implicit
2862 // declaration, or a declaration.
2863 template <typename T>
2864 static std::pair<diag::kind, SourceLocation>
2865 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2866   diag::kind PrevDiag;
2867   SourceLocation OldLocation = Old->getLocation();
2868   if (Old->isThisDeclarationADefinition())
2869     PrevDiag = diag::note_previous_definition;
2870   else if (Old->isImplicit()) {
2871     PrevDiag = diag::note_previous_implicit_declaration;
2872     if (OldLocation.isInvalid())
2873       OldLocation = New->getLocation();
2874   } else
2875     PrevDiag = diag::note_previous_declaration;
2876   return std::make_pair(PrevDiag, OldLocation);
2877 }
2878 
2879 /// canRedefineFunction - checks if a function can be redefined. Currently,
2880 /// only extern inline functions can be redefined, and even then only in
2881 /// GNU89 mode.
2882 static bool canRedefineFunction(const FunctionDecl *FD,
2883                                 const LangOptions& LangOpts) {
2884   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2885           !LangOpts.CPlusPlus &&
2886           FD->isInlineSpecified() &&
2887           FD->getStorageClass() == SC_Extern);
2888 }
2889 
2890 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2891   const AttributedType *AT = T->getAs<AttributedType>();
2892   while (AT && !AT->isCallingConv())
2893     AT = AT->getModifiedType()->getAs<AttributedType>();
2894   return AT;
2895 }
2896 
2897 template <typename T>
2898 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2899   const DeclContext *DC = Old->getDeclContext();
2900   if (DC->isRecord())
2901     return false;
2902 
2903   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2904   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2905     return true;
2906   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2907     return true;
2908   return false;
2909 }
2910 
2911 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2912 static bool isExternC(VarTemplateDecl *) { return false; }
2913 
2914 /// Check whether a redeclaration of an entity introduced by a
2915 /// using-declaration is valid, given that we know it's not an overload
2916 /// (nor a hidden tag declaration).
2917 template<typename ExpectedDecl>
2918 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2919                                    ExpectedDecl *New) {
2920   // C++11 [basic.scope.declarative]p4:
2921   //   Given a set of declarations in a single declarative region, each of
2922   //   which specifies the same unqualified name,
2923   //   -- they shall all refer to the same entity, or all refer to functions
2924   //      and function templates; or
2925   //   -- exactly one declaration shall declare a class name or enumeration
2926   //      name that is not a typedef name and the other declarations shall all
2927   //      refer to the same variable or enumerator, or all refer to functions
2928   //      and function templates; in this case the class name or enumeration
2929   //      name is hidden (3.3.10).
2930 
2931   // C++11 [namespace.udecl]p14:
2932   //   If a function declaration in namespace scope or block scope has the
2933   //   same name and the same parameter-type-list as a function introduced
2934   //   by a using-declaration, and the declarations do not declare the same
2935   //   function, the program is ill-formed.
2936 
2937   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2938   if (Old &&
2939       !Old->getDeclContext()->getRedeclContext()->Equals(
2940           New->getDeclContext()->getRedeclContext()) &&
2941       !(isExternC(Old) && isExternC(New)))
2942     Old = nullptr;
2943 
2944   if (!Old) {
2945     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2946     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2947     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2948     return true;
2949   }
2950   return false;
2951 }
2952 
2953 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2954                                             const FunctionDecl *B) {
2955   assert(A->getNumParams() == B->getNumParams());
2956 
2957   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2958     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2959     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2960     if (AttrA == AttrB)
2961       return true;
2962     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2963            AttrA->isDynamic() == AttrB->isDynamic();
2964   };
2965 
2966   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2967 }
2968 
2969 /// If necessary, adjust the semantic declaration context for a qualified
2970 /// declaration to name the correct inline namespace within the qualifier.
2971 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2972                                                DeclaratorDecl *OldD) {
2973   // The only case where we need to update the DeclContext is when
2974   // redeclaration lookup for a qualified name finds a declaration
2975   // in an inline namespace within the context named by the qualifier:
2976   //
2977   //   inline namespace N { int f(); }
2978   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2979   //
2980   // For unqualified declarations, the semantic context *can* change
2981   // along the redeclaration chain (for local extern declarations,
2982   // extern "C" declarations, and friend declarations in particular).
2983   if (!NewD->getQualifier())
2984     return;
2985 
2986   // NewD is probably already in the right context.
2987   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2988   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2989   if (NamedDC->Equals(SemaDC))
2990     return;
2991 
2992   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2993           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2994          "unexpected context for redeclaration");
2995 
2996   auto *LexDC = NewD->getLexicalDeclContext();
2997   auto FixSemaDC = [=](NamedDecl *D) {
2998     if (!D)
2999       return;
3000     D->setDeclContext(SemaDC);
3001     D->setLexicalDeclContext(LexDC);
3002   };
3003 
3004   FixSemaDC(NewD);
3005   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3006     FixSemaDC(FD->getDescribedFunctionTemplate());
3007   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3008     FixSemaDC(VD->getDescribedVarTemplate());
3009 }
3010 
3011 /// MergeFunctionDecl - We just parsed a function 'New' from
3012 /// declarator D which has the same name and scope as a previous
3013 /// declaration 'Old'.  Figure out how to resolve this situation,
3014 /// merging decls or emitting diagnostics as appropriate.
3015 ///
3016 /// In C++, New and Old must be declarations that are not
3017 /// overloaded. Use IsOverload to determine whether New and Old are
3018 /// overloaded, and to select the Old declaration that New should be
3019 /// merged with.
3020 ///
3021 /// Returns true if there was an error, false otherwise.
3022 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3023                              Scope *S, bool MergeTypeWithOld) {
3024   // Verify the old decl was also a function.
3025   FunctionDecl *Old = OldD->getAsFunction();
3026   if (!Old) {
3027     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3028       if (New->getFriendObjectKind()) {
3029         Diag(New->getLocation(), diag::err_using_decl_friend);
3030         Diag(Shadow->getTargetDecl()->getLocation(),
3031              diag::note_using_decl_target);
3032         Diag(Shadow->getUsingDecl()->getLocation(),
3033              diag::note_using_decl) << 0;
3034         return true;
3035       }
3036 
3037       // Check whether the two declarations might declare the same function.
3038       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3039         return true;
3040       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3041     } else {
3042       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3043         << New->getDeclName();
3044       notePreviousDefinition(OldD, New->getLocation());
3045       return true;
3046     }
3047   }
3048 
3049   // If the old declaration is invalid, just give up here.
3050   if (Old->isInvalidDecl())
3051     return true;
3052 
3053   // Disallow redeclaration of some builtins.
3054   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3055     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3056     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3057         << Old << Old->getType();
3058     return true;
3059   }
3060 
3061   diag::kind PrevDiag;
3062   SourceLocation OldLocation;
3063   std::tie(PrevDiag, OldLocation) =
3064       getNoteDiagForInvalidRedeclaration(Old, New);
3065 
3066   // Don't complain about this if we're in GNU89 mode and the old function
3067   // is an extern inline function.
3068   // Don't complain about specializations. They are not supposed to have
3069   // storage classes.
3070   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3071       New->getStorageClass() == SC_Static &&
3072       Old->hasExternalFormalLinkage() &&
3073       !New->getTemplateSpecializationInfo() &&
3074       !canRedefineFunction(Old, getLangOpts())) {
3075     if (getLangOpts().MicrosoftExt) {
3076       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3077       Diag(OldLocation, PrevDiag);
3078     } else {
3079       Diag(New->getLocation(), diag::err_static_non_static) << New;
3080       Diag(OldLocation, PrevDiag);
3081       return true;
3082     }
3083   }
3084 
3085   if (New->hasAttr<InternalLinkageAttr>() &&
3086       !Old->hasAttr<InternalLinkageAttr>()) {
3087     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3088         << New->getDeclName();
3089     notePreviousDefinition(Old, New->getLocation());
3090     New->dropAttr<InternalLinkageAttr>();
3091   }
3092 
3093   if (CheckRedeclarationModuleOwnership(New, Old))
3094     return true;
3095 
3096   if (!getLangOpts().CPlusPlus) {
3097     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3098     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3099       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3100         << New << OldOvl;
3101 
3102       // Try our best to find a decl that actually has the overloadable
3103       // attribute for the note. In most cases (e.g. programs with only one
3104       // broken declaration/definition), this won't matter.
3105       //
3106       // FIXME: We could do this if we juggled some extra state in
3107       // OverloadableAttr, rather than just removing it.
3108       const Decl *DiagOld = Old;
3109       if (OldOvl) {
3110         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3111           const auto *A = D->getAttr<OverloadableAttr>();
3112           return A && !A->isImplicit();
3113         });
3114         // If we've implicitly added *all* of the overloadable attrs to this
3115         // chain, emitting a "previous redecl" note is pointless.
3116         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3117       }
3118 
3119       if (DiagOld)
3120         Diag(DiagOld->getLocation(),
3121              diag::note_attribute_overloadable_prev_overload)
3122           << OldOvl;
3123 
3124       if (OldOvl)
3125         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3126       else
3127         New->dropAttr<OverloadableAttr>();
3128     }
3129   }
3130 
3131   // If a function is first declared with a calling convention, but is later
3132   // declared or defined without one, all following decls assume the calling
3133   // convention of the first.
3134   //
3135   // It's OK if a function is first declared without a calling convention,
3136   // but is later declared or defined with the default calling convention.
3137   //
3138   // To test if either decl has an explicit calling convention, we look for
3139   // AttributedType sugar nodes on the type as written.  If they are missing or
3140   // were canonicalized away, we assume the calling convention was implicit.
3141   //
3142   // Note also that we DO NOT return at this point, because we still have
3143   // other tests to run.
3144   QualType OldQType = Context.getCanonicalType(Old->getType());
3145   QualType NewQType = Context.getCanonicalType(New->getType());
3146   const FunctionType *OldType = cast<FunctionType>(OldQType);
3147   const FunctionType *NewType = cast<FunctionType>(NewQType);
3148   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3149   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3150   bool RequiresAdjustment = false;
3151 
3152   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3153     FunctionDecl *First = Old->getFirstDecl();
3154     const FunctionType *FT =
3155         First->getType().getCanonicalType()->castAs<FunctionType>();
3156     FunctionType::ExtInfo FI = FT->getExtInfo();
3157     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3158     if (!NewCCExplicit) {
3159       // Inherit the CC from the previous declaration if it was specified
3160       // there but not here.
3161       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3162       RequiresAdjustment = true;
3163     } else if (New->getBuiltinID()) {
3164       // Calling Conventions on a Builtin aren't really useful and setting a
3165       // default calling convention and cdecl'ing some builtin redeclarations is
3166       // common, so warn and ignore the calling convention on the redeclaration.
3167       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3168           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3169           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3170       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3171       RequiresAdjustment = true;
3172     } else {
3173       // Calling conventions aren't compatible, so complain.
3174       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3175       Diag(New->getLocation(), diag::err_cconv_change)
3176         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3177         << !FirstCCExplicit
3178         << (!FirstCCExplicit ? "" :
3179             FunctionType::getNameForCallConv(FI.getCC()));
3180 
3181       // Put the note on the first decl, since it is the one that matters.
3182       Diag(First->getLocation(), diag::note_previous_declaration);
3183       return true;
3184     }
3185   }
3186 
3187   // FIXME: diagnose the other way around?
3188   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3189     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3190     RequiresAdjustment = true;
3191   }
3192 
3193   // Merge regparm attribute.
3194   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3195       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3196     if (NewTypeInfo.getHasRegParm()) {
3197       Diag(New->getLocation(), diag::err_regparm_mismatch)
3198         << NewType->getRegParmType()
3199         << OldType->getRegParmType();
3200       Diag(OldLocation, diag::note_previous_declaration);
3201       return true;
3202     }
3203 
3204     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3205     RequiresAdjustment = true;
3206   }
3207 
3208   // Merge ns_returns_retained attribute.
3209   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3210     if (NewTypeInfo.getProducesResult()) {
3211       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3212           << "'ns_returns_retained'";
3213       Diag(OldLocation, diag::note_previous_declaration);
3214       return true;
3215     }
3216 
3217     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3218     RequiresAdjustment = true;
3219   }
3220 
3221   if (OldTypeInfo.getNoCallerSavedRegs() !=
3222       NewTypeInfo.getNoCallerSavedRegs()) {
3223     if (NewTypeInfo.getNoCallerSavedRegs()) {
3224       AnyX86NoCallerSavedRegistersAttr *Attr =
3225         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3226       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3227       Diag(OldLocation, diag::note_previous_declaration);
3228       return true;
3229     }
3230 
3231     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3232     RequiresAdjustment = true;
3233   }
3234 
3235   if (RequiresAdjustment) {
3236     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3237     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3238     New->setType(QualType(AdjustedType, 0));
3239     NewQType = Context.getCanonicalType(New->getType());
3240   }
3241 
3242   // If this redeclaration makes the function inline, we may need to add it to
3243   // UndefinedButUsed.
3244   if (!Old->isInlined() && New->isInlined() &&
3245       !New->hasAttr<GNUInlineAttr>() &&
3246       !getLangOpts().GNUInline &&
3247       Old->isUsed(false) &&
3248       !Old->isDefined() && !New->isThisDeclarationADefinition())
3249     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3250                                            SourceLocation()));
3251 
3252   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3253   // about it.
3254   if (New->hasAttr<GNUInlineAttr>() &&
3255       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3256     UndefinedButUsed.erase(Old->getCanonicalDecl());
3257   }
3258 
3259   // If pass_object_size params don't match up perfectly, this isn't a valid
3260   // redeclaration.
3261   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3262       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3263     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3264         << New->getDeclName();
3265     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3266     return true;
3267   }
3268 
3269   if (getLangOpts().CPlusPlus) {
3270     // C++1z [over.load]p2
3271     //   Certain function declarations cannot be overloaded:
3272     //     -- Function declarations that differ only in the return type,
3273     //        the exception specification, or both cannot be overloaded.
3274 
3275     // Check the exception specifications match. This may recompute the type of
3276     // both Old and New if it resolved exception specifications, so grab the
3277     // types again after this. Because this updates the type, we do this before
3278     // any of the other checks below, which may update the "de facto" NewQType
3279     // but do not necessarily update the type of New.
3280     if (CheckEquivalentExceptionSpec(Old, New))
3281       return true;
3282     OldQType = Context.getCanonicalType(Old->getType());
3283     NewQType = Context.getCanonicalType(New->getType());
3284 
3285     // Go back to the type source info to compare the declared return types,
3286     // per C++1y [dcl.type.auto]p13:
3287     //   Redeclarations or specializations of a function or function template
3288     //   with a declared return type that uses a placeholder type shall also
3289     //   use that placeholder, not a deduced type.
3290     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3291     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3292     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3293         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3294                                        OldDeclaredReturnType)) {
3295       QualType ResQT;
3296       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3297           OldDeclaredReturnType->isObjCObjectPointerType())
3298         // FIXME: This does the wrong thing for a deduced return type.
3299         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3300       if (ResQT.isNull()) {
3301         if (New->isCXXClassMember() && New->isOutOfLine())
3302           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3303               << New << New->getReturnTypeSourceRange();
3304         else
3305           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3306               << New->getReturnTypeSourceRange();
3307         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3308                                     << Old->getReturnTypeSourceRange();
3309         return true;
3310       }
3311       else
3312         NewQType = ResQT;
3313     }
3314 
3315     QualType OldReturnType = OldType->getReturnType();
3316     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3317     if (OldReturnType != NewReturnType) {
3318       // If this function has a deduced return type and has already been
3319       // defined, copy the deduced value from the old declaration.
3320       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3321       if (OldAT && OldAT->isDeduced()) {
3322         New->setType(
3323             SubstAutoType(New->getType(),
3324                           OldAT->isDependentType() ? Context.DependentTy
3325                                                    : OldAT->getDeducedType()));
3326         NewQType = Context.getCanonicalType(
3327             SubstAutoType(NewQType,
3328                           OldAT->isDependentType() ? Context.DependentTy
3329                                                    : OldAT->getDeducedType()));
3330       }
3331     }
3332 
3333     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3334     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3335     if (OldMethod && NewMethod) {
3336       // Preserve triviality.
3337       NewMethod->setTrivial(OldMethod->isTrivial());
3338 
3339       // MSVC allows explicit template specialization at class scope:
3340       // 2 CXXMethodDecls referring to the same function will be injected.
3341       // We don't want a redeclaration error.
3342       bool IsClassScopeExplicitSpecialization =
3343                               OldMethod->isFunctionTemplateSpecialization() &&
3344                               NewMethod->isFunctionTemplateSpecialization();
3345       bool isFriend = NewMethod->getFriendObjectKind();
3346 
3347       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3348           !IsClassScopeExplicitSpecialization) {
3349         //    -- Member function declarations with the same name and the
3350         //       same parameter types cannot be overloaded if any of them
3351         //       is a static member function declaration.
3352         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3353           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3354           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3355           return true;
3356         }
3357 
3358         // C++ [class.mem]p1:
3359         //   [...] A member shall not be declared twice in the
3360         //   member-specification, except that a nested class or member
3361         //   class template can be declared and then later defined.
3362         if (!inTemplateInstantiation()) {
3363           unsigned NewDiag;
3364           if (isa<CXXConstructorDecl>(OldMethod))
3365             NewDiag = diag::err_constructor_redeclared;
3366           else if (isa<CXXDestructorDecl>(NewMethod))
3367             NewDiag = diag::err_destructor_redeclared;
3368           else if (isa<CXXConversionDecl>(NewMethod))
3369             NewDiag = diag::err_conv_function_redeclared;
3370           else
3371             NewDiag = diag::err_member_redeclared;
3372 
3373           Diag(New->getLocation(), NewDiag);
3374         } else {
3375           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3376             << New << New->getType();
3377         }
3378         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3379         return true;
3380 
3381       // Complain if this is an explicit declaration of a special
3382       // member that was initially declared implicitly.
3383       //
3384       // As an exception, it's okay to befriend such methods in order
3385       // to permit the implicit constructor/destructor/operator calls.
3386       } else if (OldMethod->isImplicit()) {
3387         if (isFriend) {
3388           NewMethod->setImplicit();
3389         } else {
3390           Diag(NewMethod->getLocation(),
3391                diag::err_definition_of_implicitly_declared_member)
3392             << New << getSpecialMember(OldMethod);
3393           return true;
3394         }
3395       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3396         Diag(NewMethod->getLocation(),
3397              diag::err_definition_of_explicitly_defaulted_member)
3398           << getSpecialMember(OldMethod);
3399         return true;
3400       }
3401     }
3402 
3403     // C++11 [dcl.attr.noreturn]p1:
3404     //   The first declaration of a function shall specify the noreturn
3405     //   attribute if any declaration of that function specifies the noreturn
3406     //   attribute.
3407     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3408     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3409       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3410       Diag(Old->getFirstDecl()->getLocation(),
3411            diag::note_noreturn_missing_first_decl);
3412     }
3413 
3414     // C++11 [dcl.attr.depend]p2:
3415     //   The first declaration of a function shall specify the
3416     //   carries_dependency attribute for its declarator-id if any declaration
3417     //   of the function specifies the carries_dependency attribute.
3418     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3419     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3420       Diag(CDA->getLocation(),
3421            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3422       Diag(Old->getFirstDecl()->getLocation(),
3423            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3424     }
3425 
3426     // (C++98 8.3.5p3):
3427     //   All declarations for a function shall agree exactly in both the
3428     //   return type and the parameter-type-list.
3429     // We also want to respect all the extended bits except noreturn.
3430 
3431     // noreturn should now match unless the old type info didn't have it.
3432     QualType OldQTypeForComparison = OldQType;
3433     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3434       auto *OldType = OldQType->castAs<FunctionProtoType>();
3435       const FunctionType *OldTypeForComparison
3436         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3437       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3438       assert(OldQTypeForComparison.isCanonical());
3439     }
3440 
3441     if (haveIncompatibleLanguageLinkages(Old, New)) {
3442       // As a special case, retain the language linkage from previous
3443       // declarations of a friend function as an extension.
3444       //
3445       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3446       // and is useful because there's otherwise no way to specify language
3447       // linkage within class scope.
3448       //
3449       // Check cautiously as the friend object kind isn't yet complete.
3450       if (New->getFriendObjectKind() != Decl::FOK_None) {
3451         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3452         Diag(OldLocation, PrevDiag);
3453       } else {
3454         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3455         Diag(OldLocation, PrevDiag);
3456         return true;
3457       }
3458     }
3459 
3460     if (OldQTypeForComparison == NewQType)
3461       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3462 
3463     // If the types are imprecise (due to dependent constructs in friends or
3464     // local extern declarations), it's OK if they differ. We'll check again
3465     // during instantiation.
3466     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3467       return false;
3468 
3469     // Fall through for conflicting redeclarations and redefinitions.
3470   }
3471 
3472   // C: Function types need to be compatible, not identical. This handles
3473   // duplicate function decls like "void f(int); void f(enum X);" properly.
3474   if (!getLangOpts().CPlusPlus &&
3475       Context.typesAreCompatible(OldQType, NewQType)) {
3476     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3477     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3478     const FunctionProtoType *OldProto = nullptr;
3479     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3480         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3481       // The old declaration provided a function prototype, but the
3482       // new declaration does not. Merge in the prototype.
3483       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3484       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3485       NewQType =
3486           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3487                                   OldProto->getExtProtoInfo());
3488       New->setType(NewQType);
3489       New->setHasInheritedPrototype();
3490 
3491       // Synthesize parameters with the same types.
3492       SmallVector<ParmVarDecl*, 16> Params;
3493       for (const auto &ParamType : OldProto->param_types()) {
3494         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3495                                                  SourceLocation(), nullptr,
3496                                                  ParamType, /*TInfo=*/nullptr,
3497                                                  SC_None, nullptr);
3498         Param->setScopeInfo(0, Params.size());
3499         Param->setImplicit();
3500         Params.push_back(Param);
3501       }
3502 
3503       New->setParams(Params);
3504     }
3505 
3506     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3507   }
3508 
3509   // GNU C permits a K&R definition to follow a prototype declaration
3510   // if the declared types of the parameters in the K&R definition
3511   // match the types in the prototype declaration, even when the
3512   // promoted types of the parameters from the K&R definition differ
3513   // from the types in the prototype. GCC then keeps the types from
3514   // the prototype.
3515   //
3516   // If a variadic prototype is followed by a non-variadic K&R definition,
3517   // the K&R definition becomes variadic.  This is sort of an edge case, but
3518   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3519   // C99 6.9.1p8.
3520   if (!getLangOpts().CPlusPlus &&
3521       Old->hasPrototype() && !New->hasPrototype() &&
3522       New->getType()->getAs<FunctionProtoType>() &&
3523       Old->getNumParams() == New->getNumParams()) {
3524     SmallVector<QualType, 16> ArgTypes;
3525     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3526     const FunctionProtoType *OldProto
3527       = Old->getType()->getAs<FunctionProtoType>();
3528     const FunctionProtoType *NewProto
3529       = New->getType()->getAs<FunctionProtoType>();
3530 
3531     // Determine whether this is the GNU C extension.
3532     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3533                                                NewProto->getReturnType());
3534     bool LooseCompatible = !MergedReturn.isNull();
3535     for (unsigned Idx = 0, End = Old->getNumParams();
3536          LooseCompatible && Idx != End; ++Idx) {
3537       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3538       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3539       if (Context.typesAreCompatible(OldParm->getType(),
3540                                      NewProto->getParamType(Idx))) {
3541         ArgTypes.push_back(NewParm->getType());
3542       } else if (Context.typesAreCompatible(OldParm->getType(),
3543                                             NewParm->getType(),
3544                                             /*CompareUnqualified=*/true)) {
3545         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3546                                            NewProto->getParamType(Idx) };
3547         Warnings.push_back(Warn);
3548         ArgTypes.push_back(NewParm->getType());
3549       } else
3550         LooseCompatible = false;
3551     }
3552 
3553     if (LooseCompatible) {
3554       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3555         Diag(Warnings[Warn].NewParm->getLocation(),
3556              diag::ext_param_promoted_not_compatible_with_prototype)
3557           << Warnings[Warn].PromotedType
3558           << Warnings[Warn].OldParm->getType();
3559         if (Warnings[Warn].OldParm->getLocation().isValid())
3560           Diag(Warnings[Warn].OldParm->getLocation(),
3561                diag::note_previous_declaration);
3562       }
3563 
3564       if (MergeTypeWithOld)
3565         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3566                                              OldProto->getExtProtoInfo()));
3567       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3568     }
3569 
3570     // Fall through to diagnose conflicting types.
3571   }
3572 
3573   // A function that has already been declared has been redeclared or
3574   // defined with a different type; show an appropriate diagnostic.
3575 
3576   // If the previous declaration was an implicitly-generated builtin
3577   // declaration, then at the very least we should use a specialized note.
3578   unsigned BuiltinID;
3579   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3580     // If it's actually a library-defined builtin function like 'malloc'
3581     // or 'printf', just warn about the incompatible redeclaration.
3582     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3583       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3584       Diag(OldLocation, diag::note_previous_builtin_declaration)
3585         << Old << Old->getType();
3586 
3587       // If this is a global redeclaration, just forget hereafter
3588       // about the "builtin-ness" of the function.
3589       //
3590       // Doing this for local extern declarations is problematic.  If
3591       // the builtin declaration remains visible, a second invalid
3592       // local declaration will produce a hard error; if it doesn't
3593       // remain visible, a single bogus local redeclaration (which is
3594       // actually only a warning) could break all the downstream code.
3595       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3596         New->getIdentifier()->revertBuiltin();
3597 
3598       return false;
3599     }
3600 
3601     PrevDiag = diag::note_previous_builtin_declaration;
3602   }
3603 
3604   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3605   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3606   return true;
3607 }
3608 
3609 /// Completes the merge of two function declarations that are
3610 /// known to be compatible.
3611 ///
3612 /// This routine handles the merging of attributes and other
3613 /// properties of function declarations from the old declaration to
3614 /// the new declaration, once we know that New is in fact a
3615 /// redeclaration of Old.
3616 ///
3617 /// \returns false
3618 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3619                                         Scope *S, bool MergeTypeWithOld) {
3620   // Merge the attributes
3621   mergeDeclAttributes(New, Old);
3622 
3623   // Merge "pure" flag.
3624   if (Old->isPure())
3625     New->setPure();
3626 
3627   // Merge "used" flag.
3628   if (Old->getMostRecentDecl()->isUsed(false))
3629     New->setIsUsed();
3630 
3631   // Merge attributes from the parameters.  These can mismatch with K&R
3632   // declarations.
3633   if (New->getNumParams() == Old->getNumParams())
3634       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3635         ParmVarDecl *NewParam = New->getParamDecl(i);
3636         ParmVarDecl *OldParam = Old->getParamDecl(i);
3637         mergeParamDeclAttributes(NewParam, OldParam, *this);
3638         mergeParamDeclTypes(NewParam, OldParam, *this);
3639       }
3640 
3641   if (getLangOpts().CPlusPlus)
3642     return MergeCXXFunctionDecl(New, Old, S);
3643 
3644   // Merge the function types so the we get the composite types for the return
3645   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3646   // was visible.
3647   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3648   if (!Merged.isNull() && MergeTypeWithOld)
3649     New->setType(Merged);
3650 
3651   return false;
3652 }
3653 
3654 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3655                                 ObjCMethodDecl *oldMethod) {
3656   // Merge the attributes, including deprecated/unavailable
3657   AvailabilityMergeKind MergeKind =
3658     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3659       ? AMK_ProtocolImplementation
3660       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3661                                                        : AMK_Override;
3662 
3663   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3664 
3665   // Merge attributes from the parameters.
3666   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3667                                        oe = oldMethod->param_end();
3668   for (ObjCMethodDecl::param_iterator
3669          ni = newMethod->param_begin(), ne = newMethod->param_end();
3670        ni != ne && oi != oe; ++ni, ++oi)
3671     mergeParamDeclAttributes(*ni, *oi, *this);
3672 
3673   CheckObjCMethodOverride(newMethod, oldMethod);
3674 }
3675 
3676 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3677   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3678 
3679   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3680          ? diag::err_redefinition_different_type
3681          : diag::err_redeclaration_different_type)
3682     << New->getDeclName() << New->getType() << Old->getType();
3683 
3684   diag::kind PrevDiag;
3685   SourceLocation OldLocation;
3686   std::tie(PrevDiag, OldLocation)
3687     = getNoteDiagForInvalidRedeclaration(Old, New);
3688   S.Diag(OldLocation, PrevDiag);
3689   New->setInvalidDecl();
3690 }
3691 
3692 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3693 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3694 /// emitting diagnostics as appropriate.
3695 ///
3696 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3697 /// to here in AddInitializerToDecl. We can't check them before the initializer
3698 /// is attached.
3699 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3700                              bool MergeTypeWithOld) {
3701   if (New->isInvalidDecl() || Old->isInvalidDecl())
3702     return;
3703 
3704   QualType MergedT;
3705   if (getLangOpts().CPlusPlus) {
3706     if (New->getType()->isUndeducedType()) {
3707       // We don't know what the new type is until the initializer is attached.
3708       return;
3709     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3710       // These could still be something that needs exception specs checked.
3711       return MergeVarDeclExceptionSpecs(New, Old);
3712     }
3713     // C++ [basic.link]p10:
3714     //   [...] the types specified by all declarations referring to a given
3715     //   object or function shall be identical, except that declarations for an
3716     //   array object can specify array types that differ by the presence or
3717     //   absence of a major array bound (8.3.4).
3718     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3719       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3720       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3721 
3722       // We are merging a variable declaration New into Old. If it has an array
3723       // bound, and that bound differs from Old's bound, we should diagnose the
3724       // mismatch.
3725       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3726         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3727              PrevVD = PrevVD->getPreviousDecl()) {
3728           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3729           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3730             continue;
3731 
3732           if (!Context.hasSameType(NewArray, PrevVDTy))
3733             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3734         }
3735       }
3736 
3737       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3738         if (Context.hasSameType(OldArray->getElementType(),
3739                                 NewArray->getElementType()))
3740           MergedT = New->getType();
3741       }
3742       // FIXME: Check visibility. New is hidden but has a complete type. If New
3743       // has no array bound, it should not inherit one from Old, if Old is not
3744       // visible.
3745       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3746         if (Context.hasSameType(OldArray->getElementType(),
3747                                 NewArray->getElementType()))
3748           MergedT = Old->getType();
3749       }
3750     }
3751     else if (New->getType()->isObjCObjectPointerType() &&
3752                Old->getType()->isObjCObjectPointerType()) {
3753       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3754                                               Old->getType());
3755     }
3756   } else {
3757     // C 6.2.7p2:
3758     //   All declarations that refer to the same object or function shall have
3759     //   compatible type.
3760     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3761   }
3762   if (MergedT.isNull()) {
3763     // It's OK if we couldn't merge types if either type is dependent, for a
3764     // block-scope variable. In other cases (static data members of class
3765     // templates, variable templates, ...), we require the types to be
3766     // equivalent.
3767     // FIXME: The C++ standard doesn't say anything about this.
3768     if ((New->getType()->isDependentType() ||
3769          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3770       // If the old type was dependent, we can't merge with it, so the new type
3771       // becomes dependent for now. We'll reproduce the original type when we
3772       // instantiate the TypeSourceInfo for the variable.
3773       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3774         New->setType(Context.DependentTy);
3775       return;
3776     }
3777     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3778   }
3779 
3780   // Don't actually update the type on the new declaration if the old
3781   // declaration was an extern declaration in a different scope.
3782   if (MergeTypeWithOld)
3783     New->setType(MergedT);
3784 }
3785 
3786 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3787                                   LookupResult &Previous) {
3788   // C11 6.2.7p4:
3789   //   For an identifier with internal or external linkage declared
3790   //   in a scope in which a prior declaration of that identifier is
3791   //   visible, if the prior declaration specifies internal or
3792   //   external linkage, the type of the identifier at the later
3793   //   declaration becomes the composite type.
3794   //
3795   // If the variable isn't visible, we do not merge with its type.
3796   if (Previous.isShadowed())
3797     return false;
3798 
3799   if (S.getLangOpts().CPlusPlus) {
3800     // C++11 [dcl.array]p3:
3801     //   If there is a preceding declaration of the entity in the same
3802     //   scope in which the bound was specified, an omitted array bound
3803     //   is taken to be the same as in that earlier declaration.
3804     return NewVD->isPreviousDeclInSameBlockScope() ||
3805            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3806             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3807   } else {
3808     // If the old declaration was function-local, don't merge with its
3809     // type unless we're in the same function.
3810     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3811            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3812   }
3813 }
3814 
3815 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3816 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3817 /// situation, merging decls or emitting diagnostics as appropriate.
3818 ///
3819 /// Tentative definition rules (C99 6.9.2p2) are checked by
3820 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3821 /// definitions here, since the initializer hasn't been attached.
3822 ///
3823 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3824   // If the new decl is already invalid, don't do any other checking.
3825   if (New->isInvalidDecl())
3826     return;
3827 
3828   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3829     return;
3830 
3831   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3832 
3833   // Verify the old decl was also a variable or variable template.
3834   VarDecl *Old = nullptr;
3835   VarTemplateDecl *OldTemplate = nullptr;
3836   if (Previous.isSingleResult()) {
3837     if (NewTemplate) {
3838       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3839       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3840 
3841       if (auto *Shadow =
3842               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3843         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3844           return New->setInvalidDecl();
3845     } else {
3846       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3847 
3848       if (auto *Shadow =
3849               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3850         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3851           return New->setInvalidDecl();
3852     }
3853   }
3854   if (!Old) {
3855     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3856         << New->getDeclName();
3857     notePreviousDefinition(Previous.getRepresentativeDecl(),
3858                            New->getLocation());
3859     return New->setInvalidDecl();
3860   }
3861 
3862   // Ensure the template parameters are compatible.
3863   if (NewTemplate &&
3864       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3865                                       OldTemplate->getTemplateParameters(),
3866                                       /*Complain=*/true, TPL_TemplateMatch))
3867     return New->setInvalidDecl();
3868 
3869   // C++ [class.mem]p1:
3870   //   A member shall not be declared twice in the member-specification [...]
3871   //
3872   // Here, we need only consider static data members.
3873   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3874     Diag(New->getLocation(), diag::err_duplicate_member)
3875       << New->getIdentifier();
3876     Diag(Old->getLocation(), diag::note_previous_declaration);
3877     New->setInvalidDecl();
3878   }
3879 
3880   mergeDeclAttributes(New, Old);
3881   // Warn if an already-declared variable is made a weak_import in a subsequent
3882   // declaration
3883   if (New->hasAttr<WeakImportAttr>() &&
3884       Old->getStorageClass() == SC_None &&
3885       !Old->hasAttr<WeakImportAttr>()) {
3886     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3887     notePreviousDefinition(Old, New->getLocation());
3888     // Remove weak_import attribute on new declaration.
3889     New->dropAttr<WeakImportAttr>();
3890   }
3891 
3892   if (New->hasAttr<InternalLinkageAttr>() &&
3893       !Old->hasAttr<InternalLinkageAttr>()) {
3894     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3895         << New->getDeclName();
3896     notePreviousDefinition(Old, New->getLocation());
3897     New->dropAttr<InternalLinkageAttr>();
3898   }
3899 
3900   // Merge the types.
3901   VarDecl *MostRecent = Old->getMostRecentDecl();
3902   if (MostRecent != Old) {
3903     MergeVarDeclTypes(New, MostRecent,
3904                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3905     if (New->isInvalidDecl())
3906       return;
3907   }
3908 
3909   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3910   if (New->isInvalidDecl())
3911     return;
3912 
3913   diag::kind PrevDiag;
3914   SourceLocation OldLocation;
3915   std::tie(PrevDiag, OldLocation) =
3916       getNoteDiagForInvalidRedeclaration(Old, New);
3917 
3918   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3919   if (New->getStorageClass() == SC_Static &&
3920       !New->isStaticDataMember() &&
3921       Old->hasExternalFormalLinkage()) {
3922     if (getLangOpts().MicrosoftExt) {
3923       Diag(New->getLocation(), diag::ext_static_non_static)
3924           << New->getDeclName();
3925       Diag(OldLocation, PrevDiag);
3926     } else {
3927       Diag(New->getLocation(), diag::err_static_non_static)
3928           << New->getDeclName();
3929       Diag(OldLocation, PrevDiag);
3930       return New->setInvalidDecl();
3931     }
3932   }
3933   // C99 6.2.2p4:
3934   //   For an identifier declared with the storage-class specifier
3935   //   extern in a scope in which a prior declaration of that
3936   //   identifier is visible,23) if the prior declaration specifies
3937   //   internal or external linkage, the linkage of the identifier at
3938   //   the later declaration is the same as the linkage specified at
3939   //   the prior declaration. If no prior declaration is visible, or
3940   //   if the prior declaration specifies no linkage, then the
3941   //   identifier has external linkage.
3942   if (New->hasExternalStorage() && Old->hasLinkage())
3943     /* Okay */;
3944   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3945            !New->isStaticDataMember() &&
3946            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3947     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3948     Diag(OldLocation, PrevDiag);
3949     return New->setInvalidDecl();
3950   }
3951 
3952   // Check if extern is followed by non-extern and vice-versa.
3953   if (New->hasExternalStorage() &&
3954       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3955     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3956     Diag(OldLocation, PrevDiag);
3957     return New->setInvalidDecl();
3958   }
3959   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3960       !New->hasExternalStorage()) {
3961     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3962     Diag(OldLocation, PrevDiag);
3963     return New->setInvalidDecl();
3964   }
3965 
3966   if (CheckRedeclarationModuleOwnership(New, Old))
3967     return;
3968 
3969   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3970 
3971   // FIXME: The test for external storage here seems wrong? We still
3972   // need to check for mismatches.
3973   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3974       // Don't complain about out-of-line definitions of static members.
3975       !(Old->getLexicalDeclContext()->isRecord() &&
3976         !New->getLexicalDeclContext()->isRecord())) {
3977     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3978     Diag(OldLocation, PrevDiag);
3979     return New->setInvalidDecl();
3980   }
3981 
3982   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3983     if (VarDecl *Def = Old->getDefinition()) {
3984       // C++1z [dcl.fcn.spec]p4:
3985       //   If the definition of a variable appears in a translation unit before
3986       //   its first declaration as inline, the program is ill-formed.
3987       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3988       Diag(Def->getLocation(), diag::note_previous_definition);
3989     }
3990   }
3991 
3992   // If this redeclaration makes the variable inline, we may need to add it to
3993   // UndefinedButUsed.
3994   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3995       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3996     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3997                                            SourceLocation()));
3998 
3999   if (New->getTLSKind() != Old->getTLSKind()) {
4000     if (!Old->getTLSKind()) {
4001       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4002       Diag(OldLocation, PrevDiag);
4003     } else if (!New->getTLSKind()) {
4004       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4005       Diag(OldLocation, PrevDiag);
4006     } else {
4007       // Do not allow redeclaration to change the variable between requiring
4008       // static and dynamic initialization.
4009       // FIXME: GCC allows this, but uses the TLS keyword on the first
4010       // declaration to determine the kind. Do we need to be compatible here?
4011       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4012         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4013       Diag(OldLocation, PrevDiag);
4014     }
4015   }
4016 
4017   // C++ doesn't have tentative definitions, so go right ahead and check here.
4018   if (getLangOpts().CPlusPlus &&
4019       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4020     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4021         Old->getCanonicalDecl()->isConstexpr()) {
4022       // This definition won't be a definition any more once it's been merged.
4023       Diag(New->getLocation(),
4024            diag::warn_deprecated_redundant_constexpr_static_def);
4025     } else if (VarDecl *Def = Old->getDefinition()) {
4026       if (checkVarDeclRedefinition(Def, New))
4027         return;
4028     }
4029   }
4030 
4031   if (haveIncompatibleLanguageLinkages(Old, New)) {
4032     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4033     Diag(OldLocation, PrevDiag);
4034     New->setInvalidDecl();
4035     return;
4036   }
4037 
4038   // Merge "used" flag.
4039   if (Old->getMostRecentDecl()->isUsed(false))
4040     New->setIsUsed();
4041 
4042   // Keep a chain of previous declarations.
4043   New->setPreviousDecl(Old);
4044   if (NewTemplate)
4045     NewTemplate->setPreviousDecl(OldTemplate);
4046   adjustDeclContextForDeclaratorDecl(New, Old);
4047 
4048   // Inherit access appropriately.
4049   New->setAccess(Old->getAccess());
4050   if (NewTemplate)
4051     NewTemplate->setAccess(New->getAccess());
4052 
4053   if (Old->isInline())
4054     New->setImplicitlyInline();
4055 }
4056 
4057 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4058   SourceManager &SrcMgr = getSourceManager();
4059   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4060   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4061   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4062   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4063   auto &HSI = PP.getHeaderSearchInfo();
4064   StringRef HdrFilename =
4065       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4066 
4067   auto noteFromModuleOrInclude = [&](Module *Mod,
4068                                      SourceLocation IncLoc) -> bool {
4069     // Redefinition errors with modules are common with non modular mapped
4070     // headers, example: a non-modular header H in module A that also gets
4071     // included directly in a TU. Pointing twice to the same header/definition
4072     // is confusing, try to get better diagnostics when modules is on.
4073     if (IncLoc.isValid()) {
4074       if (Mod) {
4075         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4076             << HdrFilename.str() << Mod->getFullModuleName();
4077         if (!Mod->DefinitionLoc.isInvalid())
4078           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4079               << Mod->getFullModuleName();
4080       } else {
4081         Diag(IncLoc, diag::note_redefinition_include_same_file)
4082             << HdrFilename.str();
4083       }
4084       return true;
4085     }
4086 
4087     return false;
4088   };
4089 
4090   // Is it the same file and same offset? Provide more information on why
4091   // this leads to a redefinition error.
4092   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4093     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4094     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4095     bool EmittedDiag =
4096         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4097     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4098 
4099     // If the header has no guards, emit a note suggesting one.
4100     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4101       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4102 
4103     if (EmittedDiag)
4104       return;
4105   }
4106 
4107   // Redefinition coming from different files or couldn't do better above.
4108   if (Old->getLocation().isValid())
4109     Diag(Old->getLocation(), diag::note_previous_definition);
4110 }
4111 
4112 /// We've just determined that \p Old and \p New both appear to be definitions
4113 /// of the same variable. Either diagnose or fix the problem.
4114 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4115   if (!hasVisibleDefinition(Old) &&
4116       (New->getFormalLinkage() == InternalLinkage ||
4117        New->isInline() ||
4118        New->getDescribedVarTemplate() ||
4119        New->getNumTemplateParameterLists() ||
4120        New->getDeclContext()->isDependentContext())) {
4121     // The previous definition is hidden, and multiple definitions are
4122     // permitted (in separate TUs). Demote this to a declaration.
4123     New->demoteThisDefinitionToDeclaration();
4124 
4125     // Make the canonical definition visible.
4126     if (auto *OldTD = Old->getDescribedVarTemplate())
4127       makeMergedDefinitionVisible(OldTD);
4128     makeMergedDefinitionVisible(Old);
4129     return false;
4130   } else {
4131     Diag(New->getLocation(), diag::err_redefinition) << New;
4132     notePreviousDefinition(Old, New->getLocation());
4133     New->setInvalidDecl();
4134     return true;
4135   }
4136 }
4137 
4138 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4139 /// no declarator (e.g. "struct foo;") is parsed.
4140 Decl *
4141 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4142                                  RecordDecl *&AnonRecord) {
4143   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4144                                     AnonRecord);
4145 }
4146 
4147 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4148 // disambiguate entities defined in different scopes.
4149 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4150 // compatibility.
4151 // We will pick our mangling number depending on which version of MSVC is being
4152 // targeted.
4153 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4154   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4155              ? S->getMSCurManglingNumber()
4156              : S->getMSLastManglingNumber();
4157 }
4158 
4159 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4160   if (!Context.getLangOpts().CPlusPlus)
4161     return;
4162 
4163   if (isa<CXXRecordDecl>(Tag->getParent())) {
4164     // If this tag is the direct child of a class, number it if
4165     // it is anonymous.
4166     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4167       return;
4168     MangleNumberingContext &MCtx =
4169         Context.getManglingNumberContext(Tag->getParent());
4170     Context.setManglingNumber(
4171         Tag, MCtx.getManglingNumber(
4172                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4173     return;
4174   }
4175 
4176   // If this tag isn't a direct child of a class, number it if it is local.
4177   Decl *ManglingContextDecl;
4178   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4179           Tag->getDeclContext(), ManglingContextDecl)) {
4180     Context.setManglingNumber(
4181         Tag, MCtx->getManglingNumber(
4182                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4183   }
4184 }
4185 
4186 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4187                                         TypedefNameDecl *NewTD) {
4188   if (TagFromDeclSpec->isInvalidDecl())
4189     return;
4190 
4191   // Do nothing if the tag already has a name for linkage purposes.
4192   if (TagFromDeclSpec->hasNameForLinkage())
4193     return;
4194 
4195   // A well-formed anonymous tag must always be a TUK_Definition.
4196   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4197 
4198   // The type must match the tag exactly;  no qualifiers allowed.
4199   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4200                            Context.getTagDeclType(TagFromDeclSpec))) {
4201     if (getLangOpts().CPlusPlus)
4202       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4203     return;
4204   }
4205 
4206   // If we've already computed linkage for the anonymous tag, then
4207   // adding a typedef name for the anonymous decl can change that
4208   // linkage, which might be a serious problem.  Diagnose this as
4209   // unsupported and ignore the typedef name.  TODO: we should
4210   // pursue this as a language defect and establish a formal rule
4211   // for how to handle it.
4212   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4213     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4214 
4215     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4216     tagLoc = getLocForEndOfToken(tagLoc);
4217 
4218     llvm::SmallString<40> textToInsert;
4219     textToInsert += ' ';
4220     textToInsert += NewTD->getIdentifier()->getName();
4221     Diag(tagLoc, diag::note_typedef_changes_linkage)
4222         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4223     return;
4224   }
4225 
4226   // Otherwise, set this is the anon-decl typedef for the tag.
4227   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4228 }
4229 
4230 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4231   switch (T) {
4232   case DeclSpec::TST_class:
4233     return 0;
4234   case DeclSpec::TST_struct:
4235     return 1;
4236   case DeclSpec::TST_interface:
4237     return 2;
4238   case DeclSpec::TST_union:
4239     return 3;
4240   case DeclSpec::TST_enum:
4241     return 4;
4242   default:
4243     llvm_unreachable("unexpected type specifier");
4244   }
4245 }
4246 
4247 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4248 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4249 /// parameters to cope with template friend declarations.
4250 Decl *
4251 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4252                                  MultiTemplateParamsArg TemplateParams,
4253                                  bool IsExplicitInstantiation,
4254                                  RecordDecl *&AnonRecord) {
4255   Decl *TagD = nullptr;
4256   TagDecl *Tag = nullptr;
4257   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4258       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4259       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4260       DS.getTypeSpecType() == DeclSpec::TST_union ||
4261       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4262     TagD = DS.getRepAsDecl();
4263 
4264     if (!TagD) // We probably had an error
4265       return nullptr;
4266 
4267     // Note that the above type specs guarantee that the
4268     // type rep is a Decl, whereas in many of the others
4269     // it's a Type.
4270     if (isa<TagDecl>(TagD))
4271       Tag = cast<TagDecl>(TagD);
4272     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4273       Tag = CTD->getTemplatedDecl();
4274   }
4275 
4276   if (Tag) {
4277     handleTagNumbering(Tag, S);
4278     Tag->setFreeStanding();
4279     if (Tag->isInvalidDecl())
4280       return Tag;
4281   }
4282 
4283   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4284     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4285     // or incomplete types shall not be restrict-qualified."
4286     if (TypeQuals & DeclSpec::TQ_restrict)
4287       Diag(DS.getRestrictSpecLoc(),
4288            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4289            << DS.getSourceRange();
4290   }
4291 
4292   if (DS.isInlineSpecified())
4293     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4294         << getLangOpts().CPlusPlus17;
4295 
4296   if (DS.hasConstexprSpecifier()) {
4297     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4298     // and definitions of functions and variables.
4299     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4300     // the declaration of a function or function template
4301     bool IsConsteval = DS.getConstexprSpecifier() == CSK_consteval;
4302     if (Tag)
4303       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4304           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << IsConsteval;
4305     else
4306       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4307           << IsConsteval;
4308     // Don't emit warnings after this error.
4309     return TagD;
4310   }
4311 
4312   DiagnoseFunctionSpecifiers(DS);
4313 
4314   if (DS.isFriendSpecified()) {
4315     // If we're dealing with a decl but not a TagDecl, assume that
4316     // whatever routines created it handled the friendship aspect.
4317     if (TagD && !Tag)
4318       return nullptr;
4319     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4320   }
4321 
4322   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4323   bool IsExplicitSpecialization =
4324     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4325   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4326       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4327       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4328     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4329     // nested-name-specifier unless it is an explicit instantiation
4330     // or an explicit specialization.
4331     //
4332     // FIXME: We allow class template partial specializations here too, per the
4333     // obvious intent of DR1819.
4334     //
4335     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4336     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4337         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4338     return nullptr;
4339   }
4340 
4341   // Track whether this decl-specifier declares anything.
4342   bool DeclaresAnything = true;
4343 
4344   // Handle anonymous struct definitions.
4345   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4346     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4347         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4348       if (getLangOpts().CPlusPlus ||
4349           Record->getDeclContext()->isRecord()) {
4350         // If CurContext is a DeclContext that can contain statements,
4351         // RecursiveASTVisitor won't visit the decls that
4352         // BuildAnonymousStructOrUnion() will put into CurContext.
4353         // Also store them here so that they can be part of the
4354         // DeclStmt that gets created in this case.
4355         // FIXME: Also return the IndirectFieldDecls created by
4356         // BuildAnonymousStructOr union, for the same reason?
4357         if (CurContext->isFunctionOrMethod())
4358           AnonRecord = Record;
4359         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4360                                            Context.getPrintingPolicy());
4361       }
4362 
4363       DeclaresAnything = false;
4364     }
4365   }
4366 
4367   // C11 6.7.2.1p2:
4368   //   A struct-declaration that does not declare an anonymous structure or
4369   //   anonymous union shall contain a struct-declarator-list.
4370   //
4371   // This rule also existed in C89 and C99; the grammar for struct-declaration
4372   // did not permit a struct-declaration without a struct-declarator-list.
4373   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4374       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4375     // Check for Microsoft C extension: anonymous struct/union member.
4376     // Handle 2 kinds of anonymous struct/union:
4377     //   struct STRUCT;
4378     //   union UNION;
4379     // and
4380     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4381     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4382     if ((Tag && Tag->getDeclName()) ||
4383         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4384       RecordDecl *Record = nullptr;
4385       if (Tag)
4386         Record = dyn_cast<RecordDecl>(Tag);
4387       else if (const RecordType *RT =
4388                    DS.getRepAsType().get()->getAsStructureType())
4389         Record = RT->getDecl();
4390       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4391         Record = UT->getDecl();
4392 
4393       if (Record && getLangOpts().MicrosoftExt) {
4394         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4395             << Record->isUnion() << DS.getSourceRange();
4396         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4397       }
4398 
4399       DeclaresAnything = false;
4400     }
4401   }
4402 
4403   // Skip all the checks below if we have a type error.
4404   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4405       (TagD && TagD->isInvalidDecl()))
4406     return TagD;
4407 
4408   if (getLangOpts().CPlusPlus &&
4409       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4410     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4411       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4412           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4413         DeclaresAnything = false;
4414 
4415   if (!DS.isMissingDeclaratorOk()) {
4416     // Customize diagnostic for a typedef missing a name.
4417     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4418       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4419           << DS.getSourceRange();
4420     else
4421       DeclaresAnything = false;
4422   }
4423 
4424   if (DS.isModulePrivateSpecified() &&
4425       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4426     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4427       << Tag->getTagKind()
4428       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4429 
4430   ActOnDocumentableDecl(TagD);
4431 
4432   // C 6.7/2:
4433   //   A declaration [...] shall declare at least a declarator [...], a tag,
4434   //   or the members of an enumeration.
4435   // C++ [dcl.dcl]p3:
4436   //   [If there are no declarators], and except for the declaration of an
4437   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4438   //   names into the program, or shall redeclare a name introduced by a
4439   //   previous declaration.
4440   if (!DeclaresAnything) {
4441     // In C, we allow this as a (popular) extension / bug. Don't bother
4442     // producing further diagnostics for redundant qualifiers after this.
4443     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4444     return TagD;
4445   }
4446 
4447   // C++ [dcl.stc]p1:
4448   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4449   //   init-declarator-list of the declaration shall not be empty.
4450   // C++ [dcl.fct.spec]p1:
4451   //   If a cv-qualifier appears in a decl-specifier-seq, the
4452   //   init-declarator-list of the declaration shall not be empty.
4453   //
4454   // Spurious qualifiers here appear to be valid in C.
4455   unsigned DiagID = diag::warn_standalone_specifier;
4456   if (getLangOpts().CPlusPlus)
4457     DiagID = diag::ext_standalone_specifier;
4458 
4459   // Note that a linkage-specification sets a storage class, but
4460   // 'extern "C" struct foo;' is actually valid and not theoretically
4461   // useless.
4462   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4463     if (SCS == DeclSpec::SCS_mutable)
4464       // Since mutable is not a viable storage class specifier in C, there is
4465       // no reason to treat it as an extension. Instead, diagnose as an error.
4466       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4467     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4468       Diag(DS.getStorageClassSpecLoc(), DiagID)
4469         << DeclSpec::getSpecifierName(SCS);
4470   }
4471 
4472   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4473     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4474       << DeclSpec::getSpecifierName(TSCS);
4475   if (DS.getTypeQualifiers()) {
4476     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4477       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4478     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4479       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4480     // Restrict is covered above.
4481     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4482       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4483     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4484       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4485   }
4486 
4487   // Warn about ignored type attributes, for example:
4488   // __attribute__((aligned)) struct A;
4489   // Attributes should be placed after tag to apply to type declaration.
4490   if (!DS.getAttributes().empty()) {
4491     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4492     if (TypeSpecType == DeclSpec::TST_class ||
4493         TypeSpecType == DeclSpec::TST_struct ||
4494         TypeSpecType == DeclSpec::TST_interface ||
4495         TypeSpecType == DeclSpec::TST_union ||
4496         TypeSpecType == DeclSpec::TST_enum) {
4497       for (const ParsedAttr &AL : DS.getAttributes())
4498         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4499             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4500     }
4501   }
4502 
4503   return TagD;
4504 }
4505 
4506 /// We are trying to inject an anonymous member into the given scope;
4507 /// check if there's an existing declaration that can't be overloaded.
4508 ///
4509 /// \return true if this is a forbidden redeclaration
4510 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4511                                          Scope *S,
4512                                          DeclContext *Owner,
4513                                          DeclarationName Name,
4514                                          SourceLocation NameLoc,
4515                                          bool IsUnion) {
4516   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4517                  Sema::ForVisibleRedeclaration);
4518   if (!SemaRef.LookupName(R, S)) return false;
4519 
4520   // Pick a representative declaration.
4521   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4522   assert(PrevDecl && "Expected a non-null Decl");
4523 
4524   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4525     return false;
4526 
4527   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4528     << IsUnion << Name;
4529   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4530 
4531   return true;
4532 }
4533 
4534 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4535 /// anonymous struct or union AnonRecord into the owning context Owner
4536 /// and scope S. This routine will be invoked just after we realize
4537 /// that an unnamed union or struct is actually an anonymous union or
4538 /// struct, e.g.,
4539 ///
4540 /// @code
4541 /// union {
4542 ///   int i;
4543 ///   float f;
4544 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4545 ///    // f into the surrounding scope.x
4546 /// @endcode
4547 ///
4548 /// This routine is recursive, injecting the names of nested anonymous
4549 /// structs/unions into the owning context and scope as well.
4550 static bool
4551 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4552                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4553                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4554   bool Invalid = false;
4555 
4556   // Look every FieldDecl and IndirectFieldDecl with a name.
4557   for (auto *D : AnonRecord->decls()) {
4558     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4559         cast<NamedDecl>(D)->getDeclName()) {
4560       ValueDecl *VD = cast<ValueDecl>(D);
4561       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4562                                        VD->getLocation(),
4563                                        AnonRecord->isUnion())) {
4564         // C++ [class.union]p2:
4565         //   The names of the members of an anonymous union shall be
4566         //   distinct from the names of any other entity in the
4567         //   scope in which the anonymous union is declared.
4568         Invalid = true;
4569       } else {
4570         // C++ [class.union]p2:
4571         //   For the purpose of name lookup, after the anonymous union
4572         //   definition, the members of the anonymous union are
4573         //   considered to have been defined in the scope in which the
4574         //   anonymous union is declared.
4575         unsigned OldChainingSize = Chaining.size();
4576         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4577           Chaining.append(IF->chain_begin(), IF->chain_end());
4578         else
4579           Chaining.push_back(VD);
4580 
4581         assert(Chaining.size() >= 2);
4582         NamedDecl **NamedChain =
4583           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4584         for (unsigned i = 0; i < Chaining.size(); i++)
4585           NamedChain[i] = Chaining[i];
4586 
4587         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4588             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4589             VD->getType(), {NamedChain, Chaining.size()});
4590 
4591         for (const auto *Attr : VD->attrs())
4592           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4593 
4594         IndirectField->setAccess(AS);
4595         IndirectField->setImplicit();
4596         SemaRef.PushOnScopeChains(IndirectField, S);
4597 
4598         // That includes picking up the appropriate access specifier.
4599         if (AS != AS_none) IndirectField->setAccess(AS);
4600 
4601         Chaining.resize(OldChainingSize);
4602       }
4603     }
4604   }
4605 
4606   return Invalid;
4607 }
4608 
4609 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4610 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4611 /// illegal input values are mapped to SC_None.
4612 static StorageClass
4613 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4614   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4615   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4616          "Parser allowed 'typedef' as storage class VarDecl.");
4617   switch (StorageClassSpec) {
4618   case DeclSpec::SCS_unspecified:    return SC_None;
4619   case DeclSpec::SCS_extern:
4620     if (DS.isExternInLinkageSpec())
4621       return SC_None;
4622     return SC_Extern;
4623   case DeclSpec::SCS_static:         return SC_Static;
4624   case DeclSpec::SCS_auto:           return SC_Auto;
4625   case DeclSpec::SCS_register:       return SC_Register;
4626   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4627     // Illegal SCSs map to None: error reporting is up to the caller.
4628   case DeclSpec::SCS_mutable:        // Fall through.
4629   case DeclSpec::SCS_typedef:        return SC_None;
4630   }
4631   llvm_unreachable("unknown storage class specifier");
4632 }
4633 
4634 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4635   assert(Record->hasInClassInitializer());
4636 
4637   for (const auto *I : Record->decls()) {
4638     const auto *FD = dyn_cast<FieldDecl>(I);
4639     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4640       FD = IFD->getAnonField();
4641     if (FD && FD->hasInClassInitializer())
4642       return FD->getLocation();
4643   }
4644 
4645   llvm_unreachable("couldn't find in-class initializer");
4646 }
4647 
4648 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4649                                       SourceLocation DefaultInitLoc) {
4650   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4651     return;
4652 
4653   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4654   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4655 }
4656 
4657 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4658                                       CXXRecordDecl *AnonUnion) {
4659   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4660     return;
4661 
4662   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4663 }
4664 
4665 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4666 /// anonymous structure or union. Anonymous unions are a C++ feature
4667 /// (C++ [class.union]) and a C11 feature; anonymous structures
4668 /// are a C11 feature and GNU C++ extension.
4669 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4670                                         AccessSpecifier AS,
4671                                         RecordDecl *Record,
4672                                         const PrintingPolicy &Policy) {
4673   DeclContext *Owner = Record->getDeclContext();
4674 
4675   // Diagnose whether this anonymous struct/union is an extension.
4676   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4677     Diag(Record->getLocation(), diag::ext_anonymous_union);
4678   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4679     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4680   else if (!Record->isUnion() && !getLangOpts().C11)
4681     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4682 
4683   // C and C++ require different kinds of checks for anonymous
4684   // structs/unions.
4685   bool Invalid = false;
4686   if (getLangOpts().CPlusPlus) {
4687     const char *PrevSpec = nullptr;
4688     if (Record->isUnion()) {
4689       // C++ [class.union]p6:
4690       // C++17 [class.union.anon]p2:
4691       //   Anonymous unions declared in a named namespace or in the
4692       //   global namespace shall be declared static.
4693       unsigned DiagID;
4694       DeclContext *OwnerScope = Owner->getRedeclContext();
4695       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4696           (OwnerScope->isTranslationUnit() ||
4697            (OwnerScope->isNamespace() &&
4698             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4699         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4700           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4701 
4702         // Recover by adding 'static'.
4703         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4704                                PrevSpec, DiagID, Policy);
4705       }
4706       // C++ [class.union]p6:
4707       //   A storage class is not allowed in a declaration of an
4708       //   anonymous union in a class scope.
4709       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4710                isa<RecordDecl>(Owner)) {
4711         Diag(DS.getStorageClassSpecLoc(),
4712              diag::err_anonymous_union_with_storage_spec)
4713           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4714 
4715         // Recover by removing the storage specifier.
4716         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4717                                SourceLocation(),
4718                                PrevSpec, DiagID, Context.getPrintingPolicy());
4719       }
4720     }
4721 
4722     // Ignore const/volatile/restrict qualifiers.
4723     if (DS.getTypeQualifiers()) {
4724       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4725         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4726           << Record->isUnion() << "const"
4727           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4728       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4729         Diag(DS.getVolatileSpecLoc(),
4730              diag::ext_anonymous_struct_union_qualified)
4731           << Record->isUnion() << "volatile"
4732           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4733       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4734         Diag(DS.getRestrictSpecLoc(),
4735              diag::ext_anonymous_struct_union_qualified)
4736           << Record->isUnion() << "restrict"
4737           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4738       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4739         Diag(DS.getAtomicSpecLoc(),
4740              diag::ext_anonymous_struct_union_qualified)
4741           << Record->isUnion() << "_Atomic"
4742           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4743       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4744         Diag(DS.getUnalignedSpecLoc(),
4745              diag::ext_anonymous_struct_union_qualified)
4746           << Record->isUnion() << "__unaligned"
4747           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4748 
4749       DS.ClearTypeQualifiers();
4750     }
4751 
4752     // C++ [class.union]p2:
4753     //   The member-specification of an anonymous union shall only
4754     //   define non-static data members. [Note: nested types and
4755     //   functions cannot be declared within an anonymous union. ]
4756     for (auto *Mem : Record->decls()) {
4757       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4758         // C++ [class.union]p3:
4759         //   An anonymous union shall not have private or protected
4760         //   members (clause 11).
4761         assert(FD->getAccess() != AS_none);
4762         if (FD->getAccess() != AS_public) {
4763           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4764             << Record->isUnion() << (FD->getAccess() == AS_protected);
4765           Invalid = true;
4766         }
4767 
4768         // C++ [class.union]p1
4769         //   An object of a class with a non-trivial constructor, a non-trivial
4770         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4771         //   assignment operator cannot be a member of a union, nor can an
4772         //   array of such objects.
4773         if (CheckNontrivialField(FD))
4774           Invalid = true;
4775       } else if (Mem->isImplicit()) {
4776         // Any implicit members are fine.
4777       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4778         // This is a type that showed up in an
4779         // elaborated-type-specifier inside the anonymous struct or
4780         // union, but which actually declares a type outside of the
4781         // anonymous struct or union. It's okay.
4782       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4783         if (!MemRecord->isAnonymousStructOrUnion() &&
4784             MemRecord->getDeclName()) {
4785           // Visual C++ allows type definition in anonymous struct or union.
4786           if (getLangOpts().MicrosoftExt)
4787             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4788               << Record->isUnion();
4789           else {
4790             // This is a nested type declaration.
4791             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4792               << Record->isUnion();
4793             Invalid = true;
4794           }
4795         } else {
4796           // This is an anonymous type definition within another anonymous type.
4797           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4798           // not part of standard C++.
4799           Diag(MemRecord->getLocation(),
4800                diag::ext_anonymous_record_with_anonymous_type)
4801             << Record->isUnion();
4802         }
4803       } else if (isa<AccessSpecDecl>(Mem)) {
4804         // Any access specifier is fine.
4805       } else if (isa<StaticAssertDecl>(Mem)) {
4806         // In C++1z, static_assert declarations are also fine.
4807       } else {
4808         // We have something that isn't a non-static data
4809         // member. Complain about it.
4810         unsigned DK = diag::err_anonymous_record_bad_member;
4811         if (isa<TypeDecl>(Mem))
4812           DK = diag::err_anonymous_record_with_type;
4813         else if (isa<FunctionDecl>(Mem))
4814           DK = diag::err_anonymous_record_with_function;
4815         else if (isa<VarDecl>(Mem))
4816           DK = diag::err_anonymous_record_with_static;
4817 
4818         // Visual C++ allows type definition in anonymous struct or union.
4819         if (getLangOpts().MicrosoftExt &&
4820             DK == diag::err_anonymous_record_with_type)
4821           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4822             << Record->isUnion();
4823         else {
4824           Diag(Mem->getLocation(), DK) << Record->isUnion();
4825           Invalid = true;
4826         }
4827       }
4828     }
4829 
4830     // C++11 [class.union]p8 (DR1460):
4831     //   At most one variant member of a union may have a
4832     //   brace-or-equal-initializer.
4833     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4834         Owner->isRecord())
4835       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4836                                 cast<CXXRecordDecl>(Record));
4837   }
4838 
4839   if (!Record->isUnion() && !Owner->isRecord()) {
4840     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4841       << getLangOpts().CPlusPlus;
4842     Invalid = true;
4843   }
4844 
4845   // C++ [dcl.dcl]p3:
4846   //   [If there are no declarators], and except for the declaration of an
4847   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4848   //   names into the program
4849   // C++ [class.mem]p2:
4850   //   each such member-declaration shall either declare at least one member
4851   //   name of the class or declare at least one unnamed bit-field
4852   //
4853   // For C this is an error even for a named struct, and is diagnosed elsewhere.
4854   if (getLangOpts().CPlusPlus && Record->field_empty())
4855     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4856 
4857   // Mock up a declarator.
4858   Declarator Dc(DS, DeclaratorContext::MemberContext);
4859   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4860   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4861 
4862   // Create a declaration for this anonymous struct/union.
4863   NamedDecl *Anon = nullptr;
4864   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4865     Anon = FieldDecl::Create(
4866         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4867         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4868         /*BitWidth=*/nullptr, /*Mutable=*/false,
4869         /*InitStyle=*/ICIS_NoInit);
4870     Anon->setAccess(AS);
4871     if (getLangOpts().CPlusPlus)
4872       FieldCollector->Add(cast<FieldDecl>(Anon));
4873   } else {
4874     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4875     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4876     if (SCSpec == DeclSpec::SCS_mutable) {
4877       // mutable can only appear on non-static class members, so it's always
4878       // an error here
4879       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4880       Invalid = true;
4881       SC = SC_None;
4882     }
4883 
4884     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4885                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4886                            Context.getTypeDeclType(Record), TInfo, SC);
4887 
4888     // Default-initialize the implicit variable. This initialization will be
4889     // trivial in almost all cases, except if a union member has an in-class
4890     // initializer:
4891     //   union { int n = 0; };
4892     ActOnUninitializedDecl(Anon);
4893   }
4894   Anon->setImplicit();
4895 
4896   // Mark this as an anonymous struct/union type.
4897   Record->setAnonymousStructOrUnion(true);
4898 
4899   // Add the anonymous struct/union object to the current
4900   // context. We'll be referencing this object when we refer to one of
4901   // its members.
4902   Owner->addDecl(Anon);
4903 
4904   // Inject the members of the anonymous struct/union into the owning
4905   // context and into the identifier resolver chain for name lookup
4906   // purposes.
4907   SmallVector<NamedDecl*, 2> Chain;
4908   Chain.push_back(Anon);
4909 
4910   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4911     Invalid = true;
4912 
4913   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4914     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4915       Decl *ManglingContextDecl;
4916       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4917               NewVD->getDeclContext(), ManglingContextDecl)) {
4918         Context.setManglingNumber(
4919             NewVD, MCtx->getManglingNumber(
4920                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4921         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4922       }
4923     }
4924   }
4925 
4926   if (Invalid)
4927     Anon->setInvalidDecl();
4928 
4929   return Anon;
4930 }
4931 
4932 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4933 /// Microsoft C anonymous structure.
4934 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4935 /// Example:
4936 ///
4937 /// struct A { int a; };
4938 /// struct B { struct A; int b; };
4939 ///
4940 /// void foo() {
4941 ///   B var;
4942 ///   var.a = 3;
4943 /// }
4944 ///
4945 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4946                                            RecordDecl *Record) {
4947   assert(Record && "expected a record!");
4948 
4949   // Mock up a declarator.
4950   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4951   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4952   assert(TInfo && "couldn't build declarator info for anonymous struct");
4953 
4954   auto *ParentDecl = cast<RecordDecl>(CurContext);
4955   QualType RecTy = Context.getTypeDeclType(Record);
4956 
4957   // Create a declaration for this anonymous struct.
4958   NamedDecl *Anon =
4959       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4960                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4961                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4962                         /*InitStyle=*/ICIS_NoInit);
4963   Anon->setImplicit();
4964 
4965   // Add the anonymous struct object to the current context.
4966   CurContext->addDecl(Anon);
4967 
4968   // Inject the members of the anonymous struct into the current
4969   // context and into the identifier resolver chain for name lookup
4970   // purposes.
4971   SmallVector<NamedDecl*, 2> Chain;
4972   Chain.push_back(Anon);
4973 
4974   RecordDecl *RecordDef = Record->getDefinition();
4975   if (RequireCompleteType(Anon->getLocation(), RecTy,
4976                           diag::err_field_incomplete) ||
4977       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4978                                           AS_none, Chain)) {
4979     Anon->setInvalidDecl();
4980     ParentDecl->setInvalidDecl();
4981   }
4982 
4983   return Anon;
4984 }
4985 
4986 /// GetNameForDeclarator - Determine the full declaration name for the
4987 /// given Declarator.
4988 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4989   return GetNameFromUnqualifiedId(D.getName());
4990 }
4991 
4992 /// Retrieves the declaration name from a parsed unqualified-id.
4993 DeclarationNameInfo
4994 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4995   DeclarationNameInfo NameInfo;
4996   NameInfo.setLoc(Name.StartLocation);
4997 
4998   switch (Name.getKind()) {
4999 
5000   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5001   case UnqualifiedIdKind::IK_Identifier:
5002     NameInfo.setName(Name.Identifier);
5003     return NameInfo;
5004 
5005   case UnqualifiedIdKind::IK_DeductionGuideName: {
5006     // C++ [temp.deduct.guide]p3:
5007     //   The simple-template-id shall name a class template specialization.
5008     //   The template-name shall be the same identifier as the template-name
5009     //   of the simple-template-id.
5010     // These together intend to imply that the template-name shall name a
5011     // class template.
5012     // FIXME: template<typename T> struct X {};
5013     //        template<typename T> using Y = X<T>;
5014     //        Y(int) -> Y<int>;
5015     //   satisfies these rules but does not name a class template.
5016     TemplateName TN = Name.TemplateName.get().get();
5017     auto *Template = TN.getAsTemplateDecl();
5018     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5019       Diag(Name.StartLocation,
5020            diag::err_deduction_guide_name_not_class_template)
5021         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5022       if (Template)
5023         Diag(Template->getLocation(), diag::note_template_decl_here);
5024       return DeclarationNameInfo();
5025     }
5026 
5027     NameInfo.setName(
5028         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5029     return NameInfo;
5030   }
5031 
5032   case UnqualifiedIdKind::IK_OperatorFunctionId:
5033     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5034                                            Name.OperatorFunctionId.Operator));
5035     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5036       = Name.OperatorFunctionId.SymbolLocations[0];
5037     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5038       = Name.EndLocation.getRawEncoding();
5039     return NameInfo;
5040 
5041   case UnqualifiedIdKind::IK_LiteralOperatorId:
5042     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5043                                                            Name.Identifier));
5044     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5045     return NameInfo;
5046 
5047   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5048     TypeSourceInfo *TInfo;
5049     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5050     if (Ty.isNull())
5051       return DeclarationNameInfo();
5052     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5053                                                Context.getCanonicalType(Ty)));
5054     NameInfo.setNamedTypeInfo(TInfo);
5055     return NameInfo;
5056   }
5057 
5058   case UnqualifiedIdKind::IK_ConstructorName: {
5059     TypeSourceInfo *TInfo;
5060     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5061     if (Ty.isNull())
5062       return DeclarationNameInfo();
5063     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5064                                               Context.getCanonicalType(Ty)));
5065     NameInfo.setNamedTypeInfo(TInfo);
5066     return NameInfo;
5067   }
5068 
5069   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5070     // In well-formed code, we can only have a constructor
5071     // template-id that refers to the current context, so go there
5072     // to find the actual type being constructed.
5073     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5074     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5075       return DeclarationNameInfo();
5076 
5077     // Determine the type of the class being constructed.
5078     QualType CurClassType = Context.getTypeDeclType(CurClass);
5079 
5080     // FIXME: Check two things: that the template-id names the same type as
5081     // CurClassType, and that the template-id does not occur when the name
5082     // was qualified.
5083 
5084     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5085                                     Context.getCanonicalType(CurClassType)));
5086     // FIXME: should we retrieve TypeSourceInfo?
5087     NameInfo.setNamedTypeInfo(nullptr);
5088     return NameInfo;
5089   }
5090 
5091   case UnqualifiedIdKind::IK_DestructorName: {
5092     TypeSourceInfo *TInfo;
5093     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5094     if (Ty.isNull())
5095       return DeclarationNameInfo();
5096     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5097                                               Context.getCanonicalType(Ty)));
5098     NameInfo.setNamedTypeInfo(TInfo);
5099     return NameInfo;
5100   }
5101 
5102   case UnqualifiedIdKind::IK_TemplateId: {
5103     TemplateName TName = Name.TemplateId->Template.get();
5104     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5105     return Context.getNameForTemplate(TName, TNameLoc);
5106   }
5107 
5108   } // switch (Name.getKind())
5109 
5110   llvm_unreachable("Unknown name kind");
5111 }
5112 
5113 static QualType getCoreType(QualType Ty) {
5114   do {
5115     if (Ty->isPointerType() || Ty->isReferenceType())
5116       Ty = Ty->getPointeeType();
5117     else if (Ty->isArrayType())
5118       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5119     else
5120       return Ty.withoutLocalFastQualifiers();
5121   } while (true);
5122 }
5123 
5124 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5125 /// and Definition have "nearly" matching parameters. This heuristic is
5126 /// used to improve diagnostics in the case where an out-of-line function
5127 /// definition doesn't match any declaration within the class or namespace.
5128 /// Also sets Params to the list of indices to the parameters that differ
5129 /// between the declaration and the definition. If hasSimilarParameters
5130 /// returns true and Params is empty, then all of the parameters match.
5131 static bool hasSimilarParameters(ASTContext &Context,
5132                                      FunctionDecl *Declaration,
5133                                      FunctionDecl *Definition,
5134                                      SmallVectorImpl<unsigned> &Params) {
5135   Params.clear();
5136   if (Declaration->param_size() != Definition->param_size())
5137     return false;
5138   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5139     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5140     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5141 
5142     // The parameter types are identical
5143     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5144       continue;
5145 
5146     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5147     QualType DefParamBaseTy = getCoreType(DefParamTy);
5148     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5149     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5150 
5151     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5152         (DeclTyName && DeclTyName == DefTyName))
5153       Params.push_back(Idx);
5154     else  // The two parameters aren't even close
5155       return false;
5156   }
5157 
5158   return true;
5159 }
5160 
5161 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5162 /// declarator needs to be rebuilt in the current instantiation.
5163 /// Any bits of declarator which appear before the name are valid for
5164 /// consideration here.  That's specifically the type in the decl spec
5165 /// and the base type in any member-pointer chunks.
5166 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5167                                                     DeclarationName Name) {
5168   // The types we specifically need to rebuild are:
5169   //   - typenames, typeofs, and decltypes
5170   //   - types which will become injected class names
5171   // Of course, we also need to rebuild any type referencing such a
5172   // type.  It's safest to just say "dependent", but we call out a
5173   // few cases here.
5174 
5175   DeclSpec &DS = D.getMutableDeclSpec();
5176   switch (DS.getTypeSpecType()) {
5177   case DeclSpec::TST_typename:
5178   case DeclSpec::TST_typeofType:
5179   case DeclSpec::TST_underlyingType:
5180   case DeclSpec::TST_atomic: {
5181     // Grab the type from the parser.
5182     TypeSourceInfo *TSI = nullptr;
5183     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5184     if (T.isNull() || !T->isDependentType()) break;
5185 
5186     // Make sure there's a type source info.  This isn't really much
5187     // of a waste; most dependent types should have type source info
5188     // attached already.
5189     if (!TSI)
5190       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5191 
5192     // Rebuild the type in the current instantiation.
5193     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5194     if (!TSI) return true;
5195 
5196     // Store the new type back in the decl spec.
5197     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5198     DS.UpdateTypeRep(LocType);
5199     break;
5200   }
5201 
5202   case DeclSpec::TST_decltype:
5203   case DeclSpec::TST_typeofExpr: {
5204     Expr *E = DS.getRepAsExpr();
5205     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5206     if (Result.isInvalid()) return true;
5207     DS.UpdateExprRep(Result.get());
5208     break;
5209   }
5210 
5211   default:
5212     // Nothing to do for these decl specs.
5213     break;
5214   }
5215 
5216   // It doesn't matter what order we do this in.
5217   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5218     DeclaratorChunk &Chunk = D.getTypeObject(I);
5219 
5220     // The only type information in the declarator which can come
5221     // before the declaration name is the base type of a member
5222     // pointer.
5223     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5224       continue;
5225 
5226     // Rebuild the scope specifier in-place.
5227     CXXScopeSpec &SS = Chunk.Mem.Scope();
5228     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5229       return true;
5230   }
5231 
5232   return false;
5233 }
5234 
5235 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5236   D.setFunctionDefinitionKind(FDK_Declaration);
5237   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5238 
5239   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5240       Dcl && Dcl->getDeclContext()->isFileContext())
5241     Dcl->setTopLevelDeclInObjCContainer();
5242 
5243   if (getLangOpts().OpenCL)
5244     setCurrentOpenCLExtensionForDecl(Dcl);
5245 
5246   return Dcl;
5247 }
5248 
5249 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5250 ///   If T is the name of a class, then each of the following shall have a
5251 ///   name different from T:
5252 ///     - every static data member of class T;
5253 ///     - every member function of class T
5254 ///     - every member of class T that is itself a type;
5255 /// \returns true if the declaration name violates these rules.
5256 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5257                                    DeclarationNameInfo NameInfo) {
5258   DeclarationName Name = NameInfo.getName();
5259 
5260   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5261   while (Record && Record->isAnonymousStructOrUnion())
5262     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5263   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5264     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5265     return true;
5266   }
5267 
5268   return false;
5269 }
5270 
5271 /// Diagnose a declaration whose declarator-id has the given
5272 /// nested-name-specifier.
5273 ///
5274 /// \param SS The nested-name-specifier of the declarator-id.
5275 ///
5276 /// \param DC The declaration context to which the nested-name-specifier
5277 /// resolves.
5278 ///
5279 /// \param Name The name of the entity being declared.
5280 ///
5281 /// \param Loc The location of the name of the entity being declared.
5282 ///
5283 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5284 /// we're declaring an explicit / partial specialization / instantiation.
5285 ///
5286 /// \returns true if we cannot safely recover from this error, false otherwise.
5287 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5288                                         DeclarationName Name,
5289                                         SourceLocation Loc, bool IsTemplateId) {
5290   DeclContext *Cur = CurContext;
5291   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5292     Cur = Cur->getParent();
5293 
5294   // If the user provided a superfluous scope specifier that refers back to the
5295   // class in which the entity is already declared, diagnose and ignore it.
5296   //
5297   // class X {
5298   //   void X::f();
5299   // };
5300   //
5301   // Note, it was once ill-formed to give redundant qualification in all
5302   // contexts, but that rule was removed by DR482.
5303   if (Cur->Equals(DC)) {
5304     if (Cur->isRecord()) {
5305       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5306                                       : diag::err_member_extra_qualification)
5307         << Name << FixItHint::CreateRemoval(SS.getRange());
5308       SS.clear();
5309     } else {
5310       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5311     }
5312     return false;
5313   }
5314 
5315   // Check whether the qualifying scope encloses the scope of the original
5316   // declaration. For a template-id, we perform the checks in
5317   // CheckTemplateSpecializationScope.
5318   if (!Cur->Encloses(DC) && !IsTemplateId) {
5319     if (Cur->isRecord())
5320       Diag(Loc, diag::err_member_qualification)
5321         << Name << SS.getRange();
5322     else if (isa<TranslationUnitDecl>(DC))
5323       Diag(Loc, diag::err_invalid_declarator_global_scope)
5324         << Name << SS.getRange();
5325     else if (isa<FunctionDecl>(Cur))
5326       Diag(Loc, diag::err_invalid_declarator_in_function)
5327         << Name << SS.getRange();
5328     else if (isa<BlockDecl>(Cur))
5329       Diag(Loc, diag::err_invalid_declarator_in_block)
5330         << Name << SS.getRange();
5331     else
5332       Diag(Loc, diag::err_invalid_declarator_scope)
5333       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5334 
5335     return true;
5336   }
5337 
5338   if (Cur->isRecord()) {
5339     // Cannot qualify members within a class.
5340     Diag(Loc, diag::err_member_qualification)
5341       << Name << SS.getRange();
5342     SS.clear();
5343 
5344     // C++ constructors and destructors with incorrect scopes can break
5345     // our AST invariants by having the wrong underlying types. If
5346     // that's the case, then drop this declaration entirely.
5347     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5348          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5349         !Context.hasSameType(Name.getCXXNameType(),
5350                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5351       return true;
5352 
5353     return false;
5354   }
5355 
5356   // C++11 [dcl.meaning]p1:
5357   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5358   //   not begin with a decltype-specifer"
5359   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5360   while (SpecLoc.getPrefix())
5361     SpecLoc = SpecLoc.getPrefix();
5362   if (dyn_cast_or_null<DecltypeType>(
5363         SpecLoc.getNestedNameSpecifier()->getAsType()))
5364     Diag(Loc, diag::err_decltype_in_declarator)
5365       << SpecLoc.getTypeLoc().getSourceRange();
5366 
5367   return false;
5368 }
5369 
5370 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5371                                   MultiTemplateParamsArg TemplateParamLists) {
5372   // TODO: consider using NameInfo for diagnostic.
5373   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5374   DeclarationName Name = NameInfo.getName();
5375 
5376   // All of these full declarators require an identifier.  If it doesn't have
5377   // one, the ParsedFreeStandingDeclSpec action should be used.
5378   if (D.isDecompositionDeclarator()) {
5379     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5380   } else if (!Name) {
5381     if (!D.isInvalidType())  // Reject this if we think it is valid.
5382       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5383           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5384     return nullptr;
5385   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5386     return nullptr;
5387 
5388   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5389   // we find one that is.
5390   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5391          (S->getFlags() & Scope::TemplateParamScope) != 0)
5392     S = S->getParent();
5393 
5394   DeclContext *DC = CurContext;
5395   if (D.getCXXScopeSpec().isInvalid())
5396     D.setInvalidType();
5397   else if (D.getCXXScopeSpec().isSet()) {
5398     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5399                                         UPPC_DeclarationQualifier))
5400       return nullptr;
5401 
5402     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5403     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5404     if (!DC || isa<EnumDecl>(DC)) {
5405       // If we could not compute the declaration context, it's because the
5406       // declaration context is dependent but does not refer to a class,
5407       // class template, or class template partial specialization. Complain
5408       // and return early, to avoid the coming semantic disaster.
5409       Diag(D.getIdentifierLoc(),
5410            diag::err_template_qualified_declarator_no_match)
5411         << D.getCXXScopeSpec().getScopeRep()
5412         << D.getCXXScopeSpec().getRange();
5413       return nullptr;
5414     }
5415     bool IsDependentContext = DC->isDependentContext();
5416 
5417     if (!IsDependentContext &&
5418         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5419       return nullptr;
5420 
5421     // If a class is incomplete, do not parse entities inside it.
5422     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5423       Diag(D.getIdentifierLoc(),
5424            diag::err_member_def_undefined_record)
5425         << Name << DC << D.getCXXScopeSpec().getRange();
5426       return nullptr;
5427     }
5428     if (!D.getDeclSpec().isFriendSpecified()) {
5429       if (diagnoseQualifiedDeclaration(
5430               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5431               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5432         if (DC->isRecord())
5433           return nullptr;
5434 
5435         D.setInvalidType();
5436       }
5437     }
5438 
5439     // Check whether we need to rebuild the type of the given
5440     // declaration in the current instantiation.
5441     if (EnteringContext && IsDependentContext &&
5442         TemplateParamLists.size() != 0) {
5443       ContextRAII SavedContext(*this, DC);
5444       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5445         D.setInvalidType();
5446     }
5447   }
5448 
5449   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5450   QualType R = TInfo->getType();
5451 
5452   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5453                                       UPPC_DeclarationType))
5454     D.setInvalidType();
5455 
5456   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5457                         forRedeclarationInCurContext());
5458 
5459   // See if this is a redefinition of a variable in the same scope.
5460   if (!D.getCXXScopeSpec().isSet()) {
5461     bool IsLinkageLookup = false;
5462     bool CreateBuiltins = false;
5463 
5464     // If the declaration we're planning to build will be a function
5465     // or object with linkage, then look for another declaration with
5466     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5467     //
5468     // If the declaration we're planning to build will be declared with
5469     // external linkage in the translation unit, create any builtin with
5470     // the same name.
5471     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5472       /* Do nothing*/;
5473     else if (CurContext->isFunctionOrMethod() &&
5474              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5475               R->isFunctionType())) {
5476       IsLinkageLookup = true;
5477       CreateBuiltins =
5478           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5479     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5480                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5481       CreateBuiltins = true;
5482 
5483     if (IsLinkageLookup) {
5484       Previous.clear(LookupRedeclarationWithLinkage);
5485       Previous.setRedeclarationKind(ForExternalRedeclaration);
5486     }
5487 
5488     LookupName(Previous, S, CreateBuiltins);
5489   } else { // Something like "int foo::x;"
5490     LookupQualifiedName(Previous, DC);
5491 
5492     // C++ [dcl.meaning]p1:
5493     //   When the declarator-id is qualified, the declaration shall refer to a
5494     //  previously declared member of the class or namespace to which the
5495     //  qualifier refers (or, in the case of a namespace, of an element of the
5496     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5497     //  thereof; [...]
5498     //
5499     // Note that we already checked the context above, and that we do not have
5500     // enough information to make sure that Previous contains the declaration
5501     // we want to match. For example, given:
5502     //
5503     //   class X {
5504     //     void f();
5505     //     void f(float);
5506     //   };
5507     //
5508     //   void X::f(int) { } // ill-formed
5509     //
5510     // In this case, Previous will point to the overload set
5511     // containing the two f's declared in X, but neither of them
5512     // matches.
5513 
5514     // C++ [dcl.meaning]p1:
5515     //   [...] the member shall not merely have been introduced by a
5516     //   using-declaration in the scope of the class or namespace nominated by
5517     //   the nested-name-specifier of the declarator-id.
5518     RemoveUsingDecls(Previous);
5519   }
5520 
5521   if (Previous.isSingleResult() &&
5522       Previous.getFoundDecl()->isTemplateParameter()) {
5523     // Maybe we will complain about the shadowed template parameter.
5524     if (!D.isInvalidType())
5525       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5526                                       Previous.getFoundDecl());
5527 
5528     // Just pretend that we didn't see the previous declaration.
5529     Previous.clear();
5530   }
5531 
5532   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5533     // Forget that the previous declaration is the injected-class-name.
5534     Previous.clear();
5535 
5536   // In C++, the previous declaration we find might be a tag type
5537   // (class or enum). In this case, the new declaration will hide the
5538   // tag type. Note that this applies to functions, function templates, and
5539   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5540   if (Previous.isSingleTagDecl() &&
5541       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5542       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5543     Previous.clear();
5544 
5545   // Check that there are no default arguments other than in the parameters
5546   // of a function declaration (C++ only).
5547   if (getLangOpts().CPlusPlus)
5548     CheckExtraCXXDefaultArguments(D);
5549 
5550   NamedDecl *New;
5551 
5552   bool AddToScope = true;
5553   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5554     if (TemplateParamLists.size()) {
5555       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5556       return nullptr;
5557     }
5558 
5559     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5560   } else if (R->isFunctionType()) {
5561     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5562                                   TemplateParamLists,
5563                                   AddToScope);
5564   } else {
5565     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5566                                   AddToScope);
5567   }
5568 
5569   if (!New)
5570     return nullptr;
5571 
5572   // If this has an identifier and is not a function template specialization,
5573   // add it to the scope stack.
5574   if (New->getDeclName() && AddToScope)
5575     PushOnScopeChains(New, S);
5576 
5577   if (isInOpenMPDeclareTargetContext())
5578     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5579 
5580   return New;
5581 }
5582 
5583 /// Helper method to turn variable array types into constant array
5584 /// types in certain situations which would otherwise be errors (for
5585 /// GCC compatibility).
5586 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5587                                                     ASTContext &Context,
5588                                                     bool &SizeIsNegative,
5589                                                     llvm::APSInt &Oversized) {
5590   // This method tries to turn a variable array into a constant
5591   // array even when the size isn't an ICE.  This is necessary
5592   // for compatibility with code that depends on gcc's buggy
5593   // constant expression folding, like struct {char x[(int)(char*)2];}
5594   SizeIsNegative = false;
5595   Oversized = 0;
5596 
5597   if (T->isDependentType())
5598     return QualType();
5599 
5600   QualifierCollector Qs;
5601   const Type *Ty = Qs.strip(T);
5602 
5603   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5604     QualType Pointee = PTy->getPointeeType();
5605     QualType FixedType =
5606         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5607                                             Oversized);
5608     if (FixedType.isNull()) return FixedType;
5609     FixedType = Context.getPointerType(FixedType);
5610     return Qs.apply(Context, FixedType);
5611   }
5612   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5613     QualType Inner = PTy->getInnerType();
5614     QualType FixedType =
5615         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5616                                             Oversized);
5617     if (FixedType.isNull()) return FixedType;
5618     FixedType = Context.getParenType(FixedType);
5619     return Qs.apply(Context, FixedType);
5620   }
5621 
5622   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5623   if (!VLATy)
5624     return QualType();
5625   // FIXME: We should probably handle this case
5626   if (VLATy->getElementType()->isVariablyModifiedType())
5627     return QualType();
5628 
5629   Expr::EvalResult Result;
5630   if (!VLATy->getSizeExpr() ||
5631       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5632     return QualType();
5633 
5634   llvm::APSInt Res = Result.Val.getInt();
5635 
5636   // Check whether the array size is negative.
5637   if (Res.isSigned() && Res.isNegative()) {
5638     SizeIsNegative = true;
5639     return QualType();
5640   }
5641 
5642   // Check whether the array is too large to be addressed.
5643   unsigned ActiveSizeBits
5644     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5645                                               Res);
5646   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5647     Oversized = Res;
5648     return QualType();
5649   }
5650 
5651   return Context.getConstantArrayType(VLATy->getElementType(),
5652                                       Res, ArrayType::Normal, 0);
5653 }
5654 
5655 static void
5656 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5657   SrcTL = SrcTL.getUnqualifiedLoc();
5658   DstTL = DstTL.getUnqualifiedLoc();
5659   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5660     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5661     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5662                                       DstPTL.getPointeeLoc());
5663     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5664     return;
5665   }
5666   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5667     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5668     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5669                                       DstPTL.getInnerLoc());
5670     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5671     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5672     return;
5673   }
5674   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5675   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5676   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5677   TypeLoc DstElemTL = DstATL.getElementLoc();
5678   DstElemTL.initializeFullCopy(SrcElemTL);
5679   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5680   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5681   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5682 }
5683 
5684 /// Helper method to turn variable array types into constant array
5685 /// types in certain situations which would otherwise be errors (for
5686 /// GCC compatibility).
5687 static TypeSourceInfo*
5688 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5689                                               ASTContext &Context,
5690                                               bool &SizeIsNegative,
5691                                               llvm::APSInt &Oversized) {
5692   QualType FixedTy
5693     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5694                                           SizeIsNegative, Oversized);
5695   if (FixedTy.isNull())
5696     return nullptr;
5697   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5698   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5699                                     FixedTInfo->getTypeLoc());
5700   return FixedTInfo;
5701 }
5702 
5703 /// Register the given locally-scoped extern "C" declaration so
5704 /// that it can be found later for redeclarations. We include any extern "C"
5705 /// declaration that is not visible in the translation unit here, not just
5706 /// function-scope declarations.
5707 void
5708 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5709   if (!getLangOpts().CPlusPlus &&
5710       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5711     // Don't need to track declarations in the TU in C.
5712     return;
5713 
5714   // Note that we have a locally-scoped external with this name.
5715   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5716 }
5717 
5718 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5719   // FIXME: We can have multiple results via __attribute__((overloadable)).
5720   auto Result = Context.getExternCContextDecl()->lookup(Name);
5721   return Result.empty() ? nullptr : *Result.begin();
5722 }
5723 
5724 /// Diagnose function specifiers on a declaration of an identifier that
5725 /// does not identify a function.
5726 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5727   // FIXME: We should probably indicate the identifier in question to avoid
5728   // confusion for constructs like "virtual int a(), b;"
5729   if (DS.isVirtualSpecified())
5730     Diag(DS.getVirtualSpecLoc(),
5731          diag::err_virtual_non_function);
5732 
5733   if (DS.hasExplicitSpecifier())
5734     Diag(DS.getExplicitSpecLoc(),
5735          diag::err_explicit_non_function);
5736 
5737   if (DS.isNoreturnSpecified())
5738     Diag(DS.getNoreturnSpecLoc(),
5739          diag::err_noreturn_non_function);
5740 }
5741 
5742 NamedDecl*
5743 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5744                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5745   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5746   if (D.getCXXScopeSpec().isSet()) {
5747     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5748       << D.getCXXScopeSpec().getRange();
5749     D.setInvalidType();
5750     // Pretend we didn't see the scope specifier.
5751     DC = CurContext;
5752     Previous.clear();
5753   }
5754 
5755   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5756 
5757   if (D.getDeclSpec().isInlineSpecified())
5758     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5759         << getLangOpts().CPlusPlus17;
5760   if (D.getDeclSpec().hasConstexprSpecifier())
5761     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5762         << 1 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
5763 
5764   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5765     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5766       Diag(D.getName().StartLocation,
5767            diag::err_deduction_guide_invalid_specifier)
5768           << "typedef";
5769     else
5770       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5771           << D.getName().getSourceRange();
5772     return nullptr;
5773   }
5774 
5775   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5776   if (!NewTD) return nullptr;
5777 
5778   // Handle attributes prior to checking for duplicates in MergeVarDecl
5779   ProcessDeclAttributes(S, NewTD, D);
5780 
5781   CheckTypedefForVariablyModifiedType(S, NewTD);
5782 
5783   bool Redeclaration = D.isRedeclaration();
5784   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5785   D.setRedeclaration(Redeclaration);
5786   return ND;
5787 }
5788 
5789 void
5790 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5791   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5792   // then it shall have block scope.
5793   // Note that variably modified types must be fixed before merging the decl so
5794   // that redeclarations will match.
5795   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5796   QualType T = TInfo->getType();
5797   if (T->isVariablyModifiedType()) {
5798     setFunctionHasBranchProtectedScope();
5799 
5800     if (S->getFnParent() == nullptr) {
5801       bool SizeIsNegative;
5802       llvm::APSInt Oversized;
5803       TypeSourceInfo *FixedTInfo =
5804         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5805                                                       SizeIsNegative,
5806                                                       Oversized);
5807       if (FixedTInfo) {
5808         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5809         NewTD->setTypeSourceInfo(FixedTInfo);
5810       } else {
5811         if (SizeIsNegative)
5812           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5813         else if (T->isVariableArrayType())
5814           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5815         else if (Oversized.getBoolValue())
5816           Diag(NewTD->getLocation(), diag::err_array_too_large)
5817             << Oversized.toString(10);
5818         else
5819           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5820         NewTD->setInvalidDecl();
5821       }
5822     }
5823   }
5824 }
5825 
5826 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5827 /// declares a typedef-name, either using the 'typedef' type specifier or via
5828 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5829 NamedDecl*
5830 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5831                            LookupResult &Previous, bool &Redeclaration) {
5832 
5833   // Find the shadowed declaration before filtering for scope.
5834   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5835 
5836   // Merge the decl with the existing one if appropriate. If the decl is
5837   // in an outer scope, it isn't the same thing.
5838   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5839                        /*AllowInlineNamespace*/false);
5840   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5841   if (!Previous.empty()) {
5842     Redeclaration = true;
5843     MergeTypedefNameDecl(S, NewTD, Previous);
5844   }
5845 
5846   if (ShadowedDecl && !Redeclaration)
5847     CheckShadow(NewTD, ShadowedDecl, Previous);
5848 
5849   // If this is the C FILE type, notify the AST context.
5850   if (IdentifierInfo *II = NewTD->getIdentifier())
5851     if (!NewTD->isInvalidDecl() &&
5852         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5853       if (II->isStr("FILE"))
5854         Context.setFILEDecl(NewTD);
5855       else if (II->isStr("jmp_buf"))
5856         Context.setjmp_bufDecl(NewTD);
5857       else if (II->isStr("sigjmp_buf"))
5858         Context.setsigjmp_bufDecl(NewTD);
5859       else if (II->isStr("ucontext_t"))
5860         Context.setucontext_tDecl(NewTD);
5861     }
5862 
5863   return NewTD;
5864 }
5865 
5866 /// Determines whether the given declaration is an out-of-scope
5867 /// previous declaration.
5868 ///
5869 /// This routine should be invoked when name lookup has found a
5870 /// previous declaration (PrevDecl) that is not in the scope where a
5871 /// new declaration by the same name is being introduced. If the new
5872 /// declaration occurs in a local scope, previous declarations with
5873 /// linkage may still be considered previous declarations (C99
5874 /// 6.2.2p4-5, C++ [basic.link]p6).
5875 ///
5876 /// \param PrevDecl the previous declaration found by name
5877 /// lookup
5878 ///
5879 /// \param DC the context in which the new declaration is being
5880 /// declared.
5881 ///
5882 /// \returns true if PrevDecl is an out-of-scope previous declaration
5883 /// for a new delcaration with the same name.
5884 static bool
5885 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5886                                 ASTContext &Context) {
5887   if (!PrevDecl)
5888     return false;
5889 
5890   if (!PrevDecl->hasLinkage())
5891     return false;
5892 
5893   if (Context.getLangOpts().CPlusPlus) {
5894     // C++ [basic.link]p6:
5895     //   If there is a visible declaration of an entity with linkage
5896     //   having the same name and type, ignoring entities declared
5897     //   outside the innermost enclosing namespace scope, the block
5898     //   scope declaration declares that same entity and receives the
5899     //   linkage of the previous declaration.
5900     DeclContext *OuterContext = DC->getRedeclContext();
5901     if (!OuterContext->isFunctionOrMethod())
5902       // This rule only applies to block-scope declarations.
5903       return false;
5904 
5905     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5906     if (PrevOuterContext->isRecord())
5907       // We found a member function: ignore it.
5908       return false;
5909 
5910     // Find the innermost enclosing namespace for the new and
5911     // previous declarations.
5912     OuterContext = OuterContext->getEnclosingNamespaceContext();
5913     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5914 
5915     // The previous declaration is in a different namespace, so it
5916     // isn't the same function.
5917     if (!OuterContext->Equals(PrevOuterContext))
5918       return false;
5919   }
5920 
5921   return true;
5922 }
5923 
5924 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5925   CXXScopeSpec &SS = D.getCXXScopeSpec();
5926   if (!SS.isSet()) return;
5927   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5928 }
5929 
5930 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5931   QualType type = decl->getType();
5932   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5933   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5934     // Various kinds of declaration aren't allowed to be __autoreleasing.
5935     unsigned kind = -1U;
5936     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5937       if (var->hasAttr<BlocksAttr>())
5938         kind = 0; // __block
5939       else if (!var->hasLocalStorage())
5940         kind = 1; // global
5941     } else if (isa<ObjCIvarDecl>(decl)) {
5942       kind = 3; // ivar
5943     } else if (isa<FieldDecl>(decl)) {
5944       kind = 2; // field
5945     }
5946 
5947     if (kind != -1U) {
5948       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5949         << kind;
5950     }
5951   } else if (lifetime == Qualifiers::OCL_None) {
5952     // Try to infer lifetime.
5953     if (!type->isObjCLifetimeType())
5954       return false;
5955 
5956     lifetime = type->getObjCARCImplicitLifetime();
5957     type = Context.getLifetimeQualifiedType(type, lifetime);
5958     decl->setType(type);
5959   }
5960 
5961   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5962     // Thread-local variables cannot have lifetime.
5963     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5964         var->getTLSKind()) {
5965       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5966         << var->getType();
5967       return true;
5968     }
5969   }
5970 
5971   return false;
5972 }
5973 
5974 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5975   // Ensure that an auto decl is deduced otherwise the checks below might cache
5976   // the wrong linkage.
5977   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5978 
5979   // 'weak' only applies to declarations with external linkage.
5980   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5981     if (!ND.isExternallyVisible()) {
5982       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5983       ND.dropAttr<WeakAttr>();
5984     }
5985   }
5986   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5987     if (ND.isExternallyVisible()) {
5988       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5989       ND.dropAttr<WeakRefAttr>();
5990       ND.dropAttr<AliasAttr>();
5991     }
5992   }
5993 
5994   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5995     if (VD->hasInit()) {
5996       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5997         assert(VD->isThisDeclarationADefinition() &&
5998                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5999         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6000         VD->dropAttr<AliasAttr>();
6001       }
6002     }
6003   }
6004 
6005   // 'selectany' only applies to externally visible variable declarations.
6006   // It does not apply to functions.
6007   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6008     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6009       S.Diag(Attr->getLocation(),
6010              diag::err_attribute_selectany_non_extern_data);
6011       ND.dropAttr<SelectAnyAttr>();
6012     }
6013   }
6014 
6015   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6016     auto *VD = dyn_cast<VarDecl>(&ND);
6017     bool IsAnonymousNS = false;
6018     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6019     if (VD) {
6020       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6021       while (NS && !IsAnonymousNS) {
6022         IsAnonymousNS = NS->isAnonymousNamespace();
6023         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6024       }
6025     }
6026     // dll attributes require external linkage. Static locals may have external
6027     // linkage but still cannot be explicitly imported or exported.
6028     // In Microsoft mode, a variable defined in anonymous namespace must have
6029     // external linkage in order to be exported.
6030     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6031     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6032         (!AnonNSInMicrosoftMode &&
6033          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6034       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6035         << &ND << Attr;
6036       ND.setInvalidDecl();
6037     }
6038   }
6039 
6040   // Virtual functions cannot be marked as 'notail'.
6041   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6042     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6043       if (MD->isVirtual()) {
6044         S.Diag(ND.getLocation(),
6045                diag::err_invalid_attribute_on_virtual_function)
6046             << Attr;
6047         ND.dropAttr<NotTailCalledAttr>();
6048       }
6049 
6050   // Check the attributes on the function type, if any.
6051   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6052     // Don't declare this variable in the second operand of the for-statement;
6053     // GCC miscompiles that by ending its lifetime before evaluating the
6054     // third operand. See gcc.gnu.org/PR86769.
6055     AttributedTypeLoc ATL;
6056     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6057          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6058          TL = ATL.getModifiedLoc()) {
6059       // The [[lifetimebound]] attribute can be applied to the implicit object
6060       // parameter of a non-static member function (other than a ctor or dtor)
6061       // by applying it to the function type.
6062       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6063         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6064         if (!MD || MD->isStatic()) {
6065           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6066               << !MD << A->getRange();
6067         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6068           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6069               << isa<CXXDestructorDecl>(MD) << A->getRange();
6070         }
6071       }
6072     }
6073   }
6074 }
6075 
6076 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6077                                            NamedDecl *NewDecl,
6078                                            bool IsSpecialization,
6079                                            bool IsDefinition) {
6080   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6081     return;
6082 
6083   bool IsTemplate = false;
6084   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6085     OldDecl = OldTD->getTemplatedDecl();
6086     IsTemplate = true;
6087     if (!IsSpecialization)
6088       IsDefinition = false;
6089   }
6090   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6091     NewDecl = NewTD->getTemplatedDecl();
6092     IsTemplate = true;
6093   }
6094 
6095   if (!OldDecl || !NewDecl)
6096     return;
6097 
6098   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6099   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6100   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6101   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6102 
6103   // dllimport and dllexport are inheritable attributes so we have to exclude
6104   // inherited attribute instances.
6105   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6106                     (NewExportAttr && !NewExportAttr->isInherited());
6107 
6108   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6109   // the only exception being explicit specializations.
6110   // Implicitly generated declarations are also excluded for now because there
6111   // is no other way to switch these to use dllimport or dllexport.
6112   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6113 
6114   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6115     // Allow with a warning for free functions and global variables.
6116     bool JustWarn = false;
6117     if (!OldDecl->isCXXClassMember()) {
6118       auto *VD = dyn_cast<VarDecl>(OldDecl);
6119       if (VD && !VD->getDescribedVarTemplate())
6120         JustWarn = true;
6121       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6122       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6123         JustWarn = true;
6124     }
6125 
6126     // We cannot change a declaration that's been used because IR has already
6127     // been emitted. Dllimported functions will still work though (modulo
6128     // address equality) as they can use the thunk.
6129     if (OldDecl->isUsed())
6130       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6131         JustWarn = false;
6132 
6133     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6134                                : diag::err_attribute_dll_redeclaration;
6135     S.Diag(NewDecl->getLocation(), DiagID)
6136         << NewDecl
6137         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6138     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6139     if (!JustWarn) {
6140       NewDecl->setInvalidDecl();
6141       return;
6142     }
6143   }
6144 
6145   // A redeclaration is not allowed to drop a dllimport attribute, the only
6146   // exceptions being inline function definitions (except for function
6147   // templates), local extern declarations, qualified friend declarations or
6148   // special MSVC extension: in the last case, the declaration is treated as if
6149   // it were marked dllexport.
6150   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6151   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6152   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6153     // Ignore static data because out-of-line definitions are diagnosed
6154     // separately.
6155     IsStaticDataMember = VD->isStaticDataMember();
6156     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6157                    VarDecl::DeclarationOnly;
6158   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6159     IsInline = FD->isInlined();
6160     IsQualifiedFriend = FD->getQualifier() &&
6161                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6162   }
6163 
6164   if (OldImportAttr && !HasNewAttr &&
6165       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6166       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6167     if (IsMicrosoft && IsDefinition) {
6168       S.Diag(NewDecl->getLocation(),
6169              diag::warn_redeclaration_without_import_attribute)
6170           << NewDecl;
6171       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6172       NewDecl->dropAttr<DLLImportAttr>();
6173       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6174           NewImportAttr->getRange(), S.Context,
6175           NewImportAttr->getSpellingListIndex()));
6176     } else {
6177       S.Diag(NewDecl->getLocation(),
6178              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6179           << NewDecl << OldImportAttr;
6180       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6181       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6182       OldDecl->dropAttr<DLLImportAttr>();
6183       NewDecl->dropAttr<DLLImportAttr>();
6184     }
6185   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6186     // In MinGW, seeing a function declared inline drops the dllimport
6187     // attribute.
6188     OldDecl->dropAttr<DLLImportAttr>();
6189     NewDecl->dropAttr<DLLImportAttr>();
6190     S.Diag(NewDecl->getLocation(),
6191            diag::warn_dllimport_dropped_from_inline_function)
6192         << NewDecl << OldImportAttr;
6193   }
6194 
6195   // A specialization of a class template member function is processed here
6196   // since it's a redeclaration. If the parent class is dllexport, the
6197   // specialization inherits that attribute. This doesn't happen automatically
6198   // since the parent class isn't instantiated until later.
6199   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6200     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6201         !NewImportAttr && !NewExportAttr) {
6202       if (const DLLExportAttr *ParentExportAttr =
6203               MD->getParent()->getAttr<DLLExportAttr>()) {
6204         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6205         NewAttr->setInherited(true);
6206         NewDecl->addAttr(NewAttr);
6207       }
6208     }
6209   }
6210 }
6211 
6212 /// Given that we are within the definition of the given function,
6213 /// will that definition behave like C99's 'inline', where the
6214 /// definition is discarded except for optimization purposes?
6215 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6216   // Try to avoid calling GetGVALinkageForFunction.
6217 
6218   // All cases of this require the 'inline' keyword.
6219   if (!FD->isInlined()) return false;
6220 
6221   // This is only possible in C++ with the gnu_inline attribute.
6222   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6223     return false;
6224 
6225   // Okay, go ahead and call the relatively-more-expensive function.
6226   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6227 }
6228 
6229 /// Determine whether a variable is extern "C" prior to attaching
6230 /// an initializer. We can't just call isExternC() here, because that
6231 /// will also compute and cache whether the declaration is externally
6232 /// visible, which might change when we attach the initializer.
6233 ///
6234 /// This can only be used if the declaration is known to not be a
6235 /// redeclaration of an internal linkage declaration.
6236 ///
6237 /// For instance:
6238 ///
6239 ///   auto x = []{};
6240 ///
6241 /// Attaching the initializer here makes this declaration not externally
6242 /// visible, because its type has internal linkage.
6243 ///
6244 /// FIXME: This is a hack.
6245 template<typename T>
6246 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6247   if (S.getLangOpts().CPlusPlus) {
6248     // In C++, the overloadable attribute negates the effects of extern "C".
6249     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6250       return false;
6251 
6252     // So do CUDA's host/device attributes.
6253     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6254                                  D->template hasAttr<CUDAHostAttr>()))
6255       return false;
6256   }
6257   return D->isExternC();
6258 }
6259 
6260 static bool shouldConsiderLinkage(const VarDecl *VD) {
6261   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6262   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6263       isa<OMPDeclareMapperDecl>(DC))
6264     return VD->hasExternalStorage();
6265   if (DC->isFileContext())
6266     return true;
6267   if (DC->isRecord())
6268     return false;
6269   llvm_unreachable("Unexpected context");
6270 }
6271 
6272 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6273   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6274   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6275       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6276     return true;
6277   if (DC->isRecord())
6278     return false;
6279   llvm_unreachable("Unexpected context");
6280 }
6281 
6282 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6283                           ParsedAttr::Kind Kind) {
6284   // Check decl attributes on the DeclSpec.
6285   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6286     return true;
6287 
6288   // Walk the declarator structure, checking decl attributes that were in a type
6289   // position to the decl itself.
6290   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6291     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6292       return true;
6293   }
6294 
6295   // Finally, check attributes on the decl itself.
6296   return PD.getAttributes().hasAttribute(Kind);
6297 }
6298 
6299 /// Adjust the \c DeclContext for a function or variable that might be a
6300 /// function-local external declaration.
6301 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6302   if (!DC->isFunctionOrMethod())
6303     return false;
6304 
6305   // If this is a local extern function or variable declared within a function
6306   // template, don't add it into the enclosing namespace scope until it is
6307   // instantiated; it might have a dependent type right now.
6308   if (DC->isDependentContext())
6309     return true;
6310 
6311   // C++11 [basic.link]p7:
6312   //   When a block scope declaration of an entity with linkage is not found to
6313   //   refer to some other declaration, then that entity is a member of the
6314   //   innermost enclosing namespace.
6315   //
6316   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6317   // semantically-enclosing namespace, not a lexically-enclosing one.
6318   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6319     DC = DC->getParent();
6320   return true;
6321 }
6322 
6323 /// Returns true if given declaration has external C language linkage.
6324 static bool isDeclExternC(const Decl *D) {
6325   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6326     return FD->isExternC();
6327   if (const auto *VD = dyn_cast<VarDecl>(D))
6328     return VD->isExternC();
6329 
6330   llvm_unreachable("Unknown type of decl!");
6331 }
6332 
6333 NamedDecl *Sema::ActOnVariableDeclarator(
6334     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6335     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6336     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6337   QualType R = TInfo->getType();
6338   DeclarationName Name = GetNameForDeclarator(D).getName();
6339 
6340   IdentifierInfo *II = Name.getAsIdentifierInfo();
6341 
6342   if (D.isDecompositionDeclarator()) {
6343     // Take the name of the first declarator as our name for diagnostic
6344     // purposes.
6345     auto &Decomp = D.getDecompositionDeclarator();
6346     if (!Decomp.bindings().empty()) {
6347       II = Decomp.bindings()[0].Name;
6348       Name = II;
6349     }
6350   } else if (!II) {
6351     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6352     return nullptr;
6353   }
6354 
6355   if (getLangOpts().OpenCL) {
6356     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6357     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6358     // argument.
6359     if (R->isImageType() || R->isPipeType()) {
6360       Diag(D.getIdentifierLoc(),
6361            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6362           << R;
6363       D.setInvalidType();
6364       return nullptr;
6365     }
6366 
6367     // OpenCL v1.2 s6.9.r:
6368     // The event type cannot be used to declare a program scope variable.
6369     // OpenCL v2.0 s6.9.q:
6370     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6371     if (NULL == S->getParent()) {
6372       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6373         Diag(D.getIdentifierLoc(),
6374              diag::err_invalid_type_for_program_scope_var) << R;
6375         D.setInvalidType();
6376         return nullptr;
6377       }
6378     }
6379 
6380     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6381     QualType NR = R;
6382     while (NR->isPointerType()) {
6383       if (NR->isFunctionPointerType()) {
6384         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6385         D.setInvalidType();
6386         break;
6387       }
6388       NR = NR->getPointeeType();
6389     }
6390 
6391     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6392       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6393       // half array type (unless the cl_khr_fp16 extension is enabled).
6394       if (Context.getBaseElementType(R)->isHalfType()) {
6395         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6396         D.setInvalidType();
6397       }
6398     }
6399 
6400     if (R->isSamplerT()) {
6401       // OpenCL v1.2 s6.9.b p4:
6402       // The sampler type cannot be used with the __local and __global address
6403       // space qualifiers.
6404       if (R.getAddressSpace() == LangAS::opencl_local ||
6405           R.getAddressSpace() == LangAS::opencl_global) {
6406         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6407       }
6408 
6409       // OpenCL v1.2 s6.12.14.1:
6410       // A global sampler must be declared with either the constant address
6411       // space qualifier or with the const qualifier.
6412       if (DC->isTranslationUnit() &&
6413           !(R.getAddressSpace() == LangAS::opencl_constant ||
6414           R.isConstQualified())) {
6415         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6416         D.setInvalidType();
6417       }
6418     }
6419 
6420     // OpenCL v1.2 s6.9.r:
6421     // The event type cannot be used with the __local, __constant and __global
6422     // address space qualifiers.
6423     if (R->isEventT()) {
6424       if (R.getAddressSpace() != LangAS::opencl_private) {
6425         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6426         D.setInvalidType();
6427       }
6428     }
6429 
6430     // C++ for OpenCL does not allow the thread_local storage qualifier.
6431     // OpenCL C does not support thread_local either, and
6432     // also reject all other thread storage class specifiers.
6433     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6434     if (TSC != TSCS_unspecified) {
6435       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6436       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6437            diag::err_opencl_unknown_type_specifier)
6438           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6439           << DeclSpec::getSpecifierName(TSC) << 1;
6440       D.setInvalidType();
6441       return nullptr;
6442     }
6443   }
6444 
6445   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6446   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6447 
6448   // dllimport globals without explicit storage class are treated as extern. We
6449   // have to change the storage class this early to get the right DeclContext.
6450   if (SC == SC_None && !DC->isRecord() &&
6451       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6452       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6453     SC = SC_Extern;
6454 
6455   DeclContext *OriginalDC = DC;
6456   bool IsLocalExternDecl = SC == SC_Extern &&
6457                            adjustContextForLocalExternDecl(DC);
6458 
6459   if (SCSpec == DeclSpec::SCS_mutable) {
6460     // mutable can only appear on non-static class members, so it's always
6461     // an error here
6462     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6463     D.setInvalidType();
6464     SC = SC_None;
6465   }
6466 
6467   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6468       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6469                               D.getDeclSpec().getStorageClassSpecLoc())) {
6470     // In C++11, the 'register' storage class specifier is deprecated.
6471     // Suppress the warning in system macros, it's used in macros in some
6472     // popular C system headers, such as in glibc's htonl() macro.
6473     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6474          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6475                                    : diag::warn_deprecated_register)
6476       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6477   }
6478 
6479   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6480 
6481   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6482     // C99 6.9p2: The storage-class specifiers auto and register shall not
6483     // appear in the declaration specifiers in an external declaration.
6484     // Global Register+Asm is a GNU extension we support.
6485     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6486       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6487       D.setInvalidType();
6488     }
6489   }
6490 
6491   bool IsMemberSpecialization = false;
6492   bool IsVariableTemplateSpecialization = false;
6493   bool IsPartialSpecialization = false;
6494   bool IsVariableTemplate = false;
6495   VarDecl *NewVD = nullptr;
6496   VarTemplateDecl *NewTemplate = nullptr;
6497   TemplateParameterList *TemplateParams = nullptr;
6498   if (!getLangOpts().CPlusPlus) {
6499     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6500                             II, R, TInfo, SC);
6501 
6502     if (R->getContainedDeducedType())
6503       ParsingInitForAutoVars.insert(NewVD);
6504 
6505     if (D.isInvalidType())
6506       NewVD->setInvalidDecl();
6507   } else {
6508     bool Invalid = false;
6509 
6510     if (DC->isRecord() && !CurContext->isRecord()) {
6511       // This is an out-of-line definition of a static data member.
6512       switch (SC) {
6513       case SC_None:
6514         break;
6515       case SC_Static:
6516         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6517              diag::err_static_out_of_line)
6518           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6519         break;
6520       case SC_Auto:
6521       case SC_Register:
6522       case SC_Extern:
6523         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6524         // to names of variables declared in a block or to function parameters.
6525         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6526         // of class members
6527 
6528         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6529              diag::err_storage_class_for_static_member)
6530           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6531         break;
6532       case SC_PrivateExtern:
6533         llvm_unreachable("C storage class in c++!");
6534       }
6535     }
6536 
6537     if (SC == SC_Static && CurContext->isRecord()) {
6538       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6539         if (RD->isLocalClass())
6540           Diag(D.getIdentifierLoc(),
6541                diag::err_static_data_member_not_allowed_in_local_class)
6542             << Name << RD->getDeclName();
6543 
6544         // C++98 [class.union]p1: If a union contains a static data member,
6545         // the program is ill-formed. C++11 drops this restriction.
6546         if (RD->isUnion())
6547           Diag(D.getIdentifierLoc(),
6548                getLangOpts().CPlusPlus11
6549                  ? diag::warn_cxx98_compat_static_data_member_in_union
6550                  : diag::ext_static_data_member_in_union) << Name;
6551         // We conservatively disallow static data members in anonymous structs.
6552         else if (!RD->getDeclName())
6553           Diag(D.getIdentifierLoc(),
6554                diag::err_static_data_member_not_allowed_in_anon_struct)
6555             << Name << RD->isUnion();
6556       }
6557     }
6558 
6559     // Match up the template parameter lists with the scope specifier, then
6560     // determine whether we have a template or a template specialization.
6561     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6562         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6563         D.getCXXScopeSpec(),
6564         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6565             ? D.getName().TemplateId
6566             : nullptr,
6567         TemplateParamLists,
6568         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6569 
6570     if (TemplateParams) {
6571       if (!TemplateParams->size() &&
6572           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6573         // There is an extraneous 'template<>' for this variable. Complain
6574         // about it, but allow the declaration of the variable.
6575         Diag(TemplateParams->getTemplateLoc(),
6576              diag::err_template_variable_noparams)
6577           << II
6578           << SourceRange(TemplateParams->getTemplateLoc(),
6579                          TemplateParams->getRAngleLoc());
6580         TemplateParams = nullptr;
6581       } else {
6582         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6583           // This is an explicit specialization or a partial specialization.
6584           // FIXME: Check that we can declare a specialization here.
6585           IsVariableTemplateSpecialization = true;
6586           IsPartialSpecialization = TemplateParams->size() > 0;
6587         } else { // if (TemplateParams->size() > 0)
6588           // This is a template declaration.
6589           IsVariableTemplate = true;
6590 
6591           // Check that we can declare a template here.
6592           if (CheckTemplateDeclScope(S, TemplateParams))
6593             return nullptr;
6594 
6595           // Only C++1y supports variable templates (N3651).
6596           Diag(D.getIdentifierLoc(),
6597                getLangOpts().CPlusPlus14
6598                    ? diag::warn_cxx11_compat_variable_template
6599                    : diag::ext_variable_template);
6600         }
6601       }
6602     } else {
6603       assert((Invalid ||
6604               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6605              "should have a 'template<>' for this decl");
6606     }
6607 
6608     if (IsVariableTemplateSpecialization) {
6609       SourceLocation TemplateKWLoc =
6610           TemplateParamLists.size() > 0
6611               ? TemplateParamLists[0]->getTemplateLoc()
6612               : SourceLocation();
6613       DeclResult Res = ActOnVarTemplateSpecialization(
6614           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6615           IsPartialSpecialization);
6616       if (Res.isInvalid())
6617         return nullptr;
6618       NewVD = cast<VarDecl>(Res.get());
6619       AddToScope = false;
6620     } else if (D.isDecompositionDeclarator()) {
6621       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6622                                         D.getIdentifierLoc(), R, TInfo, SC,
6623                                         Bindings);
6624     } else
6625       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6626                               D.getIdentifierLoc(), II, R, TInfo, SC);
6627 
6628     // If this is supposed to be a variable template, create it as such.
6629     if (IsVariableTemplate) {
6630       NewTemplate =
6631           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6632                                   TemplateParams, NewVD);
6633       NewVD->setDescribedVarTemplate(NewTemplate);
6634     }
6635 
6636     // If this decl has an auto type in need of deduction, make a note of the
6637     // Decl so we can diagnose uses of it in its own initializer.
6638     if (R->getContainedDeducedType())
6639       ParsingInitForAutoVars.insert(NewVD);
6640 
6641     if (D.isInvalidType() || Invalid) {
6642       NewVD->setInvalidDecl();
6643       if (NewTemplate)
6644         NewTemplate->setInvalidDecl();
6645     }
6646 
6647     SetNestedNameSpecifier(*this, NewVD, D);
6648 
6649     // If we have any template parameter lists that don't directly belong to
6650     // the variable (matching the scope specifier), store them.
6651     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6652     if (TemplateParamLists.size() > VDTemplateParamLists)
6653       NewVD->setTemplateParameterListsInfo(
6654           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6655 
6656     if (D.getDeclSpec().hasConstexprSpecifier()) {
6657       NewVD->setConstexpr(true);
6658       // C++1z [dcl.spec.constexpr]p1:
6659       //   A static data member declared with the constexpr specifier is
6660       //   implicitly an inline variable.
6661       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6662         NewVD->setImplicitlyInline();
6663       if (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval)
6664         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6665              diag::err_constexpr_wrong_decl_kind)
6666             << /*consteval*/ 1;
6667     }
6668   }
6669 
6670   if (D.getDeclSpec().isInlineSpecified()) {
6671     if (!getLangOpts().CPlusPlus) {
6672       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6673           << 0;
6674     } else if (CurContext->isFunctionOrMethod()) {
6675       // 'inline' is not allowed on block scope variable declaration.
6676       Diag(D.getDeclSpec().getInlineSpecLoc(),
6677            diag::err_inline_declaration_block_scope) << Name
6678         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6679     } else {
6680       Diag(D.getDeclSpec().getInlineSpecLoc(),
6681            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6682                                      : diag::ext_inline_variable);
6683       NewVD->setInlineSpecified();
6684     }
6685   }
6686 
6687   // Set the lexical context. If the declarator has a C++ scope specifier, the
6688   // lexical context will be different from the semantic context.
6689   NewVD->setLexicalDeclContext(CurContext);
6690   if (NewTemplate)
6691     NewTemplate->setLexicalDeclContext(CurContext);
6692 
6693   if (IsLocalExternDecl) {
6694     if (D.isDecompositionDeclarator())
6695       for (auto *B : Bindings)
6696         B->setLocalExternDecl();
6697     else
6698       NewVD->setLocalExternDecl();
6699   }
6700 
6701   bool EmitTLSUnsupportedError = false;
6702   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6703     // C++11 [dcl.stc]p4:
6704     //   When thread_local is applied to a variable of block scope the
6705     //   storage-class-specifier static is implied if it does not appear
6706     //   explicitly.
6707     // Core issue: 'static' is not implied if the variable is declared
6708     //   'extern'.
6709     if (NewVD->hasLocalStorage() &&
6710         (SCSpec != DeclSpec::SCS_unspecified ||
6711          TSCS != DeclSpec::TSCS_thread_local ||
6712          !DC->isFunctionOrMethod()))
6713       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6714            diag::err_thread_non_global)
6715         << DeclSpec::getSpecifierName(TSCS);
6716     else if (!Context.getTargetInfo().isTLSSupported()) {
6717       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6718         // Postpone error emission until we've collected attributes required to
6719         // figure out whether it's a host or device variable and whether the
6720         // error should be ignored.
6721         EmitTLSUnsupportedError = true;
6722         // We still need to mark the variable as TLS so it shows up in AST with
6723         // proper storage class for other tools to use even if we're not going
6724         // to emit any code for it.
6725         NewVD->setTSCSpec(TSCS);
6726       } else
6727         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6728              diag::err_thread_unsupported);
6729     } else
6730       NewVD->setTSCSpec(TSCS);
6731   }
6732 
6733   // C99 6.7.4p3
6734   //   An inline definition of a function with external linkage shall
6735   //   not contain a definition of a modifiable object with static or
6736   //   thread storage duration...
6737   // We only apply this when the function is required to be defined
6738   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6739   // that a local variable with thread storage duration still has to
6740   // be marked 'static'.  Also note that it's possible to get these
6741   // semantics in C++ using __attribute__((gnu_inline)).
6742   if (SC == SC_Static && S->getFnParent() != nullptr &&
6743       !NewVD->getType().isConstQualified()) {
6744     FunctionDecl *CurFD = getCurFunctionDecl();
6745     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6746       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6747            diag::warn_static_local_in_extern_inline);
6748       MaybeSuggestAddingStaticToDecl(CurFD);
6749     }
6750   }
6751 
6752   if (D.getDeclSpec().isModulePrivateSpecified()) {
6753     if (IsVariableTemplateSpecialization)
6754       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6755           << (IsPartialSpecialization ? 1 : 0)
6756           << FixItHint::CreateRemoval(
6757                  D.getDeclSpec().getModulePrivateSpecLoc());
6758     else if (IsMemberSpecialization)
6759       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6760         << 2
6761         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6762     else if (NewVD->hasLocalStorage())
6763       Diag(NewVD->getLocation(), diag::err_module_private_local)
6764         << 0 << NewVD->getDeclName()
6765         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6766         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6767     else {
6768       NewVD->setModulePrivate();
6769       if (NewTemplate)
6770         NewTemplate->setModulePrivate();
6771       for (auto *B : Bindings)
6772         B->setModulePrivate();
6773     }
6774   }
6775 
6776   // Handle attributes prior to checking for duplicates in MergeVarDecl
6777   ProcessDeclAttributes(S, NewVD, D);
6778 
6779   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6780     if (EmitTLSUnsupportedError &&
6781         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6782          (getLangOpts().OpenMPIsDevice &&
6783           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6784       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6785            diag::err_thread_unsupported);
6786     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6787     // storage [duration]."
6788     if (SC == SC_None && S->getFnParent() != nullptr &&
6789         (NewVD->hasAttr<CUDASharedAttr>() ||
6790          NewVD->hasAttr<CUDAConstantAttr>())) {
6791       NewVD->setStorageClass(SC_Static);
6792     }
6793   }
6794 
6795   // Ensure that dllimport globals without explicit storage class are treated as
6796   // extern. The storage class is set above using parsed attributes. Now we can
6797   // check the VarDecl itself.
6798   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6799          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6800          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6801 
6802   // In auto-retain/release, infer strong retension for variables of
6803   // retainable type.
6804   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6805     NewVD->setInvalidDecl();
6806 
6807   // Handle GNU asm-label extension (encoded as an attribute).
6808   if (Expr *E = (Expr*)D.getAsmLabel()) {
6809     // The parser guarantees this is a string.
6810     StringLiteral *SE = cast<StringLiteral>(E);
6811     StringRef Label = SE->getString();
6812     if (S->getFnParent() != nullptr) {
6813       switch (SC) {
6814       case SC_None:
6815       case SC_Auto:
6816         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6817         break;
6818       case SC_Register:
6819         // Local Named register
6820         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6821             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6822           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6823         break;
6824       case SC_Static:
6825       case SC_Extern:
6826       case SC_PrivateExtern:
6827         break;
6828       }
6829     } else if (SC == SC_Register) {
6830       // Global Named register
6831       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6832         const auto &TI = Context.getTargetInfo();
6833         bool HasSizeMismatch;
6834 
6835         if (!TI.isValidGCCRegisterName(Label))
6836           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6837         else if (!TI.validateGlobalRegisterVariable(Label,
6838                                                     Context.getTypeSize(R),
6839                                                     HasSizeMismatch))
6840           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6841         else if (HasSizeMismatch)
6842           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6843       }
6844 
6845       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6846         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6847         NewVD->setInvalidDecl(true);
6848       }
6849     }
6850 
6851     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6852                                                 Context, Label, 0));
6853   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6854     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6855       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6856     if (I != ExtnameUndeclaredIdentifiers.end()) {
6857       if (isDeclExternC(NewVD)) {
6858         NewVD->addAttr(I->second);
6859         ExtnameUndeclaredIdentifiers.erase(I);
6860       } else
6861         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6862             << /*Variable*/1 << NewVD;
6863     }
6864   }
6865 
6866   // Find the shadowed declaration before filtering for scope.
6867   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6868                                 ? getShadowedDeclaration(NewVD, Previous)
6869                                 : nullptr;
6870 
6871   // Don't consider existing declarations that are in a different
6872   // scope and are out-of-semantic-context declarations (if the new
6873   // declaration has linkage).
6874   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6875                        D.getCXXScopeSpec().isNotEmpty() ||
6876                        IsMemberSpecialization ||
6877                        IsVariableTemplateSpecialization);
6878 
6879   // Check whether the previous declaration is in the same block scope. This
6880   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6881   if (getLangOpts().CPlusPlus &&
6882       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6883     NewVD->setPreviousDeclInSameBlockScope(
6884         Previous.isSingleResult() && !Previous.isShadowed() &&
6885         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6886 
6887   if (!getLangOpts().CPlusPlus) {
6888     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6889   } else {
6890     // If this is an explicit specialization of a static data member, check it.
6891     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6892         CheckMemberSpecialization(NewVD, Previous))
6893       NewVD->setInvalidDecl();
6894 
6895     // Merge the decl with the existing one if appropriate.
6896     if (!Previous.empty()) {
6897       if (Previous.isSingleResult() &&
6898           isa<FieldDecl>(Previous.getFoundDecl()) &&
6899           D.getCXXScopeSpec().isSet()) {
6900         // The user tried to define a non-static data member
6901         // out-of-line (C++ [dcl.meaning]p1).
6902         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6903           << D.getCXXScopeSpec().getRange();
6904         Previous.clear();
6905         NewVD->setInvalidDecl();
6906       }
6907     } else if (D.getCXXScopeSpec().isSet()) {
6908       // No previous declaration in the qualifying scope.
6909       Diag(D.getIdentifierLoc(), diag::err_no_member)
6910         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6911         << D.getCXXScopeSpec().getRange();
6912       NewVD->setInvalidDecl();
6913     }
6914 
6915     if (!IsVariableTemplateSpecialization)
6916       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6917 
6918     if (NewTemplate) {
6919       VarTemplateDecl *PrevVarTemplate =
6920           NewVD->getPreviousDecl()
6921               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6922               : nullptr;
6923 
6924       // Check the template parameter list of this declaration, possibly
6925       // merging in the template parameter list from the previous variable
6926       // template declaration.
6927       if (CheckTemplateParameterList(
6928               TemplateParams,
6929               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6930                               : nullptr,
6931               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6932                DC->isDependentContext())
6933                   ? TPC_ClassTemplateMember
6934                   : TPC_VarTemplate))
6935         NewVD->setInvalidDecl();
6936 
6937       // If we are providing an explicit specialization of a static variable
6938       // template, make a note of that.
6939       if (PrevVarTemplate &&
6940           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6941         PrevVarTemplate->setMemberSpecialization();
6942     }
6943   }
6944 
6945   // Diagnose shadowed variables iff this isn't a redeclaration.
6946   if (ShadowedDecl && !D.isRedeclaration())
6947     CheckShadow(NewVD, ShadowedDecl, Previous);
6948 
6949   ProcessPragmaWeak(S, NewVD);
6950 
6951   // If this is the first declaration of an extern C variable, update
6952   // the map of such variables.
6953   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6954       isIncompleteDeclExternC(*this, NewVD))
6955     RegisterLocallyScopedExternCDecl(NewVD, S);
6956 
6957   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6958     Decl *ManglingContextDecl;
6959     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6960             NewVD->getDeclContext(), ManglingContextDecl)) {
6961       Context.setManglingNumber(
6962           NewVD, MCtx->getManglingNumber(
6963                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6964       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6965     }
6966   }
6967 
6968   // Special handling of variable named 'main'.
6969   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6970       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6971       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6972 
6973     // C++ [basic.start.main]p3
6974     // A program that declares a variable main at global scope is ill-formed.
6975     if (getLangOpts().CPlusPlus)
6976       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6977 
6978     // In C, and external-linkage variable named main results in undefined
6979     // behavior.
6980     else if (NewVD->hasExternalFormalLinkage())
6981       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6982   }
6983 
6984   if (D.isRedeclaration() && !Previous.empty()) {
6985     NamedDecl *Prev = Previous.getRepresentativeDecl();
6986     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6987                                    D.isFunctionDefinition());
6988   }
6989 
6990   if (NewTemplate) {
6991     if (NewVD->isInvalidDecl())
6992       NewTemplate->setInvalidDecl();
6993     ActOnDocumentableDecl(NewTemplate);
6994     return NewTemplate;
6995   }
6996 
6997   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6998     CompleteMemberSpecialization(NewVD, Previous);
6999 
7000   return NewVD;
7001 }
7002 
7003 /// Enum describing the %select options in diag::warn_decl_shadow.
7004 enum ShadowedDeclKind {
7005   SDK_Local,
7006   SDK_Global,
7007   SDK_StaticMember,
7008   SDK_Field,
7009   SDK_Typedef,
7010   SDK_Using
7011 };
7012 
7013 /// Determine what kind of declaration we're shadowing.
7014 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7015                                                 const DeclContext *OldDC) {
7016   if (isa<TypeAliasDecl>(ShadowedDecl))
7017     return SDK_Using;
7018   else if (isa<TypedefDecl>(ShadowedDecl))
7019     return SDK_Typedef;
7020   else if (isa<RecordDecl>(OldDC))
7021     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7022 
7023   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7024 }
7025 
7026 /// Return the location of the capture if the given lambda captures the given
7027 /// variable \p VD, or an invalid source location otherwise.
7028 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7029                                          const VarDecl *VD) {
7030   for (const Capture &Capture : LSI->Captures) {
7031     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7032       return Capture.getLocation();
7033   }
7034   return SourceLocation();
7035 }
7036 
7037 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7038                                      const LookupResult &R) {
7039   // Only diagnose if we're shadowing an unambiguous field or variable.
7040   if (R.getResultKind() != LookupResult::Found)
7041     return false;
7042 
7043   // Return false if warning is ignored.
7044   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7045 }
7046 
7047 /// Return the declaration shadowed by the given variable \p D, or null
7048 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7049 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7050                                         const LookupResult &R) {
7051   if (!shouldWarnIfShadowedDecl(Diags, R))
7052     return nullptr;
7053 
7054   // Don't diagnose declarations at file scope.
7055   if (D->hasGlobalStorage())
7056     return nullptr;
7057 
7058   NamedDecl *ShadowedDecl = R.getFoundDecl();
7059   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7060              ? ShadowedDecl
7061              : nullptr;
7062 }
7063 
7064 /// Return the declaration shadowed by the given typedef \p D, or null
7065 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7066 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7067                                         const LookupResult &R) {
7068   // Don't warn if typedef declaration is part of a class
7069   if (D->getDeclContext()->isRecord())
7070     return nullptr;
7071 
7072   if (!shouldWarnIfShadowedDecl(Diags, R))
7073     return nullptr;
7074 
7075   NamedDecl *ShadowedDecl = R.getFoundDecl();
7076   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7077 }
7078 
7079 /// Diagnose variable or built-in function shadowing.  Implements
7080 /// -Wshadow.
7081 ///
7082 /// This method is called whenever a VarDecl is added to a "useful"
7083 /// scope.
7084 ///
7085 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7086 /// \param R the lookup of the name
7087 ///
7088 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7089                        const LookupResult &R) {
7090   DeclContext *NewDC = D->getDeclContext();
7091 
7092   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7093     // Fields are not shadowed by variables in C++ static methods.
7094     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7095       if (MD->isStatic())
7096         return;
7097 
7098     // Fields shadowed by constructor parameters are a special case. Usually
7099     // the constructor initializes the field with the parameter.
7100     if (isa<CXXConstructorDecl>(NewDC))
7101       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7102         // Remember that this was shadowed so we can either warn about its
7103         // modification or its existence depending on warning settings.
7104         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7105         return;
7106       }
7107   }
7108 
7109   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7110     if (shadowedVar->isExternC()) {
7111       // For shadowing external vars, make sure that we point to the global
7112       // declaration, not a locally scoped extern declaration.
7113       for (auto I : shadowedVar->redecls())
7114         if (I->isFileVarDecl()) {
7115           ShadowedDecl = I;
7116           break;
7117         }
7118     }
7119 
7120   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7121 
7122   unsigned WarningDiag = diag::warn_decl_shadow;
7123   SourceLocation CaptureLoc;
7124   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7125       isa<CXXMethodDecl>(NewDC)) {
7126     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7127       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7128         if (RD->getLambdaCaptureDefault() == LCD_None) {
7129           // Try to avoid warnings for lambdas with an explicit capture list.
7130           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7131           // Warn only when the lambda captures the shadowed decl explicitly.
7132           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7133           if (CaptureLoc.isInvalid())
7134             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7135         } else {
7136           // Remember that this was shadowed so we can avoid the warning if the
7137           // shadowed decl isn't captured and the warning settings allow it.
7138           cast<LambdaScopeInfo>(getCurFunction())
7139               ->ShadowingDecls.push_back(
7140                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7141           return;
7142         }
7143       }
7144 
7145       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7146         // A variable can't shadow a local variable in an enclosing scope, if
7147         // they are separated by a non-capturing declaration context.
7148         for (DeclContext *ParentDC = NewDC;
7149              ParentDC && !ParentDC->Equals(OldDC);
7150              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7151           // Only block literals, captured statements, and lambda expressions
7152           // can capture; other scopes don't.
7153           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7154               !isLambdaCallOperator(ParentDC)) {
7155             return;
7156           }
7157         }
7158       }
7159     }
7160   }
7161 
7162   // Only warn about certain kinds of shadowing for class members.
7163   if (NewDC && NewDC->isRecord()) {
7164     // In particular, don't warn about shadowing non-class members.
7165     if (!OldDC->isRecord())
7166       return;
7167 
7168     // TODO: should we warn about static data members shadowing
7169     // static data members from base classes?
7170 
7171     // TODO: don't diagnose for inaccessible shadowed members.
7172     // This is hard to do perfectly because we might friend the
7173     // shadowing context, but that's just a false negative.
7174   }
7175 
7176 
7177   DeclarationName Name = R.getLookupName();
7178 
7179   // Emit warning and note.
7180   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7181     return;
7182   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7183   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7184   if (!CaptureLoc.isInvalid())
7185     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7186         << Name << /*explicitly*/ 1;
7187   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7188 }
7189 
7190 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7191 /// when these variables are captured by the lambda.
7192 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7193   for (const auto &Shadow : LSI->ShadowingDecls) {
7194     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7195     // Try to avoid the warning when the shadowed decl isn't captured.
7196     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7197     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7198     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7199                                        ? diag::warn_decl_shadow_uncaptured_local
7200                                        : diag::warn_decl_shadow)
7201         << Shadow.VD->getDeclName()
7202         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7203     if (!CaptureLoc.isInvalid())
7204       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7205           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7206     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7207   }
7208 }
7209 
7210 /// Check -Wshadow without the advantage of a previous lookup.
7211 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7212   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7213     return;
7214 
7215   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7216                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7217   LookupName(R, S);
7218   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7219     CheckShadow(D, ShadowedDecl, R);
7220 }
7221 
7222 /// Check if 'E', which is an expression that is about to be modified, refers
7223 /// to a constructor parameter that shadows a field.
7224 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7225   // Quickly ignore expressions that can't be shadowing ctor parameters.
7226   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7227     return;
7228   E = E->IgnoreParenImpCasts();
7229   auto *DRE = dyn_cast<DeclRefExpr>(E);
7230   if (!DRE)
7231     return;
7232   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7233   auto I = ShadowingDecls.find(D);
7234   if (I == ShadowingDecls.end())
7235     return;
7236   const NamedDecl *ShadowedDecl = I->second;
7237   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7238   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7239   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7240   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7241 
7242   // Avoid issuing multiple warnings about the same decl.
7243   ShadowingDecls.erase(I);
7244 }
7245 
7246 /// Check for conflict between this global or extern "C" declaration and
7247 /// previous global or extern "C" declarations. This is only used in C++.
7248 template<typename T>
7249 static bool checkGlobalOrExternCConflict(
7250     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7251   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7252   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7253 
7254   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7255     // The common case: this global doesn't conflict with any extern "C"
7256     // declaration.
7257     return false;
7258   }
7259 
7260   if (Prev) {
7261     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7262       // Both the old and new declarations have C language linkage. This is a
7263       // redeclaration.
7264       Previous.clear();
7265       Previous.addDecl(Prev);
7266       return true;
7267     }
7268 
7269     // This is a global, non-extern "C" declaration, and there is a previous
7270     // non-global extern "C" declaration. Diagnose if this is a variable
7271     // declaration.
7272     if (!isa<VarDecl>(ND))
7273       return false;
7274   } else {
7275     // The declaration is extern "C". Check for any declaration in the
7276     // translation unit which might conflict.
7277     if (IsGlobal) {
7278       // We have already performed the lookup into the translation unit.
7279       IsGlobal = false;
7280       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7281            I != E; ++I) {
7282         if (isa<VarDecl>(*I)) {
7283           Prev = *I;
7284           break;
7285         }
7286       }
7287     } else {
7288       DeclContext::lookup_result R =
7289           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7290       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7291            I != E; ++I) {
7292         if (isa<VarDecl>(*I)) {
7293           Prev = *I;
7294           break;
7295         }
7296         // FIXME: If we have any other entity with this name in global scope,
7297         // the declaration is ill-formed, but that is a defect: it breaks the
7298         // 'stat' hack, for instance. Only variables can have mangled name
7299         // clashes with extern "C" declarations, so only they deserve a
7300         // diagnostic.
7301       }
7302     }
7303 
7304     if (!Prev)
7305       return false;
7306   }
7307 
7308   // Use the first declaration's location to ensure we point at something which
7309   // is lexically inside an extern "C" linkage-spec.
7310   assert(Prev && "should have found a previous declaration to diagnose");
7311   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7312     Prev = FD->getFirstDecl();
7313   else
7314     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7315 
7316   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7317     << IsGlobal << ND;
7318   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7319     << IsGlobal;
7320   return false;
7321 }
7322 
7323 /// Apply special rules for handling extern "C" declarations. Returns \c true
7324 /// if we have found that this is a redeclaration of some prior entity.
7325 ///
7326 /// Per C++ [dcl.link]p6:
7327 ///   Two declarations [for a function or variable] with C language linkage
7328 ///   with the same name that appear in different scopes refer to the same
7329 ///   [entity]. An entity with C language linkage shall not be declared with
7330 ///   the same name as an entity in global scope.
7331 template<typename T>
7332 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7333                                                   LookupResult &Previous) {
7334   if (!S.getLangOpts().CPlusPlus) {
7335     // In C, when declaring a global variable, look for a corresponding 'extern'
7336     // variable declared in function scope. We don't need this in C++, because
7337     // we find local extern decls in the surrounding file-scope DeclContext.
7338     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7339       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7340         Previous.clear();
7341         Previous.addDecl(Prev);
7342         return true;
7343       }
7344     }
7345     return false;
7346   }
7347 
7348   // A declaration in the translation unit can conflict with an extern "C"
7349   // declaration.
7350   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7351     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7352 
7353   // An extern "C" declaration can conflict with a declaration in the
7354   // translation unit or can be a redeclaration of an extern "C" declaration
7355   // in another scope.
7356   if (isIncompleteDeclExternC(S,ND))
7357     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7358 
7359   // Neither global nor extern "C": nothing to do.
7360   return false;
7361 }
7362 
7363 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7364   // If the decl is already known invalid, don't check it.
7365   if (NewVD->isInvalidDecl())
7366     return;
7367 
7368   QualType T = NewVD->getType();
7369 
7370   // Defer checking an 'auto' type until its initializer is attached.
7371   if (T->isUndeducedType())
7372     return;
7373 
7374   if (NewVD->hasAttrs())
7375     CheckAlignasUnderalignment(NewVD);
7376 
7377   if (T->isObjCObjectType()) {
7378     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7379       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7380     T = Context.getObjCObjectPointerType(T);
7381     NewVD->setType(T);
7382   }
7383 
7384   // Emit an error if an address space was applied to decl with local storage.
7385   // This includes arrays of objects with address space qualifiers, but not
7386   // automatic variables that point to other address spaces.
7387   // ISO/IEC TR 18037 S5.1.2
7388   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7389       T.getAddressSpace() != LangAS::Default) {
7390     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7391     NewVD->setInvalidDecl();
7392     return;
7393   }
7394 
7395   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7396   // scope.
7397   if (getLangOpts().OpenCLVersion == 120 &&
7398       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7399       NewVD->isStaticLocal()) {
7400     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7401     NewVD->setInvalidDecl();
7402     return;
7403   }
7404 
7405   if (getLangOpts().OpenCL) {
7406     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7407     if (NewVD->hasAttr<BlocksAttr>()) {
7408       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7409       return;
7410     }
7411 
7412     if (T->isBlockPointerType()) {
7413       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7414       // can't use 'extern' storage class.
7415       if (!T.isConstQualified()) {
7416         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7417             << 0 /*const*/;
7418         NewVD->setInvalidDecl();
7419         return;
7420       }
7421       if (NewVD->hasExternalStorage()) {
7422         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7423         NewVD->setInvalidDecl();
7424         return;
7425       }
7426     }
7427     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7428     // __constant address space.
7429     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7430     // variables inside a function can also be declared in the global
7431     // address space.
7432     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7433     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7434     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7435         NewVD->hasExternalStorage()) {
7436       if (!T->isSamplerT() &&
7437           !(T.getAddressSpace() == LangAS::opencl_constant ||
7438             (T.getAddressSpace() == LangAS::opencl_global &&
7439              (getLangOpts().OpenCLVersion == 200 ||
7440               getLangOpts().OpenCLCPlusPlus)))) {
7441         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7442         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7443           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7444               << Scope << "global or constant";
7445         else
7446           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7447               << Scope << "constant";
7448         NewVD->setInvalidDecl();
7449         return;
7450       }
7451     } else {
7452       if (T.getAddressSpace() == LangAS::opencl_global) {
7453         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7454             << 1 /*is any function*/ << "global";
7455         NewVD->setInvalidDecl();
7456         return;
7457       }
7458       if (T.getAddressSpace() == LangAS::opencl_constant ||
7459           T.getAddressSpace() == LangAS::opencl_local) {
7460         FunctionDecl *FD = getCurFunctionDecl();
7461         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7462         // in functions.
7463         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7464           if (T.getAddressSpace() == LangAS::opencl_constant)
7465             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7466                 << 0 /*non-kernel only*/ << "constant";
7467           else
7468             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7469                 << 0 /*non-kernel only*/ << "local";
7470           NewVD->setInvalidDecl();
7471           return;
7472         }
7473         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7474         // in the outermost scope of a kernel function.
7475         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7476           if (!getCurScope()->isFunctionScope()) {
7477             if (T.getAddressSpace() == LangAS::opencl_constant)
7478               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7479                   << "constant";
7480             else
7481               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7482                   << "local";
7483             NewVD->setInvalidDecl();
7484             return;
7485           }
7486         }
7487       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7488                  // If we are parsing a template we didn't deduce an addr
7489                  // space yet.
7490                  T.getAddressSpace() != LangAS::Default) {
7491         // Do not allow other address spaces on automatic variable.
7492         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7493         NewVD->setInvalidDecl();
7494         return;
7495       }
7496     }
7497   }
7498 
7499   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7500       && !NewVD->hasAttr<BlocksAttr>()) {
7501     if (getLangOpts().getGC() != LangOptions::NonGC)
7502       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7503     else {
7504       assert(!getLangOpts().ObjCAutoRefCount);
7505       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7506     }
7507   }
7508 
7509   bool isVM = T->isVariablyModifiedType();
7510   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7511       NewVD->hasAttr<BlocksAttr>())
7512     setFunctionHasBranchProtectedScope();
7513 
7514   if ((isVM && NewVD->hasLinkage()) ||
7515       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7516     bool SizeIsNegative;
7517     llvm::APSInt Oversized;
7518     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7519         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7520     QualType FixedT;
7521     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7522       FixedT = FixedTInfo->getType();
7523     else if (FixedTInfo) {
7524       // Type and type-as-written are canonically different. We need to fix up
7525       // both types separately.
7526       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7527                                                    Oversized);
7528     }
7529     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7530       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7531       // FIXME: This won't give the correct result for
7532       // int a[10][n];
7533       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7534 
7535       if (NewVD->isFileVarDecl())
7536         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7537         << SizeRange;
7538       else if (NewVD->isStaticLocal())
7539         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7540         << SizeRange;
7541       else
7542         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7543         << SizeRange;
7544       NewVD->setInvalidDecl();
7545       return;
7546     }
7547 
7548     if (!FixedTInfo) {
7549       if (NewVD->isFileVarDecl())
7550         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7551       else
7552         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7553       NewVD->setInvalidDecl();
7554       return;
7555     }
7556 
7557     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7558     NewVD->setType(FixedT);
7559     NewVD->setTypeSourceInfo(FixedTInfo);
7560   }
7561 
7562   if (T->isVoidType()) {
7563     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7564     //                    of objects and functions.
7565     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7566       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7567         << T;
7568       NewVD->setInvalidDecl();
7569       return;
7570     }
7571   }
7572 
7573   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7574     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7575     NewVD->setInvalidDecl();
7576     return;
7577   }
7578 
7579   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7580     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7581     NewVD->setInvalidDecl();
7582     return;
7583   }
7584 
7585   if (NewVD->isConstexpr() && !T->isDependentType() &&
7586       RequireLiteralType(NewVD->getLocation(), T,
7587                          diag::err_constexpr_var_non_literal)) {
7588     NewVD->setInvalidDecl();
7589     return;
7590   }
7591 }
7592 
7593 /// Perform semantic checking on a newly-created variable
7594 /// declaration.
7595 ///
7596 /// This routine performs all of the type-checking required for a
7597 /// variable declaration once it has been built. It is used both to
7598 /// check variables after they have been parsed and their declarators
7599 /// have been translated into a declaration, and to check variables
7600 /// that have been instantiated from a template.
7601 ///
7602 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7603 ///
7604 /// Returns true if the variable declaration is a redeclaration.
7605 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7606   CheckVariableDeclarationType(NewVD);
7607 
7608   // If the decl is already known invalid, don't check it.
7609   if (NewVD->isInvalidDecl())
7610     return false;
7611 
7612   // If we did not find anything by this name, look for a non-visible
7613   // extern "C" declaration with the same name.
7614   if (Previous.empty() &&
7615       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7616     Previous.setShadowed();
7617 
7618   if (!Previous.empty()) {
7619     MergeVarDecl(NewVD, Previous);
7620     return true;
7621   }
7622   return false;
7623 }
7624 
7625 namespace {
7626 struct FindOverriddenMethod {
7627   Sema *S;
7628   CXXMethodDecl *Method;
7629 
7630   /// Member lookup function that determines whether a given C++
7631   /// method overrides a method in a base class, to be used with
7632   /// CXXRecordDecl::lookupInBases().
7633   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7634     RecordDecl *BaseRecord =
7635         Specifier->getType()->getAs<RecordType>()->getDecl();
7636 
7637     DeclarationName Name = Method->getDeclName();
7638 
7639     // FIXME: Do we care about other names here too?
7640     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7641       // We really want to find the base class destructor here.
7642       QualType T = S->Context.getTypeDeclType(BaseRecord);
7643       CanQualType CT = S->Context.getCanonicalType(T);
7644 
7645       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7646     }
7647 
7648     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7649          Path.Decls = Path.Decls.slice(1)) {
7650       NamedDecl *D = Path.Decls.front();
7651       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7652         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7653           return true;
7654       }
7655     }
7656 
7657     return false;
7658   }
7659 };
7660 
7661 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7662 } // end anonymous namespace
7663 
7664 /// Report an error regarding overriding, along with any relevant
7665 /// overridden methods.
7666 ///
7667 /// \param DiagID the primary error to report.
7668 /// \param MD the overriding method.
7669 /// \param OEK which overrides to include as notes.
7670 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7671                             OverrideErrorKind OEK = OEK_All) {
7672   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7673   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7674     // This check (& the OEK parameter) could be replaced by a predicate, but
7675     // without lambdas that would be overkill. This is still nicer than writing
7676     // out the diag loop 3 times.
7677     if ((OEK == OEK_All) ||
7678         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7679         (OEK == OEK_Deleted && O->isDeleted()))
7680       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7681   }
7682 }
7683 
7684 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7685 /// and if so, check that it's a valid override and remember it.
7686 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7687   // Look for methods in base classes that this method might override.
7688   CXXBasePaths Paths;
7689   FindOverriddenMethod FOM;
7690   FOM.Method = MD;
7691   FOM.S = this;
7692   bool hasDeletedOverridenMethods = false;
7693   bool hasNonDeletedOverridenMethods = false;
7694   bool AddedAny = false;
7695   if (DC->lookupInBases(FOM, Paths)) {
7696     for (auto *I : Paths.found_decls()) {
7697       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7698         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7699         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7700             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7701             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7702             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7703           hasDeletedOverridenMethods |= OldMD->isDeleted();
7704           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7705           AddedAny = true;
7706         }
7707       }
7708     }
7709   }
7710 
7711   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7712     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7713   }
7714   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7715     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7716   }
7717 
7718   return AddedAny;
7719 }
7720 
7721 namespace {
7722   // Struct for holding all of the extra arguments needed by
7723   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7724   struct ActOnFDArgs {
7725     Scope *S;
7726     Declarator &D;
7727     MultiTemplateParamsArg TemplateParamLists;
7728     bool AddToScope;
7729   };
7730 } // end anonymous namespace
7731 
7732 namespace {
7733 
7734 // Callback to only accept typo corrections that have a non-zero edit distance.
7735 // Also only accept corrections that have the same parent decl.
7736 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7737  public:
7738   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7739                             CXXRecordDecl *Parent)
7740       : Context(Context), OriginalFD(TypoFD),
7741         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7742 
7743   bool ValidateCandidate(const TypoCorrection &candidate) override {
7744     if (candidate.getEditDistance() == 0)
7745       return false;
7746 
7747     SmallVector<unsigned, 1> MismatchedParams;
7748     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7749                                           CDeclEnd = candidate.end();
7750          CDecl != CDeclEnd; ++CDecl) {
7751       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7752 
7753       if (FD && !FD->hasBody() &&
7754           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7755         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7756           CXXRecordDecl *Parent = MD->getParent();
7757           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7758             return true;
7759         } else if (!ExpectedParent) {
7760           return true;
7761         }
7762       }
7763     }
7764 
7765     return false;
7766   }
7767 
7768   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7769     return llvm::make_unique<DifferentNameValidatorCCC>(*this);
7770   }
7771 
7772  private:
7773   ASTContext &Context;
7774   FunctionDecl *OriginalFD;
7775   CXXRecordDecl *ExpectedParent;
7776 };
7777 
7778 } // end anonymous namespace
7779 
7780 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7781   TypoCorrectedFunctionDefinitions.insert(F);
7782 }
7783 
7784 /// Generate diagnostics for an invalid function redeclaration.
7785 ///
7786 /// This routine handles generating the diagnostic messages for an invalid
7787 /// function redeclaration, including finding possible similar declarations
7788 /// or performing typo correction if there are no previous declarations with
7789 /// the same name.
7790 ///
7791 /// Returns a NamedDecl iff typo correction was performed and substituting in
7792 /// the new declaration name does not cause new errors.
7793 static NamedDecl *DiagnoseInvalidRedeclaration(
7794     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7795     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7796   DeclarationName Name = NewFD->getDeclName();
7797   DeclContext *NewDC = NewFD->getDeclContext();
7798   SmallVector<unsigned, 1> MismatchedParams;
7799   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7800   TypoCorrection Correction;
7801   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7802   unsigned DiagMsg =
7803     IsLocalFriend ? diag::err_no_matching_local_friend :
7804     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7805     diag::err_member_decl_does_not_match;
7806   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7807                     IsLocalFriend ? Sema::LookupLocalFriendName
7808                                   : Sema::LookupOrdinaryName,
7809                     Sema::ForVisibleRedeclaration);
7810 
7811   NewFD->setInvalidDecl();
7812   if (IsLocalFriend)
7813     SemaRef.LookupName(Prev, S);
7814   else
7815     SemaRef.LookupQualifiedName(Prev, NewDC);
7816   assert(!Prev.isAmbiguous() &&
7817          "Cannot have an ambiguity in previous-declaration lookup");
7818   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7819   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7820                                 MD ? MD->getParent() : nullptr);
7821   if (!Prev.empty()) {
7822     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7823          Func != FuncEnd; ++Func) {
7824       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7825       if (FD &&
7826           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7827         // Add 1 to the index so that 0 can mean the mismatch didn't
7828         // involve a parameter
7829         unsigned ParamNum =
7830             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7831         NearMatches.push_back(std::make_pair(FD, ParamNum));
7832       }
7833     }
7834   // If the qualified name lookup yielded nothing, try typo correction
7835   } else if ((Correction = SemaRef.CorrectTypo(
7836                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7837                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7838                   IsLocalFriend ? nullptr : NewDC))) {
7839     // Set up everything for the call to ActOnFunctionDeclarator
7840     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7841                               ExtraArgs.D.getIdentifierLoc());
7842     Previous.clear();
7843     Previous.setLookupName(Correction.getCorrection());
7844     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7845                                     CDeclEnd = Correction.end();
7846          CDecl != CDeclEnd; ++CDecl) {
7847       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7848       if (FD && !FD->hasBody() &&
7849           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7850         Previous.addDecl(FD);
7851       }
7852     }
7853     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7854 
7855     NamedDecl *Result;
7856     // Retry building the function declaration with the new previous
7857     // declarations, and with errors suppressed.
7858     {
7859       // Trap errors.
7860       Sema::SFINAETrap Trap(SemaRef);
7861 
7862       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7863       // pieces need to verify the typo-corrected C++ declaration and hopefully
7864       // eliminate the need for the parameter pack ExtraArgs.
7865       Result = SemaRef.ActOnFunctionDeclarator(
7866           ExtraArgs.S, ExtraArgs.D,
7867           Correction.getCorrectionDecl()->getDeclContext(),
7868           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7869           ExtraArgs.AddToScope);
7870 
7871       if (Trap.hasErrorOccurred())
7872         Result = nullptr;
7873     }
7874 
7875     if (Result) {
7876       // Determine which correction we picked.
7877       Decl *Canonical = Result->getCanonicalDecl();
7878       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7879            I != E; ++I)
7880         if ((*I)->getCanonicalDecl() == Canonical)
7881           Correction.setCorrectionDecl(*I);
7882 
7883       // Let Sema know about the correction.
7884       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7885       SemaRef.diagnoseTypo(
7886           Correction,
7887           SemaRef.PDiag(IsLocalFriend
7888                           ? diag::err_no_matching_local_friend_suggest
7889                           : diag::err_member_decl_does_not_match_suggest)
7890             << Name << NewDC << IsDefinition);
7891       return Result;
7892     }
7893 
7894     // Pretend the typo correction never occurred
7895     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7896                               ExtraArgs.D.getIdentifierLoc());
7897     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7898     Previous.clear();
7899     Previous.setLookupName(Name);
7900   }
7901 
7902   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7903       << Name << NewDC << IsDefinition << NewFD->getLocation();
7904 
7905   bool NewFDisConst = false;
7906   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7907     NewFDisConst = NewMD->isConst();
7908 
7909   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7910        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7911        NearMatch != NearMatchEnd; ++NearMatch) {
7912     FunctionDecl *FD = NearMatch->first;
7913     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7914     bool FDisConst = MD && MD->isConst();
7915     bool IsMember = MD || !IsLocalFriend;
7916 
7917     // FIXME: These notes are poorly worded for the local friend case.
7918     if (unsigned Idx = NearMatch->second) {
7919       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7920       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7921       if (Loc.isInvalid()) Loc = FD->getLocation();
7922       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7923                                  : diag::note_local_decl_close_param_match)
7924         << Idx << FDParam->getType()
7925         << NewFD->getParamDecl(Idx - 1)->getType();
7926     } else if (FDisConst != NewFDisConst) {
7927       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7928           << NewFDisConst << FD->getSourceRange().getEnd();
7929     } else
7930       SemaRef.Diag(FD->getLocation(),
7931                    IsMember ? diag::note_member_def_close_match
7932                             : diag::note_local_decl_close_match);
7933   }
7934   return nullptr;
7935 }
7936 
7937 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7938   switch (D.getDeclSpec().getStorageClassSpec()) {
7939   default: llvm_unreachable("Unknown storage class!");
7940   case DeclSpec::SCS_auto:
7941   case DeclSpec::SCS_register:
7942   case DeclSpec::SCS_mutable:
7943     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7944                  diag::err_typecheck_sclass_func);
7945     D.getMutableDeclSpec().ClearStorageClassSpecs();
7946     D.setInvalidType();
7947     break;
7948   case DeclSpec::SCS_unspecified: break;
7949   case DeclSpec::SCS_extern:
7950     if (D.getDeclSpec().isExternInLinkageSpec())
7951       return SC_None;
7952     return SC_Extern;
7953   case DeclSpec::SCS_static: {
7954     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7955       // C99 6.7.1p5:
7956       //   The declaration of an identifier for a function that has
7957       //   block scope shall have no explicit storage-class specifier
7958       //   other than extern
7959       // See also (C++ [dcl.stc]p4).
7960       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7961                    diag::err_static_block_func);
7962       break;
7963     } else
7964       return SC_Static;
7965   }
7966   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7967   }
7968 
7969   // No explicit storage class has already been returned
7970   return SC_None;
7971 }
7972 
7973 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7974                                            DeclContext *DC, QualType &R,
7975                                            TypeSourceInfo *TInfo,
7976                                            StorageClass SC,
7977                                            bool &IsVirtualOkay) {
7978   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7979   DeclarationName Name = NameInfo.getName();
7980 
7981   FunctionDecl *NewFD = nullptr;
7982   bool isInline = D.getDeclSpec().isInlineSpecified();
7983 
7984   if (!SemaRef.getLangOpts().CPlusPlus) {
7985     // Determine whether the function was written with a
7986     // prototype. This true when:
7987     //   - there is a prototype in the declarator, or
7988     //   - the type R of the function is some kind of typedef or other non-
7989     //     attributed reference to a type name (which eventually refers to a
7990     //     function type).
7991     bool HasPrototype =
7992       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7993       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7994 
7995     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
7996                                  R, TInfo, SC, isInline, HasPrototype,
7997                                  CSK_unspecified);
7998     if (D.isInvalidType())
7999       NewFD->setInvalidDecl();
8000 
8001     return NewFD;
8002   }
8003 
8004   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8005   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8006   // Check that the return type is not an abstract class type.
8007   // For record types, this is done by the AbstractClassUsageDiagnoser once
8008   // the class has been completely parsed.
8009   if (!DC->isRecord() &&
8010       SemaRef.RequireNonAbstractType(
8011           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
8012           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8013     D.setInvalidType();
8014 
8015   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8016     // This is a C++ constructor declaration.
8017     assert(DC->isRecord() &&
8018            "Constructors can only be declared in a member context");
8019 
8020     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8021     return CXXConstructorDecl::Create(
8022         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8023         TInfo, ExplicitSpecifier, isInline,
8024         /*isImplicitlyDeclared=*/false, ConstexprKind);
8025 
8026   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8027     // This is a C++ destructor declaration.
8028     if (DC->isRecord()) {
8029       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8030       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8031       CXXDestructorDecl *NewDD =
8032           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
8033                                     NameInfo, R, TInfo, isInline,
8034                                     /*isImplicitlyDeclared=*/false);
8035 
8036       // If the destructor needs an implicit exception specification, set it
8037       // now. FIXME: It'd be nice to be able to create the right type to start
8038       // with, but the type needs to reference the destructor declaration.
8039       if (SemaRef.getLangOpts().CPlusPlus11)
8040         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8041 
8042       IsVirtualOkay = true;
8043       return NewDD;
8044 
8045     } else {
8046       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8047       D.setInvalidType();
8048 
8049       // Create a FunctionDecl to satisfy the function definition parsing
8050       // code path.
8051       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8052                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8053                                   isInline,
8054                                   /*hasPrototype=*/true, ConstexprKind);
8055     }
8056 
8057   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8058     if (!DC->isRecord()) {
8059       SemaRef.Diag(D.getIdentifierLoc(),
8060            diag::err_conv_function_not_member);
8061       return nullptr;
8062     }
8063 
8064     SemaRef.CheckConversionDeclarator(D, R, SC);
8065     IsVirtualOkay = true;
8066     return CXXConversionDecl::Create(
8067         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8068         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8069 
8070   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8071     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8072 
8073     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8074                                          ExplicitSpecifier, NameInfo, R, TInfo,
8075                                          D.getEndLoc());
8076   } else if (DC->isRecord()) {
8077     // If the name of the function is the same as the name of the record,
8078     // then this must be an invalid constructor that has a return type.
8079     // (The parser checks for a return type and makes the declarator a
8080     // constructor if it has no return type).
8081     if (Name.getAsIdentifierInfo() &&
8082         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8083       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8084         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8085         << SourceRange(D.getIdentifierLoc());
8086       return nullptr;
8087     }
8088 
8089     // This is a C++ method declaration.
8090     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8091         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8092         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8093     IsVirtualOkay = !Ret->isStatic();
8094     return Ret;
8095   } else {
8096     bool isFriend =
8097         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8098     if (!isFriend && SemaRef.CurContext->isRecord())
8099       return nullptr;
8100 
8101     // Determine whether the function was written with a
8102     // prototype. This true when:
8103     //   - we're in C++ (where every function has a prototype),
8104     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8105                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8106                                 ConstexprKind);
8107   }
8108 }
8109 
8110 enum OpenCLParamType {
8111   ValidKernelParam,
8112   PtrPtrKernelParam,
8113   PtrKernelParam,
8114   InvalidAddrSpacePtrKernelParam,
8115   InvalidKernelParam,
8116   RecordKernelParam
8117 };
8118 
8119 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8120   // Size dependent types are just typedefs to normal integer types
8121   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8122   // integers other than by their names.
8123   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8124 
8125   // Remove typedefs one by one until we reach a typedef
8126   // for a size dependent type.
8127   QualType DesugaredTy = Ty;
8128   do {
8129     ArrayRef<StringRef> Names(SizeTypeNames);
8130     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8131     if (Names.end() != Match)
8132       return true;
8133 
8134     Ty = DesugaredTy;
8135     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8136   } while (DesugaredTy != Ty);
8137 
8138   return false;
8139 }
8140 
8141 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8142   if (PT->isPointerType()) {
8143     QualType PointeeType = PT->getPointeeType();
8144     if (PointeeType->isPointerType())
8145       return PtrPtrKernelParam;
8146     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8147         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8148         PointeeType.getAddressSpace() == LangAS::Default)
8149       return InvalidAddrSpacePtrKernelParam;
8150     return PtrKernelParam;
8151   }
8152 
8153   // OpenCL v1.2 s6.9.k:
8154   // Arguments to kernel functions in a program cannot be declared with the
8155   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8156   // uintptr_t or a struct and/or union that contain fields declared to be one
8157   // of these built-in scalar types.
8158   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8159     return InvalidKernelParam;
8160 
8161   if (PT->isImageType())
8162     return PtrKernelParam;
8163 
8164   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8165     return InvalidKernelParam;
8166 
8167   // OpenCL extension spec v1.2 s9.5:
8168   // This extension adds support for half scalar and vector types as built-in
8169   // types that can be used for arithmetic operations, conversions etc.
8170   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8171     return InvalidKernelParam;
8172 
8173   if (PT->isRecordType())
8174     return RecordKernelParam;
8175 
8176   // Look into an array argument to check if it has a forbidden type.
8177   if (PT->isArrayType()) {
8178     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8179     // Call ourself to check an underlying type of an array. Since the
8180     // getPointeeOrArrayElementType returns an innermost type which is not an
8181     // array, this recursive call only happens once.
8182     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8183   }
8184 
8185   return ValidKernelParam;
8186 }
8187 
8188 static void checkIsValidOpenCLKernelParameter(
8189   Sema &S,
8190   Declarator &D,
8191   ParmVarDecl *Param,
8192   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8193   QualType PT = Param->getType();
8194 
8195   // Cache the valid types we encounter to avoid rechecking structs that are
8196   // used again
8197   if (ValidTypes.count(PT.getTypePtr()))
8198     return;
8199 
8200   switch (getOpenCLKernelParameterType(S, PT)) {
8201   case PtrPtrKernelParam:
8202     // OpenCL v1.2 s6.9.a:
8203     // A kernel function argument cannot be declared as a
8204     // pointer to a pointer type.
8205     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8206     D.setInvalidType();
8207     return;
8208 
8209   case InvalidAddrSpacePtrKernelParam:
8210     // OpenCL v1.0 s6.5:
8211     // __kernel function arguments declared to be a pointer of a type can point
8212     // to one of the following address spaces only : __global, __local or
8213     // __constant.
8214     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8215     D.setInvalidType();
8216     return;
8217 
8218     // OpenCL v1.2 s6.9.k:
8219     // Arguments to kernel functions in a program cannot be declared with the
8220     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8221     // uintptr_t or a struct and/or union that contain fields declared to be
8222     // one of these built-in scalar types.
8223 
8224   case InvalidKernelParam:
8225     // OpenCL v1.2 s6.8 n:
8226     // A kernel function argument cannot be declared
8227     // of event_t type.
8228     // Do not diagnose half type since it is diagnosed as invalid argument
8229     // type for any function elsewhere.
8230     if (!PT->isHalfType()) {
8231       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8232 
8233       // Explain what typedefs are involved.
8234       const TypedefType *Typedef = nullptr;
8235       while ((Typedef = PT->getAs<TypedefType>())) {
8236         SourceLocation Loc = Typedef->getDecl()->getLocation();
8237         // SourceLocation may be invalid for a built-in type.
8238         if (Loc.isValid())
8239           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8240         PT = Typedef->desugar();
8241       }
8242     }
8243 
8244     D.setInvalidType();
8245     return;
8246 
8247   case PtrKernelParam:
8248   case ValidKernelParam:
8249     ValidTypes.insert(PT.getTypePtr());
8250     return;
8251 
8252   case RecordKernelParam:
8253     break;
8254   }
8255 
8256   // Track nested structs we will inspect
8257   SmallVector<const Decl *, 4> VisitStack;
8258 
8259   // Track where we are in the nested structs. Items will migrate from
8260   // VisitStack to HistoryStack as we do the DFS for bad field.
8261   SmallVector<const FieldDecl *, 4> HistoryStack;
8262   HistoryStack.push_back(nullptr);
8263 
8264   // At this point we already handled everything except of a RecordType or
8265   // an ArrayType of a RecordType.
8266   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8267   const RecordType *RecTy =
8268       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8269   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8270 
8271   VisitStack.push_back(RecTy->getDecl());
8272   assert(VisitStack.back() && "First decl null?");
8273 
8274   do {
8275     const Decl *Next = VisitStack.pop_back_val();
8276     if (!Next) {
8277       assert(!HistoryStack.empty());
8278       // Found a marker, we have gone up a level
8279       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8280         ValidTypes.insert(Hist->getType().getTypePtr());
8281 
8282       continue;
8283     }
8284 
8285     // Adds everything except the original parameter declaration (which is not a
8286     // field itself) to the history stack.
8287     const RecordDecl *RD;
8288     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8289       HistoryStack.push_back(Field);
8290 
8291       QualType FieldTy = Field->getType();
8292       // Other field types (known to be valid or invalid) are handled while we
8293       // walk around RecordDecl::fields().
8294       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8295              "Unexpected type.");
8296       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8297 
8298       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8299     } else {
8300       RD = cast<RecordDecl>(Next);
8301     }
8302 
8303     // Add a null marker so we know when we've gone back up a level
8304     VisitStack.push_back(nullptr);
8305 
8306     for (const auto *FD : RD->fields()) {
8307       QualType QT = FD->getType();
8308 
8309       if (ValidTypes.count(QT.getTypePtr()))
8310         continue;
8311 
8312       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8313       if (ParamType == ValidKernelParam)
8314         continue;
8315 
8316       if (ParamType == RecordKernelParam) {
8317         VisitStack.push_back(FD);
8318         continue;
8319       }
8320 
8321       // OpenCL v1.2 s6.9.p:
8322       // Arguments to kernel functions that are declared to be a struct or union
8323       // do not allow OpenCL objects to be passed as elements of the struct or
8324       // union.
8325       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8326           ParamType == InvalidAddrSpacePtrKernelParam) {
8327         S.Diag(Param->getLocation(),
8328                diag::err_record_with_pointers_kernel_param)
8329           << PT->isUnionType()
8330           << PT;
8331       } else {
8332         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8333       }
8334 
8335       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8336           << OrigRecDecl->getDeclName();
8337 
8338       // We have an error, now let's go back up through history and show where
8339       // the offending field came from
8340       for (ArrayRef<const FieldDecl *>::const_iterator
8341                I = HistoryStack.begin() + 1,
8342                E = HistoryStack.end();
8343            I != E; ++I) {
8344         const FieldDecl *OuterField = *I;
8345         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8346           << OuterField->getType();
8347       }
8348 
8349       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8350         << QT->isPointerType()
8351         << QT;
8352       D.setInvalidType();
8353       return;
8354     }
8355   } while (!VisitStack.empty());
8356 }
8357 
8358 /// Find the DeclContext in which a tag is implicitly declared if we see an
8359 /// elaborated type specifier in the specified context, and lookup finds
8360 /// nothing.
8361 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8362   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8363     DC = DC->getParent();
8364   return DC;
8365 }
8366 
8367 /// Find the Scope in which a tag is implicitly declared if we see an
8368 /// elaborated type specifier in the specified context, and lookup finds
8369 /// nothing.
8370 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8371   while (S->isClassScope() ||
8372          (LangOpts.CPlusPlus &&
8373           S->isFunctionPrototypeScope()) ||
8374          ((S->getFlags() & Scope::DeclScope) == 0) ||
8375          (S->getEntity() && S->getEntity()->isTransparentContext()))
8376     S = S->getParent();
8377   return S;
8378 }
8379 
8380 NamedDecl*
8381 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8382                               TypeSourceInfo *TInfo, LookupResult &Previous,
8383                               MultiTemplateParamsArg TemplateParamLists,
8384                               bool &AddToScope) {
8385   QualType R = TInfo->getType();
8386 
8387   assert(R->isFunctionType());
8388 
8389   // TODO: consider using NameInfo for diagnostic.
8390   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8391   DeclarationName Name = NameInfo.getName();
8392   StorageClass SC = getFunctionStorageClass(*this, D);
8393 
8394   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8395     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8396          diag::err_invalid_thread)
8397       << DeclSpec::getSpecifierName(TSCS);
8398 
8399   if (D.isFirstDeclarationOfMember())
8400     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8401                            D.getIdentifierLoc());
8402 
8403   bool isFriend = false;
8404   FunctionTemplateDecl *FunctionTemplate = nullptr;
8405   bool isMemberSpecialization = false;
8406   bool isFunctionTemplateSpecialization = false;
8407 
8408   bool isDependentClassScopeExplicitSpecialization = false;
8409   bool HasExplicitTemplateArgs = false;
8410   TemplateArgumentListInfo TemplateArgs;
8411 
8412   bool isVirtualOkay = false;
8413 
8414   DeclContext *OriginalDC = DC;
8415   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8416 
8417   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8418                                               isVirtualOkay);
8419   if (!NewFD) return nullptr;
8420 
8421   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8422     NewFD->setTopLevelDeclInObjCContainer();
8423 
8424   // Set the lexical context. If this is a function-scope declaration, or has a
8425   // C++ scope specifier, or is the object of a friend declaration, the lexical
8426   // context will be different from the semantic context.
8427   NewFD->setLexicalDeclContext(CurContext);
8428 
8429   if (IsLocalExternDecl)
8430     NewFD->setLocalExternDecl();
8431 
8432   if (getLangOpts().CPlusPlus) {
8433     bool isInline = D.getDeclSpec().isInlineSpecified();
8434     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8435     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8436     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8437     isFriend = D.getDeclSpec().isFriendSpecified();
8438     if (isFriend && !isInline && D.isFunctionDefinition()) {
8439       // C++ [class.friend]p5
8440       //   A function can be defined in a friend declaration of a
8441       //   class . . . . Such a function is implicitly inline.
8442       NewFD->setImplicitlyInline();
8443     }
8444 
8445     // If this is a method defined in an __interface, and is not a constructor
8446     // or an overloaded operator, then set the pure flag (isVirtual will already
8447     // return true).
8448     if (const CXXRecordDecl *Parent =
8449           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8450       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8451         NewFD->setPure(true);
8452 
8453       // C++ [class.union]p2
8454       //   A union can have member functions, but not virtual functions.
8455       if (isVirtual && Parent->isUnion())
8456         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8457     }
8458 
8459     SetNestedNameSpecifier(*this, NewFD, D);
8460     isMemberSpecialization = false;
8461     isFunctionTemplateSpecialization = false;
8462     if (D.isInvalidType())
8463       NewFD->setInvalidDecl();
8464 
8465     // Match up the template parameter lists with the scope specifier, then
8466     // determine whether we have a template or a template specialization.
8467     bool Invalid = false;
8468     if (TemplateParameterList *TemplateParams =
8469             MatchTemplateParametersToScopeSpecifier(
8470                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8471                 D.getCXXScopeSpec(),
8472                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8473                     ? D.getName().TemplateId
8474                     : nullptr,
8475                 TemplateParamLists, isFriend, isMemberSpecialization,
8476                 Invalid)) {
8477       if (TemplateParams->size() > 0) {
8478         // This is a function template
8479 
8480         // Check that we can declare a template here.
8481         if (CheckTemplateDeclScope(S, TemplateParams))
8482           NewFD->setInvalidDecl();
8483 
8484         // A destructor cannot be a template.
8485         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8486           Diag(NewFD->getLocation(), diag::err_destructor_template);
8487           NewFD->setInvalidDecl();
8488         }
8489 
8490         // If we're adding a template to a dependent context, we may need to
8491         // rebuilding some of the types used within the template parameter list,
8492         // now that we know what the current instantiation is.
8493         if (DC->isDependentContext()) {
8494           ContextRAII SavedContext(*this, DC);
8495           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8496             Invalid = true;
8497         }
8498 
8499         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8500                                                         NewFD->getLocation(),
8501                                                         Name, TemplateParams,
8502                                                         NewFD);
8503         FunctionTemplate->setLexicalDeclContext(CurContext);
8504         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8505 
8506         // For source fidelity, store the other template param lists.
8507         if (TemplateParamLists.size() > 1) {
8508           NewFD->setTemplateParameterListsInfo(Context,
8509                                                TemplateParamLists.drop_back(1));
8510         }
8511       } else {
8512         // This is a function template specialization.
8513         isFunctionTemplateSpecialization = true;
8514         // For source fidelity, store all the template param lists.
8515         if (TemplateParamLists.size() > 0)
8516           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8517 
8518         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8519         if (isFriend) {
8520           // We want to remove the "template<>", found here.
8521           SourceRange RemoveRange = TemplateParams->getSourceRange();
8522 
8523           // If we remove the template<> and the name is not a
8524           // template-id, we're actually silently creating a problem:
8525           // the friend declaration will refer to an untemplated decl,
8526           // and clearly the user wants a template specialization.  So
8527           // we need to insert '<>' after the name.
8528           SourceLocation InsertLoc;
8529           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8530             InsertLoc = D.getName().getSourceRange().getEnd();
8531             InsertLoc = getLocForEndOfToken(InsertLoc);
8532           }
8533 
8534           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8535             << Name << RemoveRange
8536             << FixItHint::CreateRemoval(RemoveRange)
8537             << FixItHint::CreateInsertion(InsertLoc, "<>");
8538         }
8539       }
8540     } else {
8541       // All template param lists were matched against the scope specifier:
8542       // this is NOT (an explicit specialization of) a template.
8543       if (TemplateParamLists.size() > 0)
8544         // For source fidelity, store all the template param lists.
8545         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8546     }
8547 
8548     if (Invalid) {
8549       NewFD->setInvalidDecl();
8550       if (FunctionTemplate)
8551         FunctionTemplate->setInvalidDecl();
8552     }
8553 
8554     // C++ [dcl.fct.spec]p5:
8555     //   The virtual specifier shall only be used in declarations of
8556     //   nonstatic class member functions that appear within a
8557     //   member-specification of a class declaration; see 10.3.
8558     //
8559     if (isVirtual && !NewFD->isInvalidDecl()) {
8560       if (!isVirtualOkay) {
8561         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8562              diag::err_virtual_non_function);
8563       } else if (!CurContext->isRecord()) {
8564         // 'virtual' was specified outside of the class.
8565         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8566              diag::err_virtual_out_of_class)
8567           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8568       } else if (NewFD->getDescribedFunctionTemplate()) {
8569         // C++ [temp.mem]p3:
8570         //  A member function template shall not be virtual.
8571         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8572              diag::err_virtual_member_function_template)
8573           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8574       } else {
8575         // Okay: Add virtual to the method.
8576         NewFD->setVirtualAsWritten(true);
8577       }
8578 
8579       if (getLangOpts().CPlusPlus14 &&
8580           NewFD->getReturnType()->isUndeducedType())
8581         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8582     }
8583 
8584     if (getLangOpts().CPlusPlus14 &&
8585         (NewFD->isDependentContext() ||
8586          (isFriend && CurContext->isDependentContext())) &&
8587         NewFD->getReturnType()->isUndeducedType()) {
8588       // If the function template is referenced directly (for instance, as a
8589       // member of the current instantiation), pretend it has a dependent type.
8590       // This is not really justified by the standard, but is the only sane
8591       // thing to do.
8592       // FIXME: For a friend function, we have not marked the function as being
8593       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8594       const FunctionProtoType *FPT =
8595           NewFD->getType()->castAs<FunctionProtoType>();
8596       QualType Result =
8597           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8598       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8599                                              FPT->getExtProtoInfo()));
8600     }
8601 
8602     // C++ [dcl.fct.spec]p3:
8603     //  The inline specifier shall not appear on a block scope function
8604     //  declaration.
8605     if (isInline && !NewFD->isInvalidDecl()) {
8606       if (CurContext->isFunctionOrMethod()) {
8607         // 'inline' is not allowed on block scope function declaration.
8608         Diag(D.getDeclSpec().getInlineSpecLoc(),
8609              diag::err_inline_declaration_block_scope) << Name
8610           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8611       }
8612     }
8613 
8614     // C++ [dcl.fct.spec]p6:
8615     //  The explicit specifier shall be used only in the declaration of a
8616     //  constructor or conversion function within its class definition;
8617     //  see 12.3.1 and 12.3.2.
8618     if (hasExplicit && !NewFD->isInvalidDecl() &&
8619         !isa<CXXDeductionGuideDecl>(NewFD)) {
8620       if (!CurContext->isRecord()) {
8621         // 'explicit' was specified outside of the class.
8622         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8623              diag::err_explicit_out_of_class)
8624             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8625       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8626                  !isa<CXXConversionDecl>(NewFD)) {
8627         // 'explicit' was specified on a function that wasn't a constructor
8628         // or conversion function.
8629         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8630              diag::err_explicit_non_ctor_or_conv_function)
8631             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8632       }
8633     }
8634 
8635     if (ConstexprKind != CSK_unspecified) {
8636       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8637       // are implicitly inline.
8638       NewFD->setImplicitlyInline();
8639 
8640       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8641       // be either constructors or to return a literal type. Therefore,
8642       // destructors cannot be declared constexpr.
8643       if (isa<CXXDestructorDecl>(NewFD))
8644         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8645             << (ConstexprKind == CSK_consteval);
8646     }
8647 
8648     // If __module_private__ was specified, mark the function accordingly.
8649     if (D.getDeclSpec().isModulePrivateSpecified()) {
8650       if (isFunctionTemplateSpecialization) {
8651         SourceLocation ModulePrivateLoc
8652           = D.getDeclSpec().getModulePrivateSpecLoc();
8653         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8654           << 0
8655           << FixItHint::CreateRemoval(ModulePrivateLoc);
8656       } else {
8657         NewFD->setModulePrivate();
8658         if (FunctionTemplate)
8659           FunctionTemplate->setModulePrivate();
8660       }
8661     }
8662 
8663     if (isFriend) {
8664       if (FunctionTemplate) {
8665         FunctionTemplate->setObjectOfFriendDecl();
8666         FunctionTemplate->setAccess(AS_public);
8667       }
8668       NewFD->setObjectOfFriendDecl();
8669       NewFD->setAccess(AS_public);
8670     }
8671 
8672     // If a function is defined as defaulted or deleted, mark it as such now.
8673     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8674     // definition kind to FDK_Definition.
8675     switch (D.getFunctionDefinitionKind()) {
8676       case FDK_Declaration:
8677       case FDK_Definition:
8678         break;
8679 
8680       case FDK_Defaulted:
8681         NewFD->setDefaulted();
8682         break;
8683 
8684       case FDK_Deleted:
8685         NewFD->setDeletedAsWritten();
8686         break;
8687     }
8688 
8689     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8690         D.isFunctionDefinition()) {
8691       // C++ [class.mfct]p2:
8692       //   A member function may be defined (8.4) in its class definition, in
8693       //   which case it is an inline member function (7.1.2)
8694       NewFD->setImplicitlyInline();
8695     }
8696 
8697     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8698         !CurContext->isRecord()) {
8699       // C++ [class.static]p1:
8700       //   A data or function member of a class may be declared static
8701       //   in a class definition, in which case it is a static member of
8702       //   the class.
8703 
8704       // Complain about the 'static' specifier if it's on an out-of-line
8705       // member function definition.
8706 
8707       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8708       // member function template declaration and class member template
8709       // declaration (MSVC versions before 2015), warn about this.
8710       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8711            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8712              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8713            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8714            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8715         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8716     }
8717 
8718     // C++11 [except.spec]p15:
8719     //   A deallocation function with no exception-specification is treated
8720     //   as if it were specified with noexcept(true).
8721     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8722     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8723          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8724         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8725       NewFD->setType(Context.getFunctionType(
8726           FPT->getReturnType(), FPT->getParamTypes(),
8727           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8728   }
8729 
8730   // Filter out previous declarations that don't match the scope.
8731   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8732                        D.getCXXScopeSpec().isNotEmpty() ||
8733                        isMemberSpecialization ||
8734                        isFunctionTemplateSpecialization);
8735 
8736   // Handle GNU asm-label extension (encoded as an attribute).
8737   if (Expr *E = (Expr*) D.getAsmLabel()) {
8738     // The parser guarantees this is a string.
8739     StringLiteral *SE = cast<StringLiteral>(E);
8740     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8741                                                 SE->getString(), 0));
8742   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8743     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8744       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8745     if (I != ExtnameUndeclaredIdentifiers.end()) {
8746       if (isDeclExternC(NewFD)) {
8747         NewFD->addAttr(I->second);
8748         ExtnameUndeclaredIdentifiers.erase(I);
8749       } else
8750         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8751             << /*Variable*/0 << NewFD;
8752     }
8753   }
8754 
8755   // Copy the parameter declarations from the declarator D to the function
8756   // declaration NewFD, if they are available.  First scavenge them into Params.
8757   SmallVector<ParmVarDecl*, 16> Params;
8758   unsigned FTIIdx;
8759   if (D.isFunctionDeclarator(FTIIdx)) {
8760     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8761 
8762     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8763     // function that takes no arguments, not a function that takes a
8764     // single void argument.
8765     // We let through "const void" here because Sema::GetTypeForDeclarator
8766     // already checks for that case.
8767     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8768       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8769         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8770         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8771         Param->setDeclContext(NewFD);
8772         Params.push_back(Param);
8773 
8774         if (Param->isInvalidDecl())
8775           NewFD->setInvalidDecl();
8776       }
8777     }
8778 
8779     if (!getLangOpts().CPlusPlus) {
8780       // In C, find all the tag declarations from the prototype and move them
8781       // into the function DeclContext. Remove them from the surrounding tag
8782       // injection context of the function, which is typically but not always
8783       // the TU.
8784       DeclContext *PrototypeTagContext =
8785           getTagInjectionContext(NewFD->getLexicalDeclContext());
8786       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8787         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8788 
8789         // We don't want to reparent enumerators. Look at their parent enum
8790         // instead.
8791         if (!TD) {
8792           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8793             TD = cast<EnumDecl>(ECD->getDeclContext());
8794         }
8795         if (!TD)
8796           continue;
8797         DeclContext *TagDC = TD->getLexicalDeclContext();
8798         if (!TagDC->containsDecl(TD))
8799           continue;
8800         TagDC->removeDecl(TD);
8801         TD->setDeclContext(NewFD);
8802         NewFD->addDecl(TD);
8803 
8804         // Preserve the lexical DeclContext if it is not the surrounding tag
8805         // injection context of the FD. In this example, the semantic context of
8806         // E will be f and the lexical context will be S, while both the
8807         // semantic and lexical contexts of S will be f:
8808         //   void f(struct S { enum E { a } f; } s);
8809         if (TagDC != PrototypeTagContext)
8810           TD->setLexicalDeclContext(TagDC);
8811       }
8812     }
8813   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8814     // When we're declaring a function with a typedef, typeof, etc as in the
8815     // following example, we'll need to synthesize (unnamed)
8816     // parameters for use in the declaration.
8817     //
8818     // @code
8819     // typedef void fn(int);
8820     // fn f;
8821     // @endcode
8822 
8823     // Synthesize a parameter for each argument type.
8824     for (const auto &AI : FT->param_types()) {
8825       ParmVarDecl *Param =
8826           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8827       Param->setScopeInfo(0, Params.size());
8828       Params.push_back(Param);
8829     }
8830   } else {
8831     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8832            "Should not need args for typedef of non-prototype fn");
8833   }
8834 
8835   // Finally, we know we have the right number of parameters, install them.
8836   NewFD->setParams(Params);
8837 
8838   if (D.getDeclSpec().isNoreturnSpecified())
8839     NewFD->addAttr(
8840         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8841                                        Context, 0));
8842 
8843   // Functions returning a variably modified type violate C99 6.7.5.2p2
8844   // because all functions have linkage.
8845   if (!NewFD->isInvalidDecl() &&
8846       NewFD->getReturnType()->isVariablyModifiedType()) {
8847     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8848     NewFD->setInvalidDecl();
8849   }
8850 
8851   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8852   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8853       !NewFD->hasAttr<SectionAttr>()) {
8854     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8855                                                  PragmaClangTextSection.SectionName,
8856                                                  PragmaClangTextSection.PragmaLocation));
8857   }
8858 
8859   // Apply an implicit SectionAttr if #pragma code_seg is active.
8860   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8861       !NewFD->hasAttr<SectionAttr>()) {
8862     NewFD->addAttr(
8863         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8864                                     CodeSegStack.CurrentValue->getString(),
8865                                     CodeSegStack.CurrentPragmaLocation));
8866     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8867                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8868                          ASTContext::PSF_Read,
8869                      NewFD))
8870       NewFD->dropAttr<SectionAttr>();
8871   }
8872 
8873   // Apply an implicit CodeSegAttr from class declspec or
8874   // apply an implicit SectionAttr from #pragma code_seg if active.
8875   if (!NewFD->hasAttr<CodeSegAttr>()) {
8876     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8877                                                                  D.isFunctionDefinition())) {
8878       NewFD->addAttr(SAttr);
8879     }
8880   }
8881 
8882   // Handle attributes.
8883   ProcessDeclAttributes(S, NewFD, D);
8884 
8885   if (getLangOpts().OpenCL) {
8886     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8887     // type declaration will generate a compilation error.
8888     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8889     if (AddressSpace != LangAS::Default) {
8890       Diag(NewFD->getLocation(),
8891            diag::err_opencl_return_value_with_address_space);
8892       NewFD->setInvalidDecl();
8893     }
8894   }
8895 
8896   if (!getLangOpts().CPlusPlus) {
8897     // Perform semantic checking on the function declaration.
8898     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8899       CheckMain(NewFD, D.getDeclSpec());
8900 
8901     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8902       CheckMSVCRTEntryPoint(NewFD);
8903 
8904     if (!NewFD->isInvalidDecl())
8905       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8906                                                   isMemberSpecialization));
8907     else if (!Previous.empty())
8908       // Recover gracefully from an invalid redeclaration.
8909       D.setRedeclaration(true);
8910     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8911             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8912            "previous declaration set still overloaded");
8913 
8914     // Diagnose no-prototype function declarations with calling conventions that
8915     // don't support variadic calls. Only do this in C and do it after merging
8916     // possibly prototyped redeclarations.
8917     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8918     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8919       CallingConv CC = FT->getExtInfo().getCC();
8920       if (!supportsVariadicCall(CC)) {
8921         // Windows system headers sometimes accidentally use stdcall without
8922         // (void) parameters, so we relax this to a warning.
8923         int DiagID =
8924             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8925         Diag(NewFD->getLocation(), DiagID)
8926             << FunctionType::getNameForCallConv(CC);
8927       }
8928     }
8929   } else {
8930     // C++11 [replacement.functions]p3:
8931     //  The program's definitions shall not be specified as inline.
8932     //
8933     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8934     //
8935     // Suppress the diagnostic if the function is __attribute__((used)), since
8936     // that forces an external definition to be emitted.
8937     if (D.getDeclSpec().isInlineSpecified() &&
8938         NewFD->isReplaceableGlobalAllocationFunction() &&
8939         !NewFD->hasAttr<UsedAttr>())
8940       Diag(D.getDeclSpec().getInlineSpecLoc(),
8941            diag::ext_operator_new_delete_declared_inline)
8942         << NewFD->getDeclName();
8943 
8944     // If the declarator is a template-id, translate the parser's template
8945     // argument list into our AST format.
8946     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8947       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8948       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8949       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8950       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8951                                          TemplateId->NumArgs);
8952       translateTemplateArguments(TemplateArgsPtr,
8953                                  TemplateArgs);
8954 
8955       HasExplicitTemplateArgs = true;
8956 
8957       if (NewFD->isInvalidDecl()) {
8958         HasExplicitTemplateArgs = false;
8959       } else if (FunctionTemplate) {
8960         // Function template with explicit template arguments.
8961         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8962           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8963 
8964         HasExplicitTemplateArgs = false;
8965       } else {
8966         assert((isFunctionTemplateSpecialization ||
8967                 D.getDeclSpec().isFriendSpecified()) &&
8968                "should have a 'template<>' for this decl");
8969         // "friend void foo<>(int);" is an implicit specialization decl.
8970         isFunctionTemplateSpecialization = true;
8971       }
8972     } else if (isFriend && isFunctionTemplateSpecialization) {
8973       // This combination is only possible in a recovery case;  the user
8974       // wrote something like:
8975       //   template <> friend void foo(int);
8976       // which we're recovering from as if the user had written:
8977       //   friend void foo<>(int);
8978       // Go ahead and fake up a template id.
8979       HasExplicitTemplateArgs = true;
8980       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8981       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8982     }
8983 
8984     // We do not add HD attributes to specializations here because
8985     // they may have different constexpr-ness compared to their
8986     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8987     // may end up with different effective targets. Instead, a
8988     // specialization inherits its target attributes from its template
8989     // in the CheckFunctionTemplateSpecialization() call below.
8990     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8991       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8992 
8993     // If it's a friend (and only if it's a friend), it's possible
8994     // that either the specialized function type or the specialized
8995     // template is dependent, and therefore matching will fail.  In
8996     // this case, don't check the specialization yet.
8997     bool InstantiationDependent = false;
8998     if (isFunctionTemplateSpecialization && isFriend &&
8999         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9000          TemplateSpecializationType::anyDependentTemplateArguments(
9001             TemplateArgs,
9002             InstantiationDependent))) {
9003       assert(HasExplicitTemplateArgs &&
9004              "friend function specialization without template args");
9005       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9006                                                        Previous))
9007         NewFD->setInvalidDecl();
9008     } else if (isFunctionTemplateSpecialization) {
9009       if (CurContext->isDependentContext() && CurContext->isRecord()
9010           && !isFriend) {
9011         isDependentClassScopeExplicitSpecialization = true;
9012       } else if (!NewFD->isInvalidDecl() &&
9013                  CheckFunctionTemplateSpecialization(
9014                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9015                      Previous))
9016         NewFD->setInvalidDecl();
9017 
9018       // C++ [dcl.stc]p1:
9019       //   A storage-class-specifier shall not be specified in an explicit
9020       //   specialization (14.7.3)
9021       FunctionTemplateSpecializationInfo *Info =
9022           NewFD->getTemplateSpecializationInfo();
9023       if (Info && SC != SC_None) {
9024         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9025           Diag(NewFD->getLocation(),
9026                diag::err_explicit_specialization_inconsistent_storage_class)
9027             << SC
9028             << FixItHint::CreateRemoval(
9029                                       D.getDeclSpec().getStorageClassSpecLoc());
9030 
9031         else
9032           Diag(NewFD->getLocation(),
9033                diag::ext_explicit_specialization_storage_class)
9034             << FixItHint::CreateRemoval(
9035                                       D.getDeclSpec().getStorageClassSpecLoc());
9036       }
9037     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9038       if (CheckMemberSpecialization(NewFD, Previous))
9039           NewFD->setInvalidDecl();
9040     }
9041 
9042     // Perform semantic checking on the function declaration.
9043     if (!isDependentClassScopeExplicitSpecialization) {
9044       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9045         CheckMain(NewFD, D.getDeclSpec());
9046 
9047       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9048         CheckMSVCRTEntryPoint(NewFD);
9049 
9050       if (!NewFD->isInvalidDecl())
9051         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9052                                                     isMemberSpecialization));
9053       else if (!Previous.empty())
9054         // Recover gracefully from an invalid redeclaration.
9055         D.setRedeclaration(true);
9056     }
9057 
9058     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9059             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9060            "previous declaration set still overloaded");
9061 
9062     NamedDecl *PrincipalDecl = (FunctionTemplate
9063                                 ? cast<NamedDecl>(FunctionTemplate)
9064                                 : NewFD);
9065 
9066     if (isFriend && NewFD->getPreviousDecl()) {
9067       AccessSpecifier Access = AS_public;
9068       if (!NewFD->isInvalidDecl())
9069         Access = NewFD->getPreviousDecl()->getAccess();
9070 
9071       NewFD->setAccess(Access);
9072       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9073     }
9074 
9075     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9076         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9077       PrincipalDecl->setNonMemberOperator();
9078 
9079     // If we have a function template, check the template parameter
9080     // list. This will check and merge default template arguments.
9081     if (FunctionTemplate) {
9082       FunctionTemplateDecl *PrevTemplate =
9083                                      FunctionTemplate->getPreviousDecl();
9084       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9085                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9086                                     : nullptr,
9087                             D.getDeclSpec().isFriendSpecified()
9088                               ? (D.isFunctionDefinition()
9089                                    ? TPC_FriendFunctionTemplateDefinition
9090                                    : TPC_FriendFunctionTemplate)
9091                               : (D.getCXXScopeSpec().isSet() &&
9092                                  DC && DC->isRecord() &&
9093                                  DC->isDependentContext())
9094                                   ? TPC_ClassTemplateMember
9095                                   : TPC_FunctionTemplate);
9096     }
9097 
9098     if (NewFD->isInvalidDecl()) {
9099       // Ignore all the rest of this.
9100     } else if (!D.isRedeclaration()) {
9101       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9102                                        AddToScope };
9103       // Fake up an access specifier if it's supposed to be a class member.
9104       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9105         NewFD->setAccess(AS_public);
9106 
9107       // Qualified decls generally require a previous declaration.
9108       if (D.getCXXScopeSpec().isSet()) {
9109         // ...with the major exception of templated-scope or
9110         // dependent-scope friend declarations.
9111 
9112         // TODO: we currently also suppress this check in dependent
9113         // contexts because (1) the parameter depth will be off when
9114         // matching friend templates and (2) we might actually be
9115         // selecting a friend based on a dependent factor.  But there
9116         // are situations where these conditions don't apply and we
9117         // can actually do this check immediately.
9118         //
9119         // Unless the scope is dependent, it's always an error if qualified
9120         // redeclaration lookup found nothing at all. Diagnose that now;
9121         // nothing will diagnose that error later.
9122         if (isFriend &&
9123             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9124              (!Previous.empty() && CurContext->isDependentContext()))) {
9125           // ignore these
9126         } else {
9127           // The user tried to provide an out-of-line definition for a
9128           // function that is a member of a class or namespace, but there
9129           // was no such member function declared (C++ [class.mfct]p2,
9130           // C++ [namespace.memdef]p2). For example:
9131           //
9132           // class X {
9133           //   void f() const;
9134           // };
9135           //
9136           // void X::f() { } // ill-formed
9137           //
9138           // Complain about this problem, and attempt to suggest close
9139           // matches (e.g., those that differ only in cv-qualifiers and
9140           // whether the parameter types are references).
9141 
9142           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9143                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9144             AddToScope = ExtraArgs.AddToScope;
9145             return Result;
9146           }
9147         }
9148 
9149         // Unqualified local friend declarations are required to resolve
9150         // to something.
9151       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9152         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9153                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9154           AddToScope = ExtraArgs.AddToScope;
9155           return Result;
9156         }
9157       }
9158     } else if (!D.isFunctionDefinition() &&
9159                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9160                !isFriend && !isFunctionTemplateSpecialization &&
9161                !isMemberSpecialization) {
9162       // An out-of-line member function declaration must also be a
9163       // definition (C++ [class.mfct]p2).
9164       // Note that this is not the case for explicit specializations of
9165       // function templates or member functions of class templates, per
9166       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9167       // extension for compatibility with old SWIG code which likes to
9168       // generate them.
9169       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9170         << D.getCXXScopeSpec().getRange();
9171     }
9172   }
9173 
9174   ProcessPragmaWeak(S, NewFD);
9175   checkAttributesAfterMerging(*this, *NewFD);
9176 
9177   AddKnownFunctionAttributes(NewFD);
9178 
9179   if (NewFD->hasAttr<OverloadableAttr>() &&
9180       !NewFD->getType()->getAs<FunctionProtoType>()) {
9181     Diag(NewFD->getLocation(),
9182          diag::err_attribute_overloadable_no_prototype)
9183       << NewFD;
9184 
9185     // Turn this into a variadic function with no parameters.
9186     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9187     FunctionProtoType::ExtProtoInfo EPI(
9188         Context.getDefaultCallingConvention(true, false));
9189     EPI.Variadic = true;
9190     EPI.ExtInfo = FT->getExtInfo();
9191 
9192     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9193     NewFD->setType(R);
9194   }
9195 
9196   // If there's a #pragma GCC visibility in scope, and this isn't a class
9197   // member, set the visibility of this function.
9198   if (!DC->isRecord() && NewFD->isExternallyVisible())
9199     AddPushedVisibilityAttribute(NewFD);
9200 
9201   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9202   // marking the function.
9203   AddCFAuditedAttribute(NewFD);
9204 
9205   // If this is a function definition, check if we have to apply optnone due to
9206   // a pragma.
9207   if(D.isFunctionDefinition())
9208     AddRangeBasedOptnone(NewFD);
9209 
9210   // If this is the first declaration of an extern C variable, update
9211   // the map of such variables.
9212   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9213       isIncompleteDeclExternC(*this, NewFD))
9214     RegisterLocallyScopedExternCDecl(NewFD, S);
9215 
9216   // Set this FunctionDecl's range up to the right paren.
9217   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9218 
9219   if (D.isRedeclaration() && !Previous.empty()) {
9220     NamedDecl *Prev = Previous.getRepresentativeDecl();
9221     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9222                                    isMemberSpecialization ||
9223                                        isFunctionTemplateSpecialization,
9224                                    D.isFunctionDefinition());
9225   }
9226 
9227   if (getLangOpts().CUDA) {
9228     IdentifierInfo *II = NewFD->getIdentifier();
9229     if (II && II->isStr(getCudaConfigureFuncName()) &&
9230         !NewFD->isInvalidDecl() &&
9231         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9232       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9233         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9234             << getCudaConfigureFuncName();
9235       Context.setcudaConfigureCallDecl(NewFD);
9236     }
9237 
9238     // Variadic functions, other than a *declaration* of printf, are not allowed
9239     // in device-side CUDA code, unless someone passed
9240     // -fcuda-allow-variadic-functions.
9241     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9242         (NewFD->hasAttr<CUDADeviceAttr>() ||
9243          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9244         !(II && II->isStr("printf") && NewFD->isExternC() &&
9245           !D.isFunctionDefinition())) {
9246       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9247     }
9248   }
9249 
9250   MarkUnusedFileScopedDecl(NewFD);
9251 
9252 
9253 
9254   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9255     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9256     if ((getLangOpts().OpenCLVersion >= 120)
9257         && (SC == SC_Static)) {
9258       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9259       D.setInvalidType();
9260     }
9261 
9262     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9263     if (!NewFD->getReturnType()->isVoidType()) {
9264       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9265       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9266           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9267                                 : FixItHint());
9268       D.setInvalidType();
9269     }
9270 
9271     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9272     for (auto Param : NewFD->parameters())
9273       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9274 
9275     if (getLangOpts().OpenCLCPlusPlus) {
9276       if (DC->isRecord()) {
9277         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9278         D.setInvalidType();
9279       }
9280       if (FunctionTemplate) {
9281         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9282         D.setInvalidType();
9283       }
9284     }
9285   }
9286 
9287   if (getLangOpts().CPlusPlus) {
9288     if (FunctionTemplate) {
9289       if (NewFD->isInvalidDecl())
9290         FunctionTemplate->setInvalidDecl();
9291       return FunctionTemplate;
9292     }
9293 
9294     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9295       CompleteMemberSpecialization(NewFD, Previous);
9296   }
9297 
9298   for (const ParmVarDecl *Param : NewFD->parameters()) {
9299     QualType PT = Param->getType();
9300 
9301     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9302     // types.
9303     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9304       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9305         QualType ElemTy = PipeTy->getElementType();
9306           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9307             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9308             D.setInvalidType();
9309           }
9310       }
9311     }
9312   }
9313 
9314   // Here we have an function template explicit specialization at class scope.
9315   // The actual specialization will be postponed to template instatiation
9316   // time via the ClassScopeFunctionSpecializationDecl node.
9317   if (isDependentClassScopeExplicitSpecialization) {
9318     ClassScopeFunctionSpecializationDecl *NewSpec =
9319                          ClassScopeFunctionSpecializationDecl::Create(
9320                                 Context, CurContext, NewFD->getLocation(),
9321                                 cast<CXXMethodDecl>(NewFD),
9322                                 HasExplicitTemplateArgs, TemplateArgs);
9323     CurContext->addDecl(NewSpec);
9324     AddToScope = false;
9325   }
9326 
9327   // Diagnose availability attributes. Availability cannot be used on functions
9328   // that are run during load/unload.
9329   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9330     if (NewFD->hasAttr<ConstructorAttr>()) {
9331       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9332           << 1;
9333       NewFD->dropAttr<AvailabilityAttr>();
9334     }
9335     if (NewFD->hasAttr<DestructorAttr>()) {
9336       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9337           << 2;
9338       NewFD->dropAttr<AvailabilityAttr>();
9339     }
9340   }
9341 
9342   return NewFD;
9343 }
9344 
9345 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9346 /// when __declspec(code_seg) "is applied to a class, all member functions of
9347 /// the class and nested classes -- this includes compiler-generated special
9348 /// member functions -- are put in the specified segment."
9349 /// The actual behavior is a little more complicated. The Microsoft compiler
9350 /// won't check outer classes if there is an active value from #pragma code_seg.
9351 /// The CodeSeg is always applied from the direct parent but only from outer
9352 /// classes when the #pragma code_seg stack is empty. See:
9353 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9354 /// available since MS has removed the page.
9355 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9356   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9357   if (!Method)
9358     return nullptr;
9359   const CXXRecordDecl *Parent = Method->getParent();
9360   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9361     Attr *NewAttr = SAttr->clone(S.getASTContext());
9362     NewAttr->setImplicit(true);
9363     return NewAttr;
9364   }
9365 
9366   // The Microsoft compiler won't check outer classes for the CodeSeg
9367   // when the #pragma code_seg stack is active.
9368   if (S.CodeSegStack.CurrentValue)
9369    return nullptr;
9370 
9371   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9372     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9373       Attr *NewAttr = SAttr->clone(S.getASTContext());
9374       NewAttr->setImplicit(true);
9375       return NewAttr;
9376     }
9377   }
9378   return nullptr;
9379 }
9380 
9381 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9382 /// containing class. Otherwise it will return implicit SectionAttr if the
9383 /// function is a definition and there is an active value on CodeSegStack
9384 /// (from the current #pragma code-seg value).
9385 ///
9386 /// \param FD Function being declared.
9387 /// \param IsDefinition Whether it is a definition or just a declarartion.
9388 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9389 ///          nullptr if no attribute should be added.
9390 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9391                                                        bool IsDefinition) {
9392   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9393     return A;
9394   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9395       CodeSegStack.CurrentValue) {
9396     return SectionAttr::CreateImplicit(getASTContext(),
9397                                        SectionAttr::Declspec_allocate,
9398                                        CodeSegStack.CurrentValue->getString(),
9399                                        CodeSegStack.CurrentPragmaLocation);
9400   }
9401   return nullptr;
9402 }
9403 
9404 /// Determines if we can perform a correct type check for \p D as a
9405 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9406 /// best-effort check.
9407 ///
9408 /// \param NewD The new declaration.
9409 /// \param OldD The old declaration.
9410 /// \param NewT The portion of the type of the new declaration to check.
9411 /// \param OldT The portion of the type of the old declaration to check.
9412 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9413                                           QualType NewT, QualType OldT) {
9414   if (!NewD->getLexicalDeclContext()->isDependentContext())
9415     return true;
9416 
9417   // For dependently-typed local extern declarations and friends, we can't
9418   // perform a correct type check in general until instantiation:
9419   //
9420   //   int f();
9421   //   template<typename T> void g() { T f(); }
9422   //
9423   // (valid if g() is only instantiated with T = int).
9424   if (NewT->isDependentType() &&
9425       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9426     return false;
9427 
9428   // Similarly, if the previous declaration was a dependent local extern
9429   // declaration, we don't really know its type yet.
9430   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9431     return false;
9432 
9433   return true;
9434 }
9435 
9436 /// Checks if the new declaration declared in dependent context must be
9437 /// put in the same redeclaration chain as the specified declaration.
9438 ///
9439 /// \param D Declaration that is checked.
9440 /// \param PrevDecl Previous declaration found with proper lookup method for the
9441 ///                 same declaration name.
9442 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9443 ///          belongs to.
9444 ///
9445 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9446   if (!D->getLexicalDeclContext()->isDependentContext())
9447     return true;
9448 
9449   // Don't chain dependent friend function definitions until instantiation, to
9450   // permit cases like
9451   //
9452   //   void func();
9453   //   template<typename T> class C1 { friend void func() {} };
9454   //   template<typename T> class C2 { friend void func() {} };
9455   //
9456   // ... which is valid if only one of C1 and C2 is ever instantiated.
9457   //
9458   // FIXME: This need only apply to function definitions. For now, we proxy
9459   // this by checking for a file-scope function. We do not want this to apply
9460   // to friend declarations nominating member functions, because that gets in
9461   // the way of access checks.
9462   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9463     return false;
9464 
9465   auto *VD = dyn_cast<ValueDecl>(D);
9466   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9467   return !VD || !PrevVD ||
9468          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9469                                         PrevVD->getType());
9470 }
9471 
9472 /// Check the target attribute of the function for MultiVersion
9473 /// validity.
9474 ///
9475 /// Returns true if there was an error, false otherwise.
9476 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9477   const auto *TA = FD->getAttr<TargetAttr>();
9478   assert(TA && "MultiVersion Candidate requires a target attribute");
9479   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9480   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9481   enum ErrType { Feature = 0, Architecture = 1 };
9482 
9483   if (!ParseInfo.Architecture.empty() &&
9484       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9485     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9486         << Architecture << ParseInfo.Architecture;
9487     return true;
9488   }
9489 
9490   for (const auto &Feat : ParseInfo.Features) {
9491     auto BareFeat = StringRef{Feat}.substr(1);
9492     if (Feat[0] == '-') {
9493       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9494           << Feature << ("no-" + BareFeat).str();
9495       return true;
9496     }
9497 
9498     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9499         !TargetInfo.isValidFeatureName(BareFeat)) {
9500       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9501           << Feature << BareFeat;
9502       return true;
9503     }
9504   }
9505   return false;
9506 }
9507 
9508 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9509                                          MultiVersionKind MVType) {
9510   for (const Attr *A : FD->attrs()) {
9511     switch (A->getKind()) {
9512     case attr::CPUDispatch:
9513     case attr::CPUSpecific:
9514       if (MVType != MultiVersionKind::CPUDispatch &&
9515           MVType != MultiVersionKind::CPUSpecific)
9516         return true;
9517       break;
9518     case attr::Target:
9519       if (MVType != MultiVersionKind::Target)
9520         return true;
9521       break;
9522     default:
9523       return true;
9524     }
9525   }
9526   return false;
9527 }
9528 
9529 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9530                                              const FunctionDecl *NewFD,
9531                                              bool CausesMV,
9532                                              MultiVersionKind MVType) {
9533   enum DoesntSupport {
9534     FuncTemplates = 0,
9535     VirtFuncs = 1,
9536     DeducedReturn = 2,
9537     Constructors = 3,
9538     Destructors = 4,
9539     DeletedFuncs = 5,
9540     DefaultedFuncs = 6,
9541     ConstexprFuncs = 7,
9542     ConstevalFuncs = 8,
9543   };
9544   enum Different {
9545     CallingConv = 0,
9546     ReturnType = 1,
9547     ConstexprSpec = 2,
9548     InlineSpec = 3,
9549     StorageClass = 4,
9550     Linkage = 5
9551   };
9552 
9553   bool IsCPUSpecificCPUDispatchMVType =
9554       MVType == MultiVersionKind::CPUDispatch ||
9555       MVType == MultiVersionKind::CPUSpecific;
9556 
9557   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9558     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9559     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9560     return true;
9561   }
9562 
9563   if (!NewFD->getType()->getAs<FunctionProtoType>())
9564     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9565 
9566   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9567     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9568     if (OldFD)
9569       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9570     return true;
9571   }
9572 
9573   // For now, disallow all other attributes.  These should be opt-in, but
9574   // an analysis of all of them is a future FIXME.
9575   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9576     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9577         << IsCPUSpecificCPUDispatchMVType;
9578     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9579     return true;
9580   }
9581 
9582   if (HasNonMultiVersionAttributes(NewFD, MVType))
9583     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9584            << IsCPUSpecificCPUDispatchMVType;
9585 
9586   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9587     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9588            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9589 
9590   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9591     if (NewCXXFD->isVirtual())
9592       return S.Diag(NewCXXFD->getLocation(),
9593                     diag::err_multiversion_doesnt_support)
9594              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9595 
9596     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9597       return S.Diag(NewCXXCtor->getLocation(),
9598                     diag::err_multiversion_doesnt_support)
9599              << IsCPUSpecificCPUDispatchMVType << Constructors;
9600 
9601     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9602       return S.Diag(NewCXXDtor->getLocation(),
9603                     diag::err_multiversion_doesnt_support)
9604              << IsCPUSpecificCPUDispatchMVType << Destructors;
9605   }
9606 
9607   if (NewFD->isDeleted())
9608     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9609            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9610 
9611   if (NewFD->isDefaulted())
9612     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9613            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9614 
9615   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9616                                MVType == MultiVersionKind::CPUSpecific))
9617     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9618            << IsCPUSpecificCPUDispatchMVType
9619            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9620 
9621   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9622   const auto *NewType = cast<FunctionType>(NewQType);
9623   QualType NewReturnType = NewType->getReturnType();
9624 
9625   if (NewReturnType->isUndeducedType())
9626     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9627            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9628 
9629   // Only allow transition to MultiVersion if it hasn't been used.
9630   if (OldFD && CausesMV && OldFD->isUsed(false))
9631     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9632 
9633   // Ensure the return type is identical.
9634   if (OldFD) {
9635     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9636     const auto *OldType = cast<FunctionType>(OldQType);
9637     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9638     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9639 
9640     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9641       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9642              << CallingConv;
9643 
9644     QualType OldReturnType = OldType->getReturnType();
9645 
9646     if (OldReturnType != NewReturnType)
9647       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9648              << ReturnType;
9649 
9650     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9651       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9652              << ConstexprSpec;
9653 
9654     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9655       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9656              << InlineSpec;
9657 
9658     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9659       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9660              << StorageClass;
9661 
9662     if (OldFD->isExternC() != NewFD->isExternC())
9663       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9664              << Linkage;
9665 
9666     if (S.CheckEquivalentExceptionSpec(
9667             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9668             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9669       return true;
9670   }
9671   return false;
9672 }
9673 
9674 /// Check the validity of a multiversion function declaration that is the
9675 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9676 ///
9677 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9678 ///
9679 /// Returns true if there was an error, false otherwise.
9680 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9681                                            MultiVersionKind MVType,
9682                                            const TargetAttr *TA) {
9683   assert(MVType != MultiVersionKind::None &&
9684          "Function lacks multiversion attribute");
9685 
9686   // Target only causes MV if it is default, otherwise this is a normal
9687   // function.
9688   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9689     return false;
9690 
9691   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9692     FD->setInvalidDecl();
9693     return true;
9694   }
9695 
9696   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9697     FD->setInvalidDecl();
9698     return true;
9699   }
9700 
9701   FD->setIsMultiVersion();
9702   return false;
9703 }
9704 
9705 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9706   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9707     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9708       return true;
9709   }
9710 
9711   return false;
9712 }
9713 
9714 static bool CheckTargetCausesMultiVersioning(
9715     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9716     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9717     LookupResult &Previous) {
9718   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9719   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9720   // Sort order doesn't matter, it just needs to be consistent.
9721   llvm::sort(NewParsed.Features);
9722 
9723   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9724   // to change, this is a simple redeclaration.
9725   if (!NewTA->isDefaultVersion() &&
9726       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9727     return false;
9728 
9729   // Otherwise, this decl causes MultiVersioning.
9730   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9731     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9732     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9733     NewFD->setInvalidDecl();
9734     return true;
9735   }
9736 
9737   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9738                                        MultiVersionKind::Target)) {
9739     NewFD->setInvalidDecl();
9740     return true;
9741   }
9742 
9743   if (CheckMultiVersionValue(S, NewFD)) {
9744     NewFD->setInvalidDecl();
9745     return true;
9746   }
9747 
9748   // If this is 'default', permit the forward declaration.
9749   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9750     Redeclaration = true;
9751     OldDecl = OldFD;
9752     OldFD->setIsMultiVersion();
9753     NewFD->setIsMultiVersion();
9754     return false;
9755   }
9756 
9757   if (CheckMultiVersionValue(S, OldFD)) {
9758     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9759     NewFD->setInvalidDecl();
9760     return true;
9761   }
9762 
9763   TargetAttr::ParsedTargetAttr OldParsed =
9764       OldTA->parse(std::less<std::string>());
9765 
9766   if (OldParsed == NewParsed) {
9767     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9768     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9769     NewFD->setInvalidDecl();
9770     return true;
9771   }
9772 
9773   for (const auto *FD : OldFD->redecls()) {
9774     const auto *CurTA = FD->getAttr<TargetAttr>();
9775     // We allow forward declarations before ANY multiversioning attributes, but
9776     // nothing after the fact.
9777     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9778         (!CurTA || CurTA->isInherited())) {
9779       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9780           << 0;
9781       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9782       NewFD->setInvalidDecl();
9783       return true;
9784     }
9785   }
9786 
9787   OldFD->setIsMultiVersion();
9788   NewFD->setIsMultiVersion();
9789   Redeclaration = false;
9790   MergeTypeWithPrevious = false;
9791   OldDecl = nullptr;
9792   Previous.clear();
9793   return false;
9794 }
9795 
9796 /// Check the validity of a new function declaration being added to an existing
9797 /// multiversioned declaration collection.
9798 static bool CheckMultiVersionAdditionalDecl(
9799     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9800     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9801     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9802     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9803     LookupResult &Previous) {
9804 
9805   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9806   // Disallow mixing of multiversioning types.
9807   if ((OldMVType == MultiVersionKind::Target &&
9808        NewMVType != MultiVersionKind::Target) ||
9809       (NewMVType == MultiVersionKind::Target &&
9810        OldMVType != MultiVersionKind::Target)) {
9811     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9812     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9813     NewFD->setInvalidDecl();
9814     return true;
9815   }
9816 
9817   TargetAttr::ParsedTargetAttr NewParsed;
9818   if (NewTA) {
9819     NewParsed = NewTA->parse();
9820     llvm::sort(NewParsed.Features);
9821   }
9822 
9823   bool UseMemberUsingDeclRules =
9824       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9825 
9826   // Next, check ALL non-overloads to see if this is a redeclaration of a
9827   // previous member of the MultiVersion set.
9828   for (NamedDecl *ND : Previous) {
9829     FunctionDecl *CurFD = ND->getAsFunction();
9830     if (!CurFD)
9831       continue;
9832     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9833       continue;
9834 
9835     if (NewMVType == MultiVersionKind::Target) {
9836       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9837       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9838         NewFD->setIsMultiVersion();
9839         Redeclaration = true;
9840         OldDecl = ND;
9841         return false;
9842       }
9843 
9844       TargetAttr::ParsedTargetAttr CurParsed =
9845           CurTA->parse(std::less<std::string>());
9846       if (CurParsed == NewParsed) {
9847         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9848         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9849         NewFD->setInvalidDecl();
9850         return true;
9851       }
9852     } else {
9853       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9854       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9855       // Handle CPUDispatch/CPUSpecific versions.
9856       // Only 1 CPUDispatch function is allowed, this will make it go through
9857       // the redeclaration errors.
9858       if (NewMVType == MultiVersionKind::CPUDispatch &&
9859           CurFD->hasAttr<CPUDispatchAttr>()) {
9860         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9861             std::equal(
9862                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9863                 NewCPUDisp->cpus_begin(),
9864                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9865                   return Cur->getName() == New->getName();
9866                 })) {
9867           NewFD->setIsMultiVersion();
9868           Redeclaration = true;
9869           OldDecl = ND;
9870           return false;
9871         }
9872 
9873         // If the declarations don't match, this is an error condition.
9874         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9875         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9876         NewFD->setInvalidDecl();
9877         return true;
9878       }
9879       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9880 
9881         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9882             std::equal(
9883                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9884                 NewCPUSpec->cpus_begin(),
9885                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9886                   return Cur->getName() == New->getName();
9887                 })) {
9888           NewFD->setIsMultiVersion();
9889           Redeclaration = true;
9890           OldDecl = ND;
9891           return false;
9892         }
9893 
9894         // Only 1 version of CPUSpecific is allowed for each CPU.
9895         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9896           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9897             if (CurII == NewII) {
9898               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9899                   << NewII;
9900               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9901               NewFD->setInvalidDecl();
9902               return true;
9903             }
9904           }
9905         }
9906       }
9907       // If the two decls aren't the same MVType, there is no possible error
9908       // condition.
9909     }
9910   }
9911 
9912   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9913   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9914   // handled in the attribute adding step.
9915   if (NewMVType == MultiVersionKind::Target &&
9916       CheckMultiVersionValue(S, NewFD)) {
9917     NewFD->setInvalidDecl();
9918     return true;
9919   }
9920 
9921   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9922                                        !OldFD->isMultiVersion(), NewMVType)) {
9923     NewFD->setInvalidDecl();
9924     return true;
9925   }
9926 
9927   // Permit forward declarations in the case where these two are compatible.
9928   if (!OldFD->isMultiVersion()) {
9929     OldFD->setIsMultiVersion();
9930     NewFD->setIsMultiVersion();
9931     Redeclaration = true;
9932     OldDecl = OldFD;
9933     return false;
9934   }
9935 
9936   NewFD->setIsMultiVersion();
9937   Redeclaration = false;
9938   MergeTypeWithPrevious = false;
9939   OldDecl = nullptr;
9940   Previous.clear();
9941   return false;
9942 }
9943 
9944 
9945 /// Check the validity of a mulitversion function declaration.
9946 /// Also sets the multiversion'ness' of the function itself.
9947 ///
9948 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9949 ///
9950 /// Returns true if there was an error, false otherwise.
9951 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9952                                       bool &Redeclaration, NamedDecl *&OldDecl,
9953                                       bool &MergeTypeWithPrevious,
9954                                       LookupResult &Previous) {
9955   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9956   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9957   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9958 
9959   // Mixing Multiversioning types is prohibited.
9960   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9961       (NewCPUDisp && NewCPUSpec)) {
9962     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9963     NewFD->setInvalidDecl();
9964     return true;
9965   }
9966 
9967   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9968 
9969   // Main isn't allowed to become a multiversion function, however it IS
9970   // permitted to have 'main' be marked with the 'target' optimization hint.
9971   if (NewFD->isMain()) {
9972     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9973         MVType == MultiVersionKind::CPUDispatch ||
9974         MVType == MultiVersionKind::CPUSpecific) {
9975       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9976       NewFD->setInvalidDecl();
9977       return true;
9978     }
9979     return false;
9980   }
9981 
9982   if (!OldDecl || !OldDecl->getAsFunction() ||
9983       OldDecl->getDeclContext()->getRedeclContext() !=
9984           NewFD->getDeclContext()->getRedeclContext()) {
9985     // If there's no previous declaration, AND this isn't attempting to cause
9986     // multiversioning, this isn't an error condition.
9987     if (MVType == MultiVersionKind::None)
9988       return false;
9989     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
9990   }
9991 
9992   FunctionDecl *OldFD = OldDecl->getAsFunction();
9993 
9994   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
9995     return false;
9996 
9997   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
9998     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9999         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10000     NewFD->setInvalidDecl();
10001     return true;
10002   }
10003 
10004   // Handle the target potentially causes multiversioning case.
10005   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10006     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10007                                             Redeclaration, OldDecl,
10008                                             MergeTypeWithPrevious, Previous);
10009 
10010   // At this point, we have a multiversion function decl (in OldFD) AND an
10011   // appropriate attribute in the current function decl.  Resolve that these are
10012   // still compatible with previous declarations.
10013   return CheckMultiVersionAdditionalDecl(
10014       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10015       OldDecl, MergeTypeWithPrevious, Previous);
10016 }
10017 
10018 /// Perform semantic checking of a new function declaration.
10019 ///
10020 /// Performs semantic analysis of the new function declaration
10021 /// NewFD. This routine performs all semantic checking that does not
10022 /// require the actual declarator involved in the declaration, and is
10023 /// used both for the declaration of functions as they are parsed
10024 /// (called via ActOnDeclarator) and for the declaration of functions
10025 /// that have been instantiated via C++ template instantiation (called
10026 /// via InstantiateDecl).
10027 ///
10028 /// \param IsMemberSpecialization whether this new function declaration is
10029 /// a member specialization (that replaces any definition provided by the
10030 /// previous declaration).
10031 ///
10032 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10033 ///
10034 /// \returns true if the function declaration is a redeclaration.
10035 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10036                                     LookupResult &Previous,
10037                                     bool IsMemberSpecialization) {
10038   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10039          "Variably modified return types are not handled here");
10040 
10041   // Determine whether the type of this function should be merged with
10042   // a previous visible declaration. This never happens for functions in C++,
10043   // and always happens in C if the previous declaration was visible.
10044   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10045                                !Previous.isShadowed();
10046 
10047   bool Redeclaration = false;
10048   NamedDecl *OldDecl = nullptr;
10049   bool MayNeedOverloadableChecks = false;
10050 
10051   // Merge or overload the declaration with an existing declaration of
10052   // the same name, if appropriate.
10053   if (!Previous.empty()) {
10054     // Determine whether NewFD is an overload of PrevDecl or
10055     // a declaration that requires merging. If it's an overload,
10056     // there's no more work to do here; we'll just add the new
10057     // function to the scope.
10058     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10059       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10060       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10061         Redeclaration = true;
10062         OldDecl = Candidate;
10063       }
10064     } else {
10065       MayNeedOverloadableChecks = true;
10066       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10067                             /*NewIsUsingDecl*/ false)) {
10068       case Ovl_Match:
10069         Redeclaration = true;
10070         break;
10071 
10072       case Ovl_NonFunction:
10073         Redeclaration = true;
10074         break;
10075 
10076       case Ovl_Overload:
10077         Redeclaration = false;
10078         break;
10079       }
10080     }
10081   }
10082 
10083   // Check for a previous extern "C" declaration with this name.
10084   if (!Redeclaration &&
10085       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10086     if (!Previous.empty()) {
10087       // This is an extern "C" declaration with the same name as a previous
10088       // declaration, and thus redeclares that entity...
10089       Redeclaration = true;
10090       OldDecl = Previous.getFoundDecl();
10091       MergeTypeWithPrevious = false;
10092 
10093       // ... except in the presence of __attribute__((overloadable)).
10094       if (OldDecl->hasAttr<OverloadableAttr>() ||
10095           NewFD->hasAttr<OverloadableAttr>()) {
10096         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10097           MayNeedOverloadableChecks = true;
10098           Redeclaration = false;
10099           OldDecl = nullptr;
10100         }
10101       }
10102     }
10103   }
10104 
10105   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10106                                 MergeTypeWithPrevious, Previous))
10107     return Redeclaration;
10108 
10109   // C++11 [dcl.constexpr]p8:
10110   //   A constexpr specifier for a non-static member function that is not
10111   //   a constructor declares that member function to be const.
10112   //
10113   // This needs to be delayed until we know whether this is an out-of-line
10114   // definition of a static member function.
10115   //
10116   // This rule is not present in C++1y, so we produce a backwards
10117   // compatibility warning whenever it happens in C++11.
10118   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10119   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10120       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10121       !MD->getMethodQualifiers().hasConst()) {
10122     CXXMethodDecl *OldMD = nullptr;
10123     if (OldDecl)
10124       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10125     if (!OldMD || !OldMD->isStatic()) {
10126       const FunctionProtoType *FPT =
10127         MD->getType()->castAs<FunctionProtoType>();
10128       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10129       EPI.TypeQuals.addConst();
10130       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10131                                           FPT->getParamTypes(), EPI));
10132 
10133       // Warn that we did this, if we're not performing template instantiation.
10134       // In that case, we'll have warned already when the template was defined.
10135       if (!inTemplateInstantiation()) {
10136         SourceLocation AddConstLoc;
10137         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10138                 .IgnoreParens().getAs<FunctionTypeLoc>())
10139           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10140 
10141         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10142           << FixItHint::CreateInsertion(AddConstLoc, " const");
10143       }
10144     }
10145   }
10146 
10147   if (Redeclaration) {
10148     // NewFD and OldDecl represent declarations that need to be
10149     // merged.
10150     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10151       NewFD->setInvalidDecl();
10152       return Redeclaration;
10153     }
10154 
10155     Previous.clear();
10156     Previous.addDecl(OldDecl);
10157 
10158     if (FunctionTemplateDecl *OldTemplateDecl =
10159             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10160       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10161       FunctionTemplateDecl *NewTemplateDecl
10162         = NewFD->getDescribedFunctionTemplate();
10163       assert(NewTemplateDecl && "Template/non-template mismatch");
10164 
10165       // The call to MergeFunctionDecl above may have created some state in
10166       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10167       // can add it as a redeclaration.
10168       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10169 
10170       NewFD->setPreviousDeclaration(OldFD);
10171       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10172       if (NewFD->isCXXClassMember()) {
10173         NewFD->setAccess(OldTemplateDecl->getAccess());
10174         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10175       }
10176 
10177       // If this is an explicit specialization of a member that is a function
10178       // template, mark it as a member specialization.
10179       if (IsMemberSpecialization &&
10180           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10181         NewTemplateDecl->setMemberSpecialization();
10182         assert(OldTemplateDecl->isMemberSpecialization());
10183         // Explicit specializations of a member template do not inherit deleted
10184         // status from the parent member template that they are specializing.
10185         if (OldFD->isDeleted()) {
10186           // FIXME: This assert will not hold in the presence of modules.
10187           assert(OldFD->getCanonicalDecl() == OldFD);
10188           // FIXME: We need an update record for this AST mutation.
10189           OldFD->setDeletedAsWritten(false);
10190         }
10191       }
10192 
10193     } else {
10194       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10195         auto *OldFD = cast<FunctionDecl>(OldDecl);
10196         // This needs to happen first so that 'inline' propagates.
10197         NewFD->setPreviousDeclaration(OldFD);
10198         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10199         if (NewFD->isCXXClassMember())
10200           NewFD->setAccess(OldFD->getAccess());
10201       }
10202     }
10203   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10204              !NewFD->getAttr<OverloadableAttr>()) {
10205     assert((Previous.empty() ||
10206             llvm::any_of(Previous,
10207                          [](const NamedDecl *ND) {
10208                            return ND->hasAttr<OverloadableAttr>();
10209                          })) &&
10210            "Non-redecls shouldn't happen without overloadable present");
10211 
10212     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10213       const auto *FD = dyn_cast<FunctionDecl>(ND);
10214       return FD && !FD->hasAttr<OverloadableAttr>();
10215     });
10216 
10217     if (OtherUnmarkedIter != Previous.end()) {
10218       Diag(NewFD->getLocation(),
10219            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10220       Diag((*OtherUnmarkedIter)->getLocation(),
10221            diag::note_attribute_overloadable_prev_overload)
10222           << false;
10223 
10224       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10225     }
10226   }
10227 
10228   // Semantic checking for this function declaration (in isolation).
10229 
10230   if (getLangOpts().CPlusPlus) {
10231     // C++-specific checks.
10232     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10233       CheckConstructor(Constructor);
10234     } else if (CXXDestructorDecl *Destructor =
10235                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10236       CXXRecordDecl *Record = Destructor->getParent();
10237       QualType ClassType = Context.getTypeDeclType(Record);
10238 
10239       // FIXME: Shouldn't we be able to perform this check even when the class
10240       // type is dependent? Both gcc and edg can handle that.
10241       if (!ClassType->isDependentType()) {
10242         DeclarationName Name
10243           = Context.DeclarationNames.getCXXDestructorName(
10244                                         Context.getCanonicalType(ClassType));
10245         if (NewFD->getDeclName() != Name) {
10246           Diag(NewFD->getLocation(), diag::err_destructor_name);
10247           NewFD->setInvalidDecl();
10248           return Redeclaration;
10249         }
10250       }
10251     } else if (CXXConversionDecl *Conversion
10252                = dyn_cast<CXXConversionDecl>(NewFD)) {
10253       ActOnConversionDeclarator(Conversion);
10254     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10255       if (auto *TD = Guide->getDescribedFunctionTemplate())
10256         CheckDeductionGuideTemplate(TD);
10257 
10258       // A deduction guide is not on the list of entities that can be
10259       // explicitly specialized.
10260       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10261         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10262             << /*explicit specialization*/ 1;
10263     }
10264 
10265     // Find any virtual functions that this function overrides.
10266     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10267       if (!Method->isFunctionTemplateSpecialization() &&
10268           !Method->getDescribedFunctionTemplate() &&
10269           Method->isCanonicalDecl()) {
10270         if (AddOverriddenMethods(Method->getParent(), Method)) {
10271           // If the function was marked as "static", we have a problem.
10272           if (NewFD->getStorageClass() == SC_Static) {
10273             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10274           }
10275         }
10276       }
10277 
10278       if (Method->isStatic())
10279         checkThisInStaticMemberFunctionType(Method);
10280     }
10281 
10282     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10283     if (NewFD->isOverloadedOperator() &&
10284         CheckOverloadedOperatorDeclaration(NewFD)) {
10285       NewFD->setInvalidDecl();
10286       return Redeclaration;
10287     }
10288 
10289     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10290     if (NewFD->getLiteralIdentifier() &&
10291         CheckLiteralOperatorDeclaration(NewFD)) {
10292       NewFD->setInvalidDecl();
10293       return Redeclaration;
10294     }
10295 
10296     // In C++, check default arguments now that we have merged decls. Unless
10297     // the lexical context is the class, because in this case this is done
10298     // during delayed parsing anyway.
10299     if (!CurContext->isRecord())
10300       CheckCXXDefaultArguments(NewFD);
10301 
10302     // If this function declares a builtin function, check the type of this
10303     // declaration against the expected type for the builtin.
10304     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10305       ASTContext::GetBuiltinTypeError Error;
10306       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10307       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10308       // If the type of the builtin differs only in its exception
10309       // specification, that's OK.
10310       // FIXME: If the types do differ in this way, it would be better to
10311       // retain the 'noexcept' form of the type.
10312       if (!T.isNull() &&
10313           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10314                                                             NewFD->getType()))
10315         // The type of this function differs from the type of the builtin,
10316         // so forget about the builtin entirely.
10317         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10318     }
10319 
10320     // If this function is declared as being extern "C", then check to see if
10321     // the function returns a UDT (class, struct, or union type) that is not C
10322     // compatible, and if it does, warn the user.
10323     // But, issue any diagnostic on the first declaration only.
10324     if (Previous.empty() && NewFD->isExternC()) {
10325       QualType R = NewFD->getReturnType();
10326       if (R->isIncompleteType() && !R->isVoidType())
10327         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10328             << NewFD << R;
10329       else if (!R.isPODType(Context) && !R->isVoidType() &&
10330                !R->isObjCObjectPointerType())
10331         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10332     }
10333 
10334     // C++1z [dcl.fct]p6:
10335     //   [...] whether the function has a non-throwing exception-specification
10336     //   [is] part of the function type
10337     //
10338     // This results in an ABI break between C++14 and C++17 for functions whose
10339     // declared type includes an exception-specification in a parameter or
10340     // return type. (Exception specifications on the function itself are OK in
10341     // most cases, and exception specifications are not permitted in most other
10342     // contexts where they could make it into a mangling.)
10343     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10344       auto HasNoexcept = [&](QualType T) -> bool {
10345         // Strip off declarator chunks that could be between us and a function
10346         // type. We don't need to look far, exception specifications are very
10347         // restricted prior to C++17.
10348         if (auto *RT = T->getAs<ReferenceType>())
10349           T = RT->getPointeeType();
10350         else if (T->isAnyPointerType())
10351           T = T->getPointeeType();
10352         else if (auto *MPT = T->getAs<MemberPointerType>())
10353           T = MPT->getPointeeType();
10354         if (auto *FPT = T->getAs<FunctionProtoType>())
10355           if (FPT->isNothrow())
10356             return true;
10357         return false;
10358       };
10359 
10360       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10361       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10362       for (QualType T : FPT->param_types())
10363         AnyNoexcept |= HasNoexcept(T);
10364       if (AnyNoexcept)
10365         Diag(NewFD->getLocation(),
10366              diag::warn_cxx17_compat_exception_spec_in_signature)
10367             << NewFD;
10368     }
10369 
10370     if (!Redeclaration && LangOpts.CUDA)
10371       checkCUDATargetOverload(NewFD, Previous);
10372   }
10373   return Redeclaration;
10374 }
10375 
10376 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10377   // C++11 [basic.start.main]p3:
10378   //   A program that [...] declares main to be inline, static or
10379   //   constexpr is ill-formed.
10380   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10381   //   appear in a declaration of main.
10382   // static main is not an error under C99, but we should warn about it.
10383   // We accept _Noreturn main as an extension.
10384   if (FD->getStorageClass() == SC_Static)
10385     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10386          ? diag::err_static_main : diag::warn_static_main)
10387       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10388   if (FD->isInlineSpecified())
10389     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10390       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10391   if (DS.isNoreturnSpecified()) {
10392     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10393     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10394     Diag(NoreturnLoc, diag::ext_noreturn_main);
10395     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10396       << FixItHint::CreateRemoval(NoreturnRange);
10397   }
10398   if (FD->isConstexpr()) {
10399     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10400         << FD->isConsteval()
10401         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10402     FD->setConstexprKind(CSK_unspecified);
10403   }
10404 
10405   if (getLangOpts().OpenCL) {
10406     Diag(FD->getLocation(), diag::err_opencl_no_main)
10407         << FD->hasAttr<OpenCLKernelAttr>();
10408     FD->setInvalidDecl();
10409     return;
10410   }
10411 
10412   QualType T = FD->getType();
10413   assert(T->isFunctionType() && "function decl is not of function type");
10414   const FunctionType* FT = T->castAs<FunctionType>();
10415 
10416   // Set default calling convention for main()
10417   if (FT->getCallConv() != CC_C) {
10418     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10419     FD->setType(QualType(FT, 0));
10420     T = Context.getCanonicalType(FD->getType());
10421   }
10422 
10423   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10424     // In C with GNU extensions we allow main() to have non-integer return
10425     // type, but we should warn about the extension, and we disable the
10426     // implicit-return-zero rule.
10427 
10428     // GCC in C mode accepts qualified 'int'.
10429     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10430       FD->setHasImplicitReturnZero(true);
10431     else {
10432       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10433       SourceRange RTRange = FD->getReturnTypeSourceRange();
10434       if (RTRange.isValid())
10435         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10436             << FixItHint::CreateReplacement(RTRange, "int");
10437     }
10438   } else {
10439     // In C and C++, main magically returns 0 if you fall off the end;
10440     // set the flag which tells us that.
10441     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10442 
10443     // All the standards say that main() should return 'int'.
10444     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10445       FD->setHasImplicitReturnZero(true);
10446     else {
10447       // Otherwise, this is just a flat-out error.
10448       SourceRange RTRange = FD->getReturnTypeSourceRange();
10449       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10450           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10451                                 : FixItHint());
10452       FD->setInvalidDecl(true);
10453     }
10454   }
10455 
10456   // Treat protoless main() as nullary.
10457   if (isa<FunctionNoProtoType>(FT)) return;
10458 
10459   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10460   unsigned nparams = FTP->getNumParams();
10461   assert(FD->getNumParams() == nparams);
10462 
10463   bool HasExtraParameters = (nparams > 3);
10464 
10465   if (FTP->isVariadic()) {
10466     Diag(FD->getLocation(), diag::ext_variadic_main);
10467     // FIXME: if we had information about the location of the ellipsis, we
10468     // could add a FixIt hint to remove it as a parameter.
10469   }
10470 
10471   // Darwin passes an undocumented fourth argument of type char**.  If
10472   // other platforms start sprouting these, the logic below will start
10473   // getting shifty.
10474   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10475     HasExtraParameters = false;
10476 
10477   if (HasExtraParameters) {
10478     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10479     FD->setInvalidDecl(true);
10480     nparams = 3;
10481   }
10482 
10483   // FIXME: a lot of the following diagnostics would be improved
10484   // if we had some location information about types.
10485 
10486   QualType CharPP =
10487     Context.getPointerType(Context.getPointerType(Context.CharTy));
10488   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10489 
10490   for (unsigned i = 0; i < nparams; ++i) {
10491     QualType AT = FTP->getParamType(i);
10492 
10493     bool mismatch = true;
10494 
10495     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10496       mismatch = false;
10497     else if (Expected[i] == CharPP) {
10498       // As an extension, the following forms are okay:
10499       //   char const **
10500       //   char const * const *
10501       //   char * const *
10502 
10503       QualifierCollector qs;
10504       const PointerType* PT;
10505       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10506           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10507           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10508                               Context.CharTy)) {
10509         qs.removeConst();
10510         mismatch = !qs.empty();
10511       }
10512     }
10513 
10514     if (mismatch) {
10515       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10516       // TODO: suggest replacing given type with expected type
10517       FD->setInvalidDecl(true);
10518     }
10519   }
10520 
10521   if (nparams == 1 && !FD->isInvalidDecl()) {
10522     Diag(FD->getLocation(), diag::warn_main_one_arg);
10523   }
10524 
10525   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10526     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10527     FD->setInvalidDecl();
10528   }
10529 }
10530 
10531 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10532   QualType T = FD->getType();
10533   assert(T->isFunctionType() && "function decl is not of function type");
10534   const FunctionType *FT = T->castAs<FunctionType>();
10535 
10536   // Set an implicit return of 'zero' if the function can return some integral,
10537   // enumeration, pointer or nullptr type.
10538   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10539       FT->getReturnType()->isAnyPointerType() ||
10540       FT->getReturnType()->isNullPtrType())
10541     // DllMain is exempt because a return value of zero means it failed.
10542     if (FD->getName() != "DllMain")
10543       FD->setHasImplicitReturnZero(true);
10544 
10545   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10546     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10547     FD->setInvalidDecl();
10548   }
10549 }
10550 
10551 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10552   // FIXME: Need strict checking.  In C89, we need to check for
10553   // any assignment, increment, decrement, function-calls, or
10554   // commas outside of a sizeof.  In C99, it's the same list,
10555   // except that the aforementioned are allowed in unevaluated
10556   // expressions.  Everything else falls under the
10557   // "may accept other forms of constant expressions" exception.
10558   // (We never end up here for C++, so the constant expression
10559   // rules there don't matter.)
10560   const Expr *Culprit;
10561   if (Init->isConstantInitializer(Context, false, &Culprit))
10562     return false;
10563   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10564     << Culprit->getSourceRange();
10565   return true;
10566 }
10567 
10568 namespace {
10569   // Visits an initialization expression to see if OrigDecl is evaluated in
10570   // its own initialization and throws a warning if it does.
10571   class SelfReferenceChecker
10572       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10573     Sema &S;
10574     Decl *OrigDecl;
10575     bool isRecordType;
10576     bool isPODType;
10577     bool isReferenceType;
10578 
10579     bool isInitList;
10580     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10581 
10582   public:
10583     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10584 
10585     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10586                                                     S(S), OrigDecl(OrigDecl) {
10587       isPODType = false;
10588       isRecordType = false;
10589       isReferenceType = false;
10590       isInitList = false;
10591       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10592         isPODType = VD->getType().isPODType(S.Context);
10593         isRecordType = VD->getType()->isRecordType();
10594         isReferenceType = VD->getType()->isReferenceType();
10595       }
10596     }
10597 
10598     // For most expressions, just call the visitor.  For initializer lists,
10599     // track the index of the field being initialized since fields are
10600     // initialized in order allowing use of previously initialized fields.
10601     void CheckExpr(Expr *E) {
10602       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10603       if (!InitList) {
10604         Visit(E);
10605         return;
10606       }
10607 
10608       // Track and increment the index here.
10609       isInitList = true;
10610       InitFieldIndex.push_back(0);
10611       for (auto Child : InitList->children()) {
10612         CheckExpr(cast<Expr>(Child));
10613         ++InitFieldIndex.back();
10614       }
10615       InitFieldIndex.pop_back();
10616     }
10617 
10618     // Returns true if MemberExpr is checked and no further checking is needed.
10619     // Returns false if additional checking is required.
10620     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10621       llvm::SmallVector<FieldDecl*, 4> Fields;
10622       Expr *Base = E;
10623       bool ReferenceField = false;
10624 
10625       // Get the field members used.
10626       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10627         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10628         if (!FD)
10629           return false;
10630         Fields.push_back(FD);
10631         if (FD->getType()->isReferenceType())
10632           ReferenceField = true;
10633         Base = ME->getBase()->IgnoreParenImpCasts();
10634       }
10635 
10636       // Keep checking only if the base Decl is the same.
10637       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10638       if (!DRE || DRE->getDecl() != OrigDecl)
10639         return false;
10640 
10641       // A reference field can be bound to an unininitialized field.
10642       if (CheckReference && !ReferenceField)
10643         return true;
10644 
10645       // Convert FieldDecls to their index number.
10646       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10647       for (const FieldDecl *I : llvm::reverse(Fields))
10648         UsedFieldIndex.push_back(I->getFieldIndex());
10649 
10650       // See if a warning is needed by checking the first difference in index
10651       // numbers.  If field being used has index less than the field being
10652       // initialized, then the use is safe.
10653       for (auto UsedIter = UsedFieldIndex.begin(),
10654                 UsedEnd = UsedFieldIndex.end(),
10655                 OrigIter = InitFieldIndex.begin(),
10656                 OrigEnd = InitFieldIndex.end();
10657            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10658         if (*UsedIter < *OrigIter)
10659           return true;
10660         if (*UsedIter > *OrigIter)
10661           break;
10662       }
10663 
10664       // TODO: Add a different warning which will print the field names.
10665       HandleDeclRefExpr(DRE);
10666       return true;
10667     }
10668 
10669     // For most expressions, the cast is directly above the DeclRefExpr.
10670     // For conditional operators, the cast can be outside the conditional
10671     // operator if both expressions are DeclRefExpr's.
10672     void HandleValue(Expr *E) {
10673       E = E->IgnoreParens();
10674       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10675         HandleDeclRefExpr(DRE);
10676         return;
10677       }
10678 
10679       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10680         Visit(CO->getCond());
10681         HandleValue(CO->getTrueExpr());
10682         HandleValue(CO->getFalseExpr());
10683         return;
10684       }
10685 
10686       if (BinaryConditionalOperator *BCO =
10687               dyn_cast<BinaryConditionalOperator>(E)) {
10688         Visit(BCO->getCond());
10689         HandleValue(BCO->getFalseExpr());
10690         return;
10691       }
10692 
10693       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10694         HandleValue(OVE->getSourceExpr());
10695         return;
10696       }
10697 
10698       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10699         if (BO->getOpcode() == BO_Comma) {
10700           Visit(BO->getLHS());
10701           HandleValue(BO->getRHS());
10702           return;
10703         }
10704       }
10705 
10706       if (isa<MemberExpr>(E)) {
10707         if (isInitList) {
10708           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10709                                       false /*CheckReference*/))
10710             return;
10711         }
10712 
10713         Expr *Base = E->IgnoreParenImpCasts();
10714         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10715           // Check for static member variables and don't warn on them.
10716           if (!isa<FieldDecl>(ME->getMemberDecl()))
10717             return;
10718           Base = ME->getBase()->IgnoreParenImpCasts();
10719         }
10720         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10721           HandleDeclRefExpr(DRE);
10722         return;
10723       }
10724 
10725       Visit(E);
10726     }
10727 
10728     // Reference types not handled in HandleValue are handled here since all
10729     // uses of references are bad, not just r-value uses.
10730     void VisitDeclRefExpr(DeclRefExpr *E) {
10731       if (isReferenceType)
10732         HandleDeclRefExpr(E);
10733     }
10734 
10735     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10736       if (E->getCastKind() == CK_LValueToRValue) {
10737         HandleValue(E->getSubExpr());
10738         return;
10739       }
10740 
10741       Inherited::VisitImplicitCastExpr(E);
10742     }
10743 
10744     void VisitMemberExpr(MemberExpr *E) {
10745       if (isInitList) {
10746         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10747           return;
10748       }
10749 
10750       // Don't warn on arrays since they can be treated as pointers.
10751       if (E->getType()->canDecayToPointerType()) return;
10752 
10753       // Warn when a non-static method call is followed by non-static member
10754       // field accesses, which is followed by a DeclRefExpr.
10755       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10756       bool Warn = (MD && !MD->isStatic());
10757       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10758       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10759         if (!isa<FieldDecl>(ME->getMemberDecl()))
10760           Warn = false;
10761         Base = ME->getBase()->IgnoreParenImpCasts();
10762       }
10763 
10764       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10765         if (Warn)
10766           HandleDeclRefExpr(DRE);
10767         return;
10768       }
10769 
10770       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10771       // Visit that expression.
10772       Visit(Base);
10773     }
10774 
10775     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10776       Expr *Callee = E->getCallee();
10777 
10778       if (isa<UnresolvedLookupExpr>(Callee))
10779         return Inherited::VisitCXXOperatorCallExpr(E);
10780 
10781       Visit(Callee);
10782       for (auto Arg: E->arguments())
10783         HandleValue(Arg->IgnoreParenImpCasts());
10784     }
10785 
10786     void VisitUnaryOperator(UnaryOperator *E) {
10787       // For POD record types, addresses of its own members are well-defined.
10788       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10789           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10790         if (!isPODType)
10791           HandleValue(E->getSubExpr());
10792         return;
10793       }
10794 
10795       if (E->isIncrementDecrementOp()) {
10796         HandleValue(E->getSubExpr());
10797         return;
10798       }
10799 
10800       Inherited::VisitUnaryOperator(E);
10801     }
10802 
10803     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10804 
10805     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10806       if (E->getConstructor()->isCopyConstructor()) {
10807         Expr *ArgExpr = E->getArg(0);
10808         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10809           if (ILE->getNumInits() == 1)
10810             ArgExpr = ILE->getInit(0);
10811         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10812           if (ICE->getCastKind() == CK_NoOp)
10813             ArgExpr = ICE->getSubExpr();
10814         HandleValue(ArgExpr);
10815         return;
10816       }
10817       Inherited::VisitCXXConstructExpr(E);
10818     }
10819 
10820     void VisitCallExpr(CallExpr *E) {
10821       // Treat std::move as a use.
10822       if (E->isCallToStdMove()) {
10823         HandleValue(E->getArg(0));
10824         return;
10825       }
10826 
10827       Inherited::VisitCallExpr(E);
10828     }
10829 
10830     void VisitBinaryOperator(BinaryOperator *E) {
10831       if (E->isCompoundAssignmentOp()) {
10832         HandleValue(E->getLHS());
10833         Visit(E->getRHS());
10834         return;
10835       }
10836 
10837       Inherited::VisitBinaryOperator(E);
10838     }
10839 
10840     // A custom visitor for BinaryConditionalOperator is needed because the
10841     // regular visitor would check the condition and true expression separately
10842     // but both point to the same place giving duplicate diagnostics.
10843     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10844       Visit(E->getCond());
10845       Visit(E->getFalseExpr());
10846     }
10847 
10848     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10849       Decl* ReferenceDecl = DRE->getDecl();
10850       if (OrigDecl != ReferenceDecl) return;
10851       unsigned diag;
10852       if (isReferenceType) {
10853         diag = diag::warn_uninit_self_reference_in_reference_init;
10854       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10855         diag = diag::warn_static_self_reference_in_init;
10856       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10857                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10858                  DRE->getDecl()->getType()->isRecordType()) {
10859         diag = diag::warn_uninit_self_reference_in_init;
10860       } else {
10861         // Local variables will be handled by the CFG analysis.
10862         return;
10863       }
10864 
10865       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10866                             S.PDiag(diag)
10867                                 << DRE->getDecl() << OrigDecl->getLocation()
10868                                 << DRE->getSourceRange());
10869     }
10870   };
10871 
10872   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10873   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10874                                  bool DirectInit) {
10875     // Parameters arguments are occassionially constructed with itself,
10876     // for instance, in recursive functions.  Skip them.
10877     if (isa<ParmVarDecl>(OrigDecl))
10878       return;
10879 
10880     E = E->IgnoreParens();
10881 
10882     // Skip checking T a = a where T is not a record or reference type.
10883     // Doing so is a way to silence uninitialized warnings.
10884     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10885       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10886         if (ICE->getCastKind() == CK_LValueToRValue)
10887           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10888             if (DRE->getDecl() == OrigDecl)
10889               return;
10890 
10891     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10892   }
10893 } // end anonymous namespace
10894 
10895 namespace {
10896   // Simple wrapper to add the name of a variable or (if no variable is
10897   // available) a DeclarationName into a diagnostic.
10898   struct VarDeclOrName {
10899     VarDecl *VDecl;
10900     DeclarationName Name;
10901 
10902     friend const Sema::SemaDiagnosticBuilder &
10903     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10904       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10905     }
10906   };
10907 } // end anonymous namespace
10908 
10909 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10910                                             DeclarationName Name, QualType Type,
10911                                             TypeSourceInfo *TSI,
10912                                             SourceRange Range, bool DirectInit,
10913                                             Expr *Init) {
10914   bool IsInitCapture = !VDecl;
10915   assert((!VDecl || !VDecl->isInitCapture()) &&
10916          "init captures are expected to be deduced prior to initialization");
10917 
10918   VarDeclOrName VN{VDecl, Name};
10919 
10920   DeducedType *Deduced = Type->getContainedDeducedType();
10921   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10922 
10923   // C++11 [dcl.spec.auto]p3
10924   if (!Init) {
10925     assert(VDecl && "no init for init capture deduction?");
10926 
10927     // Except for class argument deduction, and then for an initializing
10928     // declaration only, i.e. no static at class scope or extern.
10929     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10930         VDecl->hasExternalStorage() ||
10931         VDecl->isStaticDataMember()) {
10932       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10933         << VDecl->getDeclName() << Type;
10934       return QualType();
10935     }
10936   }
10937 
10938   ArrayRef<Expr*> DeduceInits;
10939   if (Init)
10940     DeduceInits = Init;
10941 
10942   if (DirectInit) {
10943     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10944       DeduceInits = PL->exprs();
10945   }
10946 
10947   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10948     assert(VDecl && "non-auto type for init capture deduction?");
10949     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10950     InitializationKind Kind = InitializationKind::CreateForInit(
10951         VDecl->getLocation(), DirectInit, Init);
10952     // FIXME: Initialization should not be taking a mutable list of inits.
10953     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10954     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10955                                                        InitsCopy);
10956   }
10957 
10958   if (DirectInit) {
10959     if (auto *IL = dyn_cast<InitListExpr>(Init))
10960       DeduceInits = IL->inits();
10961   }
10962 
10963   // Deduction only works if we have exactly one source expression.
10964   if (DeduceInits.empty()) {
10965     // It isn't possible to write this directly, but it is possible to
10966     // end up in this situation with "auto x(some_pack...);"
10967     Diag(Init->getBeginLoc(), IsInitCapture
10968                                   ? diag::err_init_capture_no_expression
10969                                   : diag::err_auto_var_init_no_expression)
10970         << VN << Type << Range;
10971     return QualType();
10972   }
10973 
10974   if (DeduceInits.size() > 1) {
10975     Diag(DeduceInits[1]->getBeginLoc(),
10976          IsInitCapture ? diag::err_init_capture_multiple_expressions
10977                        : diag::err_auto_var_init_multiple_expressions)
10978         << VN << Type << Range;
10979     return QualType();
10980   }
10981 
10982   Expr *DeduceInit = DeduceInits[0];
10983   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10984     Diag(Init->getBeginLoc(), IsInitCapture
10985                                   ? diag::err_init_capture_paren_braces
10986                                   : diag::err_auto_var_init_paren_braces)
10987         << isa<InitListExpr>(Init) << VN << Type << Range;
10988     return QualType();
10989   }
10990 
10991   // Expressions default to 'id' when we're in a debugger.
10992   bool DefaultedAnyToId = false;
10993   if (getLangOpts().DebuggerCastResultToId &&
10994       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10995     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10996     if (Result.isInvalid()) {
10997       return QualType();
10998     }
10999     Init = Result.get();
11000     DefaultedAnyToId = true;
11001   }
11002 
11003   // C++ [dcl.decomp]p1:
11004   //   If the assignment-expression [...] has array type A and no ref-qualifier
11005   //   is present, e has type cv A
11006   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11007       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11008       DeduceInit->getType()->isConstantArrayType())
11009     return Context.getQualifiedType(DeduceInit->getType(),
11010                                     Type.getQualifiers());
11011 
11012   QualType DeducedType;
11013   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11014     if (!IsInitCapture)
11015       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11016     else if (isa<InitListExpr>(Init))
11017       Diag(Range.getBegin(),
11018            diag::err_init_capture_deduction_failure_from_init_list)
11019           << VN
11020           << (DeduceInit->getType().isNull() ? TSI->getType()
11021                                              : DeduceInit->getType())
11022           << DeduceInit->getSourceRange();
11023     else
11024       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11025           << VN << TSI->getType()
11026           << (DeduceInit->getType().isNull() ? TSI->getType()
11027                                              : DeduceInit->getType())
11028           << DeduceInit->getSourceRange();
11029   }
11030 
11031   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11032   // 'id' instead of a specific object type prevents most of our usual
11033   // checks.
11034   // We only want to warn outside of template instantiations, though:
11035   // inside a template, the 'id' could have come from a parameter.
11036   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11037       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11038     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11039     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11040   }
11041 
11042   return DeducedType;
11043 }
11044 
11045 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11046                                          Expr *Init) {
11047   QualType DeducedType = deduceVarTypeFromInitializer(
11048       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11049       VDecl->getSourceRange(), DirectInit, Init);
11050   if (DeducedType.isNull()) {
11051     VDecl->setInvalidDecl();
11052     return true;
11053   }
11054 
11055   VDecl->setType(DeducedType);
11056   assert(VDecl->isLinkageValid());
11057 
11058   // In ARC, infer lifetime.
11059   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11060     VDecl->setInvalidDecl();
11061 
11062   // If this is a redeclaration, check that the type we just deduced matches
11063   // the previously declared type.
11064   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11065     // We never need to merge the type, because we cannot form an incomplete
11066     // array of auto, nor deduce such a type.
11067     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11068   }
11069 
11070   // Check the deduced type is valid for a variable declaration.
11071   CheckVariableDeclarationType(VDecl);
11072   return VDecl->isInvalidDecl();
11073 }
11074 
11075 /// AddInitializerToDecl - Adds the initializer Init to the
11076 /// declaration dcl. If DirectInit is true, this is C++ direct
11077 /// initialization rather than copy initialization.
11078 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11079   // If there is no declaration, there was an error parsing it.  Just ignore
11080   // the initializer.
11081   if (!RealDecl || RealDecl->isInvalidDecl()) {
11082     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11083     return;
11084   }
11085 
11086   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11087     // Pure-specifiers are handled in ActOnPureSpecifier.
11088     Diag(Method->getLocation(), diag::err_member_function_initialization)
11089       << Method->getDeclName() << Init->getSourceRange();
11090     Method->setInvalidDecl();
11091     return;
11092   }
11093 
11094   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11095   if (!VDecl) {
11096     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11097     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11098     RealDecl->setInvalidDecl();
11099     return;
11100   }
11101 
11102   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11103   if (VDecl->getType()->isUndeducedType()) {
11104     // Attempt typo correction early so that the type of the init expression can
11105     // be deduced based on the chosen correction if the original init contains a
11106     // TypoExpr.
11107     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11108     if (!Res.isUsable()) {
11109       RealDecl->setInvalidDecl();
11110       return;
11111     }
11112     Init = Res.get();
11113 
11114     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11115       return;
11116   }
11117 
11118   // dllimport cannot be used on variable definitions.
11119   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11120     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11121     VDecl->setInvalidDecl();
11122     return;
11123   }
11124 
11125   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11126     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11127     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11128     VDecl->setInvalidDecl();
11129     return;
11130   }
11131 
11132   if (!VDecl->getType()->isDependentType()) {
11133     // A definition must end up with a complete type, which means it must be
11134     // complete with the restriction that an array type might be completed by
11135     // the initializer; note that later code assumes this restriction.
11136     QualType BaseDeclType = VDecl->getType();
11137     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11138       BaseDeclType = Array->getElementType();
11139     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11140                             diag::err_typecheck_decl_incomplete_type)) {
11141       RealDecl->setInvalidDecl();
11142       return;
11143     }
11144 
11145     // The variable can not have an abstract class type.
11146     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11147                                diag::err_abstract_type_in_decl,
11148                                AbstractVariableType))
11149       VDecl->setInvalidDecl();
11150   }
11151 
11152   // If adding the initializer will turn this declaration into a definition,
11153   // and we already have a definition for this variable, diagnose or otherwise
11154   // handle the situation.
11155   VarDecl *Def;
11156   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11157       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11158       !VDecl->isThisDeclarationADemotedDefinition() &&
11159       checkVarDeclRedefinition(Def, VDecl))
11160     return;
11161 
11162   if (getLangOpts().CPlusPlus) {
11163     // C++ [class.static.data]p4
11164     //   If a static data member is of const integral or const
11165     //   enumeration type, its declaration in the class definition can
11166     //   specify a constant-initializer which shall be an integral
11167     //   constant expression (5.19). In that case, the member can appear
11168     //   in integral constant expressions. The member shall still be
11169     //   defined in a namespace scope if it is used in the program and the
11170     //   namespace scope definition shall not contain an initializer.
11171     //
11172     // We already performed a redefinition check above, but for static
11173     // data members we also need to check whether there was an in-class
11174     // declaration with an initializer.
11175     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11176       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11177           << VDecl->getDeclName();
11178       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11179            diag::note_previous_initializer)
11180           << 0;
11181       return;
11182     }
11183 
11184     if (VDecl->hasLocalStorage())
11185       setFunctionHasBranchProtectedScope();
11186 
11187     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11188       VDecl->setInvalidDecl();
11189       return;
11190     }
11191   }
11192 
11193   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11194   // a kernel function cannot be initialized."
11195   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11196     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11197     VDecl->setInvalidDecl();
11198     return;
11199   }
11200 
11201   // Get the decls type and save a reference for later, since
11202   // CheckInitializerTypes may change it.
11203   QualType DclT = VDecl->getType(), SavT = DclT;
11204 
11205   // Expressions default to 'id' when we're in a debugger
11206   // and we are assigning it to a variable of Objective-C pointer type.
11207   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11208       Init->getType() == Context.UnknownAnyTy) {
11209     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11210     if (Result.isInvalid()) {
11211       VDecl->setInvalidDecl();
11212       return;
11213     }
11214     Init = Result.get();
11215   }
11216 
11217   // Perform the initialization.
11218   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11219   if (!VDecl->isInvalidDecl()) {
11220     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11221     InitializationKind Kind = InitializationKind::CreateForInit(
11222         VDecl->getLocation(), DirectInit, Init);
11223 
11224     MultiExprArg Args = Init;
11225     if (CXXDirectInit)
11226       Args = MultiExprArg(CXXDirectInit->getExprs(),
11227                           CXXDirectInit->getNumExprs());
11228 
11229     // Try to correct any TypoExprs in the initialization arguments.
11230     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11231       ExprResult Res = CorrectDelayedTyposInExpr(
11232           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11233             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11234             return Init.Failed() ? ExprError() : E;
11235           });
11236       if (Res.isInvalid()) {
11237         VDecl->setInvalidDecl();
11238       } else if (Res.get() != Args[Idx]) {
11239         Args[Idx] = Res.get();
11240       }
11241     }
11242     if (VDecl->isInvalidDecl())
11243       return;
11244 
11245     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11246                                    /*TopLevelOfInitList=*/false,
11247                                    /*TreatUnavailableAsInvalid=*/false);
11248     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11249     if (Result.isInvalid()) {
11250       VDecl->setInvalidDecl();
11251       return;
11252     }
11253 
11254     Init = Result.getAs<Expr>();
11255   }
11256 
11257   // Check for self-references within variable initializers.
11258   // Variables declared within a function/method body (except for references)
11259   // are handled by a dataflow analysis.
11260   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11261       VDecl->getType()->isReferenceType()) {
11262     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11263   }
11264 
11265   // If the type changed, it means we had an incomplete type that was
11266   // completed by the initializer. For example:
11267   //   int ary[] = { 1, 3, 5 };
11268   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11269   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11270     VDecl->setType(DclT);
11271 
11272   if (!VDecl->isInvalidDecl()) {
11273     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11274 
11275     if (VDecl->hasAttr<BlocksAttr>())
11276       checkRetainCycles(VDecl, Init);
11277 
11278     // It is safe to assign a weak reference into a strong variable.
11279     // Although this code can still have problems:
11280     //   id x = self.weakProp;
11281     //   id y = self.weakProp;
11282     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11283     // paths through the function. This should be revisited if
11284     // -Wrepeated-use-of-weak is made flow-sensitive.
11285     if (FunctionScopeInfo *FSI = getCurFunction())
11286       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11287            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11288           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11289                            Init->getBeginLoc()))
11290         FSI->markSafeWeakUse(Init);
11291   }
11292 
11293   // The initialization is usually a full-expression.
11294   //
11295   // FIXME: If this is a braced initialization of an aggregate, it is not
11296   // an expression, and each individual field initializer is a separate
11297   // full-expression. For instance, in:
11298   //
11299   //   struct Temp { ~Temp(); };
11300   //   struct S { S(Temp); };
11301   //   struct T { S a, b; } t = { Temp(), Temp() }
11302   //
11303   // we should destroy the first Temp before constructing the second.
11304   ExprResult Result =
11305       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11306                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11307   if (Result.isInvalid()) {
11308     VDecl->setInvalidDecl();
11309     return;
11310   }
11311   Init = Result.get();
11312 
11313   // Attach the initializer to the decl.
11314   VDecl->setInit(Init);
11315 
11316   if (VDecl->isLocalVarDecl()) {
11317     // Don't check the initializer if the declaration is malformed.
11318     if (VDecl->isInvalidDecl()) {
11319       // do nothing
11320 
11321     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11322     // This is true even in C++ for OpenCL.
11323     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11324       CheckForConstantInitializer(Init, DclT);
11325 
11326     // Otherwise, C++ does not restrict the initializer.
11327     } else if (getLangOpts().CPlusPlus) {
11328       // do nothing
11329 
11330     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11331     // static storage duration shall be constant expressions or string literals.
11332     } else if (VDecl->getStorageClass() == SC_Static) {
11333       CheckForConstantInitializer(Init, DclT);
11334 
11335     // C89 is stricter than C99 for aggregate initializers.
11336     // C89 6.5.7p3: All the expressions [...] in an initializer list
11337     // for an object that has aggregate or union type shall be
11338     // constant expressions.
11339     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11340                isa<InitListExpr>(Init)) {
11341       const Expr *Culprit;
11342       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11343         Diag(Culprit->getExprLoc(),
11344              diag::ext_aggregate_init_not_constant)
11345           << Culprit->getSourceRange();
11346       }
11347     }
11348 
11349     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11350       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11351         if (VDecl->hasLocalStorage())
11352           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11353   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11354              VDecl->getLexicalDeclContext()->isRecord()) {
11355     // This is an in-class initialization for a static data member, e.g.,
11356     //
11357     // struct S {
11358     //   static const int value = 17;
11359     // };
11360 
11361     // C++ [class.mem]p4:
11362     //   A member-declarator can contain a constant-initializer only
11363     //   if it declares a static member (9.4) of const integral or
11364     //   const enumeration type, see 9.4.2.
11365     //
11366     // C++11 [class.static.data]p3:
11367     //   If a non-volatile non-inline const static data member is of integral
11368     //   or enumeration type, its declaration in the class definition can
11369     //   specify a brace-or-equal-initializer in which every initializer-clause
11370     //   that is an assignment-expression is a constant expression. A static
11371     //   data member of literal type can be declared in the class definition
11372     //   with the constexpr specifier; if so, its declaration shall specify a
11373     //   brace-or-equal-initializer in which every initializer-clause that is
11374     //   an assignment-expression is a constant expression.
11375 
11376     // Do nothing on dependent types.
11377     if (DclT->isDependentType()) {
11378 
11379     // Allow any 'static constexpr' members, whether or not they are of literal
11380     // type. We separately check that every constexpr variable is of literal
11381     // type.
11382     } else if (VDecl->isConstexpr()) {
11383 
11384     // Require constness.
11385     } else if (!DclT.isConstQualified()) {
11386       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11387         << Init->getSourceRange();
11388       VDecl->setInvalidDecl();
11389 
11390     // We allow integer constant expressions in all cases.
11391     } else if (DclT->isIntegralOrEnumerationType()) {
11392       // Check whether the expression is a constant expression.
11393       SourceLocation Loc;
11394       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11395         // In C++11, a non-constexpr const static data member with an
11396         // in-class initializer cannot be volatile.
11397         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11398       else if (Init->isValueDependent())
11399         ; // Nothing to check.
11400       else if (Init->isIntegerConstantExpr(Context, &Loc))
11401         ; // Ok, it's an ICE!
11402       else if (Init->getType()->isScopedEnumeralType() &&
11403                Init->isCXX11ConstantExpr(Context))
11404         ; // Ok, it is a scoped-enum constant expression.
11405       else if (Init->isEvaluatable(Context)) {
11406         // If we can constant fold the initializer through heroics, accept it,
11407         // but report this as a use of an extension for -pedantic.
11408         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11409           << Init->getSourceRange();
11410       } else {
11411         // Otherwise, this is some crazy unknown case.  Report the issue at the
11412         // location provided by the isIntegerConstantExpr failed check.
11413         Diag(Loc, diag::err_in_class_initializer_non_constant)
11414           << Init->getSourceRange();
11415         VDecl->setInvalidDecl();
11416       }
11417 
11418     // We allow foldable floating-point constants as an extension.
11419     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11420       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11421       // it anyway and provide a fixit to add the 'constexpr'.
11422       if (getLangOpts().CPlusPlus11) {
11423         Diag(VDecl->getLocation(),
11424              diag::ext_in_class_initializer_float_type_cxx11)
11425             << DclT << Init->getSourceRange();
11426         Diag(VDecl->getBeginLoc(),
11427              diag::note_in_class_initializer_float_type_cxx11)
11428             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11429       } else {
11430         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11431           << DclT << Init->getSourceRange();
11432 
11433         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11434           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11435             << Init->getSourceRange();
11436           VDecl->setInvalidDecl();
11437         }
11438       }
11439 
11440     // Suggest adding 'constexpr' in C++11 for literal types.
11441     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11442       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11443           << DclT << Init->getSourceRange()
11444           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11445       VDecl->setConstexpr(true);
11446 
11447     } else {
11448       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11449         << DclT << Init->getSourceRange();
11450       VDecl->setInvalidDecl();
11451     }
11452   } else if (VDecl->isFileVarDecl()) {
11453     // In C, extern is typically used to avoid tentative definitions when
11454     // declaring variables in headers, but adding an intializer makes it a
11455     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11456     // In C++, extern is often used to give implictly static const variables
11457     // external linkage, so don't warn in that case. If selectany is present,
11458     // this might be header code intended for C and C++ inclusion, so apply the
11459     // C++ rules.
11460     if (VDecl->getStorageClass() == SC_Extern &&
11461         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11462          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11463         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11464         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11465       Diag(VDecl->getLocation(), diag::warn_extern_init);
11466 
11467     // In Microsoft C++ mode, a const variable defined in namespace scope has
11468     // external linkage by default if the variable is declared with
11469     // __declspec(dllexport).
11470     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11471         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11472         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11473       VDecl->setStorageClass(SC_Extern);
11474 
11475     // C99 6.7.8p4. All file scoped initializers need to be constant.
11476     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11477       CheckForConstantInitializer(Init, DclT);
11478   }
11479 
11480   // We will represent direct-initialization similarly to copy-initialization:
11481   //    int x(1);  -as-> int x = 1;
11482   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11483   //
11484   // Clients that want to distinguish between the two forms, can check for
11485   // direct initializer using VarDecl::getInitStyle().
11486   // A major benefit is that clients that don't particularly care about which
11487   // exactly form was it (like the CodeGen) can handle both cases without
11488   // special case code.
11489 
11490   // C++ 8.5p11:
11491   // The form of initialization (using parentheses or '=') is generally
11492   // insignificant, but does matter when the entity being initialized has a
11493   // class type.
11494   if (CXXDirectInit) {
11495     assert(DirectInit && "Call-style initializer must be direct init.");
11496     VDecl->setInitStyle(VarDecl::CallInit);
11497   } else if (DirectInit) {
11498     // This must be list-initialization. No other way is direct-initialization.
11499     VDecl->setInitStyle(VarDecl::ListInit);
11500   }
11501 
11502   CheckCompleteVariableDeclaration(VDecl);
11503 }
11504 
11505 /// ActOnInitializerError - Given that there was an error parsing an
11506 /// initializer for the given declaration, try to return to some form
11507 /// of sanity.
11508 void Sema::ActOnInitializerError(Decl *D) {
11509   // Our main concern here is re-establishing invariants like "a
11510   // variable's type is either dependent or complete".
11511   if (!D || D->isInvalidDecl()) return;
11512 
11513   VarDecl *VD = dyn_cast<VarDecl>(D);
11514   if (!VD) return;
11515 
11516   // Bindings are not usable if we can't make sense of the initializer.
11517   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11518     for (auto *BD : DD->bindings())
11519       BD->setInvalidDecl();
11520 
11521   // Auto types are meaningless if we can't make sense of the initializer.
11522   if (ParsingInitForAutoVars.count(D)) {
11523     D->setInvalidDecl();
11524     return;
11525   }
11526 
11527   QualType Ty = VD->getType();
11528   if (Ty->isDependentType()) return;
11529 
11530   // Require a complete type.
11531   if (RequireCompleteType(VD->getLocation(),
11532                           Context.getBaseElementType(Ty),
11533                           diag::err_typecheck_decl_incomplete_type)) {
11534     VD->setInvalidDecl();
11535     return;
11536   }
11537 
11538   // Require a non-abstract type.
11539   if (RequireNonAbstractType(VD->getLocation(), Ty,
11540                              diag::err_abstract_type_in_decl,
11541                              AbstractVariableType)) {
11542     VD->setInvalidDecl();
11543     return;
11544   }
11545 
11546   // Don't bother complaining about constructors or destructors,
11547   // though.
11548 }
11549 
11550 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11551   // If there is no declaration, there was an error parsing it. Just ignore it.
11552   if (!RealDecl)
11553     return;
11554 
11555   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11556     QualType Type = Var->getType();
11557 
11558     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11559     if (isa<DecompositionDecl>(RealDecl)) {
11560       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11561       Var->setInvalidDecl();
11562       return;
11563     }
11564 
11565     if (Type->isUndeducedType() &&
11566         DeduceVariableDeclarationType(Var, false, nullptr))
11567       return;
11568 
11569     // C++11 [class.static.data]p3: A static data member can be declared with
11570     // the constexpr specifier; if so, its declaration shall specify
11571     // a brace-or-equal-initializer.
11572     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11573     // the definition of a variable [...] or the declaration of a static data
11574     // member.
11575     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11576         !Var->isThisDeclarationADemotedDefinition()) {
11577       if (Var->isStaticDataMember()) {
11578         // C++1z removes the relevant rule; the in-class declaration is always
11579         // a definition there.
11580         if (!getLangOpts().CPlusPlus17) {
11581           Diag(Var->getLocation(),
11582                diag::err_constexpr_static_mem_var_requires_init)
11583             << Var->getDeclName();
11584           Var->setInvalidDecl();
11585           return;
11586         }
11587       } else {
11588         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11589         Var->setInvalidDecl();
11590         return;
11591       }
11592     }
11593 
11594     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11595     // be initialized.
11596     if (!Var->isInvalidDecl() &&
11597         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11598         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11599       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11600       Var->setInvalidDecl();
11601       return;
11602     }
11603 
11604     switch (Var->isThisDeclarationADefinition()) {
11605     case VarDecl::Definition:
11606       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11607         break;
11608 
11609       // We have an out-of-line definition of a static data member
11610       // that has an in-class initializer, so we type-check this like
11611       // a declaration.
11612       //
11613       LLVM_FALLTHROUGH;
11614 
11615     case VarDecl::DeclarationOnly:
11616       // It's only a declaration.
11617 
11618       // Block scope. C99 6.7p7: If an identifier for an object is
11619       // declared with no linkage (C99 6.2.2p6), the type for the
11620       // object shall be complete.
11621       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11622           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11623           RequireCompleteType(Var->getLocation(), Type,
11624                               diag::err_typecheck_decl_incomplete_type))
11625         Var->setInvalidDecl();
11626 
11627       // Make sure that the type is not abstract.
11628       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11629           RequireNonAbstractType(Var->getLocation(), Type,
11630                                  diag::err_abstract_type_in_decl,
11631                                  AbstractVariableType))
11632         Var->setInvalidDecl();
11633       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11634           Var->getStorageClass() == SC_PrivateExtern) {
11635         Diag(Var->getLocation(), diag::warn_private_extern);
11636         Diag(Var->getLocation(), diag::note_private_extern);
11637       }
11638 
11639       return;
11640 
11641     case VarDecl::TentativeDefinition:
11642       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11643       // object that has file scope without an initializer, and without a
11644       // storage-class specifier or with the storage-class specifier "static",
11645       // constitutes a tentative definition. Note: A tentative definition with
11646       // external linkage is valid (C99 6.2.2p5).
11647       if (!Var->isInvalidDecl()) {
11648         if (const IncompleteArrayType *ArrayT
11649                                     = Context.getAsIncompleteArrayType(Type)) {
11650           if (RequireCompleteType(Var->getLocation(),
11651                                   ArrayT->getElementType(),
11652                                   diag::err_illegal_decl_array_incomplete_type))
11653             Var->setInvalidDecl();
11654         } else if (Var->getStorageClass() == SC_Static) {
11655           // C99 6.9.2p3: If the declaration of an identifier for an object is
11656           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11657           // declared type shall not be an incomplete type.
11658           // NOTE: code such as the following
11659           //     static struct s;
11660           //     struct s { int a; };
11661           // is accepted by gcc. Hence here we issue a warning instead of
11662           // an error and we do not invalidate the static declaration.
11663           // NOTE: to avoid multiple warnings, only check the first declaration.
11664           if (Var->isFirstDecl())
11665             RequireCompleteType(Var->getLocation(), Type,
11666                                 diag::ext_typecheck_decl_incomplete_type);
11667         }
11668       }
11669 
11670       // Record the tentative definition; we're done.
11671       if (!Var->isInvalidDecl())
11672         TentativeDefinitions.push_back(Var);
11673       return;
11674     }
11675 
11676     // Provide a specific diagnostic for uninitialized variable
11677     // definitions with incomplete array type.
11678     if (Type->isIncompleteArrayType()) {
11679       Diag(Var->getLocation(),
11680            diag::err_typecheck_incomplete_array_needs_initializer);
11681       Var->setInvalidDecl();
11682       return;
11683     }
11684 
11685     // Provide a specific diagnostic for uninitialized variable
11686     // definitions with reference type.
11687     if (Type->isReferenceType()) {
11688       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11689         << Var->getDeclName()
11690         << SourceRange(Var->getLocation(), Var->getLocation());
11691       Var->setInvalidDecl();
11692       return;
11693     }
11694 
11695     // Do not attempt to type-check the default initializer for a
11696     // variable with dependent type.
11697     if (Type->isDependentType())
11698       return;
11699 
11700     if (Var->isInvalidDecl())
11701       return;
11702 
11703     if (!Var->hasAttr<AliasAttr>()) {
11704       if (RequireCompleteType(Var->getLocation(),
11705                               Context.getBaseElementType(Type),
11706                               diag::err_typecheck_decl_incomplete_type)) {
11707         Var->setInvalidDecl();
11708         return;
11709       }
11710     } else {
11711       return;
11712     }
11713 
11714     // The variable can not have an abstract class type.
11715     if (RequireNonAbstractType(Var->getLocation(), Type,
11716                                diag::err_abstract_type_in_decl,
11717                                AbstractVariableType)) {
11718       Var->setInvalidDecl();
11719       return;
11720     }
11721 
11722     // Check for jumps past the implicit initializer.  C++0x
11723     // clarifies that this applies to a "variable with automatic
11724     // storage duration", not a "local variable".
11725     // C++11 [stmt.dcl]p3
11726     //   A program that jumps from a point where a variable with automatic
11727     //   storage duration is not in scope to a point where it is in scope is
11728     //   ill-formed unless the variable has scalar type, class type with a
11729     //   trivial default constructor and a trivial destructor, a cv-qualified
11730     //   version of one of these types, or an array of one of the preceding
11731     //   types and is declared without an initializer.
11732     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11733       if (const RecordType *Record
11734             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11735         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11736         // Mark the function (if we're in one) for further checking even if the
11737         // looser rules of C++11 do not require such checks, so that we can
11738         // diagnose incompatibilities with C++98.
11739         if (!CXXRecord->isPOD())
11740           setFunctionHasBranchProtectedScope();
11741       }
11742     }
11743     // In OpenCL, we can't initialize objects in the __local address space,
11744     // even implicitly, so don't synthesize an implicit initializer.
11745     if (getLangOpts().OpenCL &&
11746         Var->getType().getAddressSpace() == LangAS::opencl_local)
11747       return;
11748     // C++03 [dcl.init]p9:
11749     //   If no initializer is specified for an object, and the
11750     //   object is of (possibly cv-qualified) non-POD class type (or
11751     //   array thereof), the object shall be default-initialized; if
11752     //   the object is of const-qualified type, the underlying class
11753     //   type shall have a user-declared default
11754     //   constructor. Otherwise, if no initializer is specified for
11755     //   a non- static object, the object and its subobjects, if
11756     //   any, have an indeterminate initial value); if the object
11757     //   or any of its subobjects are of const-qualified type, the
11758     //   program is ill-formed.
11759     // C++0x [dcl.init]p11:
11760     //   If no initializer is specified for an object, the object is
11761     //   default-initialized; [...].
11762     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11763     InitializationKind Kind
11764       = InitializationKind::CreateDefault(Var->getLocation());
11765 
11766     InitializationSequence InitSeq(*this, Entity, Kind, None);
11767     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11768     if (Init.isInvalid())
11769       Var->setInvalidDecl();
11770     else if (Init.get()) {
11771       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11772       // This is important for template substitution.
11773       Var->setInitStyle(VarDecl::CallInit);
11774     }
11775 
11776     CheckCompleteVariableDeclaration(Var);
11777   }
11778 }
11779 
11780 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11781   // If there is no declaration, there was an error parsing it. Ignore it.
11782   if (!D)
11783     return;
11784 
11785   VarDecl *VD = dyn_cast<VarDecl>(D);
11786   if (!VD) {
11787     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11788     D->setInvalidDecl();
11789     return;
11790   }
11791 
11792   VD->setCXXForRangeDecl(true);
11793 
11794   // for-range-declaration cannot be given a storage class specifier.
11795   int Error = -1;
11796   switch (VD->getStorageClass()) {
11797   case SC_None:
11798     break;
11799   case SC_Extern:
11800     Error = 0;
11801     break;
11802   case SC_Static:
11803     Error = 1;
11804     break;
11805   case SC_PrivateExtern:
11806     Error = 2;
11807     break;
11808   case SC_Auto:
11809     Error = 3;
11810     break;
11811   case SC_Register:
11812     Error = 4;
11813     break;
11814   }
11815   if (Error != -1) {
11816     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11817       << VD->getDeclName() << Error;
11818     D->setInvalidDecl();
11819   }
11820 }
11821 
11822 StmtResult
11823 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11824                                  IdentifierInfo *Ident,
11825                                  ParsedAttributes &Attrs,
11826                                  SourceLocation AttrEnd) {
11827   // C++1y [stmt.iter]p1:
11828   //   A range-based for statement of the form
11829   //      for ( for-range-identifier : for-range-initializer ) statement
11830   //   is equivalent to
11831   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11832   DeclSpec DS(Attrs.getPool().getFactory());
11833 
11834   const char *PrevSpec;
11835   unsigned DiagID;
11836   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11837                      getPrintingPolicy());
11838 
11839   Declarator D(DS, DeclaratorContext::ForContext);
11840   D.SetIdentifier(Ident, IdentLoc);
11841   D.takeAttributes(Attrs, AttrEnd);
11842 
11843   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11844                 IdentLoc);
11845   Decl *Var = ActOnDeclarator(S, D);
11846   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11847   FinalizeDeclaration(Var);
11848   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11849                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11850 }
11851 
11852 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11853   if (var->isInvalidDecl()) return;
11854 
11855   if (getLangOpts().OpenCL) {
11856     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11857     // initialiser
11858     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11859         !var->hasInit()) {
11860       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11861           << 1 /*Init*/;
11862       var->setInvalidDecl();
11863       return;
11864     }
11865   }
11866 
11867   // In Objective-C, don't allow jumps past the implicit initialization of a
11868   // local retaining variable.
11869   if (getLangOpts().ObjC &&
11870       var->hasLocalStorage()) {
11871     switch (var->getType().getObjCLifetime()) {
11872     case Qualifiers::OCL_None:
11873     case Qualifiers::OCL_ExplicitNone:
11874     case Qualifiers::OCL_Autoreleasing:
11875       break;
11876 
11877     case Qualifiers::OCL_Weak:
11878     case Qualifiers::OCL_Strong:
11879       setFunctionHasBranchProtectedScope();
11880       break;
11881     }
11882   }
11883 
11884   if (var->hasLocalStorage() &&
11885       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11886     setFunctionHasBranchProtectedScope();
11887 
11888   // Warn about externally-visible variables being defined without a
11889   // prior declaration.  We only want to do this for global
11890   // declarations, but we also specifically need to avoid doing it for
11891   // class members because the linkage of an anonymous class can
11892   // change if it's later given a typedef name.
11893   if (var->isThisDeclarationADefinition() &&
11894       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11895       var->isExternallyVisible() && var->hasLinkage() &&
11896       !var->isInline() && !var->getDescribedVarTemplate() &&
11897       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11898       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11899                                   var->getLocation())) {
11900     // Find a previous declaration that's not a definition.
11901     VarDecl *prev = var->getPreviousDecl();
11902     while (prev && prev->isThisDeclarationADefinition())
11903       prev = prev->getPreviousDecl();
11904 
11905     if (!prev) {
11906       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11907       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
11908           << /* variable */ 0;
11909     }
11910   }
11911 
11912   // Cache the result of checking for constant initialization.
11913   Optional<bool> CacheHasConstInit;
11914   const Expr *CacheCulprit = nullptr;
11915   auto checkConstInit = [&]() mutable {
11916     if (!CacheHasConstInit)
11917       CacheHasConstInit = var->getInit()->isConstantInitializer(
11918             Context, var->getType()->isReferenceType(), &CacheCulprit);
11919     return *CacheHasConstInit;
11920   };
11921 
11922   if (var->getTLSKind() == VarDecl::TLS_Static) {
11923     if (var->getType().isDestructedType()) {
11924       // GNU C++98 edits for __thread, [basic.start.term]p3:
11925       //   The type of an object with thread storage duration shall not
11926       //   have a non-trivial destructor.
11927       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11928       if (getLangOpts().CPlusPlus11)
11929         Diag(var->getLocation(), diag::note_use_thread_local);
11930     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11931       if (!checkConstInit()) {
11932         // GNU C++98 edits for __thread, [basic.start.init]p4:
11933         //   An object of thread storage duration shall not require dynamic
11934         //   initialization.
11935         // FIXME: Need strict checking here.
11936         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11937           << CacheCulprit->getSourceRange();
11938         if (getLangOpts().CPlusPlus11)
11939           Diag(var->getLocation(), diag::note_use_thread_local);
11940       }
11941     }
11942   }
11943 
11944   // Apply section attributes and pragmas to global variables.
11945   bool GlobalStorage = var->hasGlobalStorage();
11946   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11947       !inTemplateInstantiation()) {
11948     PragmaStack<StringLiteral *> *Stack = nullptr;
11949     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11950     if (var->getType().isConstQualified())
11951       Stack = &ConstSegStack;
11952     else if (!var->getInit()) {
11953       Stack = &BSSSegStack;
11954       SectionFlags |= ASTContext::PSF_Write;
11955     } else {
11956       Stack = &DataSegStack;
11957       SectionFlags |= ASTContext::PSF_Write;
11958     }
11959     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11960       var->addAttr(SectionAttr::CreateImplicit(
11961           Context, SectionAttr::Declspec_allocate,
11962           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11963     }
11964     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11965       if (UnifySection(SA->getName(), SectionFlags, var))
11966         var->dropAttr<SectionAttr>();
11967 
11968     // Apply the init_seg attribute if this has an initializer.  If the
11969     // initializer turns out to not be dynamic, we'll end up ignoring this
11970     // attribute.
11971     if (CurInitSeg && var->getInit())
11972       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11973                                                CurInitSegLoc));
11974   }
11975 
11976   // All the following checks are C++ only.
11977   if (!getLangOpts().CPlusPlus) {
11978       // If this variable must be emitted, add it as an initializer for the
11979       // current module.
11980      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11981        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11982      return;
11983   }
11984 
11985   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11986     CheckCompleteDecompositionDeclaration(DD);
11987 
11988   QualType type = var->getType();
11989   if (type->isDependentType()) return;
11990 
11991   if (var->hasAttr<BlocksAttr>())
11992     getCurFunction()->addByrefBlockVar(var);
11993 
11994   Expr *Init = var->getInit();
11995   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11996   QualType baseType = Context.getBaseElementType(type);
11997 
11998   if (Init && !Init->isValueDependent()) {
11999     if (var->isConstexpr()) {
12000       SmallVector<PartialDiagnosticAt, 8> Notes;
12001       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12002         SourceLocation DiagLoc = var->getLocation();
12003         // If the note doesn't add any useful information other than a source
12004         // location, fold it into the primary diagnostic.
12005         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12006               diag::note_invalid_subexpr_in_const_expr) {
12007           DiagLoc = Notes[0].first;
12008           Notes.clear();
12009         }
12010         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12011           << var << Init->getSourceRange();
12012         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12013           Diag(Notes[I].first, Notes[I].second);
12014       }
12015     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12016       // Check whether the initializer of a const variable of integral or
12017       // enumeration type is an ICE now, since we can't tell whether it was
12018       // initialized by a constant expression if we check later.
12019       var->checkInitIsICE();
12020     }
12021 
12022     // Don't emit further diagnostics about constexpr globals since they
12023     // were just diagnosed.
12024     if (!var->isConstexpr() && GlobalStorage &&
12025             var->hasAttr<RequireConstantInitAttr>()) {
12026       // FIXME: Need strict checking in C++03 here.
12027       bool DiagErr = getLangOpts().CPlusPlus11
12028           ? !var->checkInitIsICE() : !checkConstInit();
12029       if (DiagErr) {
12030         auto attr = var->getAttr<RequireConstantInitAttr>();
12031         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12032           << Init->getSourceRange();
12033         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
12034           << attr->getRange();
12035         if (getLangOpts().CPlusPlus11) {
12036           APValue Value;
12037           SmallVector<PartialDiagnosticAt, 8> Notes;
12038           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12039           for (auto &it : Notes)
12040             Diag(it.first, it.second);
12041         } else {
12042           Diag(CacheCulprit->getExprLoc(),
12043                diag::note_invalid_subexpr_in_const_expr)
12044               << CacheCulprit->getSourceRange();
12045         }
12046       }
12047     }
12048     else if (!var->isConstexpr() && IsGlobal &&
12049              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12050                                     var->getLocation())) {
12051       // Warn about globals which don't have a constant initializer.  Don't
12052       // warn about globals with a non-trivial destructor because we already
12053       // warned about them.
12054       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12055       if (!(RD && !RD->hasTrivialDestructor())) {
12056         if (!checkConstInit())
12057           Diag(var->getLocation(), diag::warn_global_constructor)
12058             << Init->getSourceRange();
12059       }
12060     }
12061   }
12062 
12063   // Require the destructor.
12064   if (const RecordType *recordType = baseType->getAs<RecordType>())
12065     FinalizeVarWithDestructor(var, recordType);
12066 
12067   // If this variable must be emitted, add it as an initializer for the current
12068   // module.
12069   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12070     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12071 }
12072 
12073 /// Determines if a variable's alignment is dependent.
12074 static bool hasDependentAlignment(VarDecl *VD) {
12075   if (VD->getType()->isDependentType())
12076     return true;
12077   for (auto *I : VD->specific_attrs<AlignedAttr>())
12078     if (I->isAlignmentDependent())
12079       return true;
12080   return false;
12081 }
12082 
12083 /// Check if VD needs to be dllexport/dllimport due to being in a
12084 /// dllexport/import function.
12085 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12086   assert(VD->isStaticLocal());
12087 
12088   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12089 
12090   // Find outermost function when VD is in lambda function.
12091   while (FD && !getDLLAttr(FD) &&
12092          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12093          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12094     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12095   }
12096 
12097   if (!FD)
12098     return;
12099 
12100   // Static locals inherit dll attributes from their function.
12101   if (Attr *A = getDLLAttr(FD)) {
12102     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12103     NewAttr->setInherited(true);
12104     VD->addAttr(NewAttr);
12105   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12106     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12107                                                           getASTContext(),
12108                                                           A->getSpellingListIndex());
12109     NewAttr->setInherited(true);
12110     VD->addAttr(NewAttr);
12111 
12112     // Export this function to enforce exporting this static variable even
12113     // if it is not used in this compilation unit.
12114     if (!FD->hasAttr<DLLExportAttr>())
12115       FD->addAttr(NewAttr);
12116 
12117   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12118     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12119                                                           getASTContext(),
12120                                                           A->getSpellingListIndex());
12121     NewAttr->setInherited(true);
12122     VD->addAttr(NewAttr);
12123   }
12124 }
12125 
12126 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12127 /// any semantic actions necessary after any initializer has been attached.
12128 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12129   // Note that we are no longer parsing the initializer for this declaration.
12130   ParsingInitForAutoVars.erase(ThisDecl);
12131 
12132   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12133   if (!VD)
12134     return;
12135 
12136   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12137   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12138       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12139     if (PragmaClangBSSSection.Valid)
12140       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12141                                                             PragmaClangBSSSection.SectionName,
12142                                                             PragmaClangBSSSection.PragmaLocation));
12143     if (PragmaClangDataSection.Valid)
12144       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12145                                                              PragmaClangDataSection.SectionName,
12146                                                              PragmaClangDataSection.PragmaLocation));
12147     if (PragmaClangRodataSection.Valid)
12148       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12149                                                                PragmaClangRodataSection.SectionName,
12150                                                                PragmaClangRodataSection.PragmaLocation));
12151   }
12152 
12153   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12154     for (auto *BD : DD->bindings()) {
12155       FinalizeDeclaration(BD);
12156     }
12157   }
12158 
12159   checkAttributesAfterMerging(*this, *VD);
12160 
12161   // Perform TLS alignment check here after attributes attached to the variable
12162   // which may affect the alignment have been processed. Only perform the check
12163   // if the target has a maximum TLS alignment (zero means no constraints).
12164   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12165     // Protect the check so that it's not performed on dependent types and
12166     // dependent alignments (we can't determine the alignment in that case).
12167     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12168         !VD->isInvalidDecl()) {
12169       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12170       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12171         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12172           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12173           << (unsigned)MaxAlignChars.getQuantity();
12174       }
12175     }
12176   }
12177 
12178   if (VD->isStaticLocal()) {
12179     CheckStaticLocalForDllExport(VD);
12180 
12181     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12182       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12183       // function, only __shared__ variables or variables without any device
12184       // memory qualifiers may be declared with static storage class.
12185       // Note: It is unclear how a function-scope non-const static variable
12186       // without device memory qualifier is implemented, therefore only static
12187       // const variable without device memory qualifier is allowed.
12188       [&]() {
12189         if (!getLangOpts().CUDA)
12190           return;
12191         if (VD->hasAttr<CUDASharedAttr>())
12192           return;
12193         if (VD->getType().isConstQualified() &&
12194             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12195           return;
12196         if (CUDADiagIfDeviceCode(VD->getLocation(),
12197                                  diag::err_device_static_local_var)
12198             << CurrentCUDATarget())
12199           VD->setInvalidDecl();
12200       }();
12201     }
12202   }
12203 
12204   // Perform check for initializers of device-side global variables.
12205   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12206   // 7.5). We must also apply the same checks to all __shared__
12207   // variables whether they are local or not. CUDA also allows
12208   // constant initializers for __constant__ and __device__ variables.
12209   if (getLangOpts().CUDA)
12210     checkAllowedCUDAInitializer(VD);
12211 
12212   // Grab the dllimport or dllexport attribute off of the VarDecl.
12213   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12214 
12215   // Imported static data members cannot be defined out-of-line.
12216   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12217     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12218         VD->isThisDeclarationADefinition()) {
12219       // We allow definitions of dllimport class template static data members
12220       // with a warning.
12221       CXXRecordDecl *Context =
12222         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12223       bool IsClassTemplateMember =
12224           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12225           Context->getDescribedClassTemplate();
12226 
12227       Diag(VD->getLocation(),
12228            IsClassTemplateMember
12229                ? diag::warn_attribute_dllimport_static_field_definition
12230                : diag::err_attribute_dllimport_static_field_definition);
12231       Diag(IA->getLocation(), diag::note_attribute);
12232       if (!IsClassTemplateMember)
12233         VD->setInvalidDecl();
12234     }
12235   }
12236 
12237   // dllimport/dllexport variables cannot be thread local, their TLS index
12238   // isn't exported with the variable.
12239   if (DLLAttr && VD->getTLSKind()) {
12240     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12241     if (F && getDLLAttr(F)) {
12242       assert(VD->isStaticLocal());
12243       // But if this is a static local in a dlimport/dllexport function, the
12244       // function will never be inlined, which means the var would never be
12245       // imported, so having it marked import/export is safe.
12246     } else {
12247       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12248                                                                     << DLLAttr;
12249       VD->setInvalidDecl();
12250     }
12251   }
12252 
12253   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12254     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12255       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12256       VD->dropAttr<UsedAttr>();
12257     }
12258   }
12259 
12260   const DeclContext *DC = VD->getDeclContext();
12261   // If there's a #pragma GCC visibility in scope, and this isn't a class
12262   // member, set the visibility of this variable.
12263   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12264     AddPushedVisibilityAttribute(VD);
12265 
12266   // FIXME: Warn on unused var template partial specializations.
12267   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12268     MarkUnusedFileScopedDecl(VD);
12269 
12270   // Now we have parsed the initializer and can update the table of magic
12271   // tag values.
12272   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12273       !VD->getType()->isIntegralOrEnumerationType())
12274     return;
12275 
12276   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12277     const Expr *MagicValueExpr = VD->getInit();
12278     if (!MagicValueExpr) {
12279       continue;
12280     }
12281     llvm::APSInt MagicValueInt;
12282     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12283       Diag(I->getRange().getBegin(),
12284            diag::err_type_tag_for_datatype_not_ice)
12285         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12286       continue;
12287     }
12288     if (MagicValueInt.getActiveBits() > 64) {
12289       Diag(I->getRange().getBegin(),
12290            diag::err_type_tag_for_datatype_too_large)
12291         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12292       continue;
12293     }
12294     uint64_t MagicValue = MagicValueInt.getZExtValue();
12295     RegisterTypeTagForDatatype(I->getArgumentKind(),
12296                                MagicValue,
12297                                I->getMatchingCType(),
12298                                I->getLayoutCompatible(),
12299                                I->getMustBeNull());
12300   }
12301 }
12302 
12303 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12304   auto *VD = dyn_cast<VarDecl>(DD);
12305   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12306 }
12307 
12308 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12309                                                    ArrayRef<Decl *> Group) {
12310   SmallVector<Decl*, 8> Decls;
12311 
12312   if (DS.isTypeSpecOwned())
12313     Decls.push_back(DS.getRepAsDecl());
12314 
12315   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12316   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12317   bool DiagnosedMultipleDecomps = false;
12318   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12319   bool DiagnosedNonDeducedAuto = false;
12320 
12321   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12322     if (Decl *D = Group[i]) {
12323       // For declarators, there are some additional syntactic-ish checks we need
12324       // to perform.
12325       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12326         if (!FirstDeclaratorInGroup)
12327           FirstDeclaratorInGroup = DD;
12328         if (!FirstDecompDeclaratorInGroup)
12329           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12330         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12331             !hasDeducedAuto(DD))
12332           FirstNonDeducedAutoInGroup = DD;
12333 
12334         if (FirstDeclaratorInGroup != DD) {
12335           // A decomposition declaration cannot be combined with any other
12336           // declaration in the same group.
12337           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12338             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12339                  diag::err_decomp_decl_not_alone)
12340                 << FirstDeclaratorInGroup->getSourceRange()
12341                 << DD->getSourceRange();
12342             DiagnosedMultipleDecomps = true;
12343           }
12344 
12345           // A declarator that uses 'auto' in any way other than to declare a
12346           // variable with a deduced type cannot be combined with any other
12347           // declarator in the same group.
12348           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12349             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12350                  diag::err_auto_non_deduced_not_alone)
12351                 << FirstNonDeducedAutoInGroup->getType()
12352                        ->hasAutoForTrailingReturnType()
12353                 << FirstDeclaratorInGroup->getSourceRange()
12354                 << DD->getSourceRange();
12355             DiagnosedNonDeducedAuto = true;
12356           }
12357         }
12358       }
12359 
12360       Decls.push_back(D);
12361     }
12362   }
12363 
12364   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12365     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12366       handleTagNumbering(Tag, S);
12367       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12368           getLangOpts().CPlusPlus)
12369         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12370     }
12371   }
12372 
12373   return BuildDeclaratorGroup(Decls);
12374 }
12375 
12376 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12377 /// group, performing any necessary semantic checking.
12378 Sema::DeclGroupPtrTy
12379 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12380   // C++14 [dcl.spec.auto]p7: (DR1347)
12381   //   If the type that replaces the placeholder type is not the same in each
12382   //   deduction, the program is ill-formed.
12383   if (Group.size() > 1) {
12384     QualType Deduced;
12385     VarDecl *DeducedDecl = nullptr;
12386     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12387       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12388       if (!D || D->isInvalidDecl())
12389         break;
12390       DeducedType *DT = D->getType()->getContainedDeducedType();
12391       if (!DT || DT->getDeducedType().isNull())
12392         continue;
12393       if (Deduced.isNull()) {
12394         Deduced = DT->getDeducedType();
12395         DeducedDecl = D;
12396       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12397         auto *AT = dyn_cast<AutoType>(DT);
12398         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12399              diag::err_auto_different_deductions)
12400           << (AT ? (unsigned)AT->getKeyword() : 3)
12401           << Deduced << DeducedDecl->getDeclName()
12402           << DT->getDeducedType() << D->getDeclName()
12403           << DeducedDecl->getInit()->getSourceRange()
12404           << D->getInit()->getSourceRange();
12405         D->setInvalidDecl();
12406         break;
12407       }
12408     }
12409   }
12410 
12411   ActOnDocumentableDecls(Group);
12412 
12413   return DeclGroupPtrTy::make(
12414       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12415 }
12416 
12417 void Sema::ActOnDocumentableDecl(Decl *D) {
12418   ActOnDocumentableDecls(D);
12419 }
12420 
12421 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12422   // Don't parse the comment if Doxygen diagnostics are ignored.
12423   if (Group.empty() || !Group[0])
12424     return;
12425 
12426   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12427                       Group[0]->getLocation()) &&
12428       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12429                       Group[0]->getLocation()))
12430     return;
12431 
12432   if (Group.size() >= 2) {
12433     // This is a decl group.  Normally it will contain only declarations
12434     // produced from declarator list.  But in case we have any definitions or
12435     // additional declaration references:
12436     //   'typedef struct S {} S;'
12437     //   'typedef struct S *S;'
12438     //   'struct S *pS;'
12439     // FinalizeDeclaratorGroup adds these as separate declarations.
12440     Decl *MaybeTagDecl = Group[0];
12441     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12442       Group = Group.slice(1);
12443     }
12444   }
12445 
12446   // See if there are any new comments that are not attached to a decl.
12447   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12448   if (!Comments.empty() &&
12449       !Comments.back()->isAttached()) {
12450     // There is at least one comment that not attached to a decl.
12451     // Maybe it should be attached to one of these decls?
12452     //
12453     // Note that this way we pick up not only comments that precede the
12454     // declaration, but also comments that *follow* the declaration -- thanks to
12455     // the lookahead in the lexer: we've consumed the semicolon and looked
12456     // ahead through comments.
12457     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12458       Context.getCommentForDecl(Group[i], &PP);
12459   }
12460 }
12461 
12462 /// Common checks for a parameter-declaration that should apply to both function
12463 /// parameters and non-type template parameters.
12464 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12465   // Check that there are no default arguments inside the type of this
12466   // parameter.
12467   if (getLangOpts().CPlusPlus)
12468     CheckExtraCXXDefaultArguments(D);
12469 
12470   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12471   if (D.getCXXScopeSpec().isSet()) {
12472     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12473       << D.getCXXScopeSpec().getRange();
12474   }
12475 
12476   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12477   // simple identifier except [...irrelevant cases...].
12478   switch (D.getName().getKind()) {
12479   case UnqualifiedIdKind::IK_Identifier:
12480     break;
12481 
12482   case UnqualifiedIdKind::IK_OperatorFunctionId:
12483   case UnqualifiedIdKind::IK_ConversionFunctionId:
12484   case UnqualifiedIdKind::IK_LiteralOperatorId:
12485   case UnqualifiedIdKind::IK_ConstructorName:
12486   case UnqualifiedIdKind::IK_DestructorName:
12487   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12488   case UnqualifiedIdKind::IK_DeductionGuideName:
12489     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12490       << GetNameForDeclarator(D).getName();
12491     break;
12492 
12493   case UnqualifiedIdKind::IK_TemplateId:
12494   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12495     // GetNameForDeclarator would not produce a useful name in this case.
12496     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
12497     break;
12498   }
12499 }
12500 
12501 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12502 /// to introduce parameters into function prototype scope.
12503 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12504   const DeclSpec &DS = D.getDeclSpec();
12505 
12506   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12507 
12508   // C++03 [dcl.stc]p2 also permits 'auto'.
12509   StorageClass SC = SC_None;
12510   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12511     SC = SC_Register;
12512     // In C++11, the 'register' storage class specifier is deprecated.
12513     // In C++17, it is not allowed, but we tolerate it as an extension.
12514     if (getLangOpts().CPlusPlus11) {
12515       Diag(DS.getStorageClassSpecLoc(),
12516            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12517                                      : diag::warn_deprecated_register)
12518         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12519     }
12520   } else if (getLangOpts().CPlusPlus &&
12521              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12522     SC = SC_Auto;
12523   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12524     Diag(DS.getStorageClassSpecLoc(),
12525          diag::err_invalid_storage_class_in_func_decl);
12526     D.getMutableDeclSpec().ClearStorageClassSpecs();
12527   }
12528 
12529   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12530     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12531       << DeclSpec::getSpecifierName(TSCS);
12532   if (DS.isInlineSpecified())
12533     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12534         << getLangOpts().CPlusPlus17;
12535   if (DS.hasConstexprSpecifier())
12536     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12537         << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
12538 
12539   DiagnoseFunctionSpecifiers(DS);
12540 
12541   CheckFunctionOrTemplateParamDeclarator(S, D);
12542 
12543   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12544   QualType parmDeclType = TInfo->getType();
12545 
12546   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12547   IdentifierInfo *II = D.getIdentifier();
12548   if (II) {
12549     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12550                    ForVisibleRedeclaration);
12551     LookupName(R, S);
12552     if (R.isSingleResult()) {
12553       NamedDecl *PrevDecl = R.getFoundDecl();
12554       if (PrevDecl->isTemplateParameter()) {
12555         // Maybe we will complain about the shadowed template parameter.
12556         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12557         // Just pretend that we didn't see the previous declaration.
12558         PrevDecl = nullptr;
12559       } else if (S->isDeclScope(PrevDecl)) {
12560         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12561         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12562 
12563         // Recover by removing the name
12564         II = nullptr;
12565         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12566         D.setInvalidType(true);
12567       }
12568     }
12569   }
12570 
12571   // Temporarily put parameter variables in the translation unit, not
12572   // the enclosing context.  This prevents them from accidentally
12573   // looking like class members in C++.
12574   ParmVarDecl *New =
12575       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12576                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12577 
12578   if (D.isInvalidType())
12579     New->setInvalidDecl();
12580 
12581   assert(S->isFunctionPrototypeScope());
12582   assert(S->getFunctionPrototypeDepth() >= 1);
12583   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12584                     S->getNextFunctionPrototypeIndex());
12585 
12586   // Add the parameter declaration into this scope.
12587   S->AddDecl(New);
12588   if (II)
12589     IdResolver.AddDecl(New);
12590 
12591   ProcessDeclAttributes(S, New, D);
12592 
12593   if (D.getDeclSpec().isModulePrivateSpecified())
12594     Diag(New->getLocation(), diag::err_module_private_local)
12595       << 1 << New->getDeclName()
12596       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12597       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12598 
12599   if (New->hasAttr<BlocksAttr>()) {
12600     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12601   }
12602   return New;
12603 }
12604 
12605 /// Synthesizes a variable for a parameter arising from a
12606 /// typedef.
12607 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12608                                               SourceLocation Loc,
12609                                               QualType T) {
12610   /* FIXME: setting StartLoc == Loc.
12611      Would it be worth to modify callers so as to provide proper source
12612      location for the unnamed parameters, embedding the parameter's type? */
12613   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12614                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12615                                            SC_None, nullptr);
12616   Param->setImplicit();
12617   return Param;
12618 }
12619 
12620 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12621   // Don't diagnose unused-parameter errors in template instantiations; we
12622   // will already have done so in the template itself.
12623   if (inTemplateInstantiation())
12624     return;
12625 
12626   for (const ParmVarDecl *Parameter : Parameters) {
12627     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12628         !Parameter->hasAttr<UnusedAttr>()) {
12629       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12630         << Parameter->getDeclName();
12631     }
12632   }
12633 }
12634 
12635 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12636     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12637   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12638     return;
12639 
12640   // Warn if the return value is pass-by-value and larger than the specified
12641   // threshold.
12642   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12643     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12644     if (Size > LangOpts.NumLargeByValueCopy)
12645       Diag(D->getLocation(), diag::warn_return_value_size)
12646           << D->getDeclName() << Size;
12647   }
12648 
12649   // Warn if any parameter is pass-by-value and larger than the specified
12650   // threshold.
12651   for (const ParmVarDecl *Parameter : Parameters) {
12652     QualType T = Parameter->getType();
12653     if (T->isDependentType() || !T.isPODType(Context))
12654       continue;
12655     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12656     if (Size > LangOpts.NumLargeByValueCopy)
12657       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12658           << Parameter->getDeclName() << Size;
12659   }
12660 }
12661 
12662 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12663                                   SourceLocation NameLoc, IdentifierInfo *Name,
12664                                   QualType T, TypeSourceInfo *TSInfo,
12665                                   StorageClass SC) {
12666   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12667   if (getLangOpts().ObjCAutoRefCount &&
12668       T.getObjCLifetime() == Qualifiers::OCL_None &&
12669       T->isObjCLifetimeType()) {
12670 
12671     Qualifiers::ObjCLifetime lifetime;
12672 
12673     // Special cases for arrays:
12674     //   - if it's const, use __unsafe_unretained
12675     //   - otherwise, it's an error
12676     if (T->isArrayType()) {
12677       if (!T.isConstQualified()) {
12678         if (DelayedDiagnostics.shouldDelayDiagnostics())
12679           DelayedDiagnostics.add(
12680               sema::DelayedDiagnostic::makeForbiddenType(
12681               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12682         else
12683           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12684               << TSInfo->getTypeLoc().getSourceRange();
12685       }
12686       lifetime = Qualifiers::OCL_ExplicitNone;
12687     } else {
12688       lifetime = T->getObjCARCImplicitLifetime();
12689     }
12690     T = Context.getLifetimeQualifiedType(T, lifetime);
12691   }
12692 
12693   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12694                                          Context.getAdjustedParameterType(T),
12695                                          TSInfo, SC, nullptr);
12696 
12697   // Parameters can not be abstract class types.
12698   // For record types, this is done by the AbstractClassUsageDiagnoser once
12699   // the class has been completely parsed.
12700   if (!CurContext->isRecord() &&
12701       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12702                              AbstractParamType))
12703     New->setInvalidDecl();
12704 
12705   // Parameter declarators cannot be interface types. All ObjC objects are
12706   // passed by reference.
12707   if (T->isObjCObjectType()) {
12708     SourceLocation TypeEndLoc =
12709         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12710     Diag(NameLoc,
12711          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12712       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12713     T = Context.getObjCObjectPointerType(T);
12714     New->setType(T);
12715   }
12716 
12717   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12718   // duration shall not be qualified by an address-space qualifier."
12719   // Since all parameters have automatic store duration, they can not have
12720   // an address space.
12721   if (T.getAddressSpace() != LangAS::Default &&
12722       // OpenCL allows function arguments declared to be an array of a type
12723       // to be qualified with an address space.
12724       !(getLangOpts().OpenCL &&
12725         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12726     Diag(NameLoc, diag::err_arg_with_address_space);
12727     New->setInvalidDecl();
12728   }
12729 
12730   return New;
12731 }
12732 
12733 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12734                                            SourceLocation LocAfterDecls) {
12735   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12736 
12737   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12738   // for a K&R function.
12739   if (!FTI.hasPrototype) {
12740     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12741       --i;
12742       if (FTI.Params[i].Param == nullptr) {
12743         SmallString<256> Code;
12744         llvm::raw_svector_ostream(Code)
12745             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12746         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12747             << FTI.Params[i].Ident
12748             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12749 
12750         // Implicitly declare the argument as type 'int' for lack of a better
12751         // type.
12752         AttributeFactory attrs;
12753         DeclSpec DS(attrs);
12754         const char* PrevSpec; // unused
12755         unsigned DiagID; // unused
12756         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12757                            DiagID, Context.getPrintingPolicy());
12758         // Use the identifier location for the type source range.
12759         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12760         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12761         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12762         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12763         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12764       }
12765     }
12766   }
12767 }
12768 
12769 Decl *
12770 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12771                               MultiTemplateParamsArg TemplateParameterLists,
12772                               SkipBodyInfo *SkipBody) {
12773   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12774   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12775   Scope *ParentScope = FnBodyScope->getParent();
12776 
12777   D.setFunctionDefinitionKind(FDK_Definition);
12778   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12779   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12780 }
12781 
12782 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12783   Consumer.HandleInlineFunctionDefinition(D);
12784 }
12785 
12786 static bool
12787 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12788                                 const FunctionDecl *&PossiblePrototype) {
12789   // Don't warn about invalid declarations.
12790   if (FD->isInvalidDecl())
12791     return false;
12792 
12793   // Or declarations that aren't global.
12794   if (!FD->isGlobal())
12795     return false;
12796 
12797   // Don't warn about C++ member functions.
12798   if (isa<CXXMethodDecl>(FD))
12799     return false;
12800 
12801   // Don't warn about 'main'.
12802   if (FD->isMain())
12803     return false;
12804 
12805   // Don't warn about inline functions.
12806   if (FD->isInlined())
12807     return false;
12808 
12809   // Don't warn about function templates.
12810   if (FD->getDescribedFunctionTemplate())
12811     return false;
12812 
12813   // Don't warn about function template specializations.
12814   if (FD->isFunctionTemplateSpecialization())
12815     return false;
12816 
12817   // Don't warn for OpenCL kernels.
12818   if (FD->hasAttr<OpenCLKernelAttr>())
12819     return false;
12820 
12821   // Don't warn on explicitly deleted functions.
12822   if (FD->isDeleted())
12823     return false;
12824 
12825   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12826        Prev; Prev = Prev->getPreviousDecl()) {
12827     // Ignore any declarations that occur in function or method
12828     // scope, because they aren't visible from the header.
12829     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12830       continue;
12831 
12832     PossiblePrototype = Prev;
12833     return Prev->getType()->isFunctionNoProtoType();
12834   }
12835 
12836   return true;
12837 }
12838 
12839 void
12840 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12841                                    const FunctionDecl *EffectiveDefinition,
12842                                    SkipBodyInfo *SkipBody) {
12843   const FunctionDecl *Definition = EffectiveDefinition;
12844   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12845     // If this is a friend function defined in a class template, it does not
12846     // have a body until it is used, nevertheless it is a definition, see
12847     // [temp.inst]p2:
12848     //
12849     // ... for the purpose of determining whether an instantiated redeclaration
12850     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12851     // corresponds to a definition in the template is considered to be a
12852     // definition.
12853     //
12854     // The following code must produce redefinition error:
12855     //
12856     //     template<typename T> struct C20 { friend void func_20() {} };
12857     //     C20<int> c20i;
12858     //     void func_20() {}
12859     //
12860     for (auto I : FD->redecls()) {
12861       if (I != FD && !I->isInvalidDecl() &&
12862           I->getFriendObjectKind() != Decl::FOK_None) {
12863         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12864           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12865             // A merged copy of the same function, instantiated as a member of
12866             // the same class, is OK.
12867             if (declaresSameEntity(OrigFD, Original) &&
12868                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12869                                    cast<Decl>(FD->getLexicalDeclContext())))
12870               continue;
12871           }
12872 
12873           if (Original->isThisDeclarationADefinition()) {
12874             Definition = I;
12875             break;
12876           }
12877         }
12878       }
12879     }
12880   }
12881 
12882   if (!Definition)
12883     // Similar to friend functions a friend function template may be a
12884     // definition and do not have a body if it is instantiated in a class
12885     // template.
12886     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12887       for (auto I : FTD->redecls()) {
12888         auto D = cast<FunctionTemplateDecl>(I);
12889         if (D != FTD) {
12890           assert(!D->isThisDeclarationADefinition() &&
12891                  "More than one definition in redeclaration chain");
12892           if (D->getFriendObjectKind() != Decl::FOK_None)
12893             if (FunctionTemplateDecl *FT =
12894                                        D->getInstantiatedFromMemberTemplate()) {
12895               if (FT->isThisDeclarationADefinition()) {
12896                 Definition = D->getTemplatedDecl();
12897                 break;
12898               }
12899             }
12900         }
12901       }
12902     }
12903 
12904   if (!Definition)
12905     return;
12906 
12907   if (canRedefineFunction(Definition, getLangOpts()))
12908     return;
12909 
12910   // Don't emit an error when this is redefinition of a typo-corrected
12911   // definition.
12912   if (TypoCorrectedFunctionDefinitions.count(Definition))
12913     return;
12914 
12915   // If we don't have a visible definition of the function, and it's inline or
12916   // a template, skip the new definition.
12917   if (SkipBody && !hasVisibleDefinition(Definition) &&
12918       (Definition->getFormalLinkage() == InternalLinkage ||
12919        Definition->isInlined() ||
12920        Definition->getDescribedFunctionTemplate() ||
12921        Definition->getNumTemplateParameterLists())) {
12922     SkipBody->ShouldSkip = true;
12923     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12924     if (auto *TD = Definition->getDescribedFunctionTemplate())
12925       makeMergedDefinitionVisible(TD);
12926     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12927     return;
12928   }
12929 
12930   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12931       Definition->getStorageClass() == SC_Extern)
12932     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12933         << FD->getDeclName() << getLangOpts().CPlusPlus;
12934   else
12935     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12936 
12937   Diag(Definition->getLocation(), diag::note_previous_definition);
12938   FD->setInvalidDecl();
12939 }
12940 
12941 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12942                                    Sema &S) {
12943   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12944 
12945   LambdaScopeInfo *LSI = S.PushLambdaScope();
12946   LSI->CallOperator = CallOperator;
12947   LSI->Lambda = LambdaClass;
12948   LSI->ReturnType = CallOperator->getReturnType();
12949   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12950 
12951   if (LCD == LCD_None)
12952     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12953   else if (LCD == LCD_ByCopy)
12954     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12955   else if (LCD == LCD_ByRef)
12956     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12957   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12958 
12959   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12960   LSI->Mutable = !CallOperator->isConst();
12961 
12962   // Add the captures to the LSI so they can be noted as already
12963   // captured within tryCaptureVar.
12964   auto I = LambdaClass->field_begin();
12965   for (const auto &C : LambdaClass->captures()) {
12966     if (C.capturesVariable()) {
12967       VarDecl *VD = C.getCapturedVar();
12968       if (VD->isInitCapture())
12969         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12970       QualType CaptureType = VD->getType();
12971       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12972       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12973           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12974           /*EllipsisLoc*/C.isPackExpansion()
12975                          ? C.getEllipsisLoc() : SourceLocation(),
12976           CaptureType, /*Invalid*/false);
12977 
12978     } else if (C.capturesThis()) {
12979       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
12980                           C.getCaptureKind() == LCK_StarThis);
12981     } else {
12982       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
12983                              I->getType());
12984     }
12985     ++I;
12986   }
12987 }
12988 
12989 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12990                                     SkipBodyInfo *SkipBody) {
12991   if (!D) {
12992     // Parsing the function declaration failed in some way. Push on a fake scope
12993     // anyway so we can try to parse the function body.
12994     PushFunctionScope();
12995     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12996     return D;
12997   }
12998 
12999   FunctionDecl *FD = nullptr;
13000 
13001   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13002     FD = FunTmpl->getTemplatedDecl();
13003   else
13004     FD = cast<FunctionDecl>(D);
13005 
13006   // Do not push if it is a lambda because one is already pushed when building
13007   // the lambda in ActOnStartOfLambdaDefinition().
13008   if (!isLambdaCallOperator(FD))
13009     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13010 
13011   // Check for defining attributes before the check for redefinition.
13012   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13013     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13014     FD->dropAttr<AliasAttr>();
13015     FD->setInvalidDecl();
13016   }
13017   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13018     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13019     FD->dropAttr<IFuncAttr>();
13020     FD->setInvalidDecl();
13021   }
13022 
13023   // See if this is a redefinition. If 'will have body' is already set, then
13024   // these checks were already performed when it was set.
13025   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13026     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13027 
13028     // If we're skipping the body, we're done. Don't enter the scope.
13029     if (SkipBody && SkipBody->ShouldSkip)
13030       return D;
13031   }
13032 
13033   // Mark this function as "will have a body eventually".  This lets users to
13034   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13035   // this function.
13036   FD->setWillHaveBody();
13037 
13038   // If we are instantiating a generic lambda call operator, push
13039   // a LambdaScopeInfo onto the function stack.  But use the information
13040   // that's already been calculated (ActOnLambdaExpr) to prime the current
13041   // LambdaScopeInfo.
13042   // When the template operator is being specialized, the LambdaScopeInfo,
13043   // has to be properly restored so that tryCaptureVariable doesn't try
13044   // and capture any new variables. In addition when calculating potential
13045   // captures during transformation of nested lambdas, it is necessary to
13046   // have the LSI properly restored.
13047   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13048     assert(inTemplateInstantiation() &&
13049            "There should be an active template instantiation on the stack "
13050            "when instantiating a generic lambda!");
13051     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13052   } else {
13053     // Enter a new function scope
13054     PushFunctionScope();
13055   }
13056 
13057   // Builtin functions cannot be defined.
13058   if (unsigned BuiltinID = FD->getBuiltinID()) {
13059     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13060         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13061       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13062       FD->setInvalidDecl();
13063     }
13064   }
13065 
13066   // The return type of a function definition must be complete
13067   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13068   QualType ResultType = FD->getReturnType();
13069   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13070       !FD->isInvalidDecl() &&
13071       RequireCompleteType(FD->getLocation(), ResultType,
13072                           diag::err_func_def_incomplete_result))
13073     FD->setInvalidDecl();
13074 
13075   if (FnBodyScope)
13076     PushDeclContext(FnBodyScope, FD);
13077 
13078   // Check the validity of our function parameters
13079   CheckParmsForFunctionDef(FD->parameters(),
13080                            /*CheckParameterNames=*/true);
13081 
13082   // Add non-parameter declarations already in the function to the current
13083   // scope.
13084   if (FnBodyScope) {
13085     for (Decl *NPD : FD->decls()) {
13086       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13087       if (!NonParmDecl)
13088         continue;
13089       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13090              "parameters should not be in newly created FD yet");
13091 
13092       // If the decl has a name, make it accessible in the current scope.
13093       if (NonParmDecl->getDeclName())
13094         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13095 
13096       // Similarly, dive into enums and fish their constants out, making them
13097       // accessible in this scope.
13098       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13099         for (auto *EI : ED->enumerators())
13100           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13101       }
13102     }
13103   }
13104 
13105   // Introduce our parameters into the function scope
13106   for (auto Param : FD->parameters()) {
13107     Param->setOwningFunction(FD);
13108 
13109     // If this has an identifier, add it to the scope stack.
13110     if (Param->getIdentifier() && FnBodyScope) {
13111       CheckShadow(FnBodyScope, Param);
13112 
13113       PushOnScopeChains(Param, FnBodyScope);
13114     }
13115   }
13116 
13117   // Ensure that the function's exception specification is instantiated.
13118   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13119     ResolveExceptionSpec(D->getLocation(), FPT);
13120 
13121   // dllimport cannot be applied to non-inline function definitions.
13122   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13123       !FD->isTemplateInstantiation()) {
13124     assert(!FD->hasAttr<DLLExportAttr>());
13125     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13126     FD->setInvalidDecl();
13127     return D;
13128   }
13129   // We want to attach documentation to original Decl (which might be
13130   // a function template).
13131   ActOnDocumentableDecl(D);
13132   if (getCurLexicalContext()->isObjCContainer() &&
13133       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13134       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13135     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13136 
13137   return D;
13138 }
13139 
13140 /// Given the set of return statements within a function body,
13141 /// compute the variables that are subject to the named return value
13142 /// optimization.
13143 ///
13144 /// Each of the variables that is subject to the named return value
13145 /// optimization will be marked as NRVO variables in the AST, and any
13146 /// return statement that has a marked NRVO variable as its NRVO candidate can
13147 /// use the named return value optimization.
13148 ///
13149 /// This function applies a very simplistic algorithm for NRVO: if every return
13150 /// statement in the scope of a variable has the same NRVO candidate, that
13151 /// candidate is an NRVO variable.
13152 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13153   ReturnStmt **Returns = Scope->Returns.data();
13154 
13155   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13156     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13157       if (!NRVOCandidate->isNRVOVariable())
13158         Returns[I]->setNRVOCandidate(nullptr);
13159     }
13160   }
13161 }
13162 
13163 bool Sema::canDelayFunctionBody(const Declarator &D) {
13164   // We can't delay parsing the body of a constexpr function template (yet).
13165   if (D.getDeclSpec().hasConstexprSpecifier())
13166     return false;
13167 
13168   // We can't delay parsing the body of a function template with a deduced
13169   // return type (yet).
13170   if (D.getDeclSpec().hasAutoTypeSpec()) {
13171     // If the placeholder introduces a non-deduced trailing return type,
13172     // we can still delay parsing it.
13173     if (D.getNumTypeObjects()) {
13174       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13175       if (Outer.Kind == DeclaratorChunk::Function &&
13176           Outer.Fun.hasTrailingReturnType()) {
13177         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13178         return Ty.isNull() || !Ty->isUndeducedType();
13179       }
13180     }
13181     return false;
13182   }
13183 
13184   return true;
13185 }
13186 
13187 bool Sema::canSkipFunctionBody(Decl *D) {
13188   // We cannot skip the body of a function (or function template) which is
13189   // constexpr, since we may need to evaluate its body in order to parse the
13190   // rest of the file.
13191   // We cannot skip the body of a function with an undeduced return type,
13192   // because any callers of that function need to know the type.
13193   if (const FunctionDecl *FD = D->getAsFunction()) {
13194     if (FD->isConstexpr())
13195       return false;
13196     // We can't simply call Type::isUndeducedType here, because inside template
13197     // auto can be deduced to a dependent type, which is not considered
13198     // "undeduced".
13199     if (FD->getReturnType()->getContainedDeducedType())
13200       return false;
13201   }
13202   return Consumer.shouldSkipFunctionBody(D);
13203 }
13204 
13205 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13206   if (!Decl)
13207     return nullptr;
13208   if (FunctionDecl *FD = Decl->getAsFunction())
13209     FD->setHasSkippedBody();
13210   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13211     MD->setHasSkippedBody();
13212   return Decl;
13213 }
13214 
13215 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13216   return ActOnFinishFunctionBody(D, BodyArg, false);
13217 }
13218 
13219 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13220 /// body.
13221 class ExitFunctionBodyRAII {
13222 public:
13223   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13224   ~ExitFunctionBodyRAII() {
13225     if (!IsLambda)
13226       S.PopExpressionEvaluationContext();
13227   }
13228 
13229 private:
13230   Sema &S;
13231   bool IsLambda = false;
13232 };
13233 
13234 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13235   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13236 
13237   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13238     if (EscapeInfo.count(BD))
13239       return EscapeInfo[BD];
13240 
13241     bool R = false;
13242     const BlockDecl *CurBD = BD;
13243 
13244     do {
13245       R = !CurBD->doesNotEscape();
13246       if (R)
13247         break;
13248       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13249     } while (CurBD);
13250 
13251     return EscapeInfo[BD] = R;
13252   };
13253 
13254   // If the location where 'self' is implicitly retained is inside a escaping
13255   // block, emit a diagnostic.
13256   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13257        S.ImplicitlyRetainedSelfLocs)
13258     if (IsOrNestedInEscapingBlock(P.second))
13259       S.Diag(P.first, diag::warn_implicitly_retains_self)
13260           << FixItHint::CreateInsertion(P.first, "self->");
13261 }
13262 
13263 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13264                                     bool IsInstantiation) {
13265   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13266 
13267   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13268   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13269 
13270   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13271     CheckCompletedCoroutineBody(FD, Body);
13272 
13273   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13274   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13275   // meant to pop the context added in ActOnStartOfFunctionDef().
13276   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13277 
13278   if (FD) {
13279     FD->setBody(Body);
13280     FD->setWillHaveBody(false);
13281 
13282     if (getLangOpts().CPlusPlus14) {
13283       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13284           FD->getReturnType()->isUndeducedType()) {
13285         // If the function has a deduced result type but contains no 'return'
13286         // statements, the result type as written must be exactly 'auto', and
13287         // the deduced result type is 'void'.
13288         if (!FD->getReturnType()->getAs<AutoType>()) {
13289           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13290               << FD->getReturnType();
13291           FD->setInvalidDecl();
13292         } else {
13293           // Substitute 'void' for the 'auto' in the type.
13294           TypeLoc ResultType = getReturnTypeLoc(FD);
13295           Context.adjustDeducedFunctionResultType(
13296               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13297         }
13298       }
13299     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13300       // In C++11, we don't use 'auto' deduction rules for lambda call
13301       // operators because we don't support return type deduction.
13302       auto *LSI = getCurLambda();
13303       if (LSI->HasImplicitReturnType) {
13304         deduceClosureReturnType(*LSI);
13305 
13306         // C++11 [expr.prim.lambda]p4:
13307         //   [...] if there are no return statements in the compound-statement
13308         //   [the deduced type is] the type void
13309         QualType RetType =
13310             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13311 
13312         // Update the return type to the deduced type.
13313         const FunctionProtoType *Proto =
13314             FD->getType()->getAs<FunctionProtoType>();
13315         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13316                                             Proto->getExtProtoInfo()));
13317       }
13318     }
13319 
13320     // If the function implicitly returns zero (like 'main') or is naked,
13321     // don't complain about missing return statements.
13322     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13323       WP.disableCheckFallThrough();
13324 
13325     // MSVC permits the use of pure specifier (=0) on function definition,
13326     // defined at class scope, warn about this non-standard construct.
13327     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13328       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13329 
13330     if (!FD->isInvalidDecl()) {
13331       // Don't diagnose unused parameters of defaulted or deleted functions.
13332       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13333         DiagnoseUnusedParameters(FD->parameters());
13334       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13335                                              FD->getReturnType(), FD);
13336 
13337       // If this is a structor, we need a vtable.
13338       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13339         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13340       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13341         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13342 
13343       // Try to apply the named return value optimization. We have to check
13344       // if we can do this here because lambdas keep return statements around
13345       // to deduce an implicit return type.
13346       if (FD->getReturnType()->isRecordType() &&
13347           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13348         computeNRVO(Body, getCurFunction());
13349     }
13350 
13351     // GNU warning -Wmissing-prototypes:
13352     //   Warn if a global function is defined without a previous
13353     //   prototype declaration. This warning is issued even if the
13354     //   definition itself provides a prototype. The aim is to detect
13355     //   global functions that fail to be declared in header files.
13356     const FunctionDecl *PossiblePrototype = nullptr;
13357     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13358       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13359 
13360       if (PossiblePrototype) {
13361         // We found a declaration that is not a prototype,
13362         // but that could be a zero-parameter prototype
13363         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13364           TypeLoc TL = TI->getTypeLoc();
13365           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13366             Diag(PossiblePrototype->getLocation(),
13367                  diag::note_declaration_not_a_prototype)
13368                 << (FD->getNumParams() != 0)
13369                 << (FD->getNumParams() == 0
13370                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13371                         : FixItHint{});
13372         }
13373       } else {
13374         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13375             << /* function */ 1
13376             << (FD->getStorageClass() == SC_None
13377                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13378                                                  "static ")
13379                     : FixItHint{});
13380       }
13381 
13382       // GNU warning -Wstrict-prototypes
13383       //   Warn if K&R function is defined without a previous declaration.
13384       //   This warning is issued only if the definition itself does not provide
13385       //   a prototype. Only K&R definitions do not provide a prototype.
13386       //   An empty list in a function declarator that is part of a definition
13387       //   of that function specifies that the function has no parameters
13388       //   (C99 6.7.5.3p14)
13389       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13390           !LangOpts.CPlusPlus) {
13391         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13392         TypeLoc TL = TI->getTypeLoc();
13393         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13394         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13395       }
13396     }
13397 
13398     // Warn on CPUDispatch with an actual body.
13399     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13400       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13401         if (!CmpndBody->body_empty())
13402           Diag(CmpndBody->body_front()->getBeginLoc(),
13403                diag::warn_dispatch_body_ignored);
13404 
13405     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13406       const CXXMethodDecl *KeyFunction;
13407       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13408           MD->isVirtual() &&
13409           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13410           MD == KeyFunction->getCanonicalDecl()) {
13411         // Update the key-function state if necessary for this ABI.
13412         if (FD->isInlined() &&
13413             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13414           Context.setNonKeyFunction(MD);
13415 
13416           // If the newly-chosen key function is already defined, then we
13417           // need to mark the vtable as used retroactively.
13418           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13419           const FunctionDecl *Definition;
13420           if (KeyFunction && KeyFunction->isDefined(Definition))
13421             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13422         } else {
13423           // We just defined they key function; mark the vtable as used.
13424           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13425         }
13426       }
13427     }
13428 
13429     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13430            "Function parsing confused");
13431   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13432     assert(MD == getCurMethodDecl() && "Method parsing confused");
13433     MD->setBody(Body);
13434     if (!MD->isInvalidDecl()) {
13435       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13436                                              MD->getReturnType(), MD);
13437 
13438       if (Body)
13439         computeNRVO(Body, getCurFunction());
13440     }
13441     if (getCurFunction()->ObjCShouldCallSuper) {
13442       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13443           << MD->getSelector().getAsString();
13444       getCurFunction()->ObjCShouldCallSuper = false;
13445     }
13446     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13447       const ObjCMethodDecl *InitMethod = nullptr;
13448       bool isDesignated =
13449           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13450       assert(isDesignated && InitMethod);
13451       (void)isDesignated;
13452 
13453       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13454         auto IFace = MD->getClassInterface();
13455         if (!IFace)
13456           return false;
13457         auto SuperD = IFace->getSuperClass();
13458         if (!SuperD)
13459           return false;
13460         return SuperD->getIdentifier() ==
13461             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13462       };
13463       // Don't issue this warning for unavailable inits or direct subclasses
13464       // of NSObject.
13465       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13466         Diag(MD->getLocation(),
13467              diag::warn_objc_designated_init_missing_super_call);
13468         Diag(InitMethod->getLocation(),
13469              diag::note_objc_designated_init_marked_here);
13470       }
13471       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13472     }
13473     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13474       // Don't issue this warning for unavaialable inits.
13475       if (!MD->isUnavailable())
13476         Diag(MD->getLocation(),
13477              diag::warn_objc_secondary_init_missing_init_call);
13478       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13479     }
13480 
13481     diagnoseImplicitlyRetainedSelf(*this);
13482   } else {
13483     // Parsing the function declaration failed in some way. Pop the fake scope
13484     // we pushed on.
13485     PopFunctionScopeInfo(ActivePolicy, dcl);
13486     return nullptr;
13487   }
13488 
13489   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13490     DiagnoseUnguardedAvailabilityViolations(dcl);
13491 
13492   assert(!getCurFunction()->ObjCShouldCallSuper &&
13493          "This should only be set for ObjC methods, which should have been "
13494          "handled in the block above.");
13495 
13496   // Verify and clean out per-function state.
13497   if (Body && (!FD || !FD->isDefaulted())) {
13498     // C++ constructors that have function-try-blocks can't have return
13499     // statements in the handlers of that block. (C++ [except.handle]p14)
13500     // Verify this.
13501     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13502       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13503 
13504     // Verify that gotos and switch cases don't jump into scopes illegally.
13505     if (getCurFunction()->NeedsScopeChecking() &&
13506         !PP.isCodeCompletionEnabled())
13507       DiagnoseInvalidJumps(Body);
13508 
13509     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13510       if (!Destructor->getParent()->isDependentType())
13511         CheckDestructor(Destructor);
13512 
13513       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13514                                              Destructor->getParent());
13515     }
13516 
13517     // If any errors have occurred, clear out any temporaries that may have
13518     // been leftover. This ensures that these temporaries won't be picked up for
13519     // deletion in some later function.
13520     if (getDiagnostics().hasErrorOccurred() ||
13521         getDiagnostics().getSuppressAllDiagnostics()) {
13522       DiscardCleanupsInEvaluationContext();
13523     }
13524     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13525         !isa<FunctionTemplateDecl>(dcl)) {
13526       // Since the body is valid, issue any analysis-based warnings that are
13527       // enabled.
13528       ActivePolicy = &WP;
13529     }
13530 
13531     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13532         (!CheckConstexprFunctionDecl(FD) ||
13533          !CheckConstexprFunctionBody(FD, Body)))
13534       FD->setInvalidDecl();
13535 
13536     if (FD && FD->hasAttr<NakedAttr>()) {
13537       for (const Stmt *S : Body->children()) {
13538         // Allow local register variables without initializer as they don't
13539         // require prologue.
13540         bool RegisterVariables = false;
13541         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13542           for (const auto *Decl : DS->decls()) {
13543             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13544               RegisterVariables =
13545                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13546               if (!RegisterVariables)
13547                 break;
13548             }
13549           }
13550         }
13551         if (RegisterVariables)
13552           continue;
13553         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13554           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13555           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13556           FD->setInvalidDecl();
13557           break;
13558         }
13559       }
13560     }
13561 
13562     assert(ExprCleanupObjects.size() ==
13563                ExprEvalContexts.back().NumCleanupObjects &&
13564            "Leftover temporaries in function");
13565     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13566     assert(MaybeODRUseExprs.empty() &&
13567            "Leftover expressions for odr-use checking");
13568   }
13569 
13570   if (!IsInstantiation)
13571     PopDeclContext();
13572 
13573   PopFunctionScopeInfo(ActivePolicy, dcl);
13574   // If any errors have occurred, clear out any temporaries that may have
13575   // been leftover. This ensures that these temporaries won't be picked up for
13576   // deletion in some later function.
13577   if (getDiagnostics().hasErrorOccurred()) {
13578     DiscardCleanupsInEvaluationContext();
13579   }
13580 
13581   return dcl;
13582 }
13583 
13584 /// When we finish delayed parsing of an attribute, we must attach it to the
13585 /// relevant Decl.
13586 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13587                                        ParsedAttributes &Attrs) {
13588   // Always attach attributes to the underlying decl.
13589   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13590     D = TD->getTemplatedDecl();
13591   ProcessDeclAttributeList(S, D, Attrs);
13592 
13593   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13594     if (Method->isStatic())
13595       checkThisInStaticMemberFunctionAttributes(Method);
13596 }
13597 
13598 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13599 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13600 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13601                                           IdentifierInfo &II, Scope *S) {
13602   // Find the scope in which the identifier is injected and the corresponding
13603   // DeclContext.
13604   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13605   // In that case, we inject the declaration into the translation unit scope
13606   // instead.
13607   Scope *BlockScope = S;
13608   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13609     BlockScope = BlockScope->getParent();
13610 
13611   Scope *ContextScope = BlockScope;
13612   while (!ContextScope->getEntity())
13613     ContextScope = ContextScope->getParent();
13614   ContextRAII SavedContext(*this, ContextScope->getEntity());
13615 
13616   // Before we produce a declaration for an implicitly defined
13617   // function, see whether there was a locally-scoped declaration of
13618   // this name as a function or variable. If so, use that
13619   // (non-visible) declaration, and complain about it.
13620   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13621   if (ExternCPrev) {
13622     // We still need to inject the function into the enclosing block scope so
13623     // that later (non-call) uses can see it.
13624     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13625 
13626     // C89 footnote 38:
13627     //   If in fact it is not defined as having type "function returning int",
13628     //   the behavior is undefined.
13629     if (!isa<FunctionDecl>(ExternCPrev) ||
13630         !Context.typesAreCompatible(
13631             cast<FunctionDecl>(ExternCPrev)->getType(),
13632             Context.getFunctionNoProtoType(Context.IntTy))) {
13633       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13634           << ExternCPrev << !getLangOpts().C99;
13635       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13636       return ExternCPrev;
13637     }
13638   }
13639 
13640   // Extension in C99.  Legal in C90, but warn about it.
13641   unsigned diag_id;
13642   if (II.getName().startswith("__builtin_"))
13643     diag_id = diag::warn_builtin_unknown;
13644   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13645   else if (getLangOpts().OpenCL)
13646     diag_id = diag::err_opencl_implicit_function_decl;
13647   else if (getLangOpts().C99)
13648     diag_id = diag::ext_implicit_function_decl;
13649   else
13650     diag_id = diag::warn_implicit_function_decl;
13651   Diag(Loc, diag_id) << &II;
13652 
13653   // If we found a prior declaration of this function, don't bother building
13654   // another one. We've already pushed that one into scope, so there's nothing
13655   // more to do.
13656   if (ExternCPrev)
13657     return ExternCPrev;
13658 
13659   // Because typo correction is expensive, only do it if the implicit
13660   // function declaration is going to be treated as an error.
13661   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13662     TypoCorrection Corrected;
13663     DeclFilterCCC<FunctionDecl> CCC{};
13664     if (S && (Corrected =
13665                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
13666                               S, nullptr, CCC, CTK_NonError)))
13667       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13668                    /*ErrorRecovery*/false);
13669   }
13670 
13671   // Set a Declarator for the implicit definition: int foo();
13672   const char *Dummy;
13673   AttributeFactory attrFactory;
13674   DeclSpec DS(attrFactory);
13675   unsigned DiagID;
13676   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13677                                   Context.getPrintingPolicy());
13678   (void)Error; // Silence warning.
13679   assert(!Error && "Error setting up implicit decl!");
13680   SourceLocation NoLoc;
13681   Declarator D(DS, DeclaratorContext::BlockContext);
13682   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13683                                              /*IsAmbiguous=*/false,
13684                                              /*LParenLoc=*/NoLoc,
13685                                              /*Params=*/nullptr,
13686                                              /*NumParams=*/0,
13687                                              /*EllipsisLoc=*/NoLoc,
13688                                              /*RParenLoc=*/NoLoc,
13689                                              /*RefQualifierIsLvalueRef=*/true,
13690                                              /*RefQualifierLoc=*/NoLoc,
13691                                              /*MutableLoc=*/NoLoc, EST_None,
13692                                              /*ESpecRange=*/SourceRange(),
13693                                              /*Exceptions=*/nullptr,
13694                                              /*ExceptionRanges=*/nullptr,
13695                                              /*NumExceptions=*/0,
13696                                              /*NoexceptExpr=*/nullptr,
13697                                              /*ExceptionSpecTokens=*/nullptr,
13698                                              /*DeclsInPrototype=*/None, Loc,
13699                                              Loc, D),
13700                 std::move(DS.getAttributes()), SourceLocation());
13701   D.SetIdentifier(&II, Loc);
13702 
13703   // Insert this function into the enclosing block scope.
13704   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13705   FD->setImplicit();
13706 
13707   AddKnownFunctionAttributes(FD);
13708 
13709   return FD;
13710 }
13711 
13712 /// Adds any function attributes that we know a priori based on
13713 /// the declaration of this function.
13714 ///
13715 /// These attributes can apply both to implicitly-declared builtins
13716 /// (like __builtin___printf_chk) or to library-declared functions
13717 /// like NSLog or printf.
13718 ///
13719 /// We need to check for duplicate attributes both here and where user-written
13720 /// attributes are applied to declarations.
13721 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13722   if (FD->isInvalidDecl())
13723     return;
13724 
13725   // If this is a built-in function, map its builtin attributes to
13726   // actual attributes.
13727   if (unsigned BuiltinID = FD->getBuiltinID()) {
13728     // Handle printf-formatting attributes.
13729     unsigned FormatIdx;
13730     bool HasVAListArg;
13731     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13732       if (!FD->hasAttr<FormatAttr>()) {
13733         const char *fmt = "printf";
13734         unsigned int NumParams = FD->getNumParams();
13735         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13736             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13737           fmt = "NSString";
13738         FD->addAttr(FormatAttr::CreateImplicit(Context,
13739                                                &Context.Idents.get(fmt),
13740                                                FormatIdx+1,
13741                                                HasVAListArg ? 0 : FormatIdx+2,
13742                                                FD->getLocation()));
13743       }
13744     }
13745     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13746                                              HasVAListArg)) {
13747      if (!FD->hasAttr<FormatAttr>())
13748        FD->addAttr(FormatAttr::CreateImplicit(Context,
13749                                               &Context.Idents.get("scanf"),
13750                                               FormatIdx+1,
13751                                               HasVAListArg ? 0 : FormatIdx+2,
13752                                               FD->getLocation()));
13753     }
13754 
13755     // Handle automatically recognized callbacks.
13756     SmallVector<int, 4> Encoding;
13757     if (!FD->hasAttr<CallbackAttr>() &&
13758         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13759       FD->addAttr(CallbackAttr::CreateImplicit(
13760           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13761 
13762     // Mark const if we don't care about errno and that is the only thing
13763     // preventing the function from being const. This allows IRgen to use LLVM
13764     // intrinsics for such functions.
13765     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13766         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13767       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13768 
13769     // We make "fma" on some platforms const because we know it does not set
13770     // errno in those environments even though it could set errno based on the
13771     // C standard.
13772     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13773     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13774         !FD->hasAttr<ConstAttr>()) {
13775       switch (BuiltinID) {
13776       case Builtin::BI__builtin_fma:
13777       case Builtin::BI__builtin_fmaf:
13778       case Builtin::BI__builtin_fmal:
13779       case Builtin::BIfma:
13780       case Builtin::BIfmaf:
13781       case Builtin::BIfmal:
13782         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13783         break;
13784       default:
13785         break;
13786       }
13787     }
13788 
13789     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13790         !FD->hasAttr<ReturnsTwiceAttr>())
13791       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13792                                          FD->getLocation()));
13793     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13794       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13795     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13796       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13797     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13798       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13799     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13800         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13801       // Add the appropriate attribute, depending on the CUDA compilation mode
13802       // and which target the builtin belongs to. For example, during host
13803       // compilation, aux builtins are __device__, while the rest are __host__.
13804       if (getLangOpts().CUDAIsDevice !=
13805           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13806         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13807       else
13808         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13809     }
13810   }
13811 
13812   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13813   // throw, add an implicit nothrow attribute to any extern "C" function we come
13814   // across.
13815   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13816       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13817     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13818     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13819       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13820   }
13821 
13822   IdentifierInfo *Name = FD->getIdentifier();
13823   if (!Name)
13824     return;
13825   if ((!getLangOpts().CPlusPlus &&
13826        FD->getDeclContext()->isTranslationUnit()) ||
13827       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13828        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13829        LinkageSpecDecl::lang_c)) {
13830     // Okay: this could be a libc/libm/Objective-C function we know
13831     // about.
13832   } else
13833     return;
13834 
13835   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13836     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13837     // target-specific builtins, perhaps?
13838     if (!FD->hasAttr<FormatAttr>())
13839       FD->addAttr(FormatAttr::CreateImplicit(Context,
13840                                              &Context.Idents.get("printf"), 2,
13841                                              Name->isStr("vasprintf") ? 0 : 3,
13842                                              FD->getLocation()));
13843   }
13844 
13845   if (Name->isStr("__CFStringMakeConstantString")) {
13846     // We already have a __builtin___CFStringMakeConstantString,
13847     // but builds that use -fno-constant-cfstrings don't go through that.
13848     if (!FD->hasAttr<FormatArgAttr>())
13849       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13850                                                 FD->getLocation()));
13851   }
13852 }
13853 
13854 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13855                                     TypeSourceInfo *TInfo) {
13856   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13857   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13858 
13859   if (!TInfo) {
13860     assert(D.isInvalidType() && "no declarator info for valid type");
13861     TInfo = Context.getTrivialTypeSourceInfo(T);
13862   }
13863 
13864   // Scope manipulation handled by caller.
13865   TypedefDecl *NewTD =
13866       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13867                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13868 
13869   // Bail out immediately if we have an invalid declaration.
13870   if (D.isInvalidType()) {
13871     NewTD->setInvalidDecl();
13872     return NewTD;
13873   }
13874 
13875   if (D.getDeclSpec().isModulePrivateSpecified()) {
13876     if (CurContext->isFunctionOrMethod())
13877       Diag(NewTD->getLocation(), diag::err_module_private_local)
13878         << 2 << NewTD->getDeclName()
13879         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13880         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13881     else
13882       NewTD->setModulePrivate();
13883   }
13884 
13885   // C++ [dcl.typedef]p8:
13886   //   If the typedef declaration defines an unnamed class (or
13887   //   enum), the first typedef-name declared by the declaration
13888   //   to be that class type (or enum type) is used to denote the
13889   //   class type (or enum type) for linkage purposes only.
13890   // We need to check whether the type was declared in the declaration.
13891   switch (D.getDeclSpec().getTypeSpecType()) {
13892   case TST_enum:
13893   case TST_struct:
13894   case TST_interface:
13895   case TST_union:
13896   case TST_class: {
13897     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13898     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13899     break;
13900   }
13901 
13902   default:
13903     break;
13904   }
13905 
13906   return NewTD;
13907 }
13908 
13909 /// Check that this is a valid underlying type for an enum declaration.
13910 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13911   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13912   QualType T = TI->getType();
13913 
13914   if (T->isDependentType())
13915     return false;
13916 
13917   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13918     if (BT->isInteger())
13919       return false;
13920 
13921   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13922   return true;
13923 }
13924 
13925 /// Check whether this is a valid redeclaration of a previous enumeration.
13926 /// \return true if the redeclaration was invalid.
13927 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13928                                   QualType EnumUnderlyingTy, bool IsFixed,
13929                                   const EnumDecl *Prev) {
13930   if (IsScoped != Prev->isScoped()) {
13931     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13932       << Prev->isScoped();
13933     Diag(Prev->getLocation(), diag::note_previous_declaration);
13934     return true;
13935   }
13936 
13937   if (IsFixed && Prev->isFixed()) {
13938     if (!EnumUnderlyingTy->isDependentType() &&
13939         !Prev->getIntegerType()->isDependentType() &&
13940         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13941                                         Prev->getIntegerType())) {
13942       // TODO: Highlight the underlying type of the redeclaration.
13943       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13944         << EnumUnderlyingTy << Prev->getIntegerType();
13945       Diag(Prev->getLocation(), diag::note_previous_declaration)
13946           << Prev->getIntegerTypeRange();
13947       return true;
13948     }
13949   } else if (IsFixed != Prev->isFixed()) {
13950     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13951       << Prev->isFixed();
13952     Diag(Prev->getLocation(), diag::note_previous_declaration);
13953     return true;
13954   }
13955 
13956   return false;
13957 }
13958 
13959 /// Get diagnostic %select index for tag kind for
13960 /// redeclaration diagnostic message.
13961 /// WARNING: Indexes apply to particular diagnostics only!
13962 ///
13963 /// \returns diagnostic %select index.
13964 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13965   switch (Tag) {
13966   case TTK_Struct: return 0;
13967   case TTK_Interface: return 1;
13968   case TTK_Class:  return 2;
13969   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13970   }
13971 }
13972 
13973 /// Determine if tag kind is a class-key compatible with
13974 /// class for redeclaration (class, struct, or __interface).
13975 ///
13976 /// \returns true iff the tag kind is compatible.
13977 static bool isClassCompatTagKind(TagTypeKind Tag)
13978 {
13979   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13980 }
13981 
13982 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13983                                              TagTypeKind TTK) {
13984   if (isa<TypedefDecl>(PrevDecl))
13985     return NTK_Typedef;
13986   else if (isa<TypeAliasDecl>(PrevDecl))
13987     return NTK_TypeAlias;
13988   else if (isa<ClassTemplateDecl>(PrevDecl))
13989     return NTK_Template;
13990   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13991     return NTK_TypeAliasTemplate;
13992   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13993     return NTK_TemplateTemplateArgument;
13994   switch (TTK) {
13995   case TTK_Struct:
13996   case TTK_Interface:
13997   case TTK_Class:
13998     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13999   case TTK_Union:
14000     return NTK_NonUnion;
14001   case TTK_Enum:
14002     return NTK_NonEnum;
14003   }
14004   llvm_unreachable("invalid TTK");
14005 }
14006 
14007 /// Determine whether a tag with a given kind is acceptable
14008 /// as a redeclaration of the given tag declaration.
14009 ///
14010 /// \returns true if the new tag kind is acceptable, false otherwise.
14011 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14012                                         TagTypeKind NewTag, bool isDefinition,
14013                                         SourceLocation NewTagLoc,
14014                                         const IdentifierInfo *Name) {
14015   // C++ [dcl.type.elab]p3:
14016   //   The class-key or enum keyword present in the
14017   //   elaborated-type-specifier shall agree in kind with the
14018   //   declaration to which the name in the elaborated-type-specifier
14019   //   refers. This rule also applies to the form of
14020   //   elaborated-type-specifier that declares a class-name or
14021   //   friend class since it can be construed as referring to the
14022   //   definition of the class. Thus, in any
14023   //   elaborated-type-specifier, the enum keyword shall be used to
14024   //   refer to an enumeration (7.2), the union class-key shall be
14025   //   used to refer to a union (clause 9), and either the class or
14026   //   struct class-key shall be used to refer to a class (clause 9)
14027   //   declared using the class or struct class-key.
14028   TagTypeKind OldTag = Previous->getTagKind();
14029   if (OldTag != NewTag &&
14030       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14031     return false;
14032 
14033   // Tags are compatible, but we might still want to warn on mismatched tags.
14034   // Non-class tags can't be mismatched at this point.
14035   if (!isClassCompatTagKind(NewTag))
14036     return true;
14037 
14038   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14039   // by our warning analysis. We don't want to warn about mismatches with (eg)
14040   // declarations in system headers that are designed to be specialized, but if
14041   // a user asks us to warn, we should warn if their code contains mismatched
14042   // declarations.
14043   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14044     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14045                                       Loc);
14046   };
14047   if (IsIgnoredLoc(NewTagLoc))
14048     return true;
14049 
14050   auto IsIgnored = [&](const TagDecl *Tag) {
14051     return IsIgnoredLoc(Tag->getLocation());
14052   };
14053   while (IsIgnored(Previous)) {
14054     Previous = Previous->getPreviousDecl();
14055     if (!Previous)
14056       return true;
14057     OldTag = Previous->getTagKind();
14058   }
14059 
14060   bool isTemplate = false;
14061   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14062     isTemplate = Record->getDescribedClassTemplate();
14063 
14064   if (inTemplateInstantiation()) {
14065     if (OldTag != NewTag) {
14066       // In a template instantiation, do not offer fix-its for tag mismatches
14067       // since they usually mess up the template instead of fixing the problem.
14068       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14069         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14070         << getRedeclDiagFromTagKind(OldTag);
14071       // FIXME: Note previous location?
14072     }
14073     return true;
14074   }
14075 
14076   if (isDefinition) {
14077     // On definitions, check all previous tags and issue a fix-it for each
14078     // one that doesn't match the current tag.
14079     if (Previous->getDefinition()) {
14080       // Don't suggest fix-its for redefinitions.
14081       return true;
14082     }
14083 
14084     bool previousMismatch = false;
14085     for (const TagDecl *I : Previous->redecls()) {
14086       if (I->getTagKind() != NewTag) {
14087         // Ignore previous declarations for which the warning was disabled.
14088         if (IsIgnored(I))
14089           continue;
14090 
14091         if (!previousMismatch) {
14092           previousMismatch = true;
14093           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14094             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14095             << getRedeclDiagFromTagKind(I->getTagKind());
14096         }
14097         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14098           << getRedeclDiagFromTagKind(NewTag)
14099           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14100                TypeWithKeyword::getTagTypeKindName(NewTag));
14101       }
14102     }
14103     return true;
14104   }
14105 
14106   // Identify the prevailing tag kind: this is the kind of the definition (if
14107   // there is a non-ignored definition), or otherwise the kind of the prior
14108   // (non-ignored) declaration.
14109   const TagDecl *PrevDef = Previous->getDefinition();
14110   if (PrevDef && IsIgnored(PrevDef))
14111     PrevDef = nullptr;
14112   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14113   if (Redecl->getTagKind() != NewTag) {
14114     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14115       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14116       << getRedeclDiagFromTagKind(OldTag);
14117     Diag(Redecl->getLocation(), diag::note_previous_use);
14118 
14119     // If there is a previous definition, suggest a fix-it.
14120     if (PrevDef) {
14121       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14122         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14123         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14124              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14125     }
14126   }
14127 
14128   return true;
14129 }
14130 
14131 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14132 /// from an outer enclosing namespace or file scope inside a friend declaration.
14133 /// This should provide the commented out code in the following snippet:
14134 ///   namespace N {
14135 ///     struct X;
14136 ///     namespace M {
14137 ///       struct Y { friend struct /*N::*/ X; };
14138 ///     }
14139 ///   }
14140 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14141                                          SourceLocation NameLoc) {
14142   // While the decl is in a namespace, do repeated lookup of that name and see
14143   // if we get the same namespace back.  If we do not, continue until
14144   // translation unit scope, at which point we have a fully qualified NNS.
14145   SmallVector<IdentifierInfo *, 4> Namespaces;
14146   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14147   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14148     // This tag should be declared in a namespace, which can only be enclosed by
14149     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14150     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14151     if (!Namespace || Namespace->isAnonymousNamespace())
14152       return FixItHint();
14153     IdentifierInfo *II = Namespace->getIdentifier();
14154     Namespaces.push_back(II);
14155     NamedDecl *Lookup = SemaRef.LookupSingleName(
14156         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14157     if (Lookup == Namespace)
14158       break;
14159   }
14160 
14161   // Once we have all the namespaces, reverse them to go outermost first, and
14162   // build an NNS.
14163   SmallString<64> Insertion;
14164   llvm::raw_svector_ostream OS(Insertion);
14165   if (DC->isTranslationUnit())
14166     OS << "::";
14167   std::reverse(Namespaces.begin(), Namespaces.end());
14168   for (auto *II : Namespaces)
14169     OS << II->getName() << "::";
14170   return FixItHint::CreateInsertion(NameLoc, Insertion);
14171 }
14172 
14173 /// Determine whether a tag originally declared in context \p OldDC can
14174 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14175 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14176 /// using-declaration).
14177 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14178                                          DeclContext *NewDC) {
14179   OldDC = OldDC->getRedeclContext();
14180   NewDC = NewDC->getRedeclContext();
14181 
14182   if (OldDC->Equals(NewDC))
14183     return true;
14184 
14185   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14186   // encloses the other).
14187   if (S.getLangOpts().MSVCCompat &&
14188       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14189     return true;
14190 
14191   return false;
14192 }
14193 
14194 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14195 /// former case, Name will be non-null.  In the later case, Name will be null.
14196 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14197 /// reference/declaration/definition of a tag.
14198 ///
14199 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14200 /// trailing-type-specifier) other than one in an alias-declaration.
14201 ///
14202 /// \param SkipBody If non-null, will be set to indicate if the caller should
14203 /// skip the definition of this tag and treat it as if it were a declaration.
14204 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14205                      SourceLocation KWLoc, CXXScopeSpec &SS,
14206                      IdentifierInfo *Name, SourceLocation NameLoc,
14207                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14208                      SourceLocation ModulePrivateLoc,
14209                      MultiTemplateParamsArg TemplateParameterLists,
14210                      bool &OwnedDecl, bool &IsDependent,
14211                      SourceLocation ScopedEnumKWLoc,
14212                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14213                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14214                      SkipBodyInfo *SkipBody) {
14215   // If this is not a definition, it must have a name.
14216   IdentifierInfo *OrigName = Name;
14217   assert((Name != nullptr || TUK == TUK_Definition) &&
14218          "Nameless record must be a definition!");
14219   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14220 
14221   OwnedDecl = false;
14222   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14223   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14224 
14225   // FIXME: Check member specializations more carefully.
14226   bool isMemberSpecialization = false;
14227   bool Invalid = false;
14228 
14229   // We only need to do this matching if we have template parameters
14230   // or a scope specifier, which also conveniently avoids this work
14231   // for non-C++ cases.
14232   if (TemplateParameterLists.size() > 0 ||
14233       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14234     if (TemplateParameterList *TemplateParams =
14235             MatchTemplateParametersToScopeSpecifier(
14236                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14237                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14238       if (Kind == TTK_Enum) {
14239         Diag(KWLoc, diag::err_enum_template);
14240         return nullptr;
14241       }
14242 
14243       if (TemplateParams->size() > 0) {
14244         // This is a declaration or definition of a class template (which may
14245         // be a member of another template).
14246 
14247         if (Invalid)
14248           return nullptr;
14249 
14250         OwnedDecl = false;
14251         DeclResult Result = CheckClassTemplate(
14252             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14253             AS, ModulePrivateLoc,
14254             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14255             TemplateParameterLists.data(), SkipBody);
14256         return Result.get();
14257       } else {
14258         // The "template<>" header is extraneous.
14259         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14260           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14261         isMemberSpecialization = true;
14262       }
14263     }
14264   }
14265 
14266   // Figure out the underlying type if this a enum declaration. We need to do
14267   // this early, because it's needed to detect if this is an incompatible
14268   // redeclaration.
14269   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14270   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14271 
14272   if (Kind == TTK_Enum) {
14273     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14274       // No underlying type explicitly specified, or we failed to parse the
14275       // type, default to int.
14276       EnumUnderlying = Context.IntTy.getTypePtr();
14277     } else if (UnderlyingType.get()) {
14278       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14279       // integral type; any cv-qualification is ignored.
14280       TypeSourceInfo *TI = nullptr;
14281       GetTypeFromParser(UnderlyingType.get(), &TI);
14282       EnumUnderlying = TI;
14283 
14284       if (CheckEnumUnderlyingType(TI))
14285         // Recover by falling back to int.
14286         EnumUnderlying = Context.IntTy.getTypePtr();
14287 
14288       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14289                                           UPPC_FixedUnderlyingType))
14290         EnumUnderlying = Context.IntTy.getTypePtr();
14291 
14292     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14293       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14294       // of 'int'. However, if this is an unfixed forward declaration, don't set
14295       // the underlying type unless the user enables -fms-compatibility. This
14296       // makes unfixed forward declared enums incomplete and is more conforming.
14297       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14298         EnumUnderlying = Context.IntTy.getTypePtr();
14299     }
14300   }
14301 
14302   DeclContext *SearchDC = CurContext;
14303   DeclContext *DC = CurContext;
14304   bool isStdBadAlloc = false;
14305   bool isStdAlignValT = false;
14306 
14307   RedeclarationKind Redecl = forRedeclarationInCurContext();
14308   if (TUK == TUK_Friend || TUK == TUK_Reference)
14309     Redecl = NotForRedeclaration;
14310 
14311   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14312   /// implemented asks for structural equivalence checking, the returned decl
14313   /// here is passed back to the parser, allowing the tag body to be parsed.
14314   auto createTagFromNewDecl = [&]() -> TagDecl * {
14315     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14316     // If there is an identifier, use the location of the identifier as the
14317     // location of the decl, otherwise use the location of the struct/union
14318     // keyword.
14319     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14320     TagDecl *New = nullptr;
14321 
14322     if (Kind == TTK_Enum) {
14323       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14324                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14325       // If this is an undefined enum, bail.
14326       if (TUK != TUK_Definition && !Invalid)
14327         return nullptr;
14328       if (EnumUnderlying) {
14329         EnumDecl *ED = cast<EnumDecl>(New);
14330         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14331           ED->setIntegerTypeSourceInfo(TI);
14332         else
14333           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14334         ED->setPromotionType(ED->getIntegerType());
14335       }
14336     } else { // struct/union
14337       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14338                                nullptr);
14339     }
14340 
14341     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14342       // Add alignment attributes if necessary; these attributes are checked
14343       // when the ASTContext lays out the structure.
14344       //
14345       // It is important for implementing the correct semantics that this
14346       // happen here (in ActOnTag). The #pragma pack stack is
14347       // maintained as a result of parser callbacks which can occur at
14348       // many points during the parsing of a struct declaration (because
14349       // the #pragma tokens are effectively skipped over during the
14350       // parsing of the struct).
14351       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14352         AddAlignmentAttributesForRecord(RD);
14353         AddMsStructLayoutForRecord(RD);
14354       }
14355     }
14356     New->setLexicalDeclContext(CurContext);
14357     return New;
14358   };
14359 
14360   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14361   if (Name && SS.isNotEmpty()) {
14362     // We have a nested-name tag ('struct foo::bar').
14363 
14364     // Check for invalid 'foo::'.
14365     if (SS.isInvalid()) {
14366       Name = nullptr;
14367       goto CreateNewDecl;
14368     }
14369 
14370     // If this is a friend or a reference to a class in a dependent
14371     // context, don't try to make a decl for it.
14372     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14373       DC = computeDeclContext(SS, false);
14374       if (!DC) {
14375         IsDependent = true;
14376         return nullptr;
14377       }
14378     } else {
14379       DC = computeDeclContext(SS, true);
14380       if (!DC) {
14381         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14382           << SS.getRange();
14383         return nullptr;
14384       }
14385     }
14386 
14387     if (RequireCompleteDeclContext(SS, DC))
14388       return nullptr;
14389 
14390     SearchDC = DC;
14391     // Look-up name inside 'foo::'.
14392     LookupQualifiedName(Previous, DC);
14393 
14394     if (Previous.isAmbiguous())
14395       return nullptr;
14396 
14397     if (Previous.empty()) {
14398       // Name lookup did not find anything. However, if the
14399       // nested-name-specifier refers to the current instantiation,
14400       // and that current instantiation has any dependent base
14401       // classes, we might find something at instantiation time: treat
14402       // this as a dependent elaborated-type-specifier.
14403       // But this only makes any sense for reference-like lookups.
14404       if (Previous.wasNotFoundInCurrentInstantiation() &&
14405           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14406         IsDependent = true;
14407         return nullptr;
14408       }
14409 
14410       // A tag 'foo::bar' must already exist.
14411       Diag(NameLoc, diag::err_not_tag_in_scope)
14412         << Kind << Name << DC << SS.getRange();
14413       Name = nullptr;
14414       Invalid = true;
14415       goto CreateNewDecl;
14416     }
14417   } else if (Name) {
14418     // C++14 [class.mem]p14:
14419     //   If T is the name of a class, then each of the following shall have a
14420     //   name different from T:
14421     //    -- every member of class T that is itself a type
14422     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14423         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14424       return nullptr;
14425 
14426     // If this is a named struct, check to see if there was a previous forward
14427     // declaration or definition.
14428     // FIXME: We're looking into outer scopes here, even when we
14429     // shouldn't be. Doing so can result in ambiguities that we
14430     // shouldn't be diagnosing.
14431     LookupName(Previous, S);
14432 
14433     // When declaring or defining a tag, ignore ambiguities introduced
14434     // by types using'ed into this scope.
14435     if (Previous.isAmbiguous() &&
14436         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14437       LookupResult::Filter F = Previous.makeFilter();
14438       while (F.hasNext()) {
14439         NamedDecl *ND = F.next();
14440         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14441                 SearchDC->getRedeclContext()))
14442           F.erase();
14443       }
14444       F.done();
14445     }
14446 
14447     // C++11 [namespace.memdef]p3:
14448     //   If the name in a friend declaration is neither qualified nor
14449     //   a template-id and the declaration is a function or an
14450     //   elaborated-type-specifier, the lookup to determine whether
14451     //   the entity has been previously declared shall not consider
14452     //   any scopes outside the innermost enclosing namespace.
14453     //
14454     // MSVC doesn't implement the above rule for types, so a friend tag
14455     // declaration may be a redeclaration of a type declared in an enclosing
14456     // scope.  They do implement this rule for friend functions.
14457     //
14458     // Does it matter that this should be by scope instead of by
14459     // semantic context?
14460     if (!Previous.empty() && TUK == TUK_Friend) {
14461       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14462       LookupResult::Filter F = Previous.makeFilter();
14463       bool FriendSawTagOutsideEnclosingNamespace = false;
14464       while (F.hasNext()) {
14465         NamedDecl *ND = F.next();
14466         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14467         if (DC->isFileContext() &&
14468             !EnclosingNS->Encloses(ND->getDeclContext())) {
14469           if (getLangOpts().MSVCCompat)
14470             FriendSawTagOutsideEnclosingNamespace = true;
14471           else
14472             F.erase();
14473         }
14474       }
14475       F.done();
14476 
14477       // Diagnose this MSVC extension in the easy case where lookup would have
14478       // unambiguously found something outside the enclosing namespace.
14479       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14480         NamedDecl *ND = Previous.getFoundDecl();
14481         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14482             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14483       }
14484     }
14485 
14486     // Note:  there used to be some attempt at recovery here.
14487     if (Previous.isAmbiguous())
14488       return nullptr;
14489 
14490     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14491       // FIXME: This makes sure that we ignore the contexts associated
14492       // with C structs, unions, and enums when looking for a matching
14493       // tag declaration or definition. See the similar lookup tweak
14494       // in Sema::LookupName; is there a better way to deal with this?
14495       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14496         SearchDC = SearchDC->getParent();
14497     }
14498   }
14499 
14500   if (Previous.isSingleResult() &&
14501       Previous.getFoundDecl()->isTemplateParameter()) {
14502     // Maybe we will complain about the shadowed template parameter.
14503     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14504     // Just pretend that we didn't see the previous declaration.
14505     Previous.clear();
14506   }
14507 
14508   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14509       DC->Equals(getStdNamespace())) {
14510     if (Name->isStr("bad_alloc")) {
14511       // This is a declaration of or a reference to "std::bad_alloc".
14512       isStdBadAlloc = true;
14513 
14514       // If std::bad_alloc has been implicitly declared (but made invisible to
14515       // name lookup), fill in this implicit declaration as the previous
14516       // declaration, so that the declarations get chained appropriately.
14517       if (Previous.empty() && StdBadAlloc)
14518         Previous.addDecl(getStdBadAlloc());
14519     } else if (Name->isStr("align_val_t")) {
14520       isStdAlignValT = true;
14521       if (Previous.empty() && StdAlignValT)
14522         Previous.addDecl(getStdAlignValT());
14523     }
14524   }
14525 
14526   // If we didn't find a previous declaration, and this is a reference
14527   // (or friend reference), move to the correct scope.  In C++, we
14528   // also need to do a redeclaration lookup there, just in case
14529   // there's a shadow friend decl.
14530   if (Name && Previous.empty() &&
14531       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14532     if (Invalid) goto CreateNewDecl;
14533     assert(SS.isEmpty());
14534 
14535     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14536       // C++ [basic.scope.pdecl]p5:
14537       //   -- for an elaborated-type-specifier of the form
14538       //
14539       //          class-key identifier
14540       //
14541       //      if the elaborated-type-specifier is used in the
14542       //      decl-specifier-seq or parameter-declaration-clause of a
14543       //      function defined in namespace scope, the identifier is
14544       //      declared as a class-name in the namespace that contains
14545       //      the declaration; otherwise, except as a friend
14546       //      declaration, the identifier is declared in the smallest
14547       //      non-class, non-function-prototype scope that contains the
14548       //      declaration.
14549       //
14550       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14551       // C structs and unions.
14552       //
14553       // It is an error in C++ to declare (rather than define) an enum
14554       // type, including via an elaborated type specifier.  We'll
14555       // diagnose that later; for now, declare the enum in the same
14556       // scope as we would have picked for any other tag type.
14557       //
14558       // GNU C also supports this behavior as part of its incomplete
14559       // enum types extension, while GNU C++ does not.
14560       //
14561       // Find the context where we'll be declaring the tag.
14562       // FIXME: We would like to maintain the current DeclContext as the
14563       // lexical context,
14564       SearchDC = getTagInjectionContext(SearchDC);
14565 
14566       // Find the scope where we'll be declaring the tag.
14567       S = getTagInjectionScope(S, getLangOpts());
14568     } else {
14569       assert(TUK == TUK_Friend);
14570       // C++ [namespace.memdef]p3:
14571       //   If a friend declaration in a non-local class first declares a
14572       //   class or function, the friend class or function is a member of
14573       //   the innermost enclosing namespace.
14574       SearchDC = SearchDC->getEnclosingNamespaceContext();
14575     }
14576 
14577     // In C++, we need to do a redeclaration lookup to properly
14578     // diagnose some problems.
14579     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14580     // hidden declaration so that we don't get ambiguity errors when using a
14581     // type declared by an elaborated-type-specifier.  In C that is not correct
14582     // and we should instead merge compatible types found by lookup.
14583     if (getLangOpts().CPlusPlus) {
14584       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14585       LookupQualifiedName(Previous, SearchDC);
14586     } else {
14587       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14588       LookupName(Previous, S);
14589     }
14590   }
14591 
14592   // If we have a known previous declaration to use, then use it.
14593   if (Previous.empty() && SkipBody && SkipBody->Previous)
14594     Previous.addDecl(SkipBody->Previous);
14595 
14596   if (!Previous.empty()) {
14597     NamedDecl *PrevDecl = Previous.getFoundDecl();
14598     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14599 
14600     // It's okay to have a tag decl in the same scope as a typedef
14601     // which hides a tag decl in the same scope.  Finding this
14602     // insanity with a redeclaration lookup can only actually happen
14603     // in C++.
14604     //
14605     // This is also okay for elaborated-type-specifiers, which is
14606     // technically forbidden by the current standard but which is
14607     // okay according to the likely resolution of an open issue;
14608     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14609     if (getLangOpts().CPlusPlus) {
14610       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14611         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14612           TagDecl *Tag = TT->getDecl();
14613           if (Tag->getDeclName() == Name &&
14614               Tag->getDeclContext()->getRedeclContext()
14615                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14616             PrevDecl = Tag;
14617             Previous.clear();
14618             Previous.addDecl(Tag);
14619             Previous.resolveKind();
14620           }
14621         }
14622       }
14623     }
14624 
14625     // If this is a redeclaration of a using shadow declaration, it must
14626     // declare a tag in the same context. In MSVC mode, we allow a
14627     // redefinition if either context is within the other.
14628     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14629       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14630       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14631           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14632           !(OldTag && isAcceptableTagRedeclContext(
14633                           *this, OldTag->getDeclContext(), SearchDC))) {
14634         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14635         Diag(Shadow->getTargetDecl()->getLocation(),
14636              diag::note_using_decl_target);
14637         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14638             << 0;
14639         // Recover by ignoring the old declaration.
14640         Previous.clear();
14641         goto CreateNewDecl;
14642       }
14643     }
14644 
14645     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14646       // If this is a use of a previous tag, or if the tag is already declared
14647       // in the same scope (so that the definition/declaration completes or
14648       // rementions the tag), reuse the decl.
14649       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14650           isDeclInScope(DirectPrevDecl, SearchDC, S,
14651                         SS.isNotEmpty() || isMemberSpecialization)) {
14652         // Make sure that this wasn't declared as an enum and now used as a
14653         // struct or something similar.
14654         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14655                                           TUK == TUK_Definition, KWLoc,
14656                                           Name)) {
14657           bool SafeToContinue
14658             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14659                Kind != TTK_Enum);
14660           if (SafeToContinue)
14661             Diag(KWLoc, diag::err_use_with_wrong_tag)
14662               << Name
14663               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14664                                               PrevTagDecl->getKindName());
14665           else
14666             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14667           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14668 
14669           if (SafeToContinue)
14670             Kind = PrevTagDecl->getTagKind();
14671           else {
14672             // Recover by making this an anonymous redefinition.
14673             Name = nullptr;
14674             Previous.clear();
14675             Invalid = true;
14676           }
14677         }
14678 
14679         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14680           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14681 
14682           // If this is an elaborated-type-specifier for a scoped enumeration,
14683           // the 'class' keyword is not necessary and not permitted.
14684           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14685             if (ScopedEnum)
14686               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14687                 << PrevEnum->isScoped()
14688                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14689             return PrevTagDecl;
14690           }
14691 
14692           QualType EnumUnderlyingTy;
14693           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14694             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14695           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14696             EnumUnderlyingTy = QualType(T, 0);
14697 
14698           // All conflicts with previous declarations are recovered by
14699           // returning the previous declaration, unless this is a definition,
14700           // in which case we want the caller to bail out.
14701           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14702                                      ScopedEnum, EnumUnderlyingTy,
14703                                      IsFixed, PrevEnum))
14704             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14705         }
14706 
14707         // C++11 [class.mem]p1:
14708         //   A member shall not be declared twice in the member-specification,
14709         //   except that a nested class or member class template can be declared
14710         //   and then later defined.
14711         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14712             S->isDeclScope(PrevDecl)) {
14713           Diag(NameLoc, diag::ext_member_redeclared);
14714           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14715         }
14716 
14717         if (!Invalid) {
14718           // If this is a use, just return the declaration we found, unless
14719           // we have attributes.
14720           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14721             if (!Attrs.empty()) {
14722               // FIXME: Diagnose these attributes. For now, we create a new
14723               // declaration to hold them.
14724             } else if (TUK == TUK_Reference &&
14725                        (PrevTagDecl->getFriendObjectKind() ==
14726                             Decl::FOK_Undeclared ||
14727                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14728                        SS.isEmpty()) {
14729               // This declaration is a reference to an existing entity, but
14730               // has different visibility from that entity: it either makes
14731               // a friend visible or it makes a type visible in a new module.
14732               // In either case, create a new declaration. We only do this if
14733               // the declaration would have meant the same thing if no prior
14734               // declaration were found, that is, if it was found in the same
14735               // scope where we would have injected a declaration.
14736               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14737                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14738                 return PrevTagDecl;
14739               // This is in the injected scope, create a new declaration in
14740               // that scope.
14741               S = getTagInjectionScope(S, getLangOpts());
14742             } else {
14743               return PrevTagDecl;
14744             }
14745           }
14746 
14747           // Diagnose attempts to redefine a tag.
14748           if (TUK == TUK_Definition) {
14749             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14750               // If we're defining a specialization and the previous definition
14751               // is from an implicit instantiation, don't emit an error
14752               // here; we'll catch this in the general case below.
14753               bool IsExplicitSpecializationAfterInstantiation = false;
14754               if (isMemberSpecialization) {
14755                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14756                   IsExplicitSpecializationAfterInstantiation =
14757                     RD->getTemplateSpecializationKind() !=
14758                     TSK_ExplicitSpecialization;
14759                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14760                   IsExplicitSpecializationAfterInstantiation =
14761                     ED->getTemplateSpecializationKind() !=
14762                     TSK_ExplicitSpecialization;
14763               }
14764 
14765               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14766               // not keep more that one definition around (merge them). However,
14767               // ensure the decl passes the structural compatibility check in
14768               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14769               NamedDecl *Hidden = nullptr;
14770               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14771                 // There is a definition of this tag, but it is not visible. We
14772                 // explicitly make use of C++'s one definition rule here, and
14773                 // assume that this definition is identical to the hidden one
14774                 // we already have. Make the existing definition visible and
14775                 // use it in place of this one.
14776                 if (!getLangOpts().CPlusPlus) {
14777                   // Postpone making the old definition visible until after we
14778                   // complete parsing the new one and do the structural
14779                   // comparison.
14780                   SkipBody->CheckSameAsPrevious = true;
14781                   SkipBody->New = createTagFromNewDecl();
14782                   SkipBody->Previous = Def;
14783                   return Def;
14784                 } else {
14785                   SkipBody->ShouldSkip = true;
14786                   SkipBody->Previous = Def;
14787                   makeMergedDefinitionVisible(Hidden);
14788                   // Carry on and handle it like a normal definition. We'll
14789                   // skip starting the definitiion later.
14790                 }
14791               } else if (!IsExplicitSpecializationAfterInstantiation) {
14792                 // A redeclaration in function prototype scope in C isn't
14793                 // visible elsewhere, so merely issue a warning.
14794                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14795                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14796                 else
14797                   Diag(NameLoc, diag::err_redefinition) << Name;
14798                 notePreviousDefinition(Def,
14799                                        NameLoc.isValid() ? NameLoc : KWLoc);
14800                 // If this is a redefinition, recover by making this
14801                 // struct be anonymous, which will make any later
14802                 // references get the previous definition.
14803                 Name = nullptr;
14804                 Previous.clear();
14805                 Invalid = true;
14806               }
14807             } else {
14808               // If the type is currently being defined, complain
14809               // about a nested redefinition.
14810               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14811               if (TD->isBeingDefined()) {
14812                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14813                 Diag(PrevTagDecl->getLocation(),
14814                      diag::note_previous_definition);
14815                 Name = nullptr;
14816                 Previous.clear();
14817                 Invalid = true;
14818               }
14819             }
14820 
14821             // Okay, this is definition of a previously declared or referenced
14822             // tag. We're going to create a new Decl for it.
14823           }
14824 
14825           // Okay, we're going to make a redeclaration.  If this is some kind
14826           // of reference, make sure we build the redeclaration in the same DC
14827           // as the original, and ignore the current access specifier.
14828           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14829             SearchDC = PrevTagDecl->getDeclContext();
14830             AS = AS_none;
14831           }
14832         }
14833         // If we get here we have (another) forward declaration or we
14834         // have a definition.  Just create a new decl.
14835 
14836       } else {
14837         // If we get here, this is a definition of a new tag type in a nested
14838         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14839         // new decl/type.  We set PrevDecl to NULL so that the entities
14840         // have distinct types.
14841         Previous.clear();
14842       }
14843       // If we get here, we're going to create a new Decl. If PrevDecl
14844       // is non-NULL, it's a definition of the tag declared by
14845       // PrevDecl. If it's NULL, we have a new definition.
14846 
14847     // Otherwise, PrevDecl is not a tag, but was found with tag
14848     // lookup.  This is only actually possible in C++, where a few
14849     // things like templates still live in the tag namespace.
14850     } else {
14851       // Use a better diagnostic if an elaborated-type-specifier
14852       // found the wrong kind of type on the first
14853       // (non-redeclaration) lookup.
14854       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14855           !Previous.isForRedeclaration()) {
14856         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14857         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14858                                                        << Kind;
14859         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14860         Invalid = true;
14861 
14862       // Otherwise, only diagnose if the declaration is in scope.
14863       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14864                                 SS.isNotEmpty() || isMemberSpecialization)) {
14865         // do nothing
14866 
14867       // Diagnose implicit declarations introduced by elaborated types.
14868       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14869         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14870         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14871         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14872         Invalid = true;
14873 
14874       // Otherwise it's a declaration.  Call out a particularly common
14875       // case here.
14876       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14877         unsigned Kind = 0;
14878         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14879         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14880           << Name << Kind << TND->getUnderlyingType();
14881         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14882         Invalid = true;
14883 
14884       // Otherwise, diagnose.
14885       } else {
14886         // The tag name clashes with something else in the target scope,
14887         // issue an error and recover by making this tag be anonymous.
14888         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14889         notePreviousDefinition(PrevDecl, NameLoc);
14890         Name = nullptr;
14891         Invalid = true;
14892       }
14893 
14894       // The existing declaration isn't relevant to us; we're in a
14895       // new scope, so clear out the previous declaration.
14896       Previous.clear();
14897     }
14898   }
14899 
14900 CreateNewDecl:
14901 
14902   TagDecl *PrevDecl = nullptr;
14903   if (Previous.isSingleResult())
14904     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14905 
14906   // If there is an identifier, use the location of the identifier as the
14907   // location of the decl, otherwise use the location of the struct/union
14908   // keyword.
14909   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14910 
14911   // Otherwise, create a new declaration. If there is a previous
14912   // declaration of the same entity, the two will be linked via
14913   // PrevDecl.
14914   TagDecl *New;
14915 
14916   if (Kind == TTK_Enum) {
14917     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14918     // enum X { A, B, C } D;    D should chain to X.
14919     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14920                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14921                            ScopedEnumUsesClassTag, IsFixed);
14922 
14923     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14924       StdAlignValT = cast<EnumDecl>(New);
14925 
14926     // If this is an undefined enum, warn.
14927     if (TUK != TUK_Definition && !Invalid) {
14928       TagDecl *Def;
14929       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14930         // C++0x: 7.2p2: opaque-enum-declaration.
14931         // Conflicts are diagnosed above. Do nothing.
14932       }
14933       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14934         Diag(Loc, diag::ext_forward_ref_enum_def)
14935           << New;
14936         Diag(Def->getLocation(), diag::note_previous_definition);
14937       } else {
14938         unsigned DiagID = diag::ext_forward_ref_enum;
14939         if (getLangOpts().MSVCCompat)
14940           DiagID = diag::ext_ms_forward_ref_enum;
14941         else if (getLangOpts().CPlusPlus)
14942           DiagID = diag::err_forward_ref_enum;
14943         Diag(Loc, DiagID);
14944       }
14945     }
14946 
14947     if (EnumUnderlying) {
14948       EnumDecl *ED = cast<EnumDecl>(New);
14949       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14950         ED->setIntegerTypeSourceInfo(TI);
14951       else
14952         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14953       ED->setPromotionType(ED->getIntegerType());
14954       assert(ED->isComplete() && "enum with type should be complete");
14955     }
14956   } else {
14957     // struct/union/class
14958 
14959     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14960     // struct X { int A; } D;    D should chain to X.
14961     if (getLangOpts().CPlusPlus) {
14962       // FIXME: Look for a way to use RecordDecl for simple structs.
14963       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14964                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14965 
14966       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14967         StdBadAlloc = cast<CXXRecordDecl>(New);
14968     } else
14969       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14970                                cast_or_null<RecordDecl>(PrevDecl));
14971   }
14972 
14973   // C++11 [dcl.type]p3:
14974   //   A type-specifier-seq shall not define a class or enumeration [...].
14975   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14976       TUK == TUK_Definition) {
14977     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14978       << Context.getTagDeclType(New);
14979     Invalid = true;
14980   }
14981 
14982   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14983       DC->getDeclKind() == Decl::Enum) {
14984     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14985       << Context.getTagDeclType(New);
14986     Invalid = true;
14987   }
14988 
14989   // Maybe add qualifier info.
14990   if (SS.isNotEmpty()) {
14991     if (SS.isSet()) {
14992       // If this is either a declaration or a definition, check the
14993       // nested-name-specifier against the current context.
14994       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14995           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14996                                        isMemberSpecialization))
14997         Invalid = true;
14998 
14999       New->setQualifierInfo(SS.getWithLocInContext(Context));
15000       if (TemplateParameterLists.size() > 0) {
15001         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15002       }
15003     }
15004     else
15005       Invalid = true;
15006   }
15007 
15008   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15009     // Add alignment attributes if necessary; these attributes are checked when
15010     // the ASTContext lays out the structure.
15011     //
15012     // It is important for implementing the correct semantics that this
15013     // happen here (in ActOnTag). The #pragma pack stack is
15014     // maintained as a result of parser callbacks which can occur at
15015     // many points during the parsing of a struct declaration (because
15016     // the #pragma tokens are effectively skipped over during the
15017     // parsing of the struct).
15018     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15019       AddAlignmentAttributesForRecord(RD);
15020       AddMsStructLayoutForRecord(RD);
15021     }
15022   }
15023 
15024   if (ModulePrivateLoc.isValid()) {
15025     if (isMemberSpecialization)
15026       Diag(New->getLocation(), diag::err_module_private_specialization)
15027         << 2
15028         << FixItHint::CreateRemoval(ModulePrivateLoc);
15029     // __module_private__ does not apply to local classes. However, we only
15030     // diagnose this as an error when the declaration specifiers are
15031     // freestanding. Here, we just ignore the __module_private__.
15032     else if (!SearchDC->isFunctionOrMethod())
15033       New->setModulePrivate();
15034   }
15035 
15036   // If this is a specialization of a member class (of a class template),
15037   // check the specialization.
15038   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15039     Invalid = true;
15040 
15041   // If we're declaring or defining a tag in function prototype scope in C,
15042   // note that this type can only be used within the function and add it to
15043   // the list of decls to inject into the function definition scope.
15044   if ((Name || Kind == TTK_Enum) &&
15045       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15046     if (getLangOpts().CPlusPlus) {
15047       // C++ [dcl.fct]p6:
15048       //   Types shall not be defined in return or parameter types.
15049       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15050         Diag(Loc, diag::err_type_defined_in_param_type)
15051             << Name;
15052         Invalid = true;
15053       }
15054     } else if (!PrevDecl) {
15055       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15056     }
15057   }
15058 
15059   if (Invalid)
15060     New->setInvalidDecl();
15061 
15062   // Set the lexical context. If the tag has a C++ scope specifier, the
15063   // lexical context will be different from the semantic context.
15064   New->setLexicalDeclContext(CurContext);
15065 
15066   // Mark this as a friend decl if applicable.
15067   // In Microsoft mode, a friend declaration also acts as a forward
15068   // declaration so we always pass true to setObjectOfFriendDecl to make
15069   // the tag name visible.
15070   if (TUK == TUK_Friend)
15071     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15072 
15073   // Set the access specifier.
15074   if (!Invalid && SearchDC->isRecord())
15075     SetMemberAccessSpecifier(New, PrevDecl, AS);
15076 
15077   if (PrevDecl)
15078     CheckRedeclarationModuleOwnership(New, PrevDecl);
15079 
15080   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15081     New->startDefinition();
15082 
15083   ProcessDeclAttributeList(S, New, Attrs);
15084   AddPragmaAttributes(S, New);
15085 
15086   // If this has an identifier, add it to the scope stack.
15087   if (TUK == TUK_Friend) {
15088     // We might be replacing an existing declaration in the lookup tables;
15089     // if so, borrow its access specifier.
15090     if (PrevDecl)
15091       New->setAccess(PrevDecl->getAccess());
15092 
15093     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15094     DC->makeDeclVisibleInContext(New);
15095     if (Name) // can be null along some error paths
15096       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15097         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15098   } else if (Name) {
15099     S = getNonFieldDeclScope(S);
15100     PushOnScopeChains(New, S, true);
15101   } else {
15102     CurContext->addDecl(New);
15103   }
15104 
15105   // If this is the C FILE type, notify the AST context.
15106   if (IdentifierInfo *II = New->getIdentifier())
15107     if (!New->isInvalidDecl() &&
15108         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15109         II->isStr("FILE"))
15110       Context.setFILEDecl(New);
15111 
15112   if (PrevDecl)
15113     mergeDeclAttributes(New, PrevDecl);
15114 
15115   // If there's a #pragma GCC visibility in scope, set the visibility of this
15116   // record.
15117   AddPushedVisibilityAttribute(New);
15118 
15119   if (isMemberSpecialization && !New->isInvalidDecl())
15120     CompleteMemberSpecialization(New, Previous);
15121 
15122   OwnedDecl = true;
15123   // In C++, don't return an invalid declaration. We can't recover well from
15124   // the cases where we make the type anonymous.
15125   if (Invalid && getLangOpts().CPlusPlus) {
15126     if (New->isBeingDefined())
15127       if (auto RD = dyn_cast<RecordDecl>(New))
15128         RD->completeDefinition();
15129     return nullptr;
15130   } else if (SkipBody && SkipBody->ShouldSkip) {
15131     return SkipBody->Previous;
15132   } else {
15133     return New;
15134   }
15135 }
15136 
15137 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15138   AdjustDeclIfTemplate(TagD);
15139   TagDecl *Tag = cast<TagDecl>(TagD);
15140 
15141   // Enter the tag context.
15142   PushDeclContext(S, Tag);
15143 
15144   ActOnDocumentableDecl(TagD);
15145 
15146   // If there's a #pragma GCC visibility in scope, set the visibility of this
15147   // record.
15148   AddPushedVisibilityAttribute(Tag);
15149 }
15150 
15151 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15152                                     SkipBodyInfo &SkipBody) {
15153   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15154     return false;
15155 
15156   // Make the previous decl visible.
15157   makeMergedDefinitionVisible(SkipBody.Previous);
15158   return true;
15159 }
15160 
15161 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15162   assert(isa<ObjCContainerDecl>(IDecl) &&
15163          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15164   DeclContext *OCD = cast<DeclContext>(IDecl);
15165   assert(getContainingDC(OCD) == CurContext &&
15166       "The next DeclContext should be lexically contained in the current one.");
15167   CurContext = OCD;
15168   return IDecl;
15169 }
15170 
15171 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15172                                            SourceLocation FinalLoc,
15173                                            bool IsFinalSpelledSealed,
15174                                            SourceLocation LBraceLoc) {
15175   AdjustDeclIfTemplate(TagD);
15176   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15177 
15178   FieldCollector->StartClass();
15179 
15180   if (!Record->getIdentifier())
15181     return;
15182 
15183   if (FinalLoc.isValid())
15184     Record->addAttr(new (Context)
15185                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15186 
15187   // C++ [class]p2:
15188   //   [...] The class-name is also inserted into the scope of the
15189   //   class itself; this is known as the injected-class-name. For
15190   //   purposes of access checking, the injected-class-name is treated
15191   //   as if it were a public member name.
15192   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15193       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15194       Record->getLocation(), Record->getIdentifier(),
15195       /*PrevDecl=*/nullptr,
15196       /*DelayTypeCreation=*/true);
15197   Context.getTypeDeclType(InjectedClassName, Record);
15198   InjectedClassName->setImplicit();
15199   InjectedClassName->setAccess(AS_public);
15200   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15201       InjectedClassName->setDescribedClassTemplate(Template);
15202   PushOnScopeChains(InjectedClassName, S);
15203   assert(InjectedClassName->isInjectedClassName() &&
15204          "Broken injected-class-name");
15205 }
15206 
15207 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15208                                     SourceRange BraceRange) {
15209   AdjustDeclIfTemplate(TagD);
15210   TagDecl *Tag = cast<TagDecl>(TagD);
15211   Tag->setBraceRange(BraceRange);
15212 
15213   // Make sure we "complete" the definition even it is invalid.
15214   if (Tag->isBeingDefined()) {
15215     assert(Tag->isInvalidDecl() && "We should already have completed it");
15216     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15217       RD->completeDefinition();
15218   }
15219 
15220   if (isa<CXXRecordDecl>(Tag)) {
15221     FieldCollector->FinishClass();
15222   }
15223 
15224   // Exit this scope of this tag's definition.
15225   PopDeclContext();
15226 
15227   if (getCurLexicalContext()->isObjCContainer() &&
15228       Tag->getDeclContext()->isFileContext())
15229     Tag->setTopLevelDeclInObjCContainer();
15230 
15231   // Notify the consumer that we've defined a tag.
15232   if (!Tag->isInvalidDecl())
15233     Consumer.HandleTagDeclDefinition(Tag);
15234 }
15235 
15236 void Sema::ActOnObjCContainerFinishDefinition() {
15237   // Exit this scope of this interface definition.
15238   PopDeclContext();
15239 }
15240 
15241 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15242   assert(DC == CurContext && "Mismatch of container contexts");
15243   OriginalLexicalContext = DC;
15244   ActOnObjCContainerFinishDefinition();
15245 }
15246 
15247 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15248   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15249   OriginalLexicalContext = nullptr;
15250 }
15251 
15252 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15253   AdjustDeclIfTemplate(TagD);
15254   TagDecl *Tag = cast<TagDecl>(TagD);
15255   Tag->setInvalidDecl();
15256 
15257   // Make sure we "complete" the definition even it is invalid.
15258   if (Tag->isBeingDefined()) {
15259     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15260       RD->completeDefinition();
15261   }
15262 
15263   // We're undoing ActOnTagStartDefinition here, not
15264   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15265   // the FieldCollector.
15266 
15267   PopDeclContext();
15268 }
15269 
15270 // Note that FieldName may be null for anonymous bitfields.
15271 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15272                                 IdentifierInfo *FieldName,
15273                                 QualType FieldTy, bool IsMsStruct,
15274                                 Expr *BitWidth, bool *ZeroWidth) {
15275   // Default to true; that shouldn't confuse checks for emptiness
15276   if (ZeroWidth)
15277     *ZeroWidth = true;
15278 
15279   // C99 6.7.2.1p4 - verify the field type.
15280   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15281   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15282     // Handle incomplete types with specific error.
15283     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15284       return ExprError();
15285     if (FieldName)
15286       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15287         << FieldName << FieldTy << BitWidth->getSourceRange();
15288     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15289       << FieldTy << BitWidth->getSourceRange();
15290   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15291                                              UPPC_BitFieldWidth))
15292     return ExprError();
15293 
15294   // If the bit-width is type- or value-dependent, don't try to check
15295   // it now.
15296   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15297     return BitWidth;
15298 
15299   llvm::APSInt Value;
15300   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15301   if (ICE.isInvalid())
15302     return ICE;
15303   BitWidth = ICE.get();
15304 
15305   if (Value != 0 && ZeroWidth)
15306     *ZeroWidth = false;
15307 
15308   // Zero-width bitfield is ok for anonymous field.
15309   if (Value == 0 && FieldName)
15310     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15311 
15312   if (Value.isSigned() && Value.isNegative()) {
15313     if (FieldName)
15314       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15315                << FieldName << Value.toString(10);
15316     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15317       << Value.toString(10);
15318   }
15319 
15320   if (!FieldTy->isDependentType()) {
15321     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15322     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15323     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15324 
15325     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15326     // ABI.
15327     bool CStdConstraintViolation =
15328         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15329     bool MSBitfieldViolation =
15330         Value.ugt(TypeStorageSize) &&
15331         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15332     if (CStdConstraintViolation || MSBitfieldViolation) {
15333       unsigned DiagWidth =
15334           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15335       if (FieldName)
15336         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15337                << FieldName << (unsigned)Value.getZExtValue()
15338                << !CStdConstraintViolation << DiagWidth;
15339 
15340       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15341              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15342              << DiagWidth;
15343     }
15344 
15345     // Warn on types where the user might conceivably expect to get all
15346     // specified bits as value bits: that's all integral types other than
15347     // 'bool'.
15348     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15349       if (FieldName)
15350         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15351             << FieldName << (unsigned)Value.getZExtValue()
15352             << (unsigned)TypeWidth;
15353       else
15354         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15355             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15356     }
15357   }
15358 
15359   return BitWidth;
15360 }
15361 
15362 /// ActOnField - Each field of a C struct/union is passed into this in order
15363 /// to create a FieldDecl object for it.
15364 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15365                        Declarator &D, Expr *BitfieldWidth) {
15366   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15367                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15368                                /*InitStyle=*/ICIS_NoInit, AS_public);
15369   return Res;
15370 }
15371 
15372 /// HandleField - Analyze a field of a C struct or a C++ data member.
15373 ///
15374 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15375                              SourceLocation DeclStart,
15376                              Declarator &D, Expr *BitWidth,
15377                              InClassInitStyle InitStyle,
15378                              AccessSpecifier AS) {
15379   if (D.isDecompositionDeclarator()) {
15380     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15381     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15382       << Decomp.getSourceRange();
15383     return nullptr;
15384   }
15385 
15386   IdentifierInfo *II = D.getIdentifier();
15387   SourceLocation Loc = DeclStart;
15388   if (II) Loc = D.getIdentifierLoc();
15389 
15390   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15391   QualType T = TInfo->getType();
15392   if (getLangOpts().CPlusPlus) {
15393     CheckExtraCXXDefaultArguments(D);
15394 
15395     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15396                                         UPPC_DataMemberType)) {
15397       D.setInvalidType();
15398       T = Context.IntTy;
15399       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15400     }
15401   }
15402 
15403   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15404 
15405   if (D.getDeclSpec().isInlineSpecified())
15406     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15407         << getLangOpts().CPlusPlus17;
15408   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15409     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15410          diag::err_invalid_thread)
15411       << DeclSpec::getSpecifierName(TSCS);
15412 
15413   // Check to see if this name was declared as a member previously
15414   NamedDecl *PrevDecl = nullptr;
15415   LookupResult Previous(*this, II, Loc, LookupMemberName,
15416                         ForVisibleRedeclaration);
15417   LookupName(Previous, S);
15418   switch (Previous.getResultKind()) {
15419     case LookupResult::Found:
15420     case LookupResult::FoundUnresolvedValue:
15421       PrevDecl = Previous.getAsSingle<NamedDecl>();
15422       break;
15423 
15424     case LookupResult::FoundOverloaded:
15425       PrevDecl = Previous.getRepresentativeDecl();
15426       break;
15427 
15428     case LookupResult::NotFound:
15429     case LookupResult::NotFoundInCurrentInstantiation:
15430     case LookupResult::Ambiguous:
15431       break;
15432   }
15433   Previous.suppressDiagnostics();
15434 
15435   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15436     // Maybe we will complain about the shadowed template parameter.
15437     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15438     // Just pretend that we didn't see the previous declaration.
15439     PrevDecl = nullptr;
15440   }
15441 
15442   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15443     PrevDecl = nullptr;
15444 
15445   bool Mutable
15446     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15447   SourceLocation TSSL = D.getBeginLoc();
15448   FieldDecl *NewFD
15449     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15450                      TSSL, AS, PrevDecl, &D);
15451 
15452   if (NewFD->isInvalidDecl())
15453     Record->setInvalidDecl();
15454 
15455   if (D.getDeclSpec().isModulePrivateSpecified())
15456     NewFD->setModulePrivate();
15457 
15458   if (NewFD->isInvalidDecl() && PrevDecl) {
15459     // Don't introduce NewFD into scope; there's already something
15460     // with the same name in the same scope.
15461   } else if (II) {
15462     PushOnScopeChains(NewFD, S);
15463   } else
15464     Record->addDecl(NewFD);
15465 
15466   return NewFD;
15467 }
15468 
15469 /// Build a new FieldDecl and check its well-formedness.
15470 ///
15471 /// This routine builds a new FieldDecl given the fields name, type,
15472 /// record, etc. \p PrevDecl should refer to any previous declaration
15473 /// with the same name and in the same scope as the field to be
15474 /// created.
15475 ///
15476 /// \returns a new FieldDecl.
15477 ///
15478 /// \todo The Declarator argument is a hack. It will be removed once
15479 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15480                                 TypeSourceInfo *TInfo,
15481                                 RecordDecl *Record, SourceLocation Loc,
15482                                 bool Mutable, Expr *BitWidth,
15483                                 InClassInitStyle InitStyle,
15484                                 SourceLocation TSSL,
15485                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15486                                 Declarator *D) {
15487   IdentifierInfo *II = Name.getAsIdentifierInfo();
15488   bool InvalidDecl = false;
15489   if (D) InvalidDecl = D->isInvalidType();
15490 
15491   // If we receive a broken type, recover by assuming 'int' and
15492   // marking this declaration as invalid.
15493   if (T.isNull()) {
15494     InvalidDecl = true;
15495     T = Context.IntTy;
15496   }
15497 
15498   QualType EltTy = Context.getBaseElementType(T);
15499   if (!EltTy->isDependentType()) {
15500     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15501       // Fields of incomplete type force their record to be invalid.
15502       Record->setInvalidDecl();
15503       InvalidDecl = true;
15504     } else {
15505       NamedDecl *Def;
15506       EltTy->isIncompleteType(&Def);
15507       if (Def && Def->isInvalidDecl()) {
15508         Record->setInvalidDecl();
15509         InvalidDecl = true;
15510       }
15511     }
15512   }
15513 
15514   // TR 18037 does not allow fields to be declared with address space
15515   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15516       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15517     Diag(Loc, diag::err_field_with_address_space);
15518     Record->setInvalidDecl();
15519     InvalidDecl = true;
15520   }
15521 
15522   if (LangOpts.OpenCL) {
15523     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15524     // used as structure or union field: image, sampler, event or block types.
15525     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15526         T->isBlockPointerType()) {
15527       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15528       Record->setInvalidDecl();
15529       InvalidDecl = true;
15530     }
15531     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15532     if (BitWidth) {
15533       Diag(Loc, diag::err_opencl_bitfields);
15534       InvalidDecl = true;
15535     }
15536   }
15537 
15538   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15539   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15540       T.hasQualifiers()) {
15541     InvalidDecl = true;
15542     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15543   }
15544 
15545   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15546   // than a variably modified type.
15547   if (!InvalidDecl && T->isVariablyModifiedType()) {
15548     bool SizeIsNegative;
15549     llvm::APSInt Oversized;
15550 
15551     TypeSourceInfo *FixedTInfo =
15552       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15553                                                     SizeIsNegative,
15554                                                     Oversized);
15555     if (FixedTInfo) {
15556       Diag(Loc, diag::warn_illegal_constant_array_size);
15557       TInfo = FixedTInfo;
15558       T = FixedTInfo->getType();
15559     } else {
15560       if (SizeIsNegative)
15561         Diag(Loc, diag::err_typecheck_negative_array_size);
15562       else if (Oversized.getBoolValue())
15563         Diag(Loc, diag::err_array_too_large)
15564           << Oversized.toString(10);
15565       else
15566         Diag(Loc, diag::err_typecheck_field_variable_size);
15567       InvalidDecl = true;
15568     }
15569   }
15570 
15571   // Fields can not have abstract class types
15572   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15573                                              diag::err_abstract_type_in_decl,
15574                                              AbstractFieldType))
15575     InvalidDecl = true;
15576 
15577   bool ZeroWidth = false;
15578   if (InvalidDecl)
15579     BitWidth = nullptr;
15580   // If this is declared as a bit-field, check the bit-field.
15581   if (BitWidth) {
15582     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15583                               &ZeroWidth).get();
15584     if (!BitWidth) {
15585       InvalidDecl = true;
15586       BitWidth = nullptr;
15587       ZeroWidth = false;
15588     }
15589   }
15590 
15591   // Check that 'mutable' is consistent with the type of the declaration.
15592   if (!InvalidDecl && Mutable) {
15593     unsigned DiagID = 0;
15594     if (T->isReferenceType())
15595       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15596                                         : diag::err_mutable_reference;
15597     else if (T.isConstQualified())
15598       DiagID = diag::err_mutable_const;
15599 
15600     if (DiagID) {
15601       SourceLocation ErrLoc = Loc;
15602       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15603         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15604       Diag(ErrLoc, DiagID);
15605       if (DiagID != diag::ext_mutable_reference) {
15606         Mutable = false;
15607         InvalidDecl = true;
15608       }
15609     }
15610   }
15611 
15612   // C++11 [class.union]p8 (DR1460):
15613   //   At most one variant member of a union may have a
15614   //   brace-or-equal-initializer.
15615   if (InitStyle != ICIS_NoInit)
15616     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15617 
15618   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15619                                        BitWidth, Mutable, InitStyle);
15620   if (InvalidDecl)
15621     NewFD->setInvalidDecl();
15622 
15623   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15624     Diag(Loc, diag::err_duplicate_member) << II;
15625     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15626     NewFD->setInvalidDecl();
15627   }
15628 
15629   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15630     if (Record->isUnion()) {
15631       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15632         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15633         if (RDecl->getDefinition()) {
15634           // C++ [class.union]p1: An object of a class with a non-trivial
15635           // constructor, a non-trivial copy constructor, a non-trivial
15636           // destructor, or a non-trivial copy assignment operator
15637           // cannot be a member of a union, nor can an array of such
15638           // objects.
15639           if (CheckNontrivialField(NewFD))
15640             NewFD->setInvalidDecl();
15641         }
15642       }
15643 
15644       // C++ [class.union]p1: If a union contains a member of reference type,
15645       // the program is ill-formed, except when compiling with MSVC extensions
15646       // enabled.
15647       if (EltTy->isReferenceType()) {
15648         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15649                                     diag::ext_union_member_of_reference_type :
15650                                     diag::err_union_member_of_reference_type)
15651           << NewFD->getDeclName() << EltTy;
15652         if (!getLangOpts().MicrosoftExt)
15653           NewFD->setInvalidDecl();
15654       }
15655     }
15656   }
15657 
15658   // FIXME: We need to pass in the attributes given an AST
15659   // representation, not a parser representation.
15660   if (D) {
15661     // FIXME: The current scope is almost... but not entirely... correct here.
15662     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15663 
15664     if (NewFD->hasAttrs())
15665       CheckAlignasUnderalignment(NewFD);
15666   }
15667 
15668   // In auto-retain/release, infer strong retension for fields of
15669   // retainable type.
15670   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15671     NewFD->setInvalidDecl();
15672 
15673   if (T.isObjCGCWeak())
15674     Diag(Loc, diag::warn_attribute_weak_on_field);
15675 
15676   NewFD->setAccess(AS);
15677   return NewFD;
15678 }
15679 
15680 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15681   assert(FD);
15682   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15683 
15684   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15685     return false;
15686 
15687   QualType EltTy = Context.getBaseElementType(FD->getType());
15688   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15689     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15690     if (RDecl->getDefinition()) {
15691       // We check for copy constructors before constructors
15692       // because otherwise we'll never get complaints about
15693       // copy constructors.
15694 
15695       CXXSpecialMember member = CXXInvalid;
15696       // We're required to check for any non-trivial constructors. Since the
15697       // implicit default constructor is suppressed if there are any
15698       // user-declared constructors, we just need to check that there is a
15699       // trivial default constructor and a trivial copy constructor. (We don't
15700       // worry about move constructors here, since this is a C++98 check.)
15701       if (RDecl->hasNonTrivialCopyConstructor())
15702         member = CXXCopyConstructor;
15703       else if (!RDecl->hasTrivialDefaultConstructor())
15704         member = CXXDefaultConstructor;
15705       else if (RDecl->hasNonTrivialCopyAssignment())
15706         member = CXXCopyAssignment;
15707       else if (RDecl->hasNonTrivialDestructor())
15708         member = CXXDestructor;
15709 
15710       if (member != CXXInvalid) {
15711         if (!getLangOpts().CPlusPlus11 &&
15712             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15713           // Objective-C++ ARC: it is an error to have a non-trivial field of
15714           // a union. However, system headers in Objective-C programs
15715           // occasionally have Objective-C lifetime objects within unions,
15716           // and rather than cause the program to fail, we make those
15717           // members unavailable.
15718           SourceLocation Loc = FD->getLocation();
15719           if (getSourceManager().isInSystemHeader(Loc)) {
15720             if (!FD->hasAttr<UnavailableAttr>())
15721               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15722                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15723             return false;
15724           }
15725         }
15726 
15727         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15728                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15729                diag::err_illegal_union_or_anon_struct_member)
15730           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15731         DiagnoseNontrivial(RDecl, member);
15732         return !getLangOpts().CPlusPlus11;
15733       }
15734     }
15735   }
15736 
15737   return false;
15738 }
15739 
15740 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15741 ///  AST enum value.
15742 static ObjCIvarDecl::AccessControl
15743 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15744   switch (ivarVisibility) {
15745   default: llvm_unreachable("Unknown visitibility kind");
15746   case tok::objc_private: return ObjCIvarDecl::Private;
15747   case tok::objc_public: return ObjCIvarDecl::Public;
15748   case tok::objc_protected: return ObjCIvarDecl::Protected;
15749   case tok::objc_package: return ObjCIvarDecl::Package;
15750   }
15751 }
15752 
15753 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15754 /// in order to create an IvarDecl object for it.
15755 Decl *Sema::ActOnIvar(Scope *S,
15756                                 SourceLocation DeclStart,
15757                                 Declarator &D, Expr *BitfieldWidth,
15758                                 tok::ObjCKeywordKind Visibility) {
15759 
15760   IdentifierInfo *II = D.getIdentifier();
15761   Expr *BitWidth = (Expr*)BitfieldWidth;
15762   SourceLocation Loc = DeclStart;
15763   if (II) Loc = D.getIdentifierLoc();
15764 
15765   // FIXME: Unnamed fields can be handled in various different ways, for
15766   // example, unnamed unions inject all members into the struct namespace!
15767 
15768   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15769   QualType T = TInfo->getType();
15770 
15771   if (BitWidth) {
15772     // 6.7.2.1p3, 6.7.2.1p4
15773     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15774     if (!BitWidth)
15775       D.setInvalidType();
15776   } else {
15777     // Not a bitfield.
15778 
15779     // validate II.
15780 
15781   }
15782   if (T->isReferenceType()) {
15783     Diag(Loc, diag::err_ivar_reference_type);
15784     D.setInvalidType();
15785   }
15786   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15787   // than a variably modified type.
15788   else if (T->isVariablyModifiedType()) {
15789     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15790     D.setInvalidType();
15791   }
15792 
15793   // Get the visibility (access control) for this ivar.
15794   ObjCIvarDecl::AccessControl ac =
15795     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15796                                         : ObjCIvarDecl::None;
15797   // Must set ivar's DeclContext to its enclosing interface.
15798   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15799   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15800     return nullptr;
15801   ObjCContainerDecl *EnclosingContext;
15802   if (ObjCImplementationDecl *IMPDecl =
15803       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15804     if (LangOpts.ObjCRuntime.isFragile()) {
15805     // Case of ivar declared in an implementation. Context is that of its class.
15806       EnclosingContext = IMPDecl->getClassInterface();
15807       assert(EnclosingContext && "Implementation has no class interface!");
15808     }
15809     else
15810       EnclosingContext = EnclosingDecl;
15811   } else {
15812     if (ObjCCategoryDecl *CDecl =
15813         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15814       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15815         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15816         return nullptr;
15817       }
15818     }
15819     EnclosingContext = EnclosingDecl;
15820   }
15821 
15822   // Construct the decl.
15823   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15824                                              DeclStart, Loc, II, T,
15825                                              TInfo, ac, (Expr *)BitfieldWidth);
15826 
15827   if (II) {
15828     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15829                                            ForVisibleRedeclaration);
15830     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15831         && !isa<TagDecl>(PrevDecl)) {
15832       Diag(Loc, diag::err_duplicate_member) << II;
15833       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15834       NewID->setInvalidDecl();
15835     }
15836   }
15837 
15838   // Process attributes attached to the ivar.
15839   ProcessDeclAttributes(S, NewID, D);
15840 
15841   if (D.isInvalidType())
15842     NewID->setInvalidDecl();
15843 
15844   // In ARC, infer 'retaining' for ivars of retainable type.
15845   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15846     NewID->setInvalidDecl();
15847 
15848   if (D.getDeclSpec().isModulePrivateSpecified())
15849     NewID->setModulePrivate();
15850 
15851   if (II) {
15852     // FIXME: When interfaces are DeclContexts, we'll need to add
15853     // these to the interface.
15854     S->AddDecl(NewID);
15855     IdResolver.AddDecl(NewID);
15856   }
15857 
15858   if (LangOpts.ObjCRuntime.isNonFragile() &&
15859       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15860     Diag(Loc, diag::warn_ivars_in_interface);
15861 
15862   return NewID;
15863 }
15864 
15865 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15866 /// class and class extensions. For every class \@interface and class
15867 /// extension \@interface, if the last ivar is a bitfield of any type,
15868 /// then add an implicit `char :0` ivar to the end of that interface.
15869 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15870                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15871   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15872     return;
15873 
15874   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15875   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15876 
15877   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15878     return;
15879   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15880   if (!ID) {
15881     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15882       if (!CD->IsClassExtension())
15883         return;
15884     }
15885     // No need to add this to end of @implementation.
15886     else
15887       return;
15888   }
15889   // All conditions are met. Add a new bitfield to the tail end of ivars.
15890   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15891   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15892 
15893   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15894                               DeclLoc, DeclLoc, nullptr,
15895                               Context.CharTy,
15896                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15897                                                                DeclLoc),
15898                               ObjCIvarDecl::Private, BW,
15899                               true);
15900   AllIvarDecls.push_back(Ivar);
15901 }
15902 
15903 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15904                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15905                        SourceLocation RBrac,
15906                        const ParsedAttributesView &Attrs) {
15907   assert(EnclosingDecl && "missing record or interface decl");
15908 
15909   // If this is an Objective-C @implementation or category and we have
15910   // new fields here we should reset the layout of the interface since
15911   // it will now change.
15912   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15913     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15914     switch (DC->getKind()) {
15915     default: break;
15916     case Decl::ObjCCategory:
15917       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15918       break;
15919     case Decl::ObjCImplementation:
15920       Context.
15921         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15922       break;
15923     }
15924   }
15925 
15926   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15927   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15928 
15929   // Start counting up the number of named members; make sure to include
15930   // members of anonymous structs and unions in the total.
15931   unsigned NumNamedMembers = 0;
15932   if (Record) {
15933     for (const auto *I : Record->decls()) {
15934       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15935         if (IFD->getDeclName())
15936           ++NumNamedMembers;
15937     }
15938   }
15939 
15940   // Verify that all the fields are okay.
15941   SmallVector<FieldDecl*, 32> RecFields;
15942 
15943   bool ObjCFieldLifetimeErrReported = false;
15944   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15945        i != end; ++i) {
15946     FieldDecl *FD = cast<FieldDecl>(*i);
15947 
15948     // Get the type for the field.
15949     const Type *FDTy = FD->getType().getTypePtr();
15950 
15951     if (!FD->isAnonymousStructOrUnion()) {
15952       // Remember all fields written by the user.
15953       RecFields.push_back(FD);
15954     }
15955 
15956     // If the field is already invalid for some reason, don't emit more
15957     // diagnostics about it.
15958     if (FD->isInvalidDecl()) {
15959       EnclosingDecl->setInvalidDecl();
15960       continue;
15961     }
15962 
15963     // C99 6.7.2.1p2:
15964     //   A structure or union shall not contain a member with
15965     //   incomplete or function type (hence, a structure shall not
15966     //   contain an instance of itself, but may contain a pointer to
15967     //   an instance of itself), except that the last member of a
15968     //   structure with more than one named member may have incomplete
15969     //   array type; such a structure (and any union containing,
15970     //   possibly recursively, a member that is such a structure)
15971     //   shall not be a member of a structure or an element of an
15972     //   array.
15973     bool IsLastField = (i + 1 == Fields.end());
15974     if (FDTy->isFunctionType()) {
15975       // Field declared as a function.
15976       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15977         << FD->getDeclName();
15978       FD->setInvalidDecl();
15979       EnclosingDecl->setInvalidDecl();
15980       continue;
15981     } else if (FDTy->isIncompleteArrayType() &&
15982                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15983       if (Record) {
15984         // Flexible array member.
15985         // Microsoft and g++ is more permissive regarding flexible array.
15986         // It will accept flexible array in union and also
15987         // as the sole element of a struct/class.
15988         unsigned DiagID = 0;
15989         if (!Record->isUnion() && !IsLastField) {
15990           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15991             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15992           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15993           FD->setInvalidDecl();
15994           EnclosingDecl->setInvalidDecl();
15995           continue;
15996         } else if (Record->isUnion())
15997           DiagID = getLangOpts().MicrosoftExt
15998                        ? diag::ext_flexible_array_union_ms
15999                        : getLangOpts().CPlusPlus
16000                              ? diag::ext_flexible_array_union_gnu
16001                              : diag::err_flexible_array_union;
16002         else if (NumNamedMembers < 1)
16003           DiagID = getLangOpts().MicrosoftExt
16004                        ? diag::ext_flexible_array_empty_aggregate_ms
16005                        : getLangOpts().CPlusPlus
16006                              ? diag::ext_flexible_array_empty_aggregate_gnu
16007                              : diag::err_flexible_array_empty_aggregate;
16008 
16009         if (DiagID)
16010           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16011                                           << Record->getTagKind();
16012         // While the layout of types that contain virtual bases is not specified
16013         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16014         // virtual bases after the derived members.  This would make a flexible
16015         // array member declared at the end of an object not adjacent to the end
16016         // of the type.
16017         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16018           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16019               << FD->getDeclName() << Record->getTagKind();
16020         if (!getLangOpts().C99)
16021           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16022             << FD->getDeclName() << Record->getTagKind();
16023 
16024         // If the element type has a non-trivial destructor, we would not
16025         // implicitly destroy the elements, so disallow it for now.
16026         //
16027         // FIXME: GCC allows this. We should probably either implicitly delete
16028         // the destructor of the containing class, or just allow this.
16029         QualType BaseElem = Context.getBaseElementType(FD->getType());
16030         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16031           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16032             << FD->getDeclName() << FD->getType();
16033           FD->setInvalidDecl();
16034           EnclosingDecl->setInvalidDecl();
16035           continue;
16036         }
16037         // Okay, we have a legal flexible array member at the end of the struct.
16038         Record->setHasFlexibleArrayMember(true);
16039       } else {
16040         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16041         // unless they are followed by another ivar. That check is done
16042         // elsewhere, after synthesized ivars are known.
16043       }
16044     } else if (!FDTy->isDependentType() &&
16045                RequireCompleteType(FD->getLocation(), FD->getType(),
16046                                    diag::err_field_incomplete)) {
16047       // Incomplete type
16048       FD->setInvalidDecl();
16049       EnclosingDecl->setInvalidDecl();
16050       continue;
16051     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16052       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16053         // A type which contains a flexible array member is considered to be a
16054         // flexible array member.
16055         Record->setHasFlexibleArrayMember(true);
16056         if (!Record->isUnion()) {
16057           // If this is a struct/class and this is not the last element, reject
16058           // it.  Note that GCC supports variable sized arrays in the middle of
16059           // structures.
16060           if (!IsLastField)
16061             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16062               << FD->getDeclName() << FD->getType();
16063           else {
16064             // We support flexible arrays at the end of structs in
16065             // other structs as an extension.
16066             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16067               << FD->getDeclName();
16068           }
16069         }
16070       }
16071       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16072           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16073                                  diag::err_abstract_type_in_decl,
16074                                  AbstractIvarType)) {
16075         // Ivars can not have abstract class types
16076         FD->setInvalidDecl();
16077       }
16078       if (Record && FDTTy->getDecl()->hasObjectMember())
16079         Record->setHasObjectMember(true);
16080       if (Record && FDTTy->getDecl()->hasVolatileMember())
16081         Record->setHasVolatileMember(true);
16082       if (Record && Record->isUnion() &&
16083           FD->getType().isNonTrivialPrimitiveCType(Context))
16084         Diag(FD->getLocation(),
16085              diag::err_nontrivial_primitive_type_in_union);
16086     } else if (FDTy->isObjCObjectType()) {
16087       /// A field cannot be an Objective-c object
16088       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16089         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16090       QualType T = Context.getObjCObjectPointerType(FD->getType());
16091       FD->setType(T);
16092     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
16093                Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
16094                !getLangOpts().CPlusPlus) {
16095       // It's an error in ARC or Weak if a field has lifetime.
16096       // We don't want to report this in a system header, though,
16097       // so we just make the field unavailable.
16098       // FIXME: that's really not sufficient; we need to make the type
16099       // itself invalid to, say, initialize or copy.
16100       QualType T = FD->getType();
16101       if (T.hasNonTrivialObjCLifetime()) {
16102         SourceLocation loc = FD->getLocation();
16103         if (getSourceManager().isInSystemHeader(loc)) {
16104           if (!FD->hasAttr<UnavailableAttr>()) {
16105             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16106                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
16107           }
16108         } else {
16109           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
16110             << T->isBlockPointerType() << Record->getTagKind();
16111         }
16112         ObjCFieldLifetimeErrReported = true;
16113       }
16114     } else if (getLangOpts().ObjC &&
16115                getLangOpts().getGC() != LangOptions::NonGC &&
16116                Record && !Record->hasObjectMember()) {
16117       if (FD->getType()->isObjCObjectPointerType() ||
16118           FD->getType().isObjCGCStrong())
16119         Record->setHasObjectMember(true);
16120       else if (Context.getAsArrayType(FD->getType())) {
16121         QualType BaseType = Context.getBaseElementType(FD->getType());
16122         if (BaseType->isRecordType() &&
16123             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16124           Record->setHasObjectMember(true);
16125         else if (BaseType->isObjCObjectPointerType() ||
16126                  BaseType.isObjCGCStrong())
16127                Record->setHasObjectMember(true);
16128       }
16129     }
16130 
16131     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16132       QualType FT = FD->getType();
16133       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
16134         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16135       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16136       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
16137         Record->setNonTrivialToPrimitiveCopy(true);
16138       if (FT.isDestructedType()) {
16139         Record->setNonTrivialToPrimitiveDestroy(true);
16140         Record->setParamDestroyedInCallee(true);
16141       }
16142 
16143       if (const auto *RT = FT->getAs<RecordType>()) {
16144         if (RT->getDecl()->getArgPassingRestrictions() ==
16145             RecordDecl::APK_CanNeverPassInRegs)
16146           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16147       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16148         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16149     }
16150 
16151     if (Record && FD->getType().isVolatileQualified())
16152       Record->setHasVolatileMember(true);
16153     // Keep track of the number of named members.
16154     if (FD->getIdentifier())
16155       ++NumNamedMembers;
16156   }
16157 
16158   // Okay, we successfully defined 'Record'.
16159   if (Record) {
16160     bool Completed = false;
16161     if (CXXRecord) {
16162       if (!CXXRecord->isInvalidDecl()) {
16163         // Set access bits correctly on the directly-declared conversions.
16164         for (CXXRecordDecl::conversion_iterator
16165                I = CXXRecord->conversion_begin(),
16166                E = CXXRecord->conversion_end(); I != E; ++I)
16167           I.setAccess((*I)->getAccess());
16168       }
16169 
16170       if (!CXXRecord->isDependentType()) {
16171         // Add any implicitly-declared members to this class.
16172         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16173 
16174         if (!CXXRecord->isInvalidDecl()) {
16175           // If we have virtual base classes, we may end up finding multiple
16176           // final overriders for a given virtual function. Check for this
16177           // problem now.
16178           if (CXXRecord->getNumVBases()) {
16179             CXXFinalOverriderMap FinalOverriders;
16180             CXXRecord->getFinalOverriders(FinalOverriders);
16181 
16182             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16183                                              MEnd = FinalOverriders.end();
16184                  M != MEnd; ++M) {
16185               for (OverridingMethods::iterator SO = M->second.begin(),
16186                                             SOEnd = M->second.end();
16187                    SO != SOEnd; ++SO) {
16188                 assert(SO->second.size() > 0 &&
16189                        "Virtual function without overriding functions?");
16190                 if (SO->second.size() == 1)
16191                   continue;
16192 
16193                 // C++ [class.virtual]p2:
16194                 //   In a derived class, if a virtual member function of a base
16195                 //   class subobject has more than one final overrider the
16196                 //   program is ill-formed.
16197                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16198                   << (const NamedDecl *)M->first << Record;
16199                 Diag(M->first->getLocation(),
16200                      diag::note_overridden_virtual_function);
16201                 for (OverridingMethods::overriding_iterator
16202                           OM = SO->second.begin(),
16203                        OMEnd = SO->second.end();
16204                      OM != OMEnd; ++OM)
16205                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16206                     << (const NamedDecl *)M->first << OM->Method->getParent();
16207 
16208                 Record->setInvalidDecl();
16209               }
16210             }
16211             CXXRecord->completeDefinition(&FinalOverriders);
16212             Completed = true;
16213           }
16214         }
16215       }
16216     }
16217 
16218     if (!Completed)
16219       Record->completeDefinition();
16220 
16221     // Handle attributes before checking the layout.
16222     ProcessDeclAttributeList(S, Record, Attrs);
16223 
16224     // We may have deferred checking for a deleted destructor. Check now.
16225     if (CXXRecord) {
16226       auto *Dtor = CXXRecord->getDestructor();
16227       if (Dtor && Dtor->isImplicit() &&
16228           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16229         CXXRecord->setImplicitDestructorIsDeleted();
16230         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16231       }
16232     }
16233 
16234     if (Record->hasAttrs()) {
16235       CheckAlignasUnderalignment(Record);
16236 
16237       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16238         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16239                                            IA->getRange(), IA->getBestCase(),
16240                                            IA->getSemanticSpelling());
16241     }
16242 
16243     // Check if the structure/union declaration is a type that can have zero
16244     // size in C. For C this is a language extension, for C++ it may cause
16245     // compatibility problems.
16246     bool CheckForZeroSize;
16247     if (!getLangOpts().CPlusPlus) {
16248       CheckForZeroSize = true;
16249     } else {
16250       // For C++ filter out types that cannot be referenced in C code.
16251       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16252       CheckForZeroSize =
16253           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16254           !CXXRecord->isDependentType() &&
16255           CXXRecord->isCLike();
16256     }
16257     if (CheckForZeroSize) {
16258       bool ZeroSize = true;
16259       bool IsEmpty = true;
16260       unsigned NonBitFields = 0;
16261       for (RecordDecl::field_iterator I = Record->field_begin(),
16262                                       E = Record->field_end();
16263            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16264         IsEmpty = false;
16265         if (I->isUnnamedBitfield()) {
16266           if (!I->isZeroLengthBitField(Context))
16267             ZeroSize = false;
16268         } else {
16269           ++NonBitFields;
16270           QualType FieldType = I->getType();
16271           if (FieldType->isIncompleteType() ||
16272               !Context.getTypeSizeInChars(FieldType).isZero())
16273             ZeroSize = false;
16274         }
16275       }
16276 
16277       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16278       // allowed in C++, but warn if its declaration is inside
16279       // extern "C" block.
16280       if (ZeroSize) {
16281         Diag(RecLoc, getLangOpts().CPlusPlus ?
16282                          diag::warn_zero_size_struct_union_in_extern_c :
16283                          diag::warn_zero_size_struct_union_compat)
16284           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16285       }
16286 
16287       // Structs without named members are extension in C (C99 6.7.2.1p7),
16288       // but are accepted by GCC.
16289       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16290         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16291                                diag::ext_no_named_members_in_struct_union)
16292           << Record->isUnion();
16293       }
16294     }
16295   } else {
16296     ObjCIvarDecl **ClsFields =
16297       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16298     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16299       ID->setEndOfDefinitionLoc(RBrac);
16300       // Add ivar's to class's DeclContext.
16301       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16302         ClsFields[i]->setLexicalDeclContext(ID);
16303         ID->addDecl(ClsFields[i]);
16304       }
16305       // Must enforce the rule that ivars in the base classes may not be
16306       // duplicates.
16307       if (ID->getSuperClass())
16308         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16309     } else if (ObjCImplementationDecl *IMPDecl =
16310                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16311       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16312       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16313         // Ivar declared in @implementation never belongs to the implementation.
16314         // Only it is in implementation's lexical context.
16315         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16316       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16317       IMPDecl->setIvarLBraceLoc(LBrac);
16318       IMPDecl->setIvarRBraceLoc(RBrac);
16319     } else if (ObjCCategoryDecl *CDecl =
16320                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16321       // case of ivars in class extension; all other cases have been
16322       // reported as errors elsewhere.
16323       // FIXME. Class extension does not have a LocEnd field.
16324       // CDecl->setLocEnd(RBrac);
16325       // Add ivar's to class extension's DeclContext.
16326       // Diagnose redeclaration of private ivars.
16327       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16328       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16329         if (IDecl) {
16330           if (const ObjCIvarDecl *ClsIvar =
16331               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16332             Diag(ClsFields[i]->getLocation(),
16333                  diag::err_duplicate_ivar_declaration);
16334             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16335             continue;
16336           }
16337           for (const auto *Ext : IDecl->known_extensions()) {
16338             if (const ObjCIvarDecl *ClsExtIvar
16339                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16340               Diag(ClsFields[i]->getLocation(),
16341                    diag::err_duplicate_ivar_declaration);
16342               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16343               continue;
16344             }
16345           }
16346         }
16347         ClsFields[i]->setLexicalDeclContext(CDecl);
16348         CDecl->addDecl(ClsFields[i]);
16349       }
16350       CDecl->setIvarLBraceLoc(LBrac);
16351       CDecl->setIvarRBraceLoc(RBrac);
16352     }
16353   }
16354 }
16355 
16356 /// Determine whether the given integral value is representable within
16357 /// the given type T.
16358 static bool isRepresentableIntegerValue(ASTContext &Context,
16359                                         llvm::APSInt &Value,
16360                                         QualType T) {
16361   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16362          "Integral type required!");
16363   unsigned BitWidth = Context.getIntWidth(T);
16364 
16365   if (Value.isUnsigned() || Value.isNonNegative()) {
16366     if (T->isSignedIntegerOrEnumerationType())
16367       --BitWidth;
16368     return Value.getActiveBits() <= BitWidth;
16369   }
16370   return Value.getMinSignedBits() <= BitWidth;
16371 }
16372 
16373 // Given an integral type, return the next larger integral type
16374 // (or a NULL type of no such type exists).
16375 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16376   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16377   // enum checking below.
16378   assert((T->isIntegralType(Context) ||
16379          T->isEnumeralType()) && "Integral type required!");
16380   const unsigned NumTypes = 4;
16381   QualType SignedIntegralTypes[NumTypes] = {
16382     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16383   };
16384   QualType UnsignedIntegralTypes[NumTypes] = {
16385     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16386     Context.UnsignedLongLongTy
16387   };
16388 
16389   unsigned BitWidth = Context.getTypeSize(T);
16390   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16391                                                         : UnsignedIntegralTypes;
16392   for (unsigned I = 0; I != NumTypes; ++I)
16393     if (Context.getTypeSize(Types[I]) > BitWidth)
16394       return Types[I];
16395 
16396   return QualType();
16397 }
16398 
16399 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16400                                           EnumConstantDecl *LastEnumConst,
16401                                           SourceLocation IdLoc,
16402                                           IdentifierInfo *Id,
16403                                           Expr *Val) {
16404   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16405   llvm::APSInt EnumVal(IntWidth);
16406   QualType EltTy;
16407 
16408   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16409     Val = nullptr;
16410 
16411   if (Val)
16412     Val = DefaultLvalueConversion(Val).get();
16413 
16414   if (Val) {
16415     if (Enum->isDependentType() || Val->isTypeDependent())
16416       EltTy = Context.DependentTy;
16417     else {
16418       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16419           !getLangOpts().MSVCCompat) {
16420         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16421         // constant-expression in the enumerator-definition shall be a converted
16422         // constant expression of the underlying type.
16423         EltTy = Enum->getIntegerType();
16424         ExprResult Converted =
16425           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16426                                            CCEK_Enumerator);
16427         if (Converted.isInvalid())
16428           Val = nullptr;
16429         else
16430           Val = Converted.get();
16431       } else if (!Val->isValueDependent() &&
16432                  !(Val = VerifyIntegerConstantExpression(Val,
16433                                                          &EnumVal).get())) {
16434         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16435       } else {
16436         if (Enum->isComplete()) {
16437           EltTy = Enum->getIntegerType();
16438 
16439           // In Obj-C and Microsoft mode, require the enumeration value to be
16440           // representable in the underlying type of the enumeration. In C++11,
16441           // we perform a non-narrowing conversion as part of converted constant
16442           // expression checking.
16443           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16444             if (getLangOpts().MSVCCompat) {
16445               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16446               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16447             } else
16448               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16449           } else
16450             Val = ImpCastExprToType(Val, EltTy,
16451                                     EltTy->isBooleanType() ?
16452                                     CK_IntegralToBoolean : CK_IntegralCast)
16453                     .get();
16454         } else if (getLangOpts().CPlusPlus) {
16455           // C++11 [dcl.enum]p5:
16456           //   If the underlying type is not fixed, the type of each enumerator
16457           //   is the type of its initializing value:
16458           //     - If an initializer is specified for an enumerator, the
16459           //       initializing value has the same type as the expression.
16460           EltTy = Val->getType();
16461         } else {
16462           // C99 6.7.2.2p2:
16463           //   The expression that defines the value of an enumeration constant
16464           //   shall be an integer constant expression that has a value
16465           //   representable as an int.
16466 
16467           // Complain if the value is not representable in an int.
16468           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16469             Diag(IdLoc, diag::ext_enum_value_not_int)
16470               << EnumVal.toString(10) << Val->getSourceRange()
16471               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16472           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16473             // Force the type of the expression to 'int'.
16474             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16475           }
16476           EltTy = Val->getType();
16477         }
16478       }
16479     }
16480   }
16481 
16482   if (!Val) {
16483     if (Enum->isDependentType())
16484       EltTy = Context.DependentTy;
16485     else if (!LastEnumConst) {
16486       // C++0x [dcl.enum]p5:
16487       //   If the underlying type is not fixed, the type of each enumerator
16488       //   is the type of its initializing value:
16489       //     - If no initializer is specified for the first enumerator, the
16490       //       initializing value has an unspecified integral type.
16491       //
16492       // GCC uses 'int' for its unspecified integral type, as does
16493       // C99 6.7.2.2p3.
16494       if (Enum->isFixed()) {
16495         EltTy = Enum->getIntegerType();
16496       }
16497       else {
16498         EltTy = Context.IntTy;
16499       }
16500     } else {
16501       // Assign the last value + 1.
16502       EnumVal = LastEnumConst->getInitVal();
16503       ++EnumVal;
16504       EltTy = LastEnumConst->getType();
16505 
16506       // Check for overflow on increment.
16507       if (EnumVal < LastEnumConst->getInitVal()) {
16508         // C++0x [dcl.enum]p5:
16509         //   If the underlying type is not fixed, the type of each enumerator
16510         //   is the type of its initializing value:
16511         //
16512         //     - Otherwise the type of the initializing value is the same as
16513         //       the type of the initializing value of the preceding enumerator
16514         //       unless the incremented value is not representable in that type,
16515         //       in which case the type is an unspecified integral type
16516         //       sufficient to contain the incremented value. If no such type
16517         //       exists, the program is ill-formed.
16518         QualType T = getNextLargerIntegralType(Context, EltTy);
16519         if (T.isNull() || Enum->isFixed()) {
16520           // There is no integral type larger enough to represent this
16521           // value. Complain, then allow the value to wrap around.
16522           EnumVal = LastEnumConst->getInitVal();
16523           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16524           ++EnumVal;
16525           if (Enum->isFixed())
16526             // When the underlying type is fixed, this is ill-formed.
16527             Diag(IdLoc, diag::err_enumerator_wrapped)
16528               << EnumVal.toString(10)
16529               << EltTy;
16530           else
16531             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16532               << EnumVal.toString(10);
16533         } else {
16534           EltTy = T;
16535         }
16536 
16537         // Retrieve the last enumerator's value, extent that type to the
16538         // type that is supposed to be large enough to represent the incremented
16539         // value, then increment.
16540         EnumVal = LastEnumConst->getInitVal();
16541         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16542         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16543         ++EnumVal;
16544 
16545         // If we're not in C++, diagnose the overflow of enumerator values,
16546         // which in C99 means that the enumerator value is not representable in
16547         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16548         // permits enumerator values that are representable in some larger
16549         // integral type.
16550         if (!getLangOpts().CPlusPlus && !T.isNull())
16551           Diag(IdLoc, diag::warn_enum_value_overflow);
16552       } else if (!getLangOpts().CPlusPlus &&
16553                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16554         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16555         Diag(IdLoc, diag::ext_enum_value_not_int)
16556           << EnumVal.toString(10) << 1;
16557       }
16558     }
16559   }
16560 
16561   if (!EltTy->isDependentType()) {
16562     // Make the enumerator value match the signedness and size of the
16563     // enumerator's type.
16564     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16565     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16566   }
16567 
16568   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16569                                   Val, EnumVal);
16570 }
16571 
16572 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16573                                                 SourceLocation IILoc) {
16574   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16575       !getLangOpts().CPlusPlus)
16576     return SkipBodyInfo();
16577 
16578   // We have an anonymous enum definition. Look up the first enumerator to
16579   // determine if we should merge the definition with an existing one and
16580   // skip the body.
16581   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16582                                          forRedeclarationInCurContext());
16583   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16584   if (!PrevECD)
16585     return SkipBodyInfo();
16586 
16587   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16588   NamedDecl *Hidden;
16589   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16590     SkipBodyInfo Skip;
16591     Skip.Previous = Hidden;
16592     return Skip;
16593   }
16594 
16595   return SkipBodyInfo();
16596 }
16597 
16598 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16599                               SourceLocation IdLoc, IdentifierInfo *Id,
16600                               const ParsedAttributesView &Attrs,
16601                               SourceLocation EqualLoc, Expr *Val) {
16602   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16603   EnumConstantDecl *LastEnumConst =
16604     cast_or_null<EnumConstantDecl>(lastEnumConst);
16605 
16606   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16607   // we find one that is.
16608   S = getNonFieldDeclScope(S);
16609 
16610   // Verify that there isn't already something declared with this name in this
16611   // scope.
16612   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16613   LookupName(R, S);
16614   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16615 
16616   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16617     // Maybe we will complain about the shadowed template parameter.
16618     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16619     // Just pretend that we didn't see the previous declaration.
16620     PrevDecl = nullptr;
16621   }
16622 
16623   // C++ [class.mem]p15:
16624   // If T is the name of a class, then each of the following shall have a name
16625   // different from T:
16626   // - every enumerator of every member of class T that is an unscoped
16627   // enumerated type
16628   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16629     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16630                             DeclarationNameInfo(Id, IdLoc));
16631 
16632   EnumConstantDecl *New =
16633     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16634   if (!New)
16635     return nullptr;
16636 
16637   if (PrevDecl) {
16638     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16639       // Check for other kinds of shadowing not already handled.
16640       CheckShadow(New, PrevDecl, R);
16641     }
16642 
16643     // When in C++, we may get a TagDecl with the same name; in this case the
16644     // enum constant will 'hide' the tag.
16645     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16646            "Received TagDecl when not in C++!");
16647     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16648       if (isa<EnumConstantDecl>(PrevDecl))
16649         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16650       else
16651         Diag(IdLoc, diag::err_redefinition) << Id;
16652       notePreviousDefinition(PrevDecl, IdLoc);
16653       return nullptr;
16654     }
16655   }
16656 
16657   // Process attributes.
16658   ProcessDeclAttributeList(S, New, Attrs);
16659   AddPragmaAttributes(S, New);
16660 
16661   // Register this decl in the current scope stack.
16662   New->setAccess(TheEnumDecl->getAccess());
16663   PushOnScopeChains(New, S);
16664 
16665   ActOnDocumentableDecl(New);
16666 
16667   return New;
16668 }
16669 
16670 // Returns true when the enum initial expression does not trigger the
16671 // duplicate enum warning.  A few common cases are exempted as follows:
16672 // Element2 = Element1
16673 // Element2 = Element1 + 1
16674 // Element2 = Element1 - 1
16675 // Where Element2 and Element1 are from the same enum.
16676 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16677   Expr *InitExpr = ECD->getInitExpr();
16678   if (!InitExpr)
16679     return true;
16680   InitExpr = InitExpr->IgnoreImpCasts();
16681 
16682   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16683     if (!BO->isAdditiveOp())
16684       return true;
16685     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16686     if (!IL)
16687       return true;
16688     if (IL->getValue() != 1)
16689       return true;
16690 
16691     InitExpr = BO->getLHS();
16692   }
16693 
16694   // This checks if the elements are from the same enum.
16695   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16696   if (!DRE)
16697     return true;
16698 
16699   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16700   if (!EnumConstant)
16701     return true;
16702 
16703   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16704       Enum)
16705     return true;
16706 
16707   return false;
16708 }
16709 
16710 // Emits a warning when an element is implicitly set a value that
16711 // a previous element has already been set to.
16712 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16713                                         EnumDecl *Enum, QualType EnumType) {
16714   // Avoid anonymous enums
16715   if (!Enum->getIdentifier())
16716     return;
16717 
16718   // Only check for small enums.
16719   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16720     return;
16721 
16722   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16723     return;
16724 
16725   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16726   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16727 
16728   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16729   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16730 
16731   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16732   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16733     llvm::APSInt Val = D->getInitVal();
16734     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16735   };
16736 
16737   DuplicatesVector DupVector;
16738   ValueToVectorMap EnumMap;
16739 
16740   // Populate the EnumMap with all values represented by enum constants without
16741   // an initializer.
16742   for (auto *Element : Elements) {
16743     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16744 
16745     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16746     // this constant.  Skip this enum since it may be ill-formed.
16747     if (!ECD) {
16748       return;
16749     }
16750 
16751     // Constants with initalizers are handled in the next loop.
16752     if (ECD->getInitExpr())
16753       continue;
16754 
16755     // Duplicate values are handled in the next loop.
16756     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16757   }
16758 
16759   if (EnumMap.size() == 0)
16760     return;
16761 
16762   // Create vectors for any values that has duplicates.
16763   for (auto *Element : Elements) {
16764     // The last loop returned if any constant was null.
16765     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16766     if (!ValidDuplicateEnum(ECD, Enum))
16767       continue;
16768 
16769     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16770     if (Iter == EnumMap.end())
16771       continue;
16772 
16773     DeclOrVector& Entry = Iter->second;
16774     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16775       // Ensure constants are different.
16776       if (D == ECD)
16777         continue;
16778 
16779       // Create new vector and push values onto it.
16780       auto Vec = llvm::make_unique<ECDVector>();
16781       Vec->push_back(D);
16782       Vec->push_back(ECD);
16783 
16784       // Update entry to point to the duplicates vector.
16785       Entry = Vec.get();
16786 
16787       // Store the vector somewhere we can consult later for quick emission of
16788       // diagnostics.
16789       DupVector.emplace_back(std::move(Vec));
16790       continue;
16791     }
16792 
16793     ECDVector *Vec = Entry.get<ECDVector*>();
16794     // Make sure constants are not added more than once.
16795     if (*Vec->begin() == ECD)
16796       continue;
16797 
16798     Vec->push_back(ECD);
16799   }
16800 
16801   // Emit diagnostics.
16802   for (const auto &Vec : DupVector) {
16803     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16804 
16805     // Emit warning for one enum constant.
16806     auto *FirstECD = Vec->front();
16807     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16808       << FirstECD << FirstECD->getInitVal().toString(10)
16809       << FirstECD->getSourceRange();
16810 
16811     // Emit one note for each of the remaining enum constants with
16812     // the same value.
16813     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16814       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16815         << ECD << ECD->getInitVal().toString(10)
16816         << ECD->getSourceRange();
16817   }
16818 }
16819 
16820 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16821                              bool AllowMask) const {
16822   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16823   assert(ED->isCompleteDefinition() && "expected enum definition");
16824 
16825   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16826   llvm::APInt &FlagBits = R.first->second;
16827 
16828   if (R.second) {
16829     for (auto *E : ED->enumerators()) {
16830       const auto &EVal = E->getInitVal();
16831       // Only single-bit enumerators introduce new flag values.
16832       if (EVal.isPowerOf2())
16833         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16834     }
16835   }
16836 
16837   // A value is in a flag enum if either its bits are a subset of the enum's
16838   // flag bits (the first condition) or we are allowing masks and the same is
16839   // true of its complement (the second condition). When masks are allowed, we
16840   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16841   //
16842   // While it's true that any value could be used as a mask, the assumption is
16843   // that a mask will have all of the insignificant bits set. Anything else is
16844   // likely a logic error.
16845   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16846   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16847 }
16848 
16849 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16850                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16851                          const ParsedAttributesView &Attrs) {
16852   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16853   QualType EnumType = Context.getTypeDeclType(Enum);
16854 
16855   ProcessDeclAttributeList(S, Enum, Attrs);
16856 
16857   if (Enum->isDependentType()) {
16858     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16859       EnumConstantDecl *ECD =
16860         cast_or_null<EnumConstantDecl>(Elements[i]);
16861       if (!ECD) continue;
16862 
16863       ECD->setType(EnumType);
16864     }
16865 
16866     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16867     return;
16868   }
16869 
16870   // TODO: If the result value doesn't fit in an int, it must be a long or long
16871   // long value.  ISO C does not support this, but GCC does as an extension,
16872   // emit a warning.
16873   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16874   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16875   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16876 
16877   // Verify that all the values are okay, compute the size of the values, and
16878   // reverse the list.
16879   unsigned NumNegativeBits = 0;
16880   unsigned NumPositiveBits = 0;
16881 
16882   // Keep track of whether all elements have type int.
16883   bool AllElementsInt = true;
16884 
16885   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16886     EnumConstantDecl *ECD =
16887       cast_or_null<EnumConstantDecl>(Elements[i]);
16888     if (!ECD) continue;  // Already issued a diagnostic.
16889 
16890     const llvm::APSInt &InitVal = ECD->getInitVal();
16891 
16892     // Keep track of the size of positive and negative values.
16893     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16894       NumPositiveBits = std::max(NumPositiveBits,
16895                                  (unsigned)InitVal.getActiveBits());
16896     else
16897       NumNegativeBits = std::max(NumNegativeBits,
16898                                  (unsigned)InitVal.getMinSignedBits());
16899 
16900     // Keep track of whether every enum element has type int (very common).
16901     if (AllElementsInt)
16902       AllElementsInt = ECD->getType() == Context.IntTy;
16903   }
16904 
16905   // Figure out the type that should be used for this enum.
16906   QualType BestType;
16907   unsigned BestWidth;
16908 
16909   // C++0x N3000 [conv.prom]p3:
16910   //   An rvalue of an unscoped enumeration type whose underlying
16911   //   type is not fixed can be converted to an rvalue of the first
16912   //   of the following types that can represent all the values of
16913   //   the enumeration: int, unsigned int, long int, unsigned long
16914   //   int, long long int, or unsigned long long int.
16915   // C99 6.4.4.3p2:
16916   //   An identifier declared as an enumeration constant has type int.
16917   // The C99 rule is modified by a gcc extension
16918   QualType BestPromotionType;
16919 
16920   bool Packed = Enum->hasAttr<PackedAttr>();
16921   // -fshort-enums is the equivalent to specifying the packed attribute on all
16922   // enum definitions.
16923   if (LangOpts.ShortEnums)
16924     Packed = true;
16925 
16926   // If the enum already has a type because it is fixed or dictated by the
16927   // target, promote that type instead of analyzing the enumerators.
16928   if (Enum->isComplete()) {
16929     BestType = Enum->getIntegerType();
16930     if (BestType->isPromotableIntegerType())
16931       BestPromotionType = Context.getPromotedIntegerType(BestType);
16932     else
16933       BestPromotionType = BestType;
16934 
16935     BestWidth = Context.getIntWidth(BestType);
16936   }
16937   else if (NumNegativeBits) {
16938     // If there is a negative value, figure out the smallest integer type (of
16939     // int/long/longlong) that fits.
16940     // If it's packed, check also if it fits a char or a short.
16941     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16942       BestType = Context.SignedCharTy;
16943       BestWidth = CharWidth;
16944     } else if (Packed && NumNegativeBits <= ShortWidth &&
16945                NumPositiveBits < ShortWidth) {
16946       BestType = Context.ShortTy;
16947       BestWidth = ShortWidth;
16948     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16949       BestType = Context.IntTy;
16950       BestWidth = IntWidth;
16951     } else {
16952       BestWidth = Context.getTargetInfo().getLongWidth();
16953 
16954       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16955         BestType = Context.LongTy;
16956       } else {
16957         BestWidth = Context.getTargetInfo().getLongLongWidth();
16958 
16959         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16960           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16961         BestType = Context.LongLongTy;
16962       }
16963     }
16964     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16965   } else {
16966     // If there is no negative value, figure out the smallest type that fits
16967     // all of the enumerator values.
16968     // If it's packed, check also if it fits a char or a short.
16969     if (Packed && NumPositiveBits <= CharWidth) {
16970       BestType = Context.UnsignedCharTy;
16971       BestPromotionType = Context.IntTy;
16972       BestWidth = CharWidth;
16973     } else if (Packed && NumPositiveBits <= ShortWidth) {
16974       BestType = Context.UnsignedShortTy;
16975       BestPromotionType = Context.IntTy;
16976       BestWidth = ShortWidth;
16977     } else if (NumPositiveBits <= IntWidth) {
16978       BestType = Context.UnsignedIntTy;
16979       BestWidth = IntWidth;
16980       BestPromotionType
16981         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16982                            ? Context.UnsignedIntTy : Context.IntTy;
16983     } else if (NumPositiveBits <=
16984                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16985       BestType = Context.UnsignedLongTy;
16986       BestPromotionType
16987         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16988                            ? Context.UnsignedLongTy : Context.LongTy;
16989     } else {
16990       BestWidth = Context.getTargetInfo().getLongLongWidth();
16991       assert(NumPositiveBits <= BestWidth &&
16992              "How could an initializer get larger than ULL?");
16993       BestType = Context.UnsignedLongLongTy;
16994       BestPromotionType
16995         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16996                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16997     }
16998   }
16999 
17000   // Loop over all of the enumerator constants, changing their types to match
17001   // the type of the enum if needed.
17002   for (auto *D : Elements) {
17003     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17004     if (!ECD) continue;  // Already issued a diagnostic.
17005 
17006     // Standard C says the enumerators have int type, but we allow, as an
17007     // extension, the enumerators to be larger than int size.  If each
17008     // enumerator value fits in an int, type it as an int, otherwise type it the
17009     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17010     // that X has type 'int', not 'unsigned'.
17011 
17012     // Determine whether the value fits into an int.
17013     llvm::APSInt InitVal = ECD->getInitVal();
17014 
17015     // If it fits into an integer type, force it.  Otherwise force it to match
17016     // the enum decl type.
17017     QualType NewTy;
17018     unsigned NewWidth;
17019     bool NewSign;
17020     if (!getLangOpts().CPlusPlus &&
17021         !Enum->isFixed() &&
17022         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17023       NewTy = Context.IntTy;
17024       NewWidth = IntWidth;
17025       NewSign = true;
17026     } else if (ECD->getType() == BestType) {
17027       // Already the right type!
17028       if (getLangOpts().CPlusPlus)
17029         // C++ [dcl.enum]p4: Following the closing brace of an
17030         // enum-specifier, each enumerator has the type of its
17031         // enumeration.
17032         ECD->setType(EnumType);
17033       continue;
17034     } else {
17035       NewTy = BestType;
17036       NewWidth = BestWidth;
17037       NewSign = BestType->isSignedIntegerOrEnumerationType();
17038     }
17039 
17040     // Adjust the APSInt value.
17041     InitVal = InitVal.extOrTrunc(NewWidth);
17042     InitVal.setIsSigned(NewSign);
17043     ECD->setInitVal(InitVal);
17044 
17045     // Adjust the Expr initializer and type.
17046     if (ECD->getInitExpr() &&
17047         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17048       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17049                                                 CK_IntegralCast,
17050                                                 ECD->getInitExpr(),
17051                                                 /*base paths*/ nullptr,
17052                                                 VK_RValue));
17053     if (getLangOpts().CPlusPlus)
17054       // C++ [dcl.enum]p4: Following the closing brace of an
17055       // enum-specifier, each enumerator has the type of its
17056       // enumeration.
17057       ECD->setType(EnumType);
17058     else
17059       ECD->setType(NewTy);
17060   }
17061 
17062   Enum->completeDefinition(BestType, BestPromotionType,
17063                            NumPositiveBits, NumNegativeBits);
17064 
17065   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17066 
17067   if (Enum->isClosedFlag()) {
17068     for (Decl *D : Elements) {
17069       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17070       if (!ECD) continue;  // Already issued a diagnostic.
17071 
17072       llvm::APSInt InitVal = ECD->getInitVal();
17073       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17074           !IsValueInFlagEnum(Enum, InitVal, true))
17075         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17076           << ECD << Enum;
17077     }
17078   }
17079 
17080   // Now that the enum type is defined, ensure it's not been underaligned.
17081   if (Enum->hasAttrs())
17082     CheckAlignasUnderalignment(Enum);
17083 }
17084 
17085 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17086                                   SourceLocation StartLoc,
17087                                   SourceLocation EndLoc) {
17088   StringLiteral *AsmString = cast<StringLiteral>(expr);
17089 
17090   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17091                                                    AsmString, StartLoc,
17092                                                    EndLoc);
17093   CurContext->addDecl(New);
17094   return New;
17095 }
17096 
17097 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17098                                       IdentifierInfo* AliasName,
17099                                       SourceLocation PragmaLoc,
17100                                       SourceLocation NameLoc,
17101                                       SourceLocation AliasNameLoc) {
17102   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17103                                          LookupOrdinaryName);
17104   AsmLabelAttr *Attr =
17105       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17106 
17107   // If a declaration that:
17108   // 1) declares a function or a variable
17109   // 2) has external linkage
17110   // already exists, add a label attribute to it.
17111   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17112     if (isDeclExternC(PrevDecl))
17113       PrevDecl->addAttr(Attr);
17114     else
17115       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17116           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17117   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17118   } else
17119     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17120 }
17121 
17122 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17123                              SourceLocation PragmaLoc,
17124                              SourceLocation NameLoc) {
17125   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17126 
17127   if (PrevDecl) {
17128     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17129   } else {
17130     (void)WeakUndeclaredIdentifiers.insert(
17131       std::pair<IdentifierInfo*,WeakInfo>
17132         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17133   }
17134 }
17135 
17136 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17137                                 IdentifierInfo* AliasName,
17138                                 SourceLocation PragmaLoc,
17139                                 SourceLocation NameLoc,
17140                                 SourceLocation AliasNameLoc) {
17141   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17142                                     LookupOrdinaryName);
17143   WeakInfo W = WeakInfo(Name, NameLoc);
17144 
17145   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17146     if (!PrevDecl->hasAttr<AliasAttr>())
17147       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17148         DeclApplyPragmaWeak(TUScope, ND, W);
17149   } else {
17150     (void)WeakUndeclaredIdentifiers.insert(
17151       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17152   }
17153 }
17154 
17155 Decl *Sema::getObjCDeclContext() const {
17156   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17157 }
17158