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                       /*NonTrivialTypeSourceInfo=*/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_ignored)
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   bool EmittedDiag = false;
4093   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4094     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4095     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4096     EmittedDiag = 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     unsigned DiagID;
4689     if (Record->isUnion()) {
4690       // C++ [class.union]p6:
4691       // C++17 [class.union.anon]p2:
4692       //   Anonymous unions declared in a named namespace or in the
4693       //   global namespace shall be declared static.
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     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6431     // supported.  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     // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
7433     // address space additionally.
7434     // FIXME: Add local AS for OpenCL C++.
7435     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7436         NewVD->hasExternalStorage()) {
7437       if (!T->isSamplerT() &&
7438           !(T.getAddressSpace() == LangAS::opencl_constant ||
7439             (T.getAddressSpace() == LangAS::opencl_global &&
7440              (getLangOpts().OpenCLVersion == 200 ||
7441               getLangOpts().OpenCLCPlusPlus)))) {
7442         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7443         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7444           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7445               << Scope << "global or constant";
7446         else
7447           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7448               << Scope << "constant";
7449         NewVD->setInvalidDecl();
7450         return;
7451       }
7452     } else {
7453       if (T.getAddressSpace() == LangAS::opencl_global) {
7454         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7455             << 1 /*is any function*/ << "global";
7456         NewVD->setInvalidDecl();
7457         return;
7458       }
7459       if (T.getAddressSpace() == LangAS::opencl_constant ||
7460           T.getAddressSpace() == LangAS::opencl_local) {
7461         FunctionDecl *FD = getCurFunctionDecl();
7462         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7463         // in functions.
7464         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7465           if (T.getAddressSpace() == LangAS::opencl_constant)
7466             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7467                 << 0 /*non-kernel only*/ << "constant";
7468           else
7469             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7470                 << 0 /*non-kernel only*/ << "local";
7471           NewVD->setInvalidDecl();
7472           return;
7473         }
7474         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7475         // in the outermost scope of a kernel function.
7476         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7477           if (!getCurScope()->isFunctionScope()) {
7478             if (T.getAddressSpace() == LangAS::opencl_constant)
7479               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7480                   << "constant";
7481             else
7482               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7483                   << "local";
7484             NewVD->setInvalidDecl();
7485             return;
7486           }
7487         }
7488       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7489         // Do not allow other address spaces on automatic variable.
7490         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7491         NewVD->setInvalidDecl();
7492         return;
7493       }
7494     }
7495   }
7496 
7497   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7498       && !NewVD->hasAttr<BlocksAttr>()) {
7499     if (getLangOpts().getGC() != LangOptions::NonGC)
7500       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7501     else {
7502       assert(!getLangOpts().ObjCAutoRefCount);
7503       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7504     }
7505   }
7506 
7507   bool isVM = T->isVariablyModifiedType();
7508   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7509       NewVD->hasAttr<BlocksAttr>())
7510     setFunctionHasBranchProtectedScope();
7511 
7512   if ((isVM && NewVD->hasLinkage()) ||
7513       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7514     bool SizeIsNegative;
7515     llvm::APSInt Oversized;
7516     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7517         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7518     QualType FixedT;
7519     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7520       FixedT = FixedTInfo->getType();
7521     else if (FixedTInfo) {
7522       // Type and type-as-written are canonically different. We need to fix up
7523       // both types separately.
7524       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7525                                                    Oversized);
7526     }
7527     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7528       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7529       // FIXME: This won't give the correct result for
7530       // int a[10][n];
7531       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7532 
7533       if (NewVD->isFileVarDecl())
7534         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7535         << SizeRange;
7536       else if (NewVD->isStaticLocal())
7537         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7538         << SizeRange;
7539       else
7540         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7541         << SizeRange;
7542       NewVD->setInvalidDecl();
7543       return;
7544     }
7545 
7546     if (!FixedTInfo) {
7547       if (NewVD->isFileVarDecl())
7548         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7549       else
7550         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7551       NewVD->setInvalidDecl();
7552       return;
7553     }
7554 
7555     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7556     NewVD->setType(FixedT);
7557     NewVD->setTypeSourceInfo(FixedTInfo);
7558   }
7559 
7560   if (T->isVoidType()) {
7561     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7562     //                    of objects and functions.
7563     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7564       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7565         << T;
7566       NewVD->setInvalidDecl();
7567       return;
7568     }
7569   }
7570 
7571   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7572     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7573     NewVD->setInvalidDecl();
7574     return;
7575   }
7576 
7577   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7578     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7579     NewVD->setInvalidDecl();
7580     return;
7581   }
7582 
7583   if (NewVD->isConstexpr() && !T->isDependentType() &&
7584       RequireLiteralType(NewVD->getLocation(), T,
7585                          diag::err_constexpr_var_non_literal)) {
7586     NewVD->setInvalidDecl();
7587     return;
7588   }
7589 }
7590 
7591 /// Perform semantic checking on a newly-created variable
7592 /// declaration.
7593 ///
7594 /// This routine performs all of the type-checking required for a
7595 /// variable declaration once it has been built. It is used both to
7596 /// check variables after they have been parsed and their declarators
7597 /// have been translated into a declaration, and to check variables
7598 /// that have been instantiated from a template.
7599 ///
7600 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7601 ///
7602 /// Returns true if the variable declaration is a redeclaration.
7603 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7604   CheckVariableDeclarationType(NewVD);
7605 
7606   // If the decl is already known invalid, don't check it.
7607   if (NewVD->isInvalidDecl())
7608     return false;
7609 
7610   // If we did not find anything by this name, look for a non-visible
7611   // extern "C" declaration with the same name.
7612   if (Previous.empty() &&
7613       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7614     Previous.setShadowed();
7615 
7616   if (!Previous.empty()) {
7617     MergeVarDecl(NewVD, Previous);
7618     return true;
7619   }
7620   return false;
7621 }
7622 
7623 namespace {
7624 struct FindOverriddenMethod {
7625   Sema *S;
7626   CXXMethodDecl *Method;
7627 
7628   /// Member lookup function that determines whether a given C++
7629   /// method overrides a method in a base class, to be used with
7630   /// CXXRecordDecl::lookupInBases().
7631   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7632     RecordDecl *BaseRecord =
7633         Specifier->getType()->getAs<RecordType>()->getDecl();
7634 
7635     DeclarationName Name = Method->getDeclName();
7636 
7637     // FIXME: Do we care about other names here too?
7638     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7639       // We really want to find the base class destructor here.
7640       QualType T = S->Context.getTypeDeclType(BaseRecord);
7641       CanQualType CT = S->Context.getCanonicalType(T);
7642 
7643       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7644     }
7645 
7646     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7647          Path.Decls = Path.Decls.slice(1)) {
7648       NamedDecl *D = Path.Decls.front();
7649       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7650         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7651           return true;
7652       }
7653     }
7654 
7655     return false;
7656   }
7657 };
7658 
7659 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7660 } // end anonymous namespace
7661 
7662 /// Report an error regarding overriding, along with any relevant
7663 /// overridden methods.
7664 ///
7665 /// \param DiagID the primary error to report.
7666 /// \param MD the overriding method.
7667 /// \param OEK which overrides to include as notes.
7668 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7669                             OverrideErrorKind OEK = OEK_All) {
7670   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7671   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7672     // This check (& the OEK parameter) could be replaced by a predicate, but
7673     // without lambdas that would be overkill. This is still nicer than writing
7674     // out the diag loop 3 times.
7675     if ((OEK == OEK_All) ||
7676         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7677         (OEK == OEK_Deleted && O->isDeleted()))
7678       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7679   }
7680 }
7681 
7682 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7683 /// and if so, check that it's a valid override and remember it.
7684 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7685   // Look for methods in base classes that this method might override.
7686   CXXBasePaths Paths;
7687   FindOverriddenMethod FOM;
7688   FOM.Method = MD;
7689   FOM.S = this;
7690   bool hasDeletedOverridenMethods = false;
7691   bool hasNonDeletedOverridenMethods = false;
7692   bool AddedAny = false;
7693   if (DC->lookupInBases(FOM, Paths)) {
7694     for (auto *I : Paths.found_decls()) {
7695       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7696         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7697         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7698             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7699             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7700             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7701           hasDeletedOverridenMethods |= OldMD->isDeleted();
7702           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7703           AddedAny = true;
7704         }
7705       }
7706     }
7707   }
7708 
7709   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7710     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7711   }
7712   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7713     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7714   }
7715 
7716   return AddedAny;
7717 }
7718 
7719 namespace {
7720   // Struct for holding all of the extra arguments needed by
7721   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7722   struct ActOnFDArgs {
7723     Scope *S;
7724     Declarator &D;
7725     MultiTemplateParamsArg TemplateParamLists;
7726     bool AddToScope;
7727   };
7728 } // end anonymous namespace
7729 
7730 namespace {
7731 
7732 // Callback to only accept typo corrections that have a non-zero edit distance.
7733 // Also only accept corrections that have the same parent decl.
7734 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7735  public:
7736   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7737                             CXXRecordDecl *Parent)
7738       : Context(Context), OriginalFD(TypoFD),
7739         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7740 
7741   bool ValidateCandidate(const TypoCorrection &candidate) override {
7742     if (candidate.getEditDistance() == 0)
7743       return false;
7744 
7745     SmallVector<unsigned, 1> MismatchedParams;
7746     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7747                                           CDeclEnd = candidate.end();
7748          CDecl != CDeclEnd; ++CDecl) {
7749       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7750 
7751       if (FD && !FD->hasBody() &&
7752           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7753         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7754           CXXRecordDecl *Parent = MD->getParent();
7755           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7756             return true;
7757         } else if (!ExpectedParent) {
7758           return true;
7759         }
7760       }
7761     }
7762 
7763     return false;
7764   }
7765 
7766   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7767     return llvm::make_unique<DifferentNameValidatorCCC>(*this);
7768   }
7769 
7770  private:
7771   ASTContext &Context;
7772   FunctionDecl *OriginalFD;
7773   CXXRecordDecl *ExpectedParent;
7774 };
7775 
7776 } // end anonymous namespace
7777 
7778 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7779   TypoCorrectedFunctionDefinitions.insert(F);
7780 }
7781 
7782 /// Generate diagnostics for an invalid function redeclaration.
7783 ///
7784 /// This routine handles generating the diagnostic messages for an invalid
7785 /// function redeclaration, including finding possible similar declarations
7786 /// or performing typo correction if there are no previous declarations with
7787 /// the same name.
7788 ///
7789 /// Returns a NamedDecl iff typo correction was performed and substituting in
7790 /// the new declaration name does not cause new errors.
7791 static NamedDecl *DiagnoseInvalidRedeclaration(
7792     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7793     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7794   DeclarationName Name = NewFD->getDeclName();
7795   DeclContext *NewDC = NewFD->getDeclContext();
7796   SmallVector<unsigned, 1> MismatchedParams;
7797   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7798   TypoCorrection Correction;
7799   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7800   unsigned DiagMsg =
7801     IsLocalFriend ? diag::err_no_matching_local_friend :
7802     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7803     diag::err_member_decl_does_not_match;
7804   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7805                     IsLocalFriend ? Sema::LookupLocalFriendName
7806                                   : Sema::LookupOrdinaryName,
7807                     Sema::ForVisibleRedeclaration);
7808 
7809   NewFD->setInvalidDecl();
7810   if (IsLocalFriend)
7811     SemaRef.LookupName(Prev, S);
7812   else
7813     SemaRef.LookupQualifiedName(Prev, NewDC);
7814   assert(!Prev.isAmbiguous() &&
7815          "Cannot have an ambiguity in previous-declaration lookup");
7816   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7817   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7818                                 MD ? MD->getParent() : nullptr);
7819   if (!Prev.empty()) {
7820     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7821          Func != FuncEnd; ++Func) {
7822       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7823       if (FD &&
7824           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7825         // Add 1 to the index so that 0 can mean the mismatch didn't
7826         // involve a parameter
7827         unsigned ParamNum =
7828             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7829         NearMatches.push_back(std::make_pair(FD, ParamNum));
7830       }
7831     }
7832   // If the qualified name lookup yielded nothing, try typo correction
7833   } else if ((Correction = SemaRef.CorrectTypo(
7834                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7835                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7836                   IsLocalFriend ? nullptr : NewDC))) {
7837     // Set up everything for the call to ActOnFunctionDeclarator
7838     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7839                               ExtraArgs.D.getIdentifierLoc());
7840     Previous.clear();
7841     Previous.setLookupName(Correction.getCorrection());
7842     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7843                                     CDeclEnd = Correction.end();
7844          CDecl != CDeclEnd; ++CDecl) {
7845       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7846       if (FD && !FD->hasBody() &&
7847           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7848         Previous.addDecl(FD);
7849       }
7850     }
7851     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7852 
7853     NamedDecl *Result;
7854     // Retry building the function declaration with the new previous
7855     // declarations, and with errors suppressed.
7856     {
7857       // Trap errors.
7858       Sema::SFINAETrap Trap(SemaRef);
7859 
7860       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7861       // pieces need to verify the typo-corrected C++ declaration and hopefully
7862       // eliminate the need for the parameter pack ExtraArgs.
7863       Result = SemaRef.ActOnFunctionDeclarator(
7864           ExtraArgs.S, ExtraArgs.D,
7865           Correction.getCorrectionDecl()->getDeclContext(),
7866           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7867           ExtraArgs.AddToScope);
7868 
7869       if (Trap.hasErrorOccurred())
7870         Result = nullptr;
7871     }
7872 
7873     if (Result) {
7874       // Determine which correction we picked.
7875       Decl *Canonical = Result->getCanonicalDecl();
7876       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7877            I != E; ++I)
7878         if ((*I)->getCanonicalDecl() == Canonical)
7879           Correction.setCorrectionDecl(*I);
7880 
7881       // Let Sema know about the correction.
7882       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7883       SemaRef.diagnoseTypo(
7884           Correction,
7885           SemaRef.PDiag(IsLocalFriend
7886                           ? diag::err_no_matching_local_friend_suggest
7887                           : diag::err_member_decl_does_not_match_suggest)
7888             << Name << NewDC << IsDefinition);
7889       return Result;
7890     }
7891 
7892     // Pretend the typo correction never occurred
7893     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7894                               ExtraArgs.D.getIdentifierLoc());
7895     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7896     Previous.clear();
7897     Previous.setLookupName(Name);
7898   }
7899 
7900   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7901       << Name << NewDC << IsDefinition << NewFD->getLocation();
7902 
7903   bool NewFDisConst = false;
7904   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7905     NewFDisConst = NewMD->isConst();
7906 
7907   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7908        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7909        NearMatch != NearMatchEnd; ++NearMatch) {
7910     FunctionDecl *FD = NearMatch->first;
7911     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7912     bool FDisConst = MD && MD->isConst();
7913     bool IsMember = MD || !IsLocalFriend;
7914 
7915     // FIXME: These notes are poorly worded for the local friend case.
7916     if (unsigned Idx = NearMatch->second) {
7917       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7918       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7919       if (Loc.isInvalid()) Loc = FD->getLocation();
7920       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7921                                  : diag::note_local_decl_close_param_match)
7922         << Idx << FDParam->getType()
7923         << NewFD->getParamDecl(Idx - 1)->getType();
7924     } else if (FDisConst != NewFDisConst) {
7925       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7926           << NewFDisConst << FD->getSourceRange().getEnd();
7927     } else
7928       SemaRef.Diag(FD->getLocation(),
7929                    IsMember ? diag::note_member_def_close_match
7930                             : diag::note_local_decl_close_match);
7931   }
7932   return nullptr;
7933 }
7934 
7935 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7936   switch (D.getDeclSpec().getStorageClassSpec()) {
7937   default: llvm_unreachable("Unknown storage class!");
7938   case DeclSpec::SCS_auto:
7939   case DeclSpec::SCS_register:
7940   case DeclSpec::SCS_mutable:
7941     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7942                  diag::err_typecheck_sclass_func);
7943     D.getMutableDeclSpec().ClearStorageClassSpecs();
7944     D.setInvalidType();
7945     break;
7946   case DeclSpec::SCS_unspecified: break;
7947   case DeclSpec::SCS_extern:
7948     if (D.getDeclSpec().isExternInLinkageSpec())
7949       return SC_None;
7950     return SC_Extern;
7951   case DeclSpec::SCS_static: {
7952     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7953       // C99 6.7.1p5:
7954       //   The declaration of an identifier for a function that has
7955       //   block scope shall have no explicit storage-class specifier
7956       //   other than extern
7957       // See also (C++ [dcl.stc]p4).
7958       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7959                    diag::err_static_block_func);
7960       break;
7961     } else
7962       return SC_Static;
7963   }
7964   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7965   }
7966 
7967   // No explicit storage class has already been returned
7968   return SC_None;
7969 }
7970 
7971 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7972                                            DeclContext *DC, QualType &R,
7973                                            TypeSourceInfo *TInfo,
7974                                            StorageClass SC,
7975                                            bool &IsVirtualOkay) {
7976   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7977   DeclarationName Name = NameInfo.getName();
7978 
7979   FunctionDecl *NewFD = nullptr;
7980   bool isInline = D.getDeclSpec().isInlineSpecified();
7981 
7982   if (!SemaRef.getLangOpts().CPlusPlus) {
7983     // Determine whether the function was written with a
7984     // prototype. This true when:
7985     //   - there is a prototype in the declarator, or
7986     //   - the type R of the function is some kind of typedef or other non-
7987     //     attributed reference to a type name (which eventually refers to a
7988     //     function type).
7989     bool HasPrototype =
7990       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7991       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7992 
7993     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
7994                                  R, TInfo, SC, isInline, HasPrototype,
7995                                  CSK_unspecified);
7996     if (D.isInvalidType())
7997       NewFD->setInvalidDecl();
7998 
7999     return NewFD;
8000   }
8001 
8002   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8003   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8004   // Check that the return type is not an abstract class type.
8005   // For record types, this is done by the AbstractClassUsageDiagnoser once
8006   // the class has been completely parsed.
8007   if (!DC->isRecord() &&
8008       SemaRef.RequireNonAbstractType(
8009           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
8010           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8011     D.setInvalidType();
8012 
8013   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8014     // This is a C++ constructor declaration.
8015     assert(DC->isRecord() &&
8016            "Constructors can only be declared in a member context");
8017 
8018     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8019     return CXXConstructorDecl::Create(
8020         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8021         TInfo, ExplicitSpecifier, isInline,
8022         /*isImplicitlyDeclared=*/false, ConstexprKind);
8023 
8024   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8025     // This is a C++ destructor declaration.
8026     if (DC->isRecord()) {
8027       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8028       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8029       CXXDestructorDecl *NewDD =
8030           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
8031                                     NameInfo, R, TInfo, isInline,
8032                                     /*isImplicitlyDeclared=*/false);
8033 
8034       // If the destructor needs an implicit exception specification, set it
8035       // now. FIXME: It'd be nice to be able to create the right type to start
8036       // with, but the type needs to reference the destructor declaration.
8037       if (SemaRef.getLangOpts().CPlusPlus11)
8038         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8039 
8040       IsVirtualOkay = true;
8041       return NewDD;
8042 
8043     } else {
8044       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8045       D.setInvalidType();
8046 
8047       // Create a FunctionDecl to satisfy the function definition parsing
8048       // code path.
8049       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8050                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8051                                   isInline,
8052                                   /*hasPrototype=*/true, ConstexprKind);
8053     }
8054 
8055   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8056     if (!DC->isRecord()) {
8057       SemaRef.Diag(D.getIdentifierLoc(),
8058            diag::err_conv_function_not_member);
8059       return nullptr;
8060     }
8061 
8062     SemaRef.CheckConversionDeclarator(D, R, SC);
8063     IsVirtualOkay = true;
8064     return CXXConversionDecl::Create(
8065         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8066         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8067 
8068   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8069     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8070 
8071     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8072                                          ExplicitSpecifier, NameInfo, R, TInfo,
8073                                          D.getEndLoc());
8074   } else if (DC->isRecord()) {
8075     // If the name of the function is the same as the name of the record,
8076     // then this must be an invalid constructor that has a return type.
8077     // (The parser checks for a return type and makes the declarator a
8078     // constructor if it has no return type).
8079     if (Name.getAsIdentifierInfo() &&
8080         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8081       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8082         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8083         << SourceRange(D.getIdentifierLoc());
8084       return nullptr;
8085     }
8086 
8087     // This is a C++ method declaration.
8088     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8089         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8090         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8091     IsVirtualOkay = !Ret->isStatic();
8092     return Ret;
8093   } else {
8094     bool isFriend =
8095         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8096     if (!isFriend && SemaRef.CurContext->isRecord())
8097       return nullptr;
8098 
8099     // Determine whether the function was written with a
8100     // prototype. This true when:
8101     //   - we're in C++ (where every function has a prototype),
8102     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8103                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8104                                 ConstexprKind);
8105   }
8106 }
8107 
8108 enum OpenCLParamType {
8109   ValidKernelParam,
8110   PtrPtrKernelParam,
8111   PtrKernelParam,
8112   InvalidAddrSpacePtrKernelParam,
8113   InvalidKernelParam,
8114   RecordKernelParam
8115 };
8116 
8117 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8118   // Size dependent types are just typedefs to normal integer types
8119   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8120   // integers other than by their names.
8121   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8122 
8123   // Remove typedefs one by one until we reach a typedef
8124   // for a size dependent type.
8125   QualType DesugaredTy = Ty;
8126   do {
8127     ArrayRef<StringRef> Names(SizeTypeNames);
8128     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8129     if (Names.end() != Match)
8130       return true;
8131 
8132     Ty = DesugaredTy;
8133     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8134   } while (DesugaredTy != Ty);
8135 
8136   return false;
8137 }
8138 
8139 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8140   if (PT->isPointerType()) {
8141     QualType PointeeType = PT->getPointeeType();
8142     if (PointeeType->isPointerType())
8143       return PtrPtrKernelParam;
8144     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8145         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8146         PointeeType.getAddressSpace() == LangAS::Default)
8147       return InvalidAddrSpacePtrKernelParam;
8148     return PtrKernelParam;
8149   }
8150 
8151   // OpenCL v1.2 s6.9.k:
8152   // Arguments to kernel functions in a program cannot be declared with the
8153   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8154   // uintptr_t or a struct and/or union that contain fields declared to be one
8155   // of these built-in scalar types.
8156   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8157     return InvalidKernelParam;
8158 
8159   if (PT->isImageType())
8160     return PtrKernelParam;
8161 
8162   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8163     return InvalidKernelParam;
8164 
8165   // OpenCL extension spec v1.2 s9.5:
8166   // This extension adds support for half scalar and vector types as built-in
8167   // types that can be used for arithmetic operations, conversions etc.
8168   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8169     return InvalidKernelParam;
8170 
8171   if (PT->isRecordType())
8172     return RecordKernelParam;
8173 
8174   // Look into an array argument to check if it has a forbidden type.
8175   if (PT->isArrayType()) {
8176     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8177     // Call ourself to check an underlying type of an array. Since the
8178     // getPointeeOrArrayElementType returns an innermost type which is not an
8179     // array, this recursive call only happens once.
8180     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8181   }
8182 
8183   return ValidKernelParam;
8184 }
8185 
8186 static void checkIsValidOpenCLKernelParameter(
8187   Sema &S,
8188   Declarator &D,
8189   ParmVarDecl *Param,
8190   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8191   QualType PT = Param->getType();
8192 
8193   // Cache the valid types we encounter to avoid rechecking structs that are
8194   // used again
8195   if (ValidTypes.count(PT.getTypePtr()))
8196     return;
8197 
8198   switch (getOpenCLKernelParameterType(S, PT)) {
8199   case PtrPtrKernelParam:
8200     // OpenCL v1.2 s6.9.a:
8201     // A kernel function argument cannot be declared as a
8202     // pointer to a pointer type.
8203     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8204     D.setInvalidType();
8205     return;
8206 
8207   case InvalidAddrSpacePtrKernelParam:
8208     // OpenCL v1.0 s6.5:
8209     // __kernel function arguments declared to be a pointer of a type can point
8210     // to one of the following address spaces only : __global, __local or
8211     // __constant.
8212     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8213     D.setInvalidType();
8214     return;
8215 
8216     // OpenCL v1.2 s6.9.k:
8217     // Arguments to kernel functions in a program cannot be declared with the
8218     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8219     // uintptr_t or a struct and/or union that contain fields declared to be
8220     // one of these built-in scalar types.
8221 
8222   case InvalidKernelParam:
8223     // OpenCL v1.2 s6.8 n:
8224     // A kernel function argument cannot be declared
8225     // of event_t type.
8226     // Do not diagnose half type since it is diagnosed as invalid argument
8227     // type for any function elsewhere.
8228     if (!PT->isHalfType()) {
8229       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8230 
8231       // Explain what typedefs are involved.
8232       const TypedefType *Typedef = nullptr;
8233       while ((Typedef = PT->getAs<TypedefType>())) {
8234         SourceLocation Loc = Typedef->getDecl()->getLocation();
8235         // SourceLocation may be invalid for a built-in type.
8236         if (Loc.isValid())
8237           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8238         PT = Typedef->desugar();
8239       }
8240     }
8241 
8242     D.setInvalidType();
8243     return;
8244 
8245   case PtrKernelParam:
8246   case ValidKernelParam:
8247     ValidTypes.insert(PT.getTypePtr());
8248     return;
8249 
8250   case RecordKernelParam:
8251     break;
8252   }
8253 
8254   // Track nested structs we will inspect
8255   SmallVector<const Decl *, 4> VisitStack;
8256 
8257   // Track where we are in the nested structs. Items will migrate from
8258   // VisitStack to HistoryStack as we do the DFS for bad field.
8259   SmallVector<const FieldDecl *, 4> HistoryStack;
8260   HistoryStack.push_back(nullptr);
8261 
8262   // At this point we already handled everything except of a RecordType or
8263   // an ArrayType of a RecordType.
8264   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8265   const RecordType *RecTy =
8266       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8267   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8268 
8269   VisitStack.push_back(RecTy->getDecl());
8270   assert(VisitStack.back() && "First decl null?");
8271 
8272   do {
8273     const Decl *Next = VisitStack.pop_back_val();
8274     if (!Next) {
8275       assert(!HistoryStack.empty());
8276       // Found a marker, we have gone up a level
8277       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8278         ValidTypes.insert(Hist->getType().getTypePtr());
8279 
8280       continue;
8281     }
8282 
8283     // Adds everything except the original parameter declaration (which is not a
8284     // field itself) to the history stack.
8285     const RecordDecl *RD;
8286     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8287       HistoryStack.push_back(Field);
8288 
8289       QualType FieldTy = Field->getType();
8290       // Other field types (known to be valid or invalid) are handled while we
8291       // walk around RecordDecl::fields().
8292       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8293              "Unexpected type.");
8294       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8295 
8296       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8297     } else {
8298       RD = cast<RecordDecl>(Next);
8299     }
8300 
8301     // Add a null marker so we know when we've gone back up a level
8302     VisitStack.push_back(nullptr);
8303 
8304     for (const auto *FD : RD->fields()) {
8305       QualType QT = FD->getType();
8306 
8307       if (ValidTypes.count(QT.getTypePtr()))
8308         continue;
8309 
8310       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8311       if (ParamType == ValidKernelParam)
8312         continue;
8313 
8314       if (ParamType == RecordKernelParam) {
8315         VisitStack.push_back(FD);
8316         continue;
8317       }
8318 
8319       // OpenCL v1.2 s6.9.p:
8320       // Arguments to kernel functions that are declared to be a struct or union
8321       // do not allow OpenCL objects to be passed as elements of the struct or
8322       // union.
8323       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8324           ParamType == InvalidAddrSpacePtrKernelParam) {
8325         S.Diag(Param->getLocation(),
8326                diag::err_record_with_pointers_kernel_param)
8327           << PT->isUnionType()
8328           << PT;
8329       } else {
8330         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8331       }
8332 
8333       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8334           << OrigRecDecl->getDeclName();
8335 
8336       // We have an error, now let's go back up through history and show where
8337       // the offending field came from
8338       for (ArrayRef<const FieldDecl *>::const_iterator
8339                I = HistoryStack.begin() + 1,
8340                E = HistoryStack.end();
8341            I != E; ++I) {
8342         const FieldDecl *OuterField = *I;
8343         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8344           << OuterField->getType();
8345       }
8346 
8347       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8348         << QT->isPointerType()
8349         << QT;
8350       D.setInvalidType();
8351       return;
8352     }
8353   } while (!VisitStack.empty());
8354 }
8355 
8356 /// Find the DeclContext in which a tag is implicitly declared if we see an
8357 /// elaborated type specifier in the specified context, and lookup finds
8358 /// nothing.
8359 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8360   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8361     DC = DC->getParent();
8362   return DC;
8363 }
8364 
8365 /// Find the Scope in which a tag is implicitly declared if we see an
8366 /// elaborated type specifier in the specified context, and lookup finds
8367 /// nothing.
8368 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8369   while (S->isClassScope() ||
8370          (LangOpts.CPlusPlus &&
8371           S->isFunctionPrototypeScope()) ||
8372          ((S->getFlags() & Scope::DeclScope) == 0) ||
8373          (S->getEntity() && S->getEntity()->isTransparentContext()))
8374     S = S->getParent();
8375   return S;
8376 }
8377 
8378 NamedDecl*
8379 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8380                               TypeSourceInfo *TInfo, LookupResult &Previous,
8381                               MultiTemplateParamsArg TemplateParamLists,
8382                               bool &AddToScope) {
8383   QualType R = TInfo->getType();
8384 
8385   assert(R->isFunctionType());
8386 
8387   // TODO: consider using NameInfo for diagnostic.
8388   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8389   DeclarationName Name = NameInfo.getName();
8390   StorageClass SC = getFunctionStorageClass(*this, D);
8391 
8392   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8393     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8394          diag::err_invalid_thread)
8395       << DeclSpec::getSpecifierName(TSCS);
8396 
8397   if (D.isFirstDeclarationOfMember())
8398     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8399                            D.getIdentifierLoc());
8400 
8401   bool isFriend = false;
8402   FunctionTemplateDecl *FunctionTemplate = nullptr;
8403   bool isMemberSpecialization = false;
8404   bool isFunctionTemplateSpecialization = false;
8405 
8406   bool isDependentClassScopeExplicitSpecialization = false;
8407   bool HasExplicitTemplateArgs = false;
8408   TemplateArgumentListInfo TemplateArgs;
8409 
8410   bool isVirtualOkay = false;
8411 
8412   DeclContext *OriginalDC = DC;
8413   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8414 
8415   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8416                                               isVirtualOkay);
8417   if (!NewFD) return nullptr;
8418 
8419   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8420     NewFD->setTopLevelDeclInObjCContainer();
8421 
8422   // Set the lexical context. If this is a function-scope declaration, or has a
8423   // C++ scope specifier, or is the object of a friend declaration, the lexical
8424   // context will be different from the semantic context.
8425   NewFD->setLexicalDeclContext(CurContext);
8426 
8427   if (IsLocalExternDecl)
8428     NewFD->setLocalExternDecl();
8429 
8430   if (getLangOpts().CPlusPlus) {
8431     bool isInline = D.getDeclSpec().isInlineSpecified();
8432     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8433     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8434     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8435     isFriend = D.getDeclSpec().isFriendSpecified();
8436     if (isFriend && !isInline && D.isFunctionDefinition()) {
8437       // C++ [class.friend]p5
8438       //   A function can be defined in a friend declaration of a
8439       //   class . . . . Such a function is implicitly inline.
8440       NewFD->setImplicitlyInline();
8441     }
8442 
8443     // If this is a method defined in an __interface, and is not a constructor
8444     // or an overloaded operator, then set the pure flag (isVirtual will already
8445     // return true).
8446     if (const CXXRecordDecl *Parent =
8447           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8448       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8449         NewFD->setPure(true);
8450 
8451       // C++ [class.union]p2
8452       //   A union can have member functions, but not virtual functions.
8453       if (isVirtual && Parent->isUnion())
8454         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8455     }
8456 
8457     SetNestedNameSpecifier(*this, NewFD, D);
8458     isMemberSpecialization = false;
8459     isFunctionTemplateSpecialization = false;
8460     if (D.isInvalidType())
8461       NewFD->setInvalidDecl();
8462 
8463     // Match up the template parameter lists with the scope specifier, then
8464     // determine whether we have a template or a template specialization.
8465     bool Invalid = false;
8466     if (TemplateParameterList *TemplateParams =
8467             MatchTemplateParametersToScopeSpecifier(
8468                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8469                 D.getCXXScopeSpec(),
8470                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8471                     ? D.getName().TemplateId
8472                     : nullptr,
8473                 TemplateParamLists, isFriend, isMemberSpecialization,
8474                 Invalid)) {
8475       if (TemplateParams->size() > 0) {
8476         // This is a function template
8477 
8478         // Check that we can declare a template here.
8479         if (CheckTemplateDeclScope(S, TemplateParams))
8480           NewFD->setInvalidDecl();
8481 
8482         // A destructor cannot be a template.
8483         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8484           Diag(NewFD->getLocation(), diag::err_destructor_template);
8485           NewFD->setInvalidDecl();
8486         }
8487 
8488         // If we're adding a template to a dependent context, we may need to
8489         // rebuilding some of the types used within the template parameter list,
8490         // now that we know what the current instantiation is.
8491         if (DC->isDependentContext()) {
8492           ContextRAII SavedContext(*this, DC);
8493           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8494             Invalid = true;
8495         }
8496 
8497         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8498                                                         NewFD->getLocation(),
8499                                                         Name, TemplateParams,
8500                                                         NewFD);
8501         FunctionTemplate->setLexicalDeclContext(CurContext);
8502         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8503 
8504         // For source fidelity, store the other template param lists.
8505         if (TemplateParamLists.size() > 1) {
8506           NewFD->setTemplateParameterListsInfo(Context,
8507                                                TemplateParamLists.drop_back(1));
8508         }
8509       } else {
8510         // This is a function template specialization.
8511         isFunctionTemplateSpecialization = true;
8512         // For source fidelity, store all the template param lists.
8513         if (TemplateParamLists.size() > 0)
8514           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8515 
8516         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8517         if (isFriend) {
8518           // We want to remove the "template<>", found here.
8519           SourceRange RemoveRange = TemplateParams->getSourceRange();
8520 
8521           // If we remove the template<> and the name is not a
8522           // template-id, we're actually silently creating a problem:
8523           // the friend declaration will refer to an untemplated decl,
8524           // and clearly the user wants a template specialization.  So
8525           // we need to insert '<>' after the name.
8526           SourceLocation InsertLoc;
8527           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8528             InsertLoc = D.getName().getSourceRange().getEnd();
8529             InsertLoc = getLocForEndOfToken(InsertLoc);
8530           }
8531 
8532           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8533             << Name << RemoveRange
8534             << FixItHint::CreateRemoval(RemoveRange)
8535             << FixItHint::CreateInsertion(InsertLoc, "<>");
8536         }
8537       }
8538     } else {
8539       // All template param lists were matched against the scope specifier:
8540       // this is NOT (an explicit specialization of) a template.
8541       if (TemplateParamLists.size() > 0)
8542         // For source fidelity, store all the template param lists.
8543         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8544     }
8545 
8546     if (Invalid) {
8547       NewFD->setInvalidDecl();
8548       if (FunctionTemplate)
8549         FunctionTemplate->setInvalidDecl();
8550     }
8551 
8552     // C++ [dcl.fct.spec]p5:
8553     //   The virtual specifier shall only be used in declarations of
8554     //   nonstatic class member functions that appear within a
8555     //   member-specification of a class declaration; see 10.3.
8556     //
8557     if (isVirtual && !NewFD->isInvalidDecl()) {
8558       if (!isVirtualOkay) {
8559         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8560              diag::err_virtual_non_function);
8561       } else if (!CurContext->isRecord()) {
8562         // 'virtual' was specified outside of the class.
8563         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8564              diag::err_virtual_out_of_class)
8565           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8566       } else if (NewFD->getDescribedFunctionTemplate()) {
8567         // C++ [temp.mem]p3:
8568         //  A member function template shall not be virtual.
8569         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8570              diag::err_virtual_member_function_template)
8571           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8572       } else {
8573         // Okay: Add virtual to the method.
8574         NewFD->setVirtualAsWritten(true);
8575       }
8576 
8577       if (getLangOpts().CPlusPlus14 &&
8578           NewFD->getReturnType()->isUndeducedType())
8579         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8580     }
8581 
8582     if (getLangOpts().CPlusPlus14 &&
8583         (NewFD->isDependentContext() ||
8584          (isFriend && CurContext->isDependentContext())) &&
8585         NewFD->getReturnType()->isUndeducedType()) {
8586       // If the function template is referenced directly (for instance, as a
8587       // member of the current instantiation), pretend it has a dependent type.
8588       // This is not really justified by the standard, but is the only sane
8589       // thing to do.
8590       // FIXME: For a friend function, we have not marked the function as being
8591       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8592       const FunctionProtoType *FPT =
8593           NewFD->getType()->castAs<FunctionProtoType>();
8594       QualType Result =
8595           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8596       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8597                                              FPT->getExtProtoInfo()));
8598     }
8599 
8600     // C++ [dcl.fct.spec]p3:
8601     //  The inline specifier shall not appear on a block scope function
8602     //  declaration.
8603     if (isInline && !NewFD->isInvalidDecl()) {
8604       if (CurContext->isFunctionOrMethod()) {
8605         // 'inline' is not allowed on block scope function declaration.
8606         Diag(D.getDeclSpec().getInlineSpecLoc(),
8607              diag::err_inline_declaration_block_scope) << Name
8608           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8609       }
8610     }
8611 
8612     // C++ [dcl.fct.spec]p6:
8613     //  The explicit specifier shall be used only in the declaration of a
8614     //  constructor or conversion function within its class definition;
8615     //  see 12.3.1 and 12.3.2.
8616     if (hasExplicit && !NewFD->isInvalidDecl() &&
8617         !isa<CXXDeductionGuideDecl>(NewFD)) {
8618       if (!CurContext->isRecord()) {
8619         // 'explicit' was specified outside of the class.
8620         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8621              diag::err_explicit_out_of_class)
8622             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8623       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8624                  !isa<CXXConversionDecl>(NewFD)) {
8625         // 'explicit' was specified on a function that wasn't a constructor
8626         // or conversion function.
8627         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8628              diag::err_explicit_non_ctor_or_conv_function)
8629             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8630       }
8631     }
8632 
8633     if (ConstexprKind != CSK_unspecified) {
8634       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8635       // are implicitly inline.
8636       NewFD->setImplicitlyInline();
8637 
8638       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8639       // be either constructors or to return a literal type. Therefore,
8640       // destructors cannot be declared constexpr.
8641       if (isa<CXXDestructorDecl>(NewFD))
8642         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8643             << (ConstexprKind == CSK_consteval);
8644     }
8645 
8646     // If __module_private__ was specified, mark the function accordingly.
8647     if (D.getDeclSpec().isModulePrivateSpecified()) {
8648       if (isFunctionTemplateSpecialization) {
8649         SourceLocation ModulePrivateLoc
8650           = D.getDeclSpec().getModulePrivateSpecLoc();
8651         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8652           << 0
8653           << FixItHint::CreateRemoval(ModulePrivateLoc);
8654       } else {
8655         NewFD->setModulePrivate();
8656         if (FunctionTemplate)
8657           FunctionTemplate->setModulePrivate();
8658       }
8659     }
8660 
8661     if (isFriend) {
8662       if (FunctionTemplate) {
8663         FunctionTemplate->setObjectOfFriendDecl();
8664         FunctionTemplate->setAccess(AS_public);
8665       }
8666       NewFD->setObjectOfFriendDecl();
8667       NewFD->setAccess(AS_public);
8668     }
8669 
8670     // If a function is defined as defaulted or deleted, mark it as such now.
8671     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8672     // definition kind to FDK_Definition.
8673     switch (D.getFunctionDefinitionKind()) {
8674       case FDK_Declaration:
8675       case FDK_Definition:
8676         break;
8677 
8678       case FDK_Defaulted:
8679         NewFD->setDefaulted();
8680         break;
8681 
8682       case FDK_Deleted:
8683         NewFD->setDeletedAsWritten();
8684         break;
8685     }
8686 
8687     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8688         D.isFunctionDefinition()) {
8689       // C++ [class.mfct]p2:
8690       //   A member function may be defined (8.4) in its class definition, in
8691       //   which case it is an inline member function (7.1.2)
8692       NewFD->setImplicitlyInline();
8693     }
8694 
8695     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8696         !CurContext->isRecord()) {
8697       // C++ [class.static]p1:
8698       //   A data or function member of a class may be declared static
8699       //   in a class definition, in which case it is a static member of
8700       //   the class.
8701 
8702       // Complain about the 'static' specifier if it's on an out-of-line
8703       // member function definition.
8704 
8705       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8706       // member function template declaration and class member template
8707       // declaration (MSVC versions before 2015), warn about this.
8708       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8709            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8710              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8711            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8712            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8713         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8714     }
8715 
8716     // C++11 [except.spec]p15:
8717     //   A deallocation function with no exception-specification is treated
8718     //   as if it were specified with noexcept(true).
8719     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8720     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8721          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8722         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8723       NewFD->setType(Context.getFunctionType(
8724           FPT->getReturnType(), FPT->getParamTypes(),
8725           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8726   }
8727 
8728   // Filter out previous declarations that don't match the scope.
8729   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8730                        D.getCXXScopeSpec().isNotEmpty() ||
8731                        isMemberSpecialization ||
8732                        isFunctionTemplateSpecialization);
8733 
8734   // Handle GNU asm-label extension (encoded as an attribute).
8735   if (Expr *E = (Expr*) D.getAsmLabel()) {
8736     // The parser guarantees this is a string.
8737     StringLiteral *SE = cast<StringLiteral>(E);
8738     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8739                                                 SE->getString(), 0));
8740   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8741     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8742       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8743     if (I != ExtnameUndeclaredIdentifiers.end()) {
8744       if (isDeclExternC(NewFD)) {
8745         NewFD->addAttr(I->second);
8746         ExtnameUndeclaredIdentifiers.erase(I);
8747       } else
8748         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8749             << /*Variable*/0 << NewFD;
8750     }
8751   }
8752 
8753   // Copy the parameter declarations from the declarator D to the function
8754   // declaration NewFD, if they are available.  First scavenge them into Params.
8755   SmallVector<ParmVarDecl*, 16> Params;
8756   unsigned FTIIdx;
8757   if (D.isFunctionDeclarator(FTIIdx)) {
8758     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8759 
8760     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8761     // function that takes no arguments, not a function that takes a
8762     // single void argument.
8763     // We let through "const void" here because Sema::GetTypeForDeclarator
8764     // already checks for that case.
8765     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8766       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8767         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8768         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8769         Param->setDeclContext(NewFD);
8770         Params.push_back(Param);
8771 
8772         if (Param->isInvalidDecl())
8773           NewFD->setInvalidDecl();
8774       }
8775     }
8776 
8777     if (!getLangOpts().CPlusPlus) {
8778       // In C, find all the tag declarations from the prototype and move them
8779       // into the function DeclContext. Remove them from the surrounding tag
8780       // injection context of the function, which is typically but not always
8781       // the TU.
8782       DeclContext *PrototypeTagContext =
8783           getTagInjectionContext(NewFD->getLexicalDeclContext());
8784       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8785         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8786 
8787         // We don't want to reparent enumerators. Look at their parent enum
8788         // instead.
8789         if (!TD) {
8790           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8791             TD = cast<EnumDecl>(ECD->getDeclContext());
8792         }
8793         if (!TD)
8794           continue;
8795         DeclContext *TagDC = TD->getLexicalDeclContext();
8796         if (!TagDC->containsDecl(TD))
8797           continue;
8798         TagDC->removeDecl(TD);
8799         TD->setDeclContext(NewFD);
8800         NewFD->addDecl(TD);
8801 
8802         // Preserve the lexical DeclContext if it is not the surrounding tag
8803         // injection context of the FD. In this example, the semantic context of
8804         // E will be f and the lexical context will be S, while both the
8805         // semantic and lexical contexts of S will be f:
8806         //   void f(struct S { enum E { a } f; } s);
8807         if (TagDC != PrototypeTagContext)
8808           TD->setLexicalDeclContext(TagDC);
8809       }
8810     }
8811   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8812     // When we're declaring a function with a typedef, typeof, etc as in the
8813     // following example, we'll need to synthesize (unnamed)
8814     // parameters for use in the declaration.
8815     //
8816     // @code
8817     // typedef void fn(int);
8818     // fn f;
8819     // @endcode
8820 
8821     // Synthesize a parameter for each argument type.
8822     for (const auto &AI : FT->param_types()) {
8823       ParmVarDecl *Param =
8824           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8825       Param->setScopeInfo(0, Params.size());
8826       Params.push_back(Param);
8827     }
8828   } else {
8829     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8830            "Should not need args for typedef of non-prototype fn");
8831   }
8832 
8833   // Finally, we know we have the right number of parameters, install them.
8834   NewFD->setParams(Params);
8835 
8836   if (D.getDeclSpec().isNoreturnSpecified())
8837     NewFD->addAttr(
8838         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8839                                        Context, 0));
8840 
8841   // Functions returning a variably modified type violate C99 6.7.5.2p2
8842   // because all functions have linkage.
8843   if (!NewFD->isInvalidDecl() &&
8844       NewFD->getReturnType()->isVariablyModifiedType()) {
8845     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8846     NewFD->setInvalidDecl();
8847   }
8848 
8849   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8850   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8851       !NewFD->hasAttr<SectionAttr>()) {
8852     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8853                                                  PragmaClangTextSection.SectionName,
8854                                                  PragmaClangTextSection.PragmaLocation));
8855   }
8856 
8857   // Apply an implicit SectionAttr if #pragma code_seg is active.
8858   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8859       !NewFD->hasAttr<SectionAttr>()) {
8860     NewFD->addAttr(
8861         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8862                                     CodeSegStack.CurrentValue->getString(),
8863                                     CodeSegStack.CurrentPragmaLocation));
8864     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8865                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8866                          ASTContext::PSF_Read,
8867                      NewFD))
8868       NewFD->dropAttr<SectionAttr>();
8869   }
8870 
8871   // Apply an implicit CodeSegAttr from class declspec or
8872   // apply an implicit SectionAttr from #pragma code_seg if active.
8873   if (!NewFD->hasAttr<CodeSegAttr>()) {
8874     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8875                                                                  D.isFunctionDefinition())) {
8876       NewFD->addAttr(SAttr);
8877     }
8878   }
8879 
8880   // Handle attributes.
8881   ProcessDeclAttributes(S, NewFD, D);
8882 
8883   if (getLangOpts().OpenCL) {
8884     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8885     // type declaration will generate a compilation error.
8886     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8887     if (AddressSpace != LangAS::Default) {
8888       Diag(NewFD->getLocation(),
8889            diag::err_opencl_return_value_with_address_space);
8890       NewFD->setInvalidDecl();
8891     }
8892   }
8893 
8894   if (!getLangOpts().CPlusPlus) {
8895     // Perform semantic checking on the function declaration.
8896     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8897       CheckMain(NewFD, D.getDeclSpec());
8898 
8899     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8900       CheckMSVCRTEntryPoint(NewFD);
8901 
8902     if (!NewFD->isInvalidDecl())
8903       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8904                                                   isMemberSpecialization));
8905     else if (!Previous.empty())
8906       // Recover gracefully from an invalid redeclaration.
8907       D.setRedeclaration(true);
8908     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8909             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8910            "previous declaration set still overloaded");
8911 
8912     // Diagnose no-prototype function declarations with calling conventions that
8913     // don't support variadic calls. Only do this in C and do it after merging
8914     // possibly prototyped redeclarations.
8915     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8916     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8917       CallingConv CC = FT->getExtInfo().getCC();
8918       if (!supportsVariadicCall(CC)) {
8919         // Windows system headers sometimes accidentally use stdcall without
8920         // (void) parameters, so we relax this to a warning.
8921         int DiagID =
8922             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8923         Diag(NewFD->getLocation(), DiagID)
8924             << FunctionType::getNameForCallConv(CC);
8925       }
8926     }
8927   } else {
8928     // C++11 [replacement.functions]p3:
8929     //  The program's definitions shall not be specified as inline.
8930     //
8931     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8932     //
8933     // Suppress the diagnostic if the function is __attribute__((used)), since
8934     // that forces an external definition to be emitted.
8935     if (D.getDeclSpec().isInlineSpecified() &&
8936         NewFD->isReplaceableGlobalAllocationFunction() &&
8937         !NewFD->hasAttr<UsedAttr>())
8938       Diag(D.getDeclSpec().getInlineSpecLoc(),
8939            diag::ext_operator_new_delete_declared_inline)
8940         << NewFD->getDeclName();
8941 
8942     // If the declarator is a template-id, translate the parser's template
8943     // argument list into our AST format.
8944     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8945       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8946       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8947       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8948       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8949                                          TemplateId->NumArgs);
8950       translateTemplateArguments(TemplateArgsPtr,
8951                                  TemplateArgs);
8952 
8953       HasExplicitTemplateArgs = true;
8954 
8955       if (NewFD->isInvalidDecl()) {
8956         HasExplicitTemplateArgs = false;
8957       } else if (FunctionTemplate) {
8958         // Function template with explicit template arguments.
8959         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8960           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8961 
8962         HasExplicitTemplateArgs = false;
8963       } else {
8964         assert((isFunctionTemplateSpecialization ||
8965                 D.getDeclSpec().isFriendSpecified()) &&
8966                "should have a 'template<>' for this decl");
8967         // "friend void foo<>(int);" is an implicit specialization decl.
8968         isFunctionTemplateSpecialization = true;
8969       }
8970     } else if (isFriend && isFunctionTemplateSpecialization) {
8971       // This combination is only possible in a recovery case;  the user
8972       // wrote something like:
8973       //   template <> friend void foo(int);
8974       // which we're recovering from as if the user had written:
8975       //   friend void foo<>(int);
8976       // Go ahead and fake up a template id.
8977       HasExplicitTemplateArgs = true;
8978       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8979       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8980     }
8981 
8982     // We do not add HD attributes to specializations here because
8983     // they may have different constexpr-ness compared to their
8984     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8985     // may end up with different effective targets. Instead, a
8986     // specialization inherits its target attributes from its template
8987     // in the CheckFunctionTemplateSpecialization() call below.
8988     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8989       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8990 
8991     // If it's a friend (and only if it's a friend), it's possible
8992     // that either the specialized function type or the specialized
8993     // template is dependent, and therefore matching will fail.  In
8994     // this case, don't check the specialization yet.
8995     bool InstantiationDependent = false;
8996     if (isFunctionTemplateSpecialization && isFriend &&
8997         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8998          TemplateSpecializationType::anyDependentTemplateArguments(
8999             TemplateArgs,
9000             InstantiationDependent))) {
9001       assert(HasExplicitTemplateArgs &&
9002              "friend function specialization without template args");
9003       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9004                                                        Previous))
9005         NewFD->setInvalidDecl();
9006     } else if (isFunctionTemplateSpecialization) {
9007       if (CurContext->isDependentContext() && CurContext->isRecord()
9008           && !isFriend) {
9009         isDependentClassScopeExplicitSpecialization = true;
9010       } else if (!NewFD->isInvalidDecl() &&
9011                  CheckFunctionTemplateSpecialization(
9012                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9013                      Previous))
9014         NewFD->setInvalidDecl();
9015 
9016       // C++ [dcl.stc]p1:
9017       //   A storage-class-specifier shall not be specified in an explicit
9018       //   specialization (14.7.3)
9019       FunctionTemplateSpecializationInfo *Info =
9020           NewFD->getTemplateSpecializationInfo();
9021       if (Info && SC != SC_None) {
9022         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9023           Diag(NewFD->getLocation(),
9024                diag::err_explicit_specialization_inconsistent_storage_class)
9025             << SC
9026             << FixItHint::CreateRemoval(
9027                                       D.getDeclSpec().getStorageClassSpecLoc());
9028 
9029         else
9030           Diag(NewFD->getLocation(),
9031                diag::ext_explicit_specialization_storage_class)
9032             << FixItHint::CreateRemoval(
9033                                       D.getDeclSpec().getStorageClassSpecLoc());
9034       }
9035     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9036       if (CheckMemberSpecialization(NewFD, Previous))
9037           NewFD->setInvalidDecl();
9038     }
9039 
9040     // Perform semantic checking on the function declaration.
9041     if (!isDependentClassScopeExplicitSpecialization) {
9042       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9043         CheckMain(NewFD, D.getDeclSpec());
9044 
9045       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9046         CheckMSVCRTEntryPoint(NewFD);
9047 
9048       if (!NewFD->isInvalidDecl())
9049         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9050                                                     isMemberSpecialization));
9051       else if (!Previous.empty())
9052         // Recover gracefully from an invalid redeclaration.
9053         D.setRedeclaration(true);
9054     }
9055 
9056     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9057             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9058            "previous declaration set still overloaded");
9059 
9060     NamedDecl *PrincipalDecl = (FunctionTemplate
9061                                 ? cast<NamedDecl>(FunctionTemplate)
9062                                 : NewFD);
9063 
9064     if (isFriend && NewFD->getPreviousDecl()) {
9065       AccessSpecifier Access = AS_public;
9066       if (!NewFD->isInvalidDecl())
9067         Access = NewFD->getPreviousDecl()->getAccess();
9068 
9069       NewFD->setAccess(Access);
9070       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9071     }
9072 
9073     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9074         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9075       PrincipalDecl->setNonMemberOperator();
9076 
9077     // If we have a function template, check the template parameter
9078     // list. This will check and merge default template arguments.
9079     if (FunctionTemplate) {
9080       FunctionTemplateDecl *PrevTemplate =
9081                                      FunctionTemplate->getPreviousDecl();
9082       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9083                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9084                                     : nullptr,
9085                             D.getDeclSpec().isFriendSpecified()
9086                               ? (D.isFunctionDefinition()
9087                                    ? TPC_FriendFunctionTemplateDefinition
9088                                    : TPC_FriendFunctionTemplate)
9089                               : (D.getCXXScopeSpec().isSet() &&
9090                                  DC && DC->isRecord() &&
9091                                  DC->isDependentContext())
9092                                   ? TPC_ClassTemplateMember
9093                                   : TPC_FunctionTemplate);
9094     }
9095 
9096     if (NewFD->isInvalidDecl()) {
9097       // Ignore all the rest of this.
9098     } else if (!D.isRedeclaration()) {
9099       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9100                                        AddToScope };
9101       // Fake up an access specifier if it's supposed to be a class member.
9102       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9103         NewFD->setAccess(AS_public);
9104 
9105       // Qualified decls generally require a previous declaration.
9106       if (D.getCXXScopeSpec().isSet()) {
9107         // ...with the major exception of templated-scope or
9108         // dependent-scope friend declarations.
9109 
9110         // TODO: we currently also suppress this check in dependent
9111         // contexts because (1) the parameter depth will be off when
9112         // matching friend templates and (2) we might actually be
9113         // selecting a friend based on a dependent factor.  But there
9114         // are situations where these conditions don't apply and we
9115         // can actually do this check immediately.
9116         //
9117         // Unless the scope is dependent, it's always an error if qualified
9118         // redeclaration lookup found nothing at all. Diagnose that now;
9119         // nothing will diagnose that error later.
9120         if (isFriend &&
9121             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9122              (!Previous.empty() && CurContext->isDependentContext()))) {
9123           // ignore these
9124         } else {
9125           // The user tried to provide an out-of-line definition for a
9126           // function that is a member of a class or namespace, but there
9127           // was no such member function declared (C++ [class.mfct]p2,
9128           // C++ [namespace.memdef]p2). For example:
9129           //
9130           // class X {
9131           //   void f() const;
9132           // };
9133           //
9134           // void X::f() { } // ill-formed
9135           //
9136           // Complain about this problem, and attempt to suggest close
9137           // matches (e.g., those that differ only in cv-qualifiers and
9138           // whether the parameter types are references).
9139 
9140           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9141                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9142             AddToScope = ExtraArgs.AddToScope;
9143             return Result;
9144           }
9145         }
9146 
9147         // Unqualified local friend declarations are required to resolve
9148         // to something.
9149       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9150         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9151                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9152           AddToScope = ExtraArgs.AddToScope;
9153           return Result;
9154         }
9155       }
9156     } else if (!D.isFunctionDefinition() &&
9157                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9158                !isFriend && !isFunctionTemplateSpecialization &&
9159                !isMemberSpecialization) {
9160       // An out-of-line member function declaration must also be a
9161       // definition (C++ [class.mfct]p2).
9162       // Note that this is not the case for explicit specializations of
9163       // function templates or member functions of class templates, per
9164       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9165       // extension for compatibility with old SWIG code which likes to
9166       // generate them.
9167       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9168         << D.getCXXScopeSpec().getRange();
9169     }
9170   }
9171 
9172   ProcessPragmaWeak(S, NewFD);
9173   checkAttributesAfterMerging(*this, *NewFD);
9174 
9175   AddKnownFunctionAttributes(NewFD);
9176 
9177   if (NewFD->hasAttr<OverloadableAttr>() &&
9178       !NewFD->getType()->getAs<FunctionProtoType>()) {
9179     Diag(NewFD->getLocation(),
9180          diag::err_attribute_overloadable_no_prototype)
9181       << NewFD;
9182 
9183     // Turn this into a variadic function with no parameters.
9184     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9185     FunctionProtoType::ExtProtoInfo EPI(
9186         Context.getDefaultCallingConvention(true, false));
9187     EPI.Variadic = true;
9188     EPI.ExtInfo = FT->getExtInfo();
9189 
9190     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9191     NewFD->setType(R);
9192   }
9193 
9194   // If there's a #pragma GCC visibility in scope, and this isn't a class
9195   // member, set the visibility of this function.
9196   if (!DC->isRecord() && NewFD->isExternallyVisible())
9197     AddPushedVisibilityAttribute(NewFD);
9198 
9199   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9200   // marking the function.
9201   AddCFAuditedAttribute(NewFD);
9202 
9203   // If this is a function definition, check if we have to apply optnone due to
9204   // a pragma.
9205   if(D.isFunctionDefinition())
9206     AddRangeBasedOptnone(NewFD);
9207 
9208   // If this is the first declaration of an extern C variable, update
9209   // the map of such variables.
9210   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9211       isIncompleteDeclExternC(*this, NewFD))
9212     RegisterLocallyScopedExternCDecl(NewFD, S);
9213 
9214   // Set this FunctionDecl's range up to the right paren.
9215   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9216 
9217   if (D.isRedeclaration() && !Previous.empty()) {
9218     NamedDecl *Prev = Previous.getRepresentativeDecl();
9219     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9220                                    isMemberSpecialization ||
9221                                        isFunctionTemplateSpecialization,
9222                                    D.isFunctionDefinition());
9223   }
9224 
9225   if (getLangOpts().CUDA) {
9226     IdentifierInfo *II = NewFD->getIdentifier();
9227     if (II && II->isStr(getCudaConfigureFuncName()) &&
9228         !NewFD->isInvalidDecl() &&
9229         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9230       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9231         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9232             << getCudaConfigureFuncName();
9233       Context.setcudaConfigureCallDecl(NewFD);
9234     }
9235 
9236     // Variadic functions, other than a *declaration* of printf, are not allowed
9237     // in device-side CUDA code, unless someone passed
9238     // -fcuda-allow-variadic-functions.
9239     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9240         (NewFD->hasAttr<CUDADeviceAttr>() ||
9241          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9242         !(II && II->isStr("printf") && NewFD->isExternC() &&
9243           !D.isFunctionDefinition())) {
9244       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9245     }
9246   }
9247 
9248   MarkUnusedFileScopedDecl(NewFD);
9249 
9250 
9251 
9252   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9253     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9254     if ((getLangOpts().OpenCLVersion >= 120)
9255         && (SC == SC_Static)) {
9256       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9257       D.setInvalidType();
9258     }
9259 
9260     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9261     if (!NewFD->getReturnType()->isVoidType()) {
9262       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9263       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9264           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9265                                 : FixItHint());
9266       D.setInvalidType();
9267     }
9268 
9269     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9270     for (auto Param : NewFD->parameters())
9271       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9272 
9273     if (getLangOpts().OpenCLCPlusPlus) {
9274       if (DC->isRecord()) {
9275         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9276         D.setInvalidType();
9277       }
9278       if (FunctionTemplate) {
9279         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9280         D.setInvalidType();
9281       }
9282     }
9283   }
9284 
9285   if (getLangOpts().CPlusPlus) {
9286     if (FunctionTemplate) {
9287       if (NewFD->isInvalidDecl())
9288         FunctionTemplate->setInvalidDecl();
9289       return FunctionTemplate;
9290     }
9291 
9292     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9293       CompleteMemberSpecialization(NewFD, Previous);
9294   }
9295 
9296   for (const ParmVarDecl *Param : NewFD->parameters()) {
9297     QualType PT = Param->getType();
9298 
9299     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9300     // types.
9301     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9302       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9303         QualType ElemTy = PipeTy->getElementType();
9304           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9305             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9306             D.setInvalidType();
9307           }
9308       }
9309     }
9310   }
9311 
9312   // Here we have an function template explicit specialization at class scope.
9313   // The actual specialization will be postponed to template instatiation
9314   // time via the ClassScopeFunctionSpecializationDecl node.
9315   if (isDependentClassScopeExplicitSpecialization) {
9316     ClassScopeFunctionSpecializationDecl *NewSpec =
9317                          ClassScopeFunctionSpecializationDecl::Create(
9318                                 Context, CurContext, NewFD->getLocation(),
9319                                 cast<CXXMethodDecl>(NewFD),
9320                                 HasExplicitTemplateArgs, TemplateArgs);
9321     CurContext->addDecl(NewSpec);
9322     AddToScope = false;
9323   }
9324 
9325   // Diagnose availability attributes. Availability cannot be used on functions
9326   // that are run during load/unload.
9327   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9328     if (NewFD->hasAttr<ConstructorAttr>()) {
9329       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9330           << 1;
9331       NewFD->dropAttr<AvailabilityAttr>();
9332     }
9333     if (NewFD->hasAttr<DestructorAttr>()) {
9334       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9335           << 2;
9336       NewFD->dropAttr<AvailabilityAttr>();
9337     }
9338   }
9339 
9340   return NewFD;
9341 }
9342 
9343 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9344 /// when __declspec(code_seg) "is applied to a class, all member functions of
9345 /// the class and nested classes -- this includes compiler-generated special
9346 /// member functions -- are put in the specified segment."
9347 /// The actual behavior is a little more complicated. The Microsoft compiler
9348 /// won't check outer classes if there is an active value from #pragma code_seg.
9349 /// The CodeSeg is always applied from the direct parent but only from outer
9350 /// classes when the #pragma code_seg stack is empty. See:
9351 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9352 /// available since MS has removed the page.
9353 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9354   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9355   if (!Method)
9356     return nullptr;
9357   const CXXRecordDecl *Parent = Method->getParent();
9358   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9359     Attr *NewAttr = SAttr->clone(S.getASTContext());
9360     NewAttr->setImplicit(true);
9361     return NewAttr;
9362   }
9363 
9364   // The Microsoft compiler won't check outer classes for the CodeSeg
9365   // when the #pragma code_seg stack is active.
9366   if (S.CodeSegStack.CurrentValue)
9367    return nullptr;
9368 
9369   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9370     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9371       Attr *NewAttr = SAttr->clone(S.getASTContext());
9372       NewAttr->setImplicit(true);
9373       return NewAttr;
9374     }
9375   }
9376   return nullptr;
9377 }
9378 
9379 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9380 /// containing class. Otherwise it will return implicit SectionAttr if the
9381 /// function is a definition and there is an active value on CodeSegStack
9382 /// (from the current #pragma code-seg value).
9383 ///
9384 /// \param FD Function being declared.
9385 /// \param IsDefinition Whether it is a definition or just a declarartion.
9386 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9387 ///          nullptr if no attribute should be added.
9388 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9389                                                        bool IsDefinition) {
9390   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9391     return A;
9392   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9393       CodeSegStack.CurrentValue) {
9394     return SectionAttr::CreateImplicit(getASTContext(),
9395                                        SectionAttr::Declspec_allocate,
9396                                        CodeSegStack.CurrentValue->getString(),
9397                                        CodeSegStack.CurrentPragmaLocation);
9398   }
9399   return nullptr;
9400 }
9401 
9402 /// Determines if we can perform a correct type check for \p D as a
9403 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9404 /// best-effort check.
9405 ///
9406 /// \param NewD The new declaration.
9407 /// \param OldD The old declaration.
9408 /// \param NewT The portion of the type of the new declaration to check.
9409 /// \param OldT The portion of the type of the old declaration to check.
9410 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9411                                           QualType NewT, QualType OldT) {
9412   if (!NewD->getLexicalDeclContext()->isDependentContext())
9413     return true;
9414 
9415   // For dependently-typed local extern declarations and friends, we can't
9416   // perform a correct type check in general until instantiation:
9417   //
9418   //   int f();
9419   //   template<typename T> void g() { T f(); }
9420   //
9421   // (valid if g() is only instantiated with T = int).
9422   if (NewT->isDependentType() &&
9423       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9424     return false;
9425 
9426   // Similarly, if the previous declaration was a dependent local extern
9427   // declaration, we don't really know its type yet.
9428   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9429     return false;
9430 
9431   return true;
9432 }
9433 
9434 /// Checks if the new declaration declared in dependent context must be
9435 /// put in the same redeclaration chain as the specified declaration.
9436 ///
9437 /// \param D Declaration that is checked.
9438 /// \param PrevDecl Previous declaration found with proper lookup method for the
9439 ///                 same declaration name.
9440 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9441 ///          belongs to.
9442 ///
9443 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9444   if (!D->getLexicalDeclContext()->isDependentContext())
9445     return true;
9446 
9447   // Don't chain dependent friend function definitions until instantiation, to
9448   // permit cases like
9449   //
9450   //   void func();
9451   //   template<typename T> class C1 { friend void func() {} };
9452   //   template<typename T> class C2 { friend void func() {} };
9453   //
9454   // ... which is valid if only one of C1 and C2 is ever instantiated.
9455   //
9456   // FIXME: This need only apply to function definitions. For now, we proxy
9457   // this by checking for a file-scope function. We do not want this to apply
9458   // to friend declarations nominating member functions, because that gets in
9459   // the way of access checks.
9460   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9461     return false;
9462 
9463   auto *VD = dyn_cast<ValueDecl>(D);
9464   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9465   return !VD || !PrevVD ||
9466          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9467                                         PrevVD->getType());
9468 }
9469 
9470 /// Check the target attribute of the function for MultiVersion
9471 /// validity.
9472 ///
9473 /// Returns true if there was an error, false otherwise.
9474 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9475   const auto *TA = FD->getAttr<TargetAttr>();
9476   assert(TA && "MultiVersion Candidate requires a target attribute");
9477   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9478   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9479   enum ErrType { Feature = 0, Architecture = 1 };
9480 
9481   if (!ParseInfo.Architecture.empty() &&
9482       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9483     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9484         << Architecture << ParseInfo.Architecture;
9485     return true;
9486   }
9487 
9488   for (const auto &Feat : ParseInfo.Features) {
9489     auto BareFeat = StringRef{Feat}.substr(1);
9490     if (Feat[0] == '-') {
9491       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9492           << Feature << ("no-" + BareFeat).str();
9493       return true;
9494     }
9495 
9496     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9497         !TargetInfo.isValidFeatureName(BareFeat)) {
9498       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9499           << Feature << BareFeat;
9500       return true;
9501     }
9502   }
9503   return false;
9504 }
9505 
9506 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9507                                          MultiVersionKind MVType) {
9508   for (const Attr *A : FD->attrs()) {
9509     switch (A->getKind()) {
9510     case attr::CPUDispatch:
9511     case attr::CPUSpecific:
9512       if (MVType != MultiVersionKind::CPUDispatch &&
9513           MVType != MultiVersionKind::CPUSpecific)
9514         return true;
9515       break;
9516     case attr::Target:
9517       if (MVType != MultiVersionKind::Target)
9518         return true;
9519       break;
9520     default:
9521       return true;
9522     }
9523   }
9524   return false;
9525 }
9526 
9527 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9528                                              const FunctionDecl *NewFD,
9529                                              bool CausesMV,
9530                                              MultiVersionKind MVType) {
9531   enum DoesntSupport {
9532     FuncTemplates = 0,
9533     VirtFuncs = 1,
9534     DeducedReturn = 2,
9535     Constructors = 3,
9536     Destructors = 4,
9537     DeletedFuncs = 5,
9538     DefaultedFuncs = 6,
9539     ConstexprFuncs = 7,
9540     ConstevalFuncs = 8,
9541   };
9542   enum Different {
9543     CallingConv = 0,
9544     ReturnType = 1,
9545     ConstexprSpec = 2,
9546     InlineSpec = 3,
9547     StorageClass = 4,
9548     Linkage = 5
9549   };
9550 
9551   bool IsCPUSpecificCPUDispatchMVType =
9552       MVType == MultiVersionKind::CPUDispatch ||
9553       MVType == MultiVersionKind::CPUSpecific;
9554 
9555   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9556     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9557     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9558     return true;
9559   }
9560 
9561   if (!NewFD->getType()->getAs<FunctionProtoType>())
9562     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9563 
9564   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9565     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9566     if (OldFD)
9567       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9568     return true;
9569   }
9570 
9571   // For now, disallow all other attributes.  These should be opt-in, but
9572   // an analysis of all of them is a future FIXME.
9573   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9574     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9575         << IsCPUSpecificCPUDispatchMVType;
9576     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9577     return true;
9578   }
9579 
9580   if (HasNonMultiVersionAttributes(NewFD, MVType))
9581     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9582            << IsCPUSpecificCPUDispatchMVType;
9583 
9584   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9585     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9586            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9587 
9588   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9589     if (NewCXXFD->isVirtual())
9590       return S.Diag(NewCXXFD->getLocation(),
9591                     diag::err_multiversion_doesnt_support)
9592              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9593 
9594     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9595       return S.Diag(NewCXXCtor->getLocation(),
9596                     diag::err_multiversion_doesnt_support)
9597              << IsCPUSpecificCPUDispatchMVType << Constructors;
9598 
9599     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9600       return S.Diag(NewCXXDtor->getLocation(),
9601                     diag::err_multiversion_doesnt_support)
9602              << IsCPUSpecificCPUDispatchMVType << Destructors;
9603   }
9604 
9605   if (NewFD->isDeleted())
9606     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9607            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9608 
9609   if (NewFD->isDefaulted())
9610     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9611            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9612 
9613   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9614                                MVType == MultiVersionKind::CPUSpecific))
9615     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9616            << IsCPUSpecificCPUDispatchMVType
9617            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9618 
9619   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9620   const auto *NewType = cast<FunctionType>(NewQType);
9621   QualType NewReturnType = NewType->getReturnType();
9622 
9623   if (NewReturnType->isUndeducedType())
9624     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9625            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9626 
9627   // Only allow transition to MultiVersion if it hasn't been used.
9628   if (OldFD && CausesMV && OldFD->isUsed(false))
9629     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9630 
9631   // Ensure the return type is identical.
9632   if (OldFD) {
9633     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9634     const auto *OldType = cast<FunctionType>(OldQType);
9635     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9636     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9637 
9638     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9639       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9640              << CallingConv;
9641 
9642     QualType OldReturnType = OldType->getReturnType();
9643 
9644     if (OldReturnType != NewReturnType)
9645       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9646              << ReturnType;
9647 
9648     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9649       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9650              << ConstexprSpec;
9651 
9652     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9653       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9654              << InlineSpec;
9655 
9656     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9657       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9658              << StorageClass;
9659 
9660     if (OldFD->isExternC() != NewFD->isExternC())
9661       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9662              << Linkage;
9663 
9664     if (S.CheckEquivalentExceptionSpec(
9665             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9666             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9667       return true;
9668   }
9669   return false;
9670 }
9671 
9672 /// Check the validity of a multiversion function declaration that is the
9673 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9674 ///
9675 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9676 ///
9677 /// Returns true if there was an error, false otherwise.
9678 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9679                                            MultiVersionKind MVType,
9680                                            const TargetAttr *TA) {
9681   assert(MVType != MultiVersionKind::None &&
9682          "Function lacks multiversion attribute");
9683 
9684   // Target only causes MV if it is default, otherwise this is a normal
9685   // function.
9686   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9687     return false;
9688 
9689   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9690     FD->setInvalidDecl();
9691     return true;
9692   }
9693 
9694   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9695     FD->setInvalidDecl();
9696     return true;
9697   }
9698 
9699   FD->setIsMultiVersion();
9700   return false;
9701 }
9702 
9703 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9704   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9705     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9706       return true;
9707   }
9708 
9709   return false;
9710 }
9711 
9712 static bool CheckTargetCausesMultiVersioning(
9713     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9714     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9715     LookupResult &Previous) {
9716   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9717   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9718   // Sort order doesn't matter, it just needs to be consistent.
9719   llvm::sort(NewParsed.Features);
9720 
9721   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9722   // to change, this is a simple redeclaration.
9723   if (!NewTA->isDefaultVersion() &&
9724       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9725     return false;
9726 
9727   // Otherwise, this decl causes MultiVersioning.
9728   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9729     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9730     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9731     NewFD->setInvalidDecl();
9732     return true;
9733   }
9734 
9735   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9736                                        MultiVersionKind::Target)) {
9737     NewFD->setInvalidDecl();
9738     return true;
9739   }
9740 
9741   if (CheckMultiVersionValue(S, NewFD)) {
9742     NewFD->setInvalidDecl();
9743     return true;
9744   }
9745 
9746   // If this is 'default', permit the forward declaration.
9747   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9748     Redeclaration = true;
9749     OldDecl = OldFD;
9750     OldFD->setIsMultiVersion();
9751     NewFD->setIsMultiVersion();
9752     return false;
9753   }
9754 
9755   if (CheckMultiVersionValue(S, OldFD)) {
9756     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9757     NewFD->setInvalidDecl();
9758     return true;
9759   }
9760 
9761   TargetAttr::ParsedTargetAttr OldParsed =
9762       OldTA->parse(std::less<std::string>());
9763 
9764   if (OldParsed == NewParsed) {
9765     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9766     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9767     NewFD->setInvalidDecl();
9768     return true;
9769   }
9770 
9771   for (const auto *FD : OldFD->redecls()) {
9772     const auto *CurTA = FD->getAttr<TargetAttr>();
9773     // We allow forward declarations before ANY multiversioning attributes, but
9774     // nothing after the fact.
9775     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9776         (!CurTA || CurTA->isInherited())) {
9777       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9778           << 0;
9779       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9780       NewFD->setInvalidDecl();
9781       return true;
9782     }
9783   }
9784 
9785   OldFD->setIsMultiVersion();
9786   NewFD->setIsMultiVersion();
9787   Redeclaration = false;
9788   MergeTypeWithPrevious = false;
9789   OldDecl = nullptr;
9790   Previous.clear();
9791   return false;
9792 }
9793 
9794 /// Check the validity of a new function declaration being added to an existing
9795 /// multiversioned declaration collection.
9796 static bool CheckMultiVersionAdditionalDecl(
9797     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9798     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9799     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9800     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9801     LookupResult &Previous) {
9802 
9803   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9804   // Disallow mixing of multiversioning types.
9805   if ((OldMVType == MultiVersionKind::Target &&
9806        NewMVType != MultiVersionKind::Target) ||
9807       (NewMVType == MultiVersionKind::Target &&
9808        OldMVType != MultiVersionKind::Target)) {
9809     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9810     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9811     NewFD->setInvalidDecl();
9812     return true;
9813   }
9814 
9815   TargetAttr::ParsedTargetAttr NewParsed;
9816   if (NewTA) {
9817     NewParsed = NewTA->parse();
9818     llvm::sort(NewParsed.Features);
9819   }
9820 
9821   bool UseMemberUsingDeclRules =
9822       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9823 
9824   // Next, check ALL non-overloads to see if this is a redeclaration of a
9825   // previous member of the MultiVersion set.
9826   for (NamedDecl *ND : Previous) {
9827     FunctionDecl *CurFD = ND->getAsFunction();
9828     if (!CurFD)
9829       continue;
9830     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9831       continue;
9832 
9833     if (NewMVType == MultiVersionKind::Target) {
9834       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9835       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9836         NewFD->setIsMultiVersion();
9837         Redeclaration = true;
9838         OldDecl = ND;
9839         return false;
9840       }
9841 
9842       TargetAttr::ParsedTargetAttr CurParsed =
9843           CurTA->parse(std::less<std::string>());
9844       if (CurParsed == NewParsed) {
9845         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9846         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9847         NewFD->setInvalidDecl();
9848         return true;
9849       }
9850     } else {
9851       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9852       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9853       // Handle CPUDispatch/CPUSpecific versions.
9854       // Only 1 CPUDispatch function is allowed, this will make it go through
9855       // the redeclaration errors.
9856       if (NewMVType == MultiVersionKind::CPUDispatch &&
9857           CurFD->hasAttr<CPUDispatchAttr>()) {
9858         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9859             std::equal(
9860                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9861                 NewCPUDisp->cpus_begin(),
9862                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9863                   return Cur->getName() == New->getName();
9864                 })) {
9865           NewFD->setIsMultiVersion();
9866           Redeclaration = true;
9867           OldDecl = ND;
9868           return false;
9869         }
9870 
9871         // If the declarations don't match, this is an error condition.
9872         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9873         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9874         NewFD->setInvalidDecl();
9875         return true;
9876       }
9877       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9878 
9879         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9880             std::equal(
9881                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9882                 NewCPUSpec->cpus_begin(),
9883                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9884                   return Cur->getName() == New->getName();
9885                 })) {
9886           NewFD->setIsMultiVersion();
9887           Redeclaration = true;
9888           OldDecl = ND;
9889           return false;
9890         }
9891 
9892         // Only 1 version of CPUSpecific is allowed for each CPU.
9893         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9894           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9895             if (CurII == NewII) {
9896               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9897                   << NewII;
9898               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9899               NewFD->setInvalidDecl();
9900               return true;
9901             }
9902           }
9903         }
9904       }
9905       // If the two decls aren't the same MVType, there is no possible error
9906       // condition.
9907     }
9908   }
9909 
9910   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9911   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9912   // handled in the attribute adding step.
9913   if (NewMVType == MultiVersionKind::Target &&
9914       CheckMultiVersionValue(S, NewFD)) {
9915     NewFD->setInvalidDecl();
9916     return true;
9917   }
9918 
9919   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9920                                        !OldFD->isMultiVersion(), NewMVType)) {
9921     NewFD->setInvalidDecl();
9922     return true;
9923   }
9924 
9925   // Permit forward declarations in the case where these two are compatible.
9926   if (!OldFD->isMultiVersion()) {
9927     OldFD->setIsMultiVersion();
9928     NewFD->setIsMultiVersion();
9929     Redeclaration = true;
9930     OldDecl = OldFD;
9931     return false;
9932   }
9933 
9934   NewFD->setIsMultiVersion();
9935   Redeclaration = false;
9936   MergeTypeWithPrevious = false;
9937   OldDecl = nullptr;
9938   Previous.clear();
9939   return false;
9940 }
9941 
9942 
9943 /// Check the validity of a mulitversion function declaration.
9944 /// Also sets the multiversion'ness' of the function itself.
9945 ///
9946 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9947 ///
9948 /// Returns true if there was an error, false otherwise.
9949 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9950                                       bool &Redeclaration, NamedDecl *&OldDecl,
9951                                       bool &MergeTypeWithPrevious,
9952                                       LookupResult &Previous) {
9953   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9954   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9955   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9956 
9957   // Mixing Multiversioning types is prohibited.
9958   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9959       (NewCPUDisp && NewCPUSpec)) {
9960     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9961     NewFD->setInvalidDecl();
9962     return true;
9963   }
9964 
9965   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9966 
9967   // Main isn't allowed to become a multiversion function, however it IS
9968   // permitted to have 'main' be marked with the 'target' optimization hint.
9969   if (NewFD->isMain()) {
9970     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9971         MVType == MultiVersionKind::CPUDispatch ||
9972         MVType == MultiVersionKind::CPUSpecific) {
9973       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9974       NewFD->setInvalidDecl();
9975       return true;
9976     }
9977     return false;
9978   }
9979 
9980   if (!OldDecl || !OldDecl->getAsFunction() ||
9981       OldDecl->getDeclContext()->getRedeclContext() !=
9982           NewFD->getDeclContext()->getRedeclContext()) {
9983     // If there's no previous declaration, AND this isn't attempting to cause
9984     // multiversioning, this isn't an error condition.
9985     if (MVType == MultiVersionKind::None)
9986       return false;
9987     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
9988   }
9989 
9990   FunctionDecl *OldFD = OldDecl->getAsFunction();
9991 
9992   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
9993     return false;
9994 
9995   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
9996     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9997         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
9998     NewFD->setInvalidDecl();
9999     return true;
10000   }
10001 
10002   // Handle the target potentially causes multiversioning case.
10003   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10004     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10005                                             Redeclaration, OldDecl,
10006                                             MergeTypeWithPrevious, Previous);
10007 
10008   // At this point, we have a multiversion function decl (in OldFD) AND an
10009   // appropriate attribute in the current function decl.  Resolve that these are
10010   // still compatible with previous declarations.
10011   return CheckMultiVersionAdditionalDecl(
10012       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10013       OldDecl, MergeTypeWithPrevious, Previous);
10014 }
10015 
10016 /// Perform semantic checking of a new function declaration.
10017 ///
10018 /// Performs semantic analysis of the new function declaration
10019 /// NewFD. This routine performs all semantic checking that does not
10020 /// require the actual declarator involved in the declaration, and is
10021 /// used both for the declaration of functions as they are parsed
10022 /// (called via ActOnDeclarator) and for the declaration of functions
10023 /// that have been instantiated via C++ template instantiation (called
10024 /// via InstantiateDecl).
10025 ///
10026 /// \param IsMemberSpecialization whether this new function declaration is
10027 /// a member specialization (that replaces any definition provided by the
10028 /// previous declaration).
10029 ///
10030 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10031 ///
10032 /// \returns true if the function declaration is a redeclaration.
10033 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10034                                     LookupResult &Previous,
10035                                     bool IsMemberSpecialization) {
10036   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10037          "Variably modified return types are not handled here");
10038 
10039   // Determine whether the type of this function should be merged with
10040   // a previous visible declaration. This never happens for functions in C++,
10041   // and always happens in C if the previous declaration was visible.
10042   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10043                                !Previous.isShadowed();
10044 
10045   bool Redeclaration = false;
10046   NamedDecl *OldDecl = nullptr;
10047   bool MayNeedOverloadableChecks = false;
10048 
10049   // Merge or overload the declaration with an existing declaration of
10050   // the same name, if appropriate.
10051   if (!Previous.empty()) {
10052     // Determine whether NewFD is an overload of PrevDecl or
10053     // a declaration that requires merging. If it's an overload,
10054     // there's no more work to do here; we'll just add the new
10055     // function to the scope.
10056     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10057       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10058       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10059         Redeclaration = true;
10060         OldDecl = Candidate;
10061       }
10062     } else {
10063       MayNeedOverloadableChecks = true;
10064       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10065                             /*NewIsUsingDecl*/ false)) {
10066       case Ovl_Match:
10067         Redeclaration = true;
10068         break;
10069 
10070       case Ovl_NonFunction:
10071         Redeclaration = true;
10072         break;
10073 
10074       case Ovl_Overload:
10075         Redeclaration = false;
10076         break;
10077       }
10078     }
10079   }
10080 
10081   // Check for a previous extern "C" declaration with this name.
10082   if (!Redeclaration &&
10083       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10084     if (!Previous.empty()) {
10085       // This is an extern "C" declaration with the same name as a previous
10086       // declaration, and thus redeclares that entity...
10087       Redeclaration = true;
10088       OldDecl = Previous.getFoundDecl();
10089       MergeTypeWithPrevious = false;
10090 
10091       // ... except in the presence of __attribute__((overloadable)).
10092       if (OldDecl->hasAttr<OverloadableAttr>() ||
10093           NewFD->hasAttr<OverloadableAttr>()) {
10094         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10095           MayNeedOverloadableChecks = true;
10096           Redeclaration = false;
10097           OldDecl = nullptr;
10098         }
10099       }
10100     }
10101   }
10102 
10103   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10104                                 MergeTypeWithPrevious, Previous))
10105     return Redeclaration;
10106 
10107   // C++11 [dcl.constexpr]p8:
10108   //   A constexpr specifier for a non-static member function that is not
10109   //   a constructor declares that member function to be const.
10110   //
10111   // This needs to be delayed until we know whether this is an out-of-line
10112   // definition of a static member function.
10113   //
10114   // This rule is not present in C++1y, so we produce a backwards
10115   // compatibility warning whenever it happens in C++11.
10116   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10117   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10118       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10119       !MD->getMethodQualifiers().hasConst()) {
10120     CXXMethodDecl *OldMD = nullptr;
10121     if (OldDecl)
10122       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10123     if (!OldMD || !OldMD->isStatic()) {
10124       const FunctionProtoType *FPT =
10125         MD->getType()->castAs<FunctionProtoType>();
10126       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10127       EPI.TypeQuals.addConst();
10128       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10129                                           FPT->getParamTypes(), EPI));
10130 
10131       // Warn that we did this, if we're not performing template instantiation.
10132       // In that case, we'll have warned already when the template was defined.
10133       if (!inTemplateInstantiation()) {
10134         SourceLocation AddConstLoc;
10135         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10136                 .IgnoreParens().getAs<FunctionTypeLoc>())
10137           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10138 
10139         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10140           << FixItHint::CreateInsertion(AddConstLoc, " const");
10141       }
10142     }
10143   }
10144 
10145   if (Redeclaration) {
10146     // NewFD and OldDecl represent declarations that need to be
10147     // merged.
10148     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10149       NewFD->setInvalidDecl();
10150       return Redeclaration;
10151     }
10152 
10153     Previous.clear();
10154     Previous.addDecl(OldDecl);
10155 
10156     if (FunctionTemplateDecl *OldTemplateDecl =
10157             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10158       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10159       FunctionTemplateDecl *NewTemplateDecl
10160         = NewFD->getDescribedFunctionTemplate();
10161       assert(NewTemplateDecl && "Template/non-template mismatch");
10162 
10163       // The call to MergeFunctionDecl above may have created some state in
10164       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10165       // can add it as a redeclaration.
10166       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10167 
10168       NewFD->setPreviousDeclaration(OldFD);
10169       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10170       if (NewFD->isCXXClassMember()) {
10171         NewFD->setAccess(OldTemplateDecl->getAccess());
10172         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10173       }
10174 
10175       // If this is an explicit specialization of a member that is a function
10176       // template, mark it as a member specialization.
10177       if (IsMemberSpecialization &&
10178           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10179         NewTemplateDecl->setMemberSpecialization();
10180         assert(OldTemplateDecl->isMemberSpecialization());
10181         // Explicit specializations of a member template do not inherit deleted
10182         // status from the parent member template that they are specializing.
10183         if (OldFD->isDeleted()) {
10184           // FIXME: This assert will not hold in the presence of modules.
10185           assert(OldFD->getCanonicalDecl() == OldFD);
10186           // FIXME: We need an update record for this AST mutation.
10187           OldFD->setDeletedAsWritten(false);
10188         }
10189       }
10190 
10191     } else {
10192       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10193         auto *OldFD = cast<FunctionDecl>(OldDecl);
10194         // This needs to happen first so that 'inline' propagates.
10195         NewFD->setPreviousDeclaration(OldFD);
10196         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10197         if (NewFD->isCXXClassMember())
10198           NewFD->setAccess(OldFD->getAccess());
10199       }
10200     }
10201   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10202              !NewFD->getAttr<OverloadableAttr>()) {
10203     assert((Previous.empty() ||
10204             llvm::any_of(Previous,
10205                          [](const NamedDecl *ND) {
10206                            return ND->hasAttr<OverloadableAttr>();
10207                          })) &&
10208            "Non-redecls shouldn't happen without overloadable present");
10209 
10210     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10211       const auto *FD = dyn_cast<FunctionDecl>(ND);
10212       return FD && !FD->hasAttr<OverloadableAttr>();
10213     });
10214 
10215     if (OtherUnmarkedIter != Previous.end()) {
10216       Diag(NewFD->getLocation(),
10217            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10218       Diag((*OtherUnmarkedIter)->getLocation(),
10219            diag::note_attribute_overloadable_prev_overload)
10220           << false;
10221 
10222       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10223     }
10224   }
10225 
10226   // Semantic checking for this function declaration (in isolation).
10227 
10228   if (getLangOpts().CPlusPlus) {
10229     // C++-specific checks.
10230     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10231       CheckConstructor(Constructor);
10232     } else if (CXXDestructorDecl *Destructor =
10233                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10234       CXXRecordDecl *Record = Destructor->getParent();
10235       QualType ClassType = Context.getTypeDeclType(Record);
10236 
10237       // FIXME: Shouldn't we be able to perform this check even when the class
10238       // type is dependent? Both gcc and edg can handle that.
10239       if (!ClassType->isDependentType()) {
10240         DeclarationName Name
10241           = Context.DeclarationNames.getCXXDestructorName(
10242                                         Context.getCanonicalType(ClassType));
10243         if (NewFD->getDeclName() != Name) {
10244           Diag(NewFD->getLocation(), diag::err_destructor_name);
10245           NewFD->setInvalidDecl();
10246           return Redeclaration;
10247         }
10248       }
10249     } else if (CXXConversionDecl *Conversion
10250                = dyn_cast<CXXConversionDecl>(NewFD)) {
10251       ActOnConversionDeclarator(Conversion);
10252     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10253       if (auto *TD = Guide->getDescribedFunctionTemplate())
10254         CheckDeductionGuideTemplate(TD);
10255 
10256       // A deduction guide is not on the list of entities that can be
10257       // explicitly specialized.
10258       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10259         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10260             << /*explicit specialization*/ 1;
10261     }
10262 
10263     // Find any virtual functions that this function overrides.
10264     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10265       if (!Method->isFunctionTemplateSpecialization() &&
10266           !Method->getDescribedFunctionTemplate() &&
10267           Method->isCanonicalDecl()) {
10268         if (AddOverriddenMethods(Method->getParent(), Method)) {
10269           // If the function was marked as "static", we have a problem.
10270           if (NewFD->getStorageClass() == SC_Static) {
10271             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10272           }
10273         }
10274       }
10275 
10276       if (Method->isStatic())
10277         checkThisInStaticMemberFunctionType(Method);
10278     }
10279 
10280     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10281     if (NewFD->isOverloadedOperator() &&
10282         CheckOverloadedOperatorDeclaration(NewFD)) {
10283       NewFD->setInvalidDecl();
10284       return Redeclaration;
10285     }
10286 
10287     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10288     if (NewFD->getLiteralIdentifier() &&
10289         CheckLiteralOperatorDeclaration(NewFD)) {
10290       NewFD->setInvalidDecl();
10291       return Redeclaration;
10292     }
10293 
10294     // In C++, check default arguments now that we have merged decls. Unless
10295     // the lexical context is the class, because in this case this is done
10296     // during delayed parsing anyway.
10297     if (!CurContext->isRecord())
10298       CheckCXXDefaultArguments(NewFD);
10299 
10300     // If this function declares a builtin function, check the type of this
10301     // declaration against the expected type for the builtin.
10302     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10303       ASTContext::GetBuiltinTypeError Error;
10304       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10305       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10306       // If the type of the builtin differs only in its exception
10307       // specification, that's OK.
10308       // FIXME: If the types do differ in this way, it would be better to
10309       // retain the 'noexcept' form of the type.
10310       if (!T.isNull() &&
10311           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10312                                                             NewFD->getType()))
10313         // The type of this function differs from the type of the builtin,
10314         // so forget about the builtin entirely.
10315         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10316     }
10317 
10318     // If this function is declared as being extern "C", then check to see if
10319     // the function returns a UDT (class, struct, or union type) that is not C
10320     // compatible, and if it does, warn the user.
10321     // But, issue any diagnostic on the first declaration only.
10322     if (Previous.empty() && NewFD->isExternC()) {
10323       QualType R = NewFD->getReturnType();
10324       if (R->isIncompleteType() && !R->isVoidType())
10325         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10326             << NewFD << R;
10327       else if (!R.isPODType(Context) && !R->isVoidType() &&
10328                !R->isObjCObjectPointerType())
10329         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10330     }
10331 
10332     // C++1z [dcl.fct]p6:
10333     //   [...] whether the function has a non-throwing exception-specification
10334     //   [is] part of the function type
10335     //
10336     // This results in an ABI break between C++14 and C++17 for functions whose
10337     // declared type includes an exception-specification in a parameter or
10338     // return type. (Exception specifications on the function itself are OK in
10339     // most cases, and exception specifications are not permitted in most other
10340     // contexts where they could make it into a mangling.)
10341     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10342       auto HasNoexcept = [&](QualType T) -> bool {
10343         // Strip off declarator chunks that could be between us and a function
10344         // type. We don't need to look far, exception specifications are very
10345         // restricted prior to C++17.
10346         if (auto *RT = T->getAs<ReferenceType>())
10347           T = RT->getPointeeType();
10348         else if (T->isAnyPointerType())
10349           T = T->getPointeeType();
10350         else if (auto *MPT = T->getAs<MemberPointerType>())
10351           T = MPT->getPointeeType();
10352         if (auto *FPT = T->getAs<FunctionProtoType>())
10353           if (FPT->isNothrow())
10354             return true;
10355         return false;
10356       };
10357 
10358       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10359       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10360       for (QualType T : FPT->param_types())
10361         AnyNoexcept |= HasNoexcept(T);
10362       if (AnyNoexcept)
10363         Diag(NewFD->getLocation(),
10364              diag::warn_cxx17_compat_exception_spec_in_signature)
10365             << NewFD;
10366     }
10367 
10368     if (!Redeclaration && LangOpts.CUDA)
10369       checkCUDATargetOverload(NewFD, Previous);
10370   }
10371   return Redeclaration;
10372 }
10373 
10374 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10375   // C++11 [basic.start.main]p3:
10376   //   A program that [...] declares main to be inline, static or
10377   //   constexpr is ill-formed.
10378   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10379   //   appear in a declaration of main.
10380   // static main is not an error under C99, but we should warn about it.
10381   // We accept _Noreturn main as an extension.
10382   if (FD->getStorageClass() == SC_Static)
10383     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10384          ? diag::err_static_main : diag::warn_static_main)
10385       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10386   if (FD->isInlineSpecified())
10387     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10388       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10389   if (DS.isNoreturnSpecified()) {
10390     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10391     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10392     Diag(NoreturnLoc, diag::ext_noreturn_main);
10393     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10394       << FixItHint::CreateRemoval(NoreturnRange);
10395   }
10396   if (FD->isConstexpr()) {
10397     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10398         << FD->isConsteval()
10399         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10400     FD->setConstexprKind(CSK_unspecified);
10401   }
10402 
10403   if (getLangOpts().OpenCL) {
10404     Diag(FD->getLocation(), diag::err_opencl_no_main)
10405         << FD->hasAttr<OpenCLKernelAttr>();
10406     FD->setInvalidDecl();
10407     return;
10408   }
10409 
10410   QualType T = FD->getType();
10411   assert(T->isFunctionType() && "function decl is not of function type");
10412   const FunctionType* FT = T->castAs<FunctionType>();
10413 
10414   // Set default calling convention for main()
10415   if (FT->getCallConv() != CC_C) {
10416     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10417     FD->setType(QualType(FT, 0));
10418     T = Context.getCanonicalType(FD->getType());
10419   }
10420 
10421   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10422     // In C with GNU extensions we allow main() to have non-integer return
10423     // type, but we should warn about the extension, and we disable the
10424     // implicit-return-zero rule.
10425 
10426     // GCC in C mode accepts qualified 'int'.
10427     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10428       FD->setHasImplicitReturnZero(true);
10429     else {
10430       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10431       SourceRange RTRange = FD->getReturnTypeSourceRange();
10432       if (RTRange.isValid())
10433         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10434             << FixItHint::CreateReplacement(RTRange, "int");
10435     }
10436   } else {
10437     // In C and C++, main magically returns 0 if you fall off the end;
10438     // set the flag which tells us that.
10439     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10440 
10441     // All the standards say that main() should return 'int'.
10442     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10443       FD->setHasImplicitReturnZero(true);
10444     else {
10445       // Otherwise, this is just a flat-out error.
10446       SourceRange RTRange = FD->getReturnTypeSourceRange();
10447       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10448           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10449                                 : FixItHint());
10450       FD->setInvalidDecl(true);
10451     }
10452   }
10453 
10454   // Treat protoless main() as nullary.
10455   if (isa<FunctionNoProtoType>(FT)) return;
10456 
10457   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10458   unsigned nparams = FTP->getNumParams();
10459   assert(FD->getNumParams() == nparams);
10460 
10461   bool HasExtraParameters = (nparams > 3);
10462 
10463   if (FTP->isVariadic()) {
10464     Diag(FD->getLocation(), diag::ext_variadic_main);
10465     // FIXME: if we had information about the location of the ellipsis, we
10466     // could add a FixIt hint to remove it as a parameter.
10467   }
10468 
10469   // Darwin passes an undocumented fourth argument of type char**.  If
10470   // other platforms start sprouting these, the logic below will start
10471   // getting shifty.
10472   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10473     HasExtraParameters = false;
10474 
10475   if (HasExtraParameters) {
10476     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10477     FD->setInvalidDecl(true);
10478     nparams = 3;
10479   }
10480 
10481   // FIXME: a lot of the following diagnostics would be improved
10482   // if we had some location information about types.
10483 
10484   QualType CharPP =
10485     Context.getPointerType(Context.getPointerType(Context.CharTy));
10486   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10487 
10488   for (unsigned i = 0; i < nparams; ++i) {
10489     QualType AT = FTP->getParamType(i);
10490 
10491     bool mismatch = true;
10492 
10493     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10494       mismatch = false;
10495     else if (Expected[i] == CharPP) {
10496       // As an extension, the following forms are okay:
10497       //   char const **
10498       //   char const * const *
10499       //   char * const *
10500 
10501       QualifierCollector qs;
10502       const PointerType* PT;
10503       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10504           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10505           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10506                               Context.CharTy)) {
10507         qs.removeConst();
10508         mismatch = !qs.empty();
10509       }
10510     }
10511 
10512     if (mismatch) {
10513       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10514       // TODO: suggest replacing given type with expected type
10515       FD->setInvalidDecl(true);
10516     }
10517   }
10518 
10519   if (nparams == 1 && !FD->isInvalidDecl()) {
10520     Diag(FD->getLocation(), diag::warn_main_one_arg);
10521   }
10522 
10523   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10524     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10525     FD->setInvalidDecl();
10526   }
10527 }
10528 
10529 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10530   QualType T = FD->getType();
10531   assert(T->isFunctionType() && "function decl is not of function type");
10532   const FunctionType *FT = T->castAs<FunctionType>();
10533 
10534   // Set an implicit return of 'zero' if the function can return some integral,
10535   // enumeration, pointer or nullptr type.
10536   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10537       FT->getReturnType()->isAnyPointerType() ||
10538       FT->getReturnType()->isNullPtrType())
10539     // DllMain is exempt because a return value of zero means it failed.
10540     if (FD->getName() != "DllMain")
10541       FD->setHasImplicitReturnZero(true);
10542 
10543   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10544     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10545     FD->setInvalidDecl();
10546   }
10547 }
10548 
10549 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10550   // FIXME: Need strict checking.  In C89, we need to check for
10551   // any assignment, increment, decrement, function-calls, or
10552   // commas outside of a sizeof.  In C99, it's the same list,
10553   // except that the aforementioned are allowed in unevaluated
10554   // expressions.  Everything else falls under the
10555   // "may accept other forms of constant expressions" exception.
10556   // (We never end up here for C++, so the constant expression
10557   // rules there don't matter.)
10558   const Expr *Culprit;
10559   if (Init->isConstantInitializer(Context, false, &Culprit))
10560     return false;
10561   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10562     << Culprit->getSourceRange();
10563   return true;
10564 }
10565 
10566 namespace {
10567   // Visits an initialization expression to see if OrigDecl is evaluated in
10568   // its own initialization and throws a warning if it does.
10569   class SelfReferenceChecker
10570       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10571     Sema &S;
10572     Decl *OrigDecl;
10573     bool isRecordType;
10574     bool isPODType;
10575     bool isReferenceType;
10576 
10577     bool isInitList;
10578     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10579 
10580   public:
10581     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10582 
10583     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10584                                                     S(S), OrigDecl(OrigDecl) {
10585       isPODType = false;
10586       isRecordType = false;
10587       isReferenceType = false;
10588       isInitList = false;
10589       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10590         isPODType = VD->getType().isPODType(S.Context);
10591         isRecordType = VD->getType()->isRecordType();
10592         isReferenceType = VD->getType()->isReferenceType();
10593       }
10594     }
10595 
10596     // For most expressions, just call the visitor.  For initializer lists,
10597     // track the index of the field being initialized since fields are
10598     // initialized in order allowing use of previously initialized fields.
10599     void CheckExpr(Expr *E) {
10600       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10601       if (!InitList) {
10602         Visit(E);
10603         return;
10604       }
10605 
10606       // Track and increment the index here.
10607       isInitList = true;
10608       InitFieldIndex.push_back(0);
10609       for (auto Child : InitList->children()) {
10610         CheckExpr(cast<Expr>(Child));
10611         ++InitFieldIndex.back();
10612       }
10613       InitFieldIndex.pop_back();
10614     }
10615 
10616     // Returns true if MemberExpr is checked and no further checking is needed.
10617     // Returns false if additional checking is required.
10618     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10619       llvm::SmallVector<FieldDecl*, 4> Fields;
10620       Expr *Base = E;
10621       bool ReferenceField = false;
10622 
10623       // Get the field members used.
10624       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10625         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10626         if (!FD)
10627           return false;
10628         Fields.push_back(FD);
10629         if (FD->getType()->isReferenceType())
10630           ReferenceField = true;
10631         Base = ME->getBase()->IgnoreParenImpCasts();
10632       }
10633 
10634       // Keep checking only if the base Decl is the same.
10635       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10636       if (!DRE || DRE->getDecl() != OrigDecl)
10637         return false;
10638 
10639       // A reference field can be bound to an unininitialized field.
10640       if (CheckReference && !ReferenceField)
10641         return true;
10642 
10643       // Convert FieldDecls to their index number.
10644       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10645       for (const FieldDecl *I : llvm::reverse(Fields))
10646         UsedFieldIndex.push_back(I->getFieldIndex());
10647 
10648       // See if a warning is needed by checking the first difference in index
10649       // numbers.  If field being used has index less than the field being
10650       // initialized, then the use is safe.
10651       for (auto UsedIter = UsedFieldIndex.begin(),
10652                 UsedEnd = UsedFieldIndex.end(),
10653                 OrigIter = InitFieldIndex.begin(),
10654                 OrigEnd = InitFieldIndex.end();
10655            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10656         if (*UsedIter < *OrigIter)
10657           return true;
10658         if (*UsedIter > *OrigIter)
10659           break;
10660       }
10661 
10662       // TODO: Add a different warning which will print the field names.
10663       HandleDeclRefExpr(DRE);
10664       return true;
10665     }
10666 
10667     // For most expressions, the cast is directly above the DeclRefExpr.
10668     // For conditional operators, the cast can be outside the conditional
10669     // operator if both expressions are DeclRefExpr's.
10670     void HandleValue(Expr *E) {
10671       E = E->IgnoreParens();
10672       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10673         HandleDeclRefExpr(DRE);
10674         return;
10675       }
10676 
10677       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10678         Visit(CO->getCond());
10679         HandleValue(CO->getTrueExpr());
10680         HandleValue(CO->getFalseExpr());
10681         return;
10682       }
10683 
10684       if (BinaryConditionalOperator *BCO =
10685               dyn_cast<BinaryConditionalOperator>(E)) {
10686         Visit(BCO->getCond());
10687         HandleValue(BCO->getFalseExpr());
10688         return;
10689       }
10690 
10691       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10692         HandleValue(OVE->getSourceExpr());
10693         return;
10694       }
10695 
10696       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10697         if (BO->getOpcode() == BO_Comma) {
10698           Visit(BO->getLHS());
10699           HandleValue(BO->getRHS());
10700           return;
10701         }
10702       }
10703 
10704       if (isa<MemberExpr>(E)) {
10705         if (isInitList) {
10706           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10707                                       false /*CheckReference*/))
10708             return;
10709         }
10710 
10711         Expr *Base = E->IgnoreParenImpCasts();
10712         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10713           // Check for static member variables and don't warn on them.
10714           if (!isa<FieldDecl>(ME->getMemberDecl()))
10715             return;
10716           Base = ME->getBase()->IgnoreParenImpCasts();
10717         }
10718         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10719           HandleDeclRefExpr(DRE);
10720         return;
10721       }
10722 
10723       Visit(E);
10724     }
10725 
10726     // Reference types not handled in HandleValue are handled here since all
10727     // uses of references are bad, not just r-value uses.
10728     void VisitDeclRefExpr(DeclRefExpr *E) {
10729       if (isReferenceType)
10730         HandleDeclRefExpr(E);
10731     }
10732 
10733     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10734       if (E->getCastKind() == CK_LValueToRValue) {
10735         HandleValue(E->getSubExpr());
10736         return;
10737       }
10738 
10739       Inherited::VisitImplicitCastExpr(E);
10740     }
10741 
10742     void VisitMemberExpr(MemberExpr *E) {
10743       if (isInitList) {
10744         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10745           return;
10746       }
10747 
10748       // Don't warn on arrays since they can be treated as pointers.
10749       if (E->getType()->canDecayToPointerType()) return;
10750 
10751       // Warn when a non-static method call is followed by non-static member
10752       // field accesses, which is followed by a DeclRefExpr.
10753       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10754       bool Warn = (MD && !MD->isStatic());
10755       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10756       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10757         if (!isa<FieldDecl>(ME->getMemberDecl()))
10758           Warn = false;
10759         Base = ME->getBase()->IgnoreParenImpCasts();
10760       }
10761 
10762       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10763         if (Warn)
10764           HandleDeclRefExpr(DRE);
10765         return;
10766       }
10767 
10768       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10769       // Visit that expression.
10770       Visit(Base);
10771     }
10772 
10773     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10774       Expr *Callee = E->getCallee();
10775 
10776       if (isa<UnresolvedLookupExpr>(Callee))
10777         return Inherited::VisitCXXOperatorCallExpr(E);
10778 
10779       Visit(Callee);
10780       for (auto Arg: E->arguments())
10781         HandleValue(Arg->IgnoreParenImpCasts());
10782     }
10783 
10784     void VisitUnaryOperator(UnaryOperator *E) {
10785       // For POD record types, addresses of its own members are well-defined.
10786       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10787           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10788         if (!isPODType)
10789           HandleValue(E->getSubExpr());
10790         return;
10791       }
10792 
10793       if (E->isIncrementDecrementOp()) {
10794         HandleValue(E->getSubExpr());
10795         return;
10796       }
10797 
10798       Inherited::VisitUnaryOperator(E);
10799     }
10800 
10801     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10802 
10803     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10804       if (E->getConstructor()->isCopyConstructor()) {
10805         Expr *ArgExpr = E->getArg(0);
10806         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10807           if (ILE->getNumInits() == 1)
10808             ArgExpr = ILE->getInit(0);
10809         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10810           if (ICE->getCastKind() == CK_NoOp)
10811             ArgExpr = ICE->getSubExpr();
10812         HandleValue(ArgExpr);
10813         return;
10814       }
10815       Inherited::VisitCXXConstructExpr(E);
10816     }
10817 
10818     void VisitCallExpr(CallExpr *E) {
10819       // Treat std::move as a use.
10820       if (E->isCallToStdMove()) {
10821         HandleValue(E->getArg(0));
10822         return;
10823       }
10824 
10825       Inherited::VisitCallExpr(E);
10826     }
10827 
10828     void VisitBinaryOperator(BinaryOperator *E) {
10829       if (E->isCompoundAssignmentOp()) {
10830         HandleValue(E->getLHS());
10831         Visit(E->getRHS());
10832         return;
10833       }
10834 
10835       Inherited::VisitBinaryOperator(E);
10836     }
10837 
10838     // A custom visitor for BinaryConditionalOperator is needed because the
10839     // regular visitor would check the condition and true expression separately
10840     // but both point to the same place giving duplicate diagnostics.
10841     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10842       Visit(E->getCond());
10843       Visit(E->getFalseExpr());
10844     }
10845 
10846     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10847       Decl* ReferenceDecl = DRE->getDecl();
10848       if (OrigDecl != ReferenceDecl) return;
10849       unsigned diag;
10850       if (isReferenceType) {
10851         diag = diag::warn_uninit_self_reference_in_reference_init;
10852       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10853         diag = diag::warn_static_self_reference_in_init;
10854       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10855                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10856                  DRE->getDecl()->getType()->isRecordType()) {
10857         diag = diag::warn_uninit_self_reference_in_init;
10858       } else {
10859         // Local variables will be handled by the CFG analysis.
10860         return;
10861       }
10862 
10863       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10864                             S.PDiag(diag)
10865                                 << DRE->getDecl() << OrigDecl->getLocation()
10866                                 << DRE->getSourceRange());
10867     }
10868   };
10869 
10870   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10871   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10872                                  bool DirectInit) {
10873     // Parameters arguments are occassionially constructed with itself,
10874     // for instance, in recursive functions.  Skip them.
10875     if (isa<ParmVarDecl>(OrigDecl))
10876       return;
10877 
10878     E = E->IgnoreParens();
10879 
10880     // Skip checking T a = a where T is not a record or reference type.
10881     // Doing so is a way to silence uninitialized warnings.
10882     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10883       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10884         if (ICE->getCastKind() == CK_LValueToRValue)
10885           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10886             if (DRE->getDecl() == OrigDecl)
10887               return;
10888 
10889     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10890   }
10891 } // end anonymous namespace
10892 
10893 namespace {
10894   // Simple wrapper to add the name of a variable or (if no variable is
10895   // available) a DeclarationName into a diagnostic.
10896   struct VarDeclOrName {
10897     VarDecl *VDecl;
10898     DeclarationName Name;
10899 
10900     friend const Sema::SemaDiagnosticBuilder &
10901     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10902       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10903     }
10904   };
10905 } // end anonymous namespace
10906 
10907 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10908                                             DeclarationName Name, QualType Type,
10909                                             TypeSourceInfo *TSI,
10910                                             SourceRange Range, bool DirectInit,
10911                                             Expr *Init) {
10912   bool IsInitCapture = !VDecl;
10913   assert((!VDecl || !VDecl->isInitCapture()) &&
10914          "init captures are expected to be deduced prior to initialization");
10915 
10916   VarDeclOrName VN{VDecl, Name};
10917 
10918   DeducedType *Deduced = Type->getContainedDeducedType();
10919   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10920 
10921   // C++11 [dcl.spec.auto]p3
10922   if (!Init) {
10923     assert(VDecl && "no init for init capture deduction?");
10924 
10925     // Except for class argument deduction, and then for an initializing
10926     // declaration only, i.e. no static at class scope or extern.
10927     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10928         VDecl->hasExternalStorage() ||
10929         VDecl->isStaticDataMember()) {
10930       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10931         << VDecl->getDeclName() << Type;
10932       return QualType();
10933     }
10934   }
10935 
10936   ArrayRef<Expr*> DeduceInits;
10937   if (Init)
10938     DeduceInits = Init;
10939 
10940   if (DirectInit) {
10941     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10942       DeduceInits = PL->exprs();
10943   }
10944 
10945   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10946     assert(VDecl && "non-auto type for init capture deduction?");
10947     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10948     InitializationKind Kind = InitializationKind::CreateForInit(
10949         VDecl->getLocation(), DirectInit, Init);
10950     // FIXME: Initialization should not be taking a mutable list of inits.
10951     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10952     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10953                                                        InitsCopy);
10954   }
10955 
10956   if (DirectInit) {
10957     if (auto *IL = dyn_cast<InitListExpr>(Init))
10958       DeduceInits = IL->inits();
10959   }
10960 
10961   // Deduction only works if we have exactly one source expression.
10962   if (DeduceInits.empty()) {
10963     // It isn't possible to write this directly, but it is possible to
10964     // end up in this situation with "auto x(some_pack...);"
10965     Diag(Init->getBeginLoc(), IsInitCapture
10966                                   ? diag::err_init_capture_no_expression
10967                                   : diag::err_auto_var_init_no_expression)
10968         << VN << Type << Range;
10969     return QualType();
10970   }
10971 
10972   if (DeduceInits.size() > 1) {
10973     Diag(DeduceInits[1]->getBeginLoc(),
10974          IsInitCapture ? diag::err_init_capture_multiple_expressions
10975                        : diag::err_auto_var_init_multiple_expressions)
10976         << VN << Type << Range;
10977     return QualType();
10978   }
10979 
10980   Expr *DeduceInit = DeduceInits[0];
10981   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10982     Diag(Init->getBeginLoc(), IsInitCapture
10983                                   ? diag::err_init_capture_paren_braces
10984                                   : diag::err_auto_var_init_paren_braces)
10985         << isa<InitListExpr>(Init) << VN << Type << Range;
10986     return QualType();
10987   }
10988 
10989   // Expressions default to 'id' when we're in a debugger.
10990   bool DefaultedAnyToId = false;
10991   if (getLangOpts().DebuggerCastResultToId &&
10992       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10993     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10994     if (Result.isInvalid()) {
10995       return QualType();
10996     }
10997     Init = Result.get();
10998     DefaultedAnyToId = true;
10999   }
11000 
11001   // C++ [dcl.decomp]p1:
11002   //   If the assignment-expression [...] has array type A and no ref-qualifier
11003   //   is present, e has type cv A
11004   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11005       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11006       DeduceInit->getType()->isConstantArrayType())
11007     return Context.getQualifiedType(DeduceInit->getType(),
11008                                     Type.getQualifiers());
11009 
11010   QualType DeducedType;
11011   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11012     if (!IsInitCapture)
11013       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11014     else if (isa<InitListExpr>(Init))
11015       Diag(Range.getBegin(),
11016            diag::err_init_capture_deduction_failure_from_init_list)
11017           << VN
11018           << (DeduceInit->getType().isNull() ? TSI->getType()
11019                                              : DeduceInit->getType())
11020           << DeduceInit->getSourceRange();
11021     else
11022       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11023           << VN << TSI->getType()
11024           << (DeduceInit->getType().isNull() ? TSI->getType()
11025                                              : DeduceInit->getType())
11026           << DeduceInit->getSourceRange();
11027   }
11028 
11029   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11030   // 'id' instead of a specific object type prevents most of our usual
11031   // checks.
11032   // We only want to warn outside of template instantiations, though:
11033   // inside a template, the 'id' could have come from a parameter.
11034   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11035       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11036     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11037     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11038   }
11039 
11040   return DeducedType;
11041 }
11042 
11043 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11044                                          Expr *Init) {
11045   QualType DeducedType = deduceVarTypeFromInitializer(
11046       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11047       VDecl->getSourceRange(), DirectInit, Init);
11048   if (DeducedType.isNull()) {
11049     VDecl->setInvalidDecl();
11050     return true;
11051   }
11052 
11053   VDecl->setType(DeducedType);
11054   assert(VDecl->isLinkageValid());
11055 
11056   // In ARC, infer lifetime.
11057   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11058     VDecl->setInvalidDecl();
11059 
11060   // If this is a redeclaration, check that the type we just deduced matches
11061   // the previously declared type.
11062   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11063     // We never need to merge the type, because we cannot form an incomplete
11064     // array of auto, nor deduce such a type.
11065     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11066   }
11067 
11068   // Check the deduced type is valid for a variable declaration.
11069   CheckVariableDeclarationType(VDecl);
11070   return VDecl->isInvalidDecl();
11071 }
11072 
11073 /// AddInitializerToDecl - Adds the initializer Init to the
11074 /// declaration dcl. If DirectInit is true, this is C++ direct
11075 /// initialization rather than copy initialization.
11076 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11077   // If there is no declaration, there was an error parsing it.  Just ignore
11078   // the initializer.
11079   if (!RealDecl || RealDecl->isInvalidDecl()) {
11080     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11081     return;
11082   }
11083 
11084   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11085     // Pure-specifiers are handled in ActOnPureSpecifier.
11086     Diag(Method->getLocation(), diag::err_member_function_initialization)
11087       << Method->getDeclName() << Init->getSourceRange();
11088     Method->setInvalidDecl();
11089     return;
11090   }
11091 
11092   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11093   if (!VDecl) {
11094     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11095     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11096     RealDecl->setInvalidDecl();
11097     return;
11098   }
11099 
11100   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11101   if (VDecl->getType()->isUndeducedType()) {
11102     // Attempt typo correction early so that the type of the init expression can
11103     // be deduced based on the chosen correction if the original init contains a
11104     // TypoExpr.
11105     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11106     if (!Res.isUsable()) {
11107       RealDecl->setInvalidDecl();
11108       return;
11109     }
11110     Init = Res.get();
11111 
11112     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11113       return;
11114   }
11115 
11116   // dllimport cannot be used on variable definitions.
11117   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11118     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11119     VDecl->setInvalidDecl();
11120     return;
11121   }
11122 
11123   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11124     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11125     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11126     VDecl->setInvalidDecl();
11127     return;
11128   }
11129 
11130   if (!VDecl->getType()->isDependentType()) {
11131     // A definition must end up with a complete type, which means it must be
11132     // complete with the restriction that an array type might be completed by
11133     // the initializer; note that later code assumes this restriction.
11134     QualType BaseDeclType = VDecl->getType();
11135     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11136       BaseDeclType = Array->getElementType();
11137     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11138                             diag::err_typecheck_decl_incomplete_type)) {
11139       RealDecl->setInvalidDecl();
11140       return;
11141     }
11142 
11143     // The variable can not have an abstract class type.
11144     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11145                                diag::err_abstract_type_in_decl,
11146                                AbstractVariableType))
11147       VDecl->setInvalidDecl();
11148   }
11149 
11150   // If adding the initializer will turn this declaration into a definition,
11151   // and we already have a definition for this variable, diagnose or otherwise
11152   // handle the situation.
11153   VarDecl *Def;
11154   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11155       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11156       !VDecl->isThisDeclarationADemotedDefinition() &&
11157       checkVarDeclRedefinition(Def, VDecl))
11158     return;
11159 
11160   if (getLangOpts().CPlusPlus) {
11161     // C++ [class.static.data]p4
11162     //   If a static data member is of const integral or const
11163     //   enumeration type, its declaration in the class definition can
11164     //   specify a constant-initializer which shall be an integral
11165     //   constant expression (5.19). In that case, the member can appear
11166     //   in integral constant expressions. The member shall still be
11167     //   defined in a namespace scope if it is used in the program and the
11168     //   namespace scope definition shall not contain an initializer.
11169     //
11170     // We already performed a redefinition check above, but for static
11171     // data members we also need to check whether there was an in-class
11172     // declaration with an initializer.
11173     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11174       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11175           << VDecl->getDeclName();
11176       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11177            diag::note_previous_initializer)
11178           << 0;
11179       return;
11180     }
11181 
11182     if (VDecl->hasLocalStorage())
11183       setFunctionHasBranchProtectedScope();
11184 
11185     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11186       VDecl->setInvalidDecl();
11187       return;
11188     }
11189   }
11190 
11191   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11192   // a kernel function cannot be initialized."
11193   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11194     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11195     VDecl->setInvalidDecl();
11196     return;
11197   }
11198 
11199   // Get the decls type and save a reference for later, since
11200   // CheckInitializerTypes may change it.
11201   QualType DclT = VDecl->getType(), SavT = DclT;
11202 
11203   // Expressions default to 'id' when we're in a debugger
11204   // and we are assigning it to a variable of Objective-C pointer type.
11205   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11206       Init->getType() == Context.UnknownAnyTy) {
11207     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11208     if (Result.isInvalid()) {
11209       VDecl->setInvalidDecl();
11210       return;
11211     }
11212     Init = Result.get();
11213   }
11214 
11215   // Perform the initialization.
11216   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11217   if (!VDecl->isInvalidDecl()) {
11218     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11219     InitializationKind Kind = InitializationKind::CreateForInit(
11220         VDecl->getLocation(), DirectInit, Init);
11221 
11222     MultiExprArg Args = Init;
11223     if (CXXDirectInit)
11224       Args = MultiExprArg(CXXDirectInit->getExprs(),
11225                           CXXDirectInit->getNumExprs());
11226 
11227     // Try to correct any TypoExprs in the initialization arguments.
11228     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11229       ExprResult Res = CorrectDelayedTyposInExpr(
11230           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11231             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11232             return Init.Failed() ? ExprError() : E;
11233           });
11234       if (Res.isInvalid()) {
11235         VDecl->setInvalidDecl();
11236       } else if (Res.get() != Args[Idx]) {
11237         Args[Idx] = Res.get();
11238       }
11239     }
11240     if (VDecl->isInvalidDecl())
11241       return;
11242 
11243     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11244                                    /*TopLevelOfInitList=*/false,
11245                                    /*TreatUnavailableAsInvalid=*/false);
11246     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11247     if (Result.isInvalid()) {
11248       VDecl->setInvalidDecl();
11249       return;
11250     }
11251 
11252     Init = Result.getAs<Expr>();
11253   }
11254 
11255   // Check for self-references within variable initializers.
11256   // Variables declared within a function/method body (except for references)
11257   // are handled by a dataflow analysis.
11258   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11259       VDecl->getType()->isReferenceType()) {
11260     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11261   }
11262 
11263   // If the type changed, it means we had an incomplete type that was
11264   // completed by the initializer. For example:
11265   //   int ary[] = { 1, 3, 5 };
11266   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11267   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11268     VDecl->setType(DclT);
11269 
11270   if (!VDecl->isInvalidDecl()) {
11271     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11272 
11273     if (VDecl->hasAttr<BlocksAttr>())
11274       checkRetainCycles(VDecl, Init);
11275 
11276     // It is safe to assign a weak reference into a strong variable.
11277     // Although this code can still have problems:
11278     //   id x = self.weakProp;
11279     //   id y = self.weakProp;
11280     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11281     // paths through the function. This should be revisited if
11282     // -Wrepeated-use-of-weak is made flow-sensitive.
11283     if (FunctionScopeInfo *FSI = getCurFunction())
11284       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11285            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11286           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11287                            Init->getBeginLoc()))
11288         FSI->markSafeWeakUse(Init);
11289   }
11290 
11291   // The initialization is usually a full-expression.
11292   //
11293   // FIXME: If this is a braced initialization of an aggregate, it is not
11294   // an expression, and each individual field initializer is a separate
11295   // full-expression. For instance, in:
11296   //
11297   //   struct Temp { ~Temp(); };
11298   //   struct S { S(Temp); };
11299   //   struct T { S a, b; } t = { Temp(), Temp() }
11300   //
11301   // we should destroy the first Temp before constructing the second.
11302   ExprResult Result =
11303       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11304                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11305   if (Result.isInvalid()) {
11306     VDecl->setInvalidDecl();
11307     return;
11308   }
11309   Init = Result.get();
11310 
11311   // Attach the initializer to the decl.
11312   VDecl->setInit(Init);
11313 
11314   if (VDecl->isLocalVarDecl()) {
11315     // Don't check the initializer if the declaration is malformed.
11316     if (VDecl->isInvalidDecl()) {
11317       // do nothing
11318 
11319     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11320     // This is true even in OpenCL C++.
11321     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11322       CheckForConstantInitializer(Init, DclT);
11323 
11324     // Otherwise, C++ does not restrict the initializer.
11325     } else if (getLangOpts().CPlusPlus) {
11326       // do nothing
11327 
11328     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11329     // static storage duration shall be constant expressions or string literals.
11330     } else if (VDecl->getStorageClass() == SC_Static) {
11331       CheckForConstantInitializer(Init, DclT);
11332 
11333     // C89 is stricter than C99 for aggregate initializers.
11334     // C89 6.5.7p3: All the expressions [...] in an initializer list
11335     // for an object that has aggregate or union type shall be
11336     // constant expressions.
11337     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11338                isa<InitListExpr>(Init)) {
11339       const Expr *Culprit;
11340       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11341         Diag(Culprit->getExprLoc(),
11342              diag::ext_aggregate_init_not_constant)
11343           << Culprit->getSourceRange();
11344       }
11345     }
11346 
11347     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11348       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11349         if (VDecl->hasLocalStorage())
11350           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11351   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11352              VDecl->getLexicalDeclContext()->isRecord()) {
11353     // This is an in-class initialization for a static data member, e.g.,
11354     //
11355     // struct S {
11356     //   static const int value = 17;
11357     // };
11358 
11359     // C++ [class.mem]p4:
11360     //   A member-declarator can contain a constant-initializer only
11361     //   if it declares a static member (9.4) of const integral or
11362     //   const enumeration type, see 9.4.2.
11363     //
11364     // C++11 [class.static.data]p3:
11365     //   If a non-volatile non-inline const static data member is of integral
11366     //   or enumeration type, its declaration in the class definition can
11367     //   specify a brace-or-equal-initializer in which every initializer-clause
11368     //   that is an assignment-expression is a constant expression. A static
11369     //   data member of literal type can be declared in the class definition
11370     //   with the constexpr specifier; if so, its declaration shall specify a
11371     //   brace-or-equal-initializer in which every initializer-clause that is
11372     //   an assignment-expression is a constant expression.
11373 
11374     // Do nothing on dependent types.
11375     if (DclT->isDependentType()) {
11376 
11377     // Allow any 'static constexpr' members, whether or not they are of literal
11378     // type. We separately check that every constexpr variable is of literal
11379     // type.
11380     } else if (VDecl->isConstexpr()) {
11381 
11382     // Require constness.
11383     } else if (!DclT.isConstQualified()) {
11384       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11385         << Init->getSourceRange();
11386       VDecl->setInvalidDecl();
11387 
11388     // We allow integer constant expressions in all cases.
11389     } else if (DclT->isIntegralOrEnumerationType()) {
11390       // Check whether the expression is a constant expression.
11391       SourceLocation Loc;
11392       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11393         // In C++11, a non-constexpr const static data member with an
11394         // in-class initializer cannot be volatile.
11395         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11396       else if (Init->isValueDependent())
11397         ; // Nothing to check.
11398       else if (Init->isIntegerConstantExpr(Context, &Loc))
11399         ; // Ok, it's an ICE!
11400       else if (Init->getType()->isScopedEnumeralType() &&
11401                Init->isCXX11ConstantExpr(Context))
11402         ; // Ok, it is a scoped-enum constant expression.
11403       else if (Init->isEvaluatable(Context)) {
11404         // If we can constant fold the initializer through heroics, accept it,
11405         // but report this as a use of an extension for -pedantic.
11406         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11407           << Init->getSourceRange();
11408       } else {
11409         // Otherwise, this is some crazy unknown case.  Report the issue at the
11410         // location provided by the isIntegerConstantExpr failed check.
11411         Diag(Loc, diag::err_in_class_initializer_non_constant)
11412           << Init->getSourceRange();
11413         VDecl->setInvalidDecl();
11414       }
11415 
11416     // We allow foldable floating-point constants as an extension.
11417     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11418       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11419       // it anyway and provide a fixit to add the 'constexpr'.
11420       if (getLangOpts().CPlusPlus11) {
11421         Diag(VDecl->getLocation(),
11422              diag::ext_in_class_initializer_float_type_cxx11)
11423             << DclT << Init->getSourceRange();
11424         Diag(VDecl->getBeginLoc(),
11425              diag::note_in_class_initializer_float_type_cxx11)
11426             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11427       } else {
11428         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11429           << DclT << Init->getSourceRange();
11430 
11431         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11432           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11433             << Init->getSourceRange();
11434           VDecl->setInvalidDecl();
11435         }
11436       }
11437 
11438     // Suggest adding 'constexpr' in C++11 for literal types.
11439     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11440       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11441           << DclT << Init->getSourceRange()
11442           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11443       VDecl->setConstexpr(true);
11444 
11445     } else {
11446       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11447         << DclT << Init->getSourceRange();
11448       VDecl->setInvalidDecl();
11449     }
11450   } else if (VDecl->isFileVarDecl()) {
11451     // In C, extern is typically used to avoid tentative definitions when
11452     // declaring variables in headers, but adding an intializer makes it a
11453     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11454     // In C++, extern is often used to give implictly static const variables
11455     // external linkage, so don't warn in that case. If selectany is present,
11456     // this might be header code intended for C and C++ inclusion, so apply the
11457     // C++ rules.
11458     if (VDecl->getStorageClass() == SC_Extern &&
11459         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11460          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11461         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11462         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11463       Diag(VDecl->getLocation(), diag::warn_extern_init);
11464 
11465     // In Microsoft C++ mode, a const variable defined in namespace scope has
11466     // external linkage by default if the variable is declared with
11467     // __declspec(dllexport).
11468     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11469         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11470         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11471       VDecl->setStorageClass(SC_Extern);
11472 
11473     // C99 6.7.8p4. All file scoped initializers need to be constant.
11474     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11475       CheckForConstantInitializer(Init, DclT);
11476   }
11477 
11478   // We will represent direct-initialization similarly to copy-initialization:
11479   //    int x(1);  -as-> int x = 1;
11480   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11481   //
11482   // Clients that want to distinguish between the two forms, can check for
11483   // direct initializer using VarDecl::getInitStyle().
11484   // A major benefit is that clients that don't particularly care about which
11485   // exactly form was it (like the CodeGen) can handle both cases without
11486   // special case code.
11487 
11488   // C++ 8.5p11:
11489   // The form of initialization (using parentheses or '=') is generally
11490   // insignificant, but does matter when the entity being initialized has a
11491   // class type.
11492   if (CXXDirectInit) {
11493     assert(DirectInit && "Call-style initializer must be direct init.");
11494     VDecl->setInitStyle(VarDecl::CallInit);
11495   } else if (DirectInit) {
11496     // This must be list-initialization. No other way is direct-initialization.
11497     VDecl->setInitStyle(VarDecl::ListInit);
11498   }
11499 
11500   CheckCompleteVariableDeclaration(VDecl);
11501 }
11502 
11503 /// ActOnInitializerError - Given that there was an error parsing an
11504 /// initializer for the given declaration, try to return to some form
11505 /// of sanity.
11506 void Sema::ActOnInitializerError(Decl *D) {
11507   // Our main concern here is re-establishing invariants like "a
11508   // variable's type is either dependent or complete".
11509   if (!D || D->isInvalidDecl()) return;
11510 
11511   VarDecl *VD = dyn_cast<VarDecl>(D);
11512   if (!VD) return;
11513 
11514   // Bindings are not usable if we can't make sense of the initializer.
11515   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11516     for (auto *BD : DD->bindings())
11517       BD->setInvalidDecl();
11518 
11519   // Auto types are meaningless if we can't make sense of the initializer.
11520   if (ParsingInitForAutoVars.count(D)) {
11521     D->setInvalidDecl();
11522     return;
11523   }
11524 
11525   QualType Ty = VD->getType();
11526   if (Ty->isDependentType()) return;
11527 
11528   // Require a complete type.
11529   if (RequireCompleteType(VD->getLocation(),
11530                           Context.getBaseElementType(Ty),
11531                           diag::err_typecheck_decl_incomplete_type)) {
11532     VD->setInvalidDecl();
11533     return;
11534   }
11535 
11536   // Require a non-abstract type.
11537   if (RequireNonAbstractType(VD->getLocation(), Ty,
11538                              diag::err_abstract_type_in_decl,
11539                              AbstractVariableType)) {
11540     VD->setInvalidDecl();
11541     return;
11542   }
11543 
11544   // Don't bother complaining about constructors or destructors,
11545   // though.
11546 }
11547 
11548 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11549   // If there is no declaration, there was an error parsing it. Just ignore it.
11550   if (!RealDecl)
11551     return;
11552 
11553   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11554     QualType Type = Var->getType();
11555 
11556     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11557     if (isa<DecompositionDecl>(RealDecl)) {
11558       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11559       Var->setInvalidDecl();
11560       return;
11561     }
11562 
11563     if (Type->isUndeducedType() &&
11564         DeduceVariableDeclarationType(Var, false, nullptr))
11565       return;
11566 
11567     // C++11 [class.static.data]p3: A static data member can be declared with
11568     // the constexpr specifier; if so, its declaration shall specify
11569     // a brace-or-equal-initializer.
11570     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11571     // the definition of a variable [...] or the declaration of a static data
11572     // member.
11573     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11574         !Var->isThisDeclarationADemotedDefinition()) {
11575       if (Var->isStaticDataMember()) {
11576         // C++1z removes the relevant rule; the in-class declaration is always
11577         // a definition there.
11578         if (!getLangOpts().CPlusPlus17) {
11579           Diag(Var->getLocation(),
11580                diag::err_constexpr_static_mem_var_requires_init)
11581             << Var->getDeclName();
11582           Var->setInvalidDecl();
11583           return;
11584         }
11585       } else {
11586         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11587         Var->setInvalidDecl();
11588         return;
11589       }
11590     }
11591 
11592     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11593     // be initialized.
11594     if (!Var->isInvalidDecl() &&
11595         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11596         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11597       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11598       Var->setInvalidDecl();
11599       return;
11600     }
11601 
11602     switch (Var->isThisDeclarationADefinition()) {
11603     case VarDecl::Definition:
11604       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11605         break;
11606 
11607       // We have an out-of-line definition of a static data member
11608       // that has an in-class initializer, so we type-check this like
11609       // a declaration.
11610       //
11611       LLVM_FALLTHROUGH;
11612 
11613     case VarDecl::DeclarationOnly:
11614       // It's only a declaration.
11615 
11616       // Block scope. C99 6.7p7: If an identifier for an object is
11617       // declared with no linkage (C99 6.2.2p6), the type for the
11618       // object shall be complete.
11619       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11620           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11621           RequireCompleteType(Var->getLocation(), Type,
11622                               diag::err_typecheck_decl_incomplete_type))
11623         Var->setInvalidDecl();
11624 
11625       // Make sure that the type is not abstract.
11626       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11627           RequireNonAbstractType(Var->getLocation(), Type,
11628                                  diag::err_abstract_type_in_decl,
11629                                  AbstractVariableType))
11630         Var->setInvalidDecl();
11631       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11632           Var->getStorageClass() == SC_PrivateExtern) {
11633         Diag(Var->getLocation(), diag::warn_private_extern);
11634         Diag(Var->getLocation(), diag::note_private_extern);
11635       }
11636 
11637       return;
11638 
11639     case VarDecl::TentativeDefinition:
11640       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11641       // object that has file scope without an initializer, and without a
11642       // storage-class specifier or with the storage-class specifier "static",
11643       // constitutes a tentative definition. Note: A tentative definition with
11644       // external linkage is valid (C99 6.2.2p5).
11645       if (!Var->isInvalidDecl()) {
11646         if (const IncompleteArrayType *ArrayT
11647                                     = Context.getAsIncompleteArrayType(Type)) {
11648           if (RequireCompleteType(Var->getLocation(),
11649                                   ArrayT->getElementType(),
11650                                   diag::err_illegal_decl_array_incomplete_type))
11651             Var->setInvalidDecl();
11652         } else if (Var->getStorageClass() == SC_Static) {
11653           // C99 6.9.2p3: If the declaration of an identifier for an object is
11654           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11655           // declared type shall not be an incomplete type.
11656           // NOTE: code such as the following
11657           //     static struct s;
11658           //     struct s { int a; };
11659           // is accepted by gcc. Hence here we issue a warning instead of
11660           // an error and we do not invalidate the static declaration.
11661           // NOTE: to avoid multiple warnings, only check the first declaration.
11662           if (Var->isFirstDecl())
11663             RequireCompleteType(Var->getLocation(), Type,
11664                                 diag::ext_typecheck_decl_incomplete_type);
11665         }
11666       }
11667 
11668       // Record the tentative definition; we're done.
11669       if (!Var->isInvalidDecl())
11670         TentativeDefinitions.push_back(Var);
11671       return;
11672     }
11673 
11674     // Provide a specific diagnostic for uninitialized variable
11675     // definitions with incomplete array type.
11676     if (Type->isIncompleteArrayType()) {
11677       Diag(Var->getLocation(),
11678            diag::err_typecheck_incomplete_array_needs_initializer);
11679       Var->setInvalidDecl();
11680       return;
11681     }
11682 
11683     // Provide a specific diagnostic for uninitialized variable
11684     // definitions with reference type.
11685     if (Type->isReferenceType()) {
11686       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11687         << Var->getDeclName()
11688         << SourceRange(Var->getLocation(), Var->getLocation());
11689       Var->setInvalidDecl();
11690       return;
11691     }
11692 
11693     // Do not attempt to type-check the default initializer for a
11694     // variable with dependent type.
11695     if (Type->isDependentType())
11696       return;
11697 
11698     if (Var->isInvalidDecl())
11699       return;
11700 
11701     if (!Var->hasAttr<AliasAttr>()) {
11702       if (RequireCompleteType(Var->getLocation(),
11703                               Context.getBaseElementType(Type),
11704                               diag::err_typecheck_decl_incomplete_type)) {
11705         Var->setInvalidDecl();
11706         return;
11707       }
11708     } else {
11709       return;
11710     }
11711 
11712     // The variable can not have an abstract class type.
11713     if (RequireNonAbstractType(Var->getLocation(), Type,
11714                                diag::err_abstract_type_in_decl,
11715                                AbstractVariableType)) {
11716       Var->setInvalidDecl();
11717       return;
11718     }
11719 
11720     // Check for jumps past the implicit initializer.  C++0x
11721     // clarifies that this applies to a "variable with automatic
11722     // storage duration", not a "local variable".
11723     // C++11 [stmt.dcl]p3
11724     //   A program that jumps from a point where a variable with automatic
11725     //   storage duration is not in scope to a point where it is in scope is
11726     //   ill-formed unless the variable has scalar type, class type with a
11727     //   trivial default constructor and a trivial destructor, a cv-qualified
11728     //   version of one of these types, or an array of one of the preceding
11729     //   types and is declared without an initializer.
11730     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11731       if (const RecordType *Record
11732             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11733         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11734         // Mark the function (if we're in one) for further checking even if the
11735         // looser rules of C++11 do not require such checks, so that we can
11736         // diagnose incompatibilities with C++98.
11737         if (!CXXRecord->isPOD())
11738           setFunctionHasBranchProtectedScope();
11739       }
11740     }
11741     // In OpenCL, we can't initialize objects in the __local address space,
11742     // even implicitly, so don't synthesize an implicit initializer.
11743     if (getLangOpts().OpenCL &&
11744         Var->getType().getAddressSpace() == LangAS::opencl_local)
11745       return;
11746     // C++03 [dcl.init]p9:
11747     //   If no initializer is specified for an object, and the
11748     //   object is of (possibly cv-qualified) non-POD class type (or
11749     //   array thereof), the object shall be default-initialized; if
11750     //   the object is of const-qualified type, the underlying class
11751     //   type shall have a user-declared default
11752     //   constructor. Otherwise, if no initializer is specified for
11753     //   a non- static object, the object and its subobjects, if
11754     //   any, have an indeterminate initial value); if the object
11755     //   or any of its subobjects are of const-qualified type, the
11756     //   program is ill-formed.
11757     // C++0x [dcl.init]p11:
11758     //   If no initializer is specified for an object, the object is
11759     //   default-initialized; [...].
11760     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11761     InitializationKind Kind
11762       = InitializationKind::CreateDefault(Var->getLocation());
11763 
11764     InitializationSequence InitSeq(*this, Entity, Kind, None);
11765     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11766     if (Init.isInvalid())
11767       Var->setInvalidDecl();
11768     else if (Init.get()) {
11769       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11770       // This is important for template substitution.
11771       Var->setInitStyle(VarDecl::CallInit);
11772     }
11773 
11774     CheckCompleteVariableDeclaration(Var);
11775   }
11776 }
11777 
11778 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11779   // If there is no declaration, there was an error parsing it. Ignore it.
11780   if (!D)
11781     return;
11782 
11783   VarDecl *VD = dyn_cast<VarDecl>(D);
11784   if (!VD) {
11785     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11786     D->setInvalidDecl();
11787     return;
11788   }
11789 
11790   VD->setCXXForRangeDecl(true);
11791 
11792   // for-range-declaration cannot be given a storage class specifier.
11793   int Error = -1;
11794   switch (VD->getStorageClass()) {
11795   case SC_None:
11796     break;
11797   case SC_Extern:
11798     Error = 0;
11799     break;
11800   case SC_Static:
11801     Error = 1;
11802     break;
11803   case SC_PrivateExtern:
11804     Error = 2;
11805     break;
11806   case SC_Auto:
11807     Error = 3;
11808     break;
11809   case SC_Register:
11810     Error = 4;
11811     break;
11812   }
11813   if (Error != -1) {
11814     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11815       << VD->getDeclName() << Error;
11816     D->setInvalidDecl();
11817   }
11818 }
11819 
11820 StmtResult
11821 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11822                                  IdentifierInfo *Ident,
11823                                  ParsedAttributes &Attrs,
11824                                  SourceLocation AttrEnd) {
11825   // C++1y [stmt.iter]p1:
11826   //   A range-based for statement of the form
11827   //      for ( for-range-identifier : for-range-initializer ) statement
11828   //   is equivalent to
11829   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11830   DeclSpec DS(Attrs.getPool().getFactory());
11831 
11832   const char *PrevSpec;
11833   unsigned DiagID;
11834   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11835                      getPrintingPolicy());
11836 
11837   Declarator D(DS, DeclaratorContext::ForContext);
11838   D.SetIdentifier(Ident, IdentLoc);
11839   D.takeAttributes(Attrs, AttrEnd);
11840 
11841   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11842                 IdentLoc);
11843   Decl *Var = ActOnDeclarator(S, D);
11844   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11845   FinalizeDeclaration(Var);
11846   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11847                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11848 }
11849 
11850 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11851   if (var->isInvalidDecl()) return;
11852 
11853   if (getLangOpts().OpenCL) {
11854     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11855     // initialiser
11856     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11857         !var->hasInit()) {
11858       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11859           << 1 /*Init*/;
11860       var->setInvalidDecl();
11861       return;
11862     }
11863   }
11864 
11865   // In Objective-C, don't allow jumps past the implicit initialization of a
11866   // local retaining variable.
11867   if (getLangOpts().ObjC &&
11868       var->hasLocalStorage()) {
11869     switch (var->getType().getObjCLifetime()) {
11870     case Qualifiers::OCL_None:
11871     case Qualifiers::OCL_ExplicitNone:
11872     case Qualifiers::OCL_Autoreleasing:
11873       break;
11874 
11875     case Qualifiers::OCL_Weak:
11876     case Qualifiers::OCL_Strong:
11877       setFunctionHasBranchProtectedScope();
11878       break;
11879     }
11880   }
11881 
11882   if (var->hasLocalStorage() &&
11883       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11884     setFunctionHasBranchProtectedScope();
11885 
11886   // Warn about externally-visible variables being defined without a
11887   // prior declaration.  We only want to do this for global
11888   // declarations, but we also specifically need to avoid doing it for
11889   // class members because the linkage of an anonymous class can
11890   // change if it's later given a typedef name.
11891   if (var->isThisDeclarationADefinition() &&
11892       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11893       var->isExternallyVisible() && var->hasLinkage() &&
11894       !var->isInline() && !var->getDescribedVarTemplate() &&
11895       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11896       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11897                                   var->getLocation())) {
11898     // Find a previous declaration that's not a definition.
11899     VarDecl *prev = var->getPreviousDecl();
11900     while (prev && prev->isThisDeclarationADefinition())
11901       prev = prev->getPreviousDecl();
11902 
11903     if (!prev) {
11904       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11905       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
11906           << /* variable */ 0;
11907     }
11908   }
11909 
11910   // Cache the result of checking for constant initialization.
11911   Optional<bool> CacheHasConstInit;
11912   const Expr *CacheCulprit;
11913   auto checkConstInit = [&]() mutable {
11914     if (!CacheHasConstInit)
11915       CacheHasConstInit = var->getInit()->isConstantInitializer(
11916             Context, var->getType()->isReferenceType(), &CacheCulprit);
11917     return *CacheHasConstInit;
11918   };
11919 
11920   if (var->getTLSKind() == VarDecl::TLS_Static) {
11921     if (var->getType().isDestructedType()) {
11922       // GNU C++98 edits for __thread, [basic.start.term]p3:
11923       //   The type of an object with thread storage duration shall not
11924       //   have a non-trivial destructor.
11925       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11926       if (getLangOpts().CPlusPlus11)
11927         Diag(var->getLocation(), diag::note_use_thread_local);
11928     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11929       if (!checkConstInit()) {
11930         // GNU C++98 edits for __thread, [basic.start.init]p4:
11931         //   An object of thread storage duration shall not require dynamic
11932         //   initialization.
11933         // FIXME: Need strict checking here.
11934         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11935           << CacheCulprit->getSourceRange();
11936         if (getLangOpts().CPlusPlus11)
11937           Diag(var->getLocation(), diag::note_use_thread_local);
11938       }
11939     }
11940   }
11941 
11942   // Apply section attributes and pragmas to global variables.
11943   bool GlobalStorage = var->hasGlobalStorage();
11944   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11945       !inTemplateInstantiation()) {
11946     PragmaStack<StringLiteral *> *Stack = nullptr;
11947     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11948     if (var->getType().isConstQualified())
11949       Stack = &ConstSegStack;
11950     else if (!var->getInit()) {
11951       Stack = &BSSSegStack;
11952       SectionFlags |= ASTContext::PSF_Write;
11953     } else {
11954       Stack = &DataSegStack;
11955       SectionFlags |= ASTContext::PSF_Write;
11956     }
11957     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11958       var->addAttr(SectionAttr::CreateImplicit(
11959           Context, SectionAttr::Declspec_allocate,
11960           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11961     }
11962     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11963       if (UnifySection(SA->getName(), SectionFlags, var))
11964         var->dropAttr<SectionAttr>();
11965 
11966     // Apply the init_seg attribute if this has an initializer.  If the
11967     // initializer turns out to not be dynamic, we'll end up ignoring this
11968     // attribute.
11969     if (CurInitSeg && var->getInit())
11970       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11971                                                CurInitSegLoc));
11972   }
11973 
11974   // All the following checks are C++ only.
11975   if (!getLangOpts().CPlusPlus) {
11976       // If this variable must be emitted, add it as an initializer for the
11977       // current module.
11978      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11979        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11980      return;
11981   }
11982 
11983   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11984     CheckCompleteDecompositionDeclaration(DD);
11985 
11986   QualType type = var->getType();
11987   if (type->isDependentType()) return;
11988 
11989   if (var->hasAttr<BlocksAttr>())
11990     getCurFunction()->addByrefBlockVar(var);
11991 
11992   Expr *Init = var->getInit();
11993   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11994   QualType baseType = Context.getBaseElementType(type);
11995 
11996   if (Init && !Init->isValueDependent()) {
11997     if (var->isConstexpr()) {
11998       SmallVector<PartialDiagnosticAt, 8> Notes;
11999       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12000         SourceLocation DiagLoc = var->getLocation();
12001         // If the note doesn't add any useful information other than a source
12002         // location, fold it into the primary diagnostic.
12003         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12004               diag::note_invalid_subexpr_in_const_expr) {
12005           DiagLoc = Notes[0].first;
12006           Notes.clear();
12007         }
12008         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12009           << var << Init->getSourceRange();
12010         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12011           Diag(Notes[I].first, Notes[I].second);
12012       }
12013     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12014       // Check whether the initializer of a const variable of integral or
12015       // enumeration type is an ICE now, since we can't tell whether it was
12016       // initialized by a constant expression if we check later.
12017       var->checkInitIsICE();
12018     }
12019 
12020     // Don't emit further diagnostics about constexpr globals since they
12021     // were just diagnosed.
12022     if (!var->isConstexpr() && GlobalStorage &&
12023             var->hasAttr<RequireConstantInitAttr>()) {
12024       // FIXME: Need strict checking in C++03 here.
12025       bool DiagErr = getLangOpts().CPlusPlus11
12026           ? !var->checkInitIsICE() : !checkConstInit();
12027       if (DiagErr) {
12028         auto attr = var->getAttr<RequireConstantInitAttr>();
12029         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12030           << Init->getSourceRange();
12031         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
12032           << attr->getRange();
12033         if (getLangOpts().CPlusPlus11) {
12034           APValue Value;
12035           SmallVector<PartialDiagnosticAt, 8> Notes;
12036           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12037           for (auto &it : Notes)
12038             Diag(it.first, it.second);
12039         } else {
12040           Diag(CacheCulprit->getExprLoc(),
12041                diag::note_invalid_subexpr_in_const_expr)
12042               << CacheCulprit->getSourceRange();
12043         }
12044       }
12045     }
12046     else if (!var->isConstexpr() && IsGlobal &&
12047              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12048                                     var->getLocation())) {
12049       // Warn about globals which don't have a constant initializer.  Don't
12050       // warn about globals with a non-trivial destructor because we already
12051       // warned about them.
12052       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12053       if (!(RD && !RD->hasTrivialDestructor())) {
12054         if (!checkConstInit())
12055           Diag(var->getLocation(), diag::warn_global_constructor)
12056             << Init->getSourceRange();
12057       }
12058     }
12059   }
12060 
12061   // Require the destructor.
12062   if (const RecordType *recordType = baseType->getAs<RecordType>())
12063     FinalizeVarWithDestructor(var, recordType);
12064 
12065   // If this variable must be emitted, add it as an initializer for the current
12066   // module.
12067   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12068     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12069 }
12070 
12071 /// Determines if a variable's alignment is dependent.
12072 static bool hasDependentAlignment(VarDecl *VD) {
12073   if (VD->getType()->isDependentType())
12074     return true;
12075   for (auto *I : VD->specific_attrs<AlignedAttr>())
12076     if (I->isAlignmentDependent())
12077       return true;
12078   return false;
12079 }
12080 
12081 /// Check if VD needs to be dllexport/dllimport due to being in a
12082 /// dllexport/import function.
12083 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12084   assert(VD->isStaticLocal());
12085 
12086   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12087 
12088   // Find outermost function when VD is in lambda function.
12089   while (FD && !getDLLAttr(FD) &&
12090          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12091          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12092     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12093   }
12094 
12095   if (!FD)
12096     return;
12097 
12098   // Static locals inherit dll attributes from their function.
12099   if (Attr *A = getDLLAttr(FD)) {
12100     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12101     NewAttr->setInherited(true);
12102     VD->addAttr(NewAttr);
12103   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12104     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12105                                                           getASTContext(),
12106                                                           A->getSpellingListIndex());
12107     NewAttr->setInherited(true);
12108     VD->addAttr(NewAttr);
12109 
12110     // Export this function to enforce exporting this static variable even
12111     // if it is not used in this compilation unit.
12112     if (!FD->hasAttr<DLLExportAttr>())
12113       FD->addAttr(NewAttr);
12114 
12115   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12116     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12117                                                           getASTContext(),
12118                                                           A->getSpellingListIndex());
12119     NewAttr->setInherited(true);
12120     VD->addAttr(NewAttr);
12121   }
12122 }
12123 
12124 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12125 /// any semantic actions necessary after any initializer has been attached.
12126 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12127   // Note that we are no longer parsing the initializer for this declaration.
12128   ParsingInitForAutoVars.erase(ThisDecl);
12129 
12130   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12131   if (!VD)
12132     return;
12133 
12134   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12135   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12136       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12137     if (PragmaClangBSSSection.Valid)
12138       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12139                                                             PragmaClangBSSSection.SectionName,
12140                                                             PragmaClangBSSSection.PragmaLocation));
12141     if (PragmaClangDataSection.Valid)
12142       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12143                                                              PragmaClangDataSection.SectionName,
12144                                                              PragmaClangDataSection.PragmaLocation));
12145     if (PragmaClangRodataSection.Valid)
12146       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12147                                                                PragmaClangRodataSection.SectionName,
12148                                                                PragmaClangRodataSection.PragmaLocation));
12149   }
12150 
12151   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12152     for (auto *BD : DD->bindings()) {
12153       FinalizeDeclaration(BD);
12154     }
12155   }
12156 
12157   checkAttributesAfterMerging(*this, *VD);
12158 
12159   // Perform TLS alignment check here after attributes attached to the variable
12160   // which may affect the alignment have been processed. Only perform the check
12161   // if the target has a maximum TLS alignment (zero means no constraints).
12162   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12163     // Protect the check so that it's not performed on dependent types and
12164     // dependent alignments (we can't determine the alignment in that case).
12165     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12166         !VD->isInvalidDecl()) {
12167       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12168       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12169         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12170           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12171           << (unsigned)MaxAlignChars.getQuantity();
12172       }
12173     }
12174   }
12175 
12176   if (VD->isStaticLocal()) {
12177     CheckStaticLocalForDllExport(VD);
12178 
12179     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12180       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12181       // function, only __shared__ variables or variables without any device
12182       // memory qualifiers may be declared with static storage class.
12183       // Note: It is unclear how a function-scope non-const static variable
12184       // without device memory qualifier is implemented, therefore only static
12185       // const variable without device memory qualifier is allowed.
12186       [&]() {
12187         if (!getLangOpts().CUDA)
12188           return;
12189         if (VD->hasAttr<CUDASharedAttr>())
12190           return;
12191         if (VD->getType().isConstQualified() &&
12192             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12193           return;
12194         if (CUDADiagIfDeviceCode(VD->getLocation(),
12195                                  diag::err_device_static_local_var)
12196             << CurrentCUDATarget())
12197           VD->setInvalidDecl();
12198       }();
12199     }
12200   }
12201 
12202   // Perform check for initializers of device-side global variables.
12203   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12204   // 7.5). We must also apply the same checks to all __shared__
12205   // variables whether they are local or not. CUDA also allows
12206   // constant initializers for __constant__ and __device__ variables.
12207   if (getLangOpts().CUDA)
12208     checkAllowedCUDAInitializer(VD);
12209 
12210   // Grab the dllimport or dllexport attribute off of the VarDecl.
12211   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12212 
12213   // Imported static data members cannot be defined out-of-line.
12214   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12215     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12216         VD->isThisDeclarationADefinition()) {
12217       // We allow definitions of dllimport class template static data members
12218       // with a warning.
12219       CXXRecordDecl *Context =
12220         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12221       bool IsClassTemplateMember =
12222           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12223           Context->getDescribedClassTemplate();
12224 
12225       Diag(VD->getLocation(),
12226            IsClassTemplateMember
12227                ? diag::warn_attribute_dllimport_static_field_definition
12228                : diag::err_attribute_dllimport_static_field_definition);
12229       Diag(IA->getLocation(), diag::note_attribute);
12230       if (!IsClassTemplateMember)
12231         VD->setInvalidDecl();
12232     }
12233   }
12234 
12235   // dllimport/dllexport variables cannot be thread local, their TLS index
12236   // isn't exported with the variable.
12237   if (DLLAttr && VD->getTLSKind()) {
12238     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12239     if (F && getDLLAttr(F)) {
12240       assert(VD->isStaticLocal());
12241       // But if this is a static local in a dlimport/dllexport function, the
12242       // function will never be inlined, which means the var would never be
12243       // imported, so having it marked import/export is safe.
12244     } else {
12245       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12246                                                                     << DLLAttr;
12247       VD->setInvalidDecl();
12248     }
12249   }
12250 
12251   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12252     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12253       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12254       VD->dropAttr<UsedAttr>();
12255     }
12256   }
12257 
12258   const DeclContext *DC = VD->getDeclContext();
12259   // If there's a #pragma GCC visibility in scope, and this isn't a class
12260   // member, set the visibility of this variable.
12261   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12262     AddPushedVisibilityAttribute(VD);
12263 
12264   // FIXME: Warn on unused var template partial specializations.
12265   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12266     MarkUnusedFileScopedDecl(VD);
12267 
12268   // Now we have parsed the initializer and can update the table of magic
12269   // tag values.
12270   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12271       !VD->getType()->isIntegralOrEnumerationType())
12272     return;
12273 
12274   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12275     const Expr *MagicValueExpr = VD->getInit();
12276     if (!MagicValueExpr) {
12277       continue;
12278     }
12279     llvm::APSInt MagicValueInt;
12280     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12281       Diag(I->getRange().getBegin(),
12282            diag::err_type_tag_for_datatype_not_ice)
12283         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12284       continue;
12285     }
12286     if (MagicValueInt.getActiveBits() > 64) {
12287       Diag(I->getRange().getBegin(),
12288            diag::err_type_tag_for_datatype_too_large)
12289         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12290       continue;
12291     }
12292     uint64_t MagicValue = MagicValueInt.getZExtValue();
12293     RegisterTypeTagForDatatype(I->getArgumentKind(),
12294                                MagicValue,
12295                                I->getMatchingCType(),
12296                                I->getLayoutCompatible(),
12297                                I->getMustBeNull());
12298   }
12299 }
12300 
12301 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12302   auto *VD = dyn_cast<VarDecl>(DD);
12303   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12304 }
12305 
12306 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12307                                                    ArrayRef<Decl *> Group) {
12308   SmallVector<Decl*, 8> Decls;
12309 
12310   if (DS.isTypeSpecOwned())
12311     Decls.push_back(DS.getRepAsDecl());
12312 
12313   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12314   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12315   bool DiagnosedMultipleDecomps = false;
12316   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12317   bool DiagnosedNonDeducedAuto = false;
12318 
12319   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12320     if (Decl *D = Group[i]) {
12321       // For declarators, there are some additional syntactic-ish checks we need
12322       // to perform.
12323       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12324         if (!FirstDeclaratorInGroup)
12325           FirstDeclaratorInGroup = DD;
12326         if (!FirstDecompDeclaratorInGroup)
12327           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12328         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12329             !hasDeducedAuto(DD))
12330           FirstNonDeducedAutoInGroup = DD;
12331 
12332         if (FirstDeclaratorInGroup != DD) {
12333           // A decomposition declaration cannot be combined with any other
12334           // declaration in the same group.
12335           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12336             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12337                  diag::err_decomp_decl_not_alone)
12338                 << FirstDeclaratorInGroup->getSourceRange()
12339                 << DD->getSourceRange();
12340             DiagnosedMultipleDecomps = true;
12341           }
12342 
12343           // A declarator that uses 'auto' in any way other than to declare a
12344           // variable with a deduced type cannot be combined with any other
12345           // declarator in the same group.
12346           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12347             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12348                  diag::err_auto_non_deduced_not_alone)
12349                 << FirstNonDeducedAutoInGroup->getType()
12350                        ->hasAutoForTrailingReturnType()
12351                 << FirstDeclaratorInGroup->getSourceRange()
12352                 << DD->getSourceRange();
12353             DiagnosedNonDeducedAuto = true;
12354           }
12355         }
12356       }
12357 
12358       Decls.push_back(D);
12359     }
12360   }
12361 
12362   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12363     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12364       handleTagNumbering(Tag, S);
12365       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12366           getLangOpts().CPlusPlus)
12367         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12368     }
12369   }
12370 
12371   return BuildDeclaratorGroup(Decls);
12372 }
12373 
12374 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12375 /// group, performing any necessary semantic checking.
12376 Sema::DeclGroupPtrTy
12377 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12378   // C++14 [dcl.spec.auto]p7: (DR1347)
12379   //   If the type that replaces the placeholder type is not the same in each
12380   //   deduction, the program is ill-formed.
12381   if (Group.size() > 1) {
12382     QualType Deduced;
12383     VarDecl *DeducedDecl = nullptr;
12384     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12385       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12386       if (!D || D->isInvalidDecl())
12387         break;
12388       DeducedType *DT = D->getType()->getContainedDeducedType();
12389       if (!DT || DT->getDeducedType().isNull())
12390         continue;
12391       if (Deduced.isNull()) {
12392         Deduced = DT->getDeducedType();
12393         DeducedDecl = D;
12394       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12395         auto *AT = dyn_cast<AutoType>(DT);
12396         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12397              diag::err_auto_different_deductions)
12398           << (AT ? (unsigned)AT->getKeyword() : 3)
12399           << Deduced << DeducedDecl->getDeclName()
12400           << DT->getDeducedType() << D->getDeclName()
12401           << DeducedDecl->getInit()->getSourceRange()
12402           << D->getInit()->getSourceRange();
12403         D->setInvalidDecl();
12404         break;
12405       }
12406     }
12407   }
12408 
12409   ActOnDocumentableDecls(Group);
12410 
12411   return DeclGroupPtrTy::make(
12412       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12413 }
12414 
12415 void Sema::ActOnDocumentableDecl(Decl *D) {
12416   ActOnDocumentableDecls(D);
12417 }
12418 
12419 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12420   // Don't parse the comment if Doxygen diagnostics are ignored.
12421   if (Group.empty() || !Group[0])
12422     return;
12423 
12424   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12425                       Group[0]->getLocation()) &&
12426       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12427                       Group[0]->getLocation()))
12428     return;
12429 
12430   if (Group.size() >= 2) {
12431     // This is a decl group.  Normally it will contain only declarations
12432     // produced from declarator list.  But in case we have any definitions or
12433     // additional declaration references:
12434     //   'typedef struct S {} S;'
12435     //   'typedef struct S *S;'
12436     //   'struct S *pS;'
12437     // FinalizeDeclaratorGroup adds these as separate declarations.
12438     Decl *MaybeTagDecl = Group[0];
12439     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12440       Group = Group.slice(1);
12441     }
12442   }
12443 
12444   // See if there are any new comments that are not attached to a decl.
12445   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12446   if (!Comments.empty() &&
12447       !Comments.back()->isAttached()) {
12448     // There is at least one comment that not attached to a decl.
12449     // Maybe it should be attached to one of these decls?
12450     //
12451     // Note that this way we pick up not only comments that precede the
12452     // declaration, but also comments that *follow* the declaration -- thanks to
12453     // the lookahead in the lexer: we've consumed the semicolon and looked
12454     // ahead through comments.
12455     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12456       Context.getCommentForDecl(Group[i], &PP);
12457   }
12458 }
12459 
12460 /// Common checks for a parameter-declaration that should apply to both function
12461 /// parameters and non-type template parameters.
12462 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12463   // Check that there are no default arguments inside the type of this
12464   // parameter.
12465   if (getLangOpts().CPlusPlus)
12466     CheckExtraCXXDefaultArguments(D);
12467 
12468   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12469   if (D.getCXXScopeSpec().isSet()) {
12470     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12471       << D.getCXXScopeSpec().getRange();
12472   }
12473 
12474   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12475   // simple identifier except [...irrelevant cases...].
12476   switch (D.getName().getKind()) {
12477   case UnqualifiedIdKind::IK_Identifier:
12478     break;
12479 
12480   case UnqualifiedIdKind::IK_OperatorFunctionId:
12481   case UnqualifiedIdKind::IK_ConversionFunctionId:
12482   case UnqualifiedIdKind::IK_LiteralOperatorId:
12483   case UnqualifiedIdKind::IK_ConstructorName:
12484   case UnqualifiedIdKind::IK_DestructorName:
12485   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12486   case UnqualifiedIdKind::IK_DeductionGuideName:
12487     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12488       << GetNameForDeclarator(D).getName();
12489     break;
12490 
12491   case UnqualifiedIdKind::IK_TemplateId:
12492   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12493     // GetNameForDeclarator would not produce a useful name in this case.
12494     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
12495     break;
12496   }
12497 }
12498 
12499 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12500 /// to introduce parameters into function prototype scope.
12501 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12502   const DeclSpec &DS = D.getDeclSpec();
12503 
12504   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12505 
12506   // C++03 [dcl.stc]p2 also permits 'auto'.
12507   StorageClass SC = SC_None;
12508   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12509     SC = SC_Register;
12510     // In C++11, the 'register' storage class specifier is deprecated.
12511     // In C++17, it is not allowed, but we tolerate it as an extension.
12512     if (getLangOpts().CPlusPlus11) {
12513       Diag(DS.getStorageClassSpecLoc(),
12514            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12515                                      : diag::warn_deprecated_register)
12516         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12517     }
12518   } else if (getLangOpts().CPlusPlus &&
12519              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12520     SC = SC_Auto;
12521   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12522     Diag(DS.getStorageClassSpecLoc(),
12523          diag::err_invalid_storage_class_in_func_decl);
12524     D.getMutableDeclSpec().ClearStorageClassSpecs();
12525   }
12526 
12527   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12528     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12529       << DeclSpec::getSpecifierName(TSCS);
12530   if (DS.isInlineSpecified())
12531     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12532         << getLangOpts().CPlusPlus17;
12533   if (DS.hasConstexprSpecifier())
12534     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12535         << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
12536 
12537   DiagnoseFunctionSpecifiers(DS);
12538 
12539   CheckFunctionOrTemplateParamDeclarator(S, D);
12540 
12541   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12542   QualType parmDeclType = TInfo->getType();
12543 
12544   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12545   IdentifierInfo *II = D.getIdentifier();
12546   if (II) {
12547     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12548                    ForVisibleRedeclaration);
12549     LookupName(R, S);
12550     if (R.isSingleResult()) {
12551       NamedDecl *PrevDecl = R.getFoundDecl();
12552       if (PrevDecl->isTemplateParameter()) {
12553         // Maybe we will complain about the shadowed template parameter.
12554         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12555         // Just pretend that we didn't see the previous declaration.
12556         PrevDecl = nullptr;
12557       } else if (S->isDeclScope(PrevDecl)) {
12558         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12559         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12560 
12561         // Recover by removing the name
12562         II = nullptr;
12563         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12564         D.setInvalidType(true);
12565       }
12566     }
12567   }
12568 
12569   // Temporarily put parameter variables in the translation unit, not
12570   // the enclosing context.  This prevents them from accidentally
12571   // looking like class members in C++.
12572   ParmVarDecl *New =
12573       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12574                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12575 
12576   if (D.isInvalidType())
12577     New->setInvalidDecl();
12578 
12579   assert(S->isFunctionPrototypeScope());
12580   assert(S->getFunctionPrototypeDepth() >= 1);
12581   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12582                     S->getNextFunctionPrototypeIndex());
12583 
12584   // Add the parameter declaration into this scope.
12585   S->AddDecl(New);
12586   if (II)
12587     IdResolver.AddDecl(New);
12588 
12589   ProcessDeclAttributes(S, New, D);
12590 
12591   if (D.getDeclSpec().isModulePrivateSpecified())
12592     Diag(New->getLocation(), diag::err_module_private_local)
12593       << 1 << New->getDeclName()
12594       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12595       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12596 
12597   if (New->hasAttr<BlocksAttr>()) {
12598     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12599   }
12600   return New;
12601 }
12602 
12603 /// Synthesizes a variable for a parameter arising from a
12604 /// typedef.
12605 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12606                                               SourceLocation Loc,
12607                                               QualType T) {
12608   /* FIXME: setting StartLoc == Loc.
12609      Would it be worth to modify callers so as to provide proper source
12610      location for the unnamed parameters, embedding the parameter's type? */
12611   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12612                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12613                                            SC_None, nullptr);
12614   Param->setImplicit();
12615   return Param;
12616 }
12617 
12618 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12619   // Don't diagnose unused-parameter errors in template instantiations; we
12620   // will already have done so in the template itself.
12621   if (inTemplateInstantiation())
12622     return;
12623 
12624   for (const ParmVarDecl *Parameter : Parameters) {
12625     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12626         !Parameter->hasAttr<UnusedAttr>()) {
12627       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12628         << Parameter->getDeclName();
12629     }
12630   }
12631 }
12632 
12633 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12634     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12635   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12636     return;
12637 
12638   // Warn if the return value is pass-by-value and larger than the specified
12639   // threshold.
12640   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12641     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12642     if (Size > LangOpts.NumLargeByValueCopy)
12643       Diag(D->getLocation(), diag::warn_return_value_size)
12644           << D->getDeclName() << Size;
12645   }
12646 
12647   // Warn if any parameter is pass-by-value and larger than the specified
12648   // threshold.
12649   for (const ParmVarDecl *Parameter : Parameters) {
12650     QualType T = Parameter->getType();
12651     if (T->isDependentType() || !T.isPODType(Context))
12652       continue;
12653     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12654     if (Size > LangOpts.NumLargeByValueCopy)
12655       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12656           << Parameter->getDeclName() << Size;
12657   }
12658 }
12659 
12660 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12661                                   SourceLocation NameLoc, IdentifierInfo *Name,
12662                                   QualType T, TypeSourceInfo *TSInfo,
12663                                   StorageClass SC) {
12664   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12665   if (getLangOpts().ObjCAutoRefCount &&
12666       T.getObjCLifetime() == Qualifiers::OCL_None &&
12667       T->isObjCLifetimeType()) {
12668 
12669     Qualifiers::ObjCLifetime lifetime;
12670 
12671     // Special cases for arrays:
12672     //   - if it's const, use __unsafe_unretained
12673     //   - otherwise, it's an error
12674     if (T->isArrayType()) {
12675       if (!T.isConstQualified()) {
12676         if (DelayedDiagnostics.shouldDelayDiagnostics())
12677           DelayedDiagnostics.add(
12678               sema::DelayedDiagnostic::makeForbiddenType(
12679               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12680         else
12681           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12682               << TSInfo->getTypeLoc().getSourceRange();
12683       }
12684       lifetime = Qualifiers::OCL_ExplicitNone;
12685     } else {
12686       lifetime = T->getObjCARCImplicitLifetime();
12687     }
12688     T = Context.getLifetimeQualifiedType(T, lifetime);
12689   }
12690 
12691   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12692                                          Context.getAdjustedParameterType(T),
12693                                          TSInfo, SC, nullptr);
12694 
12695   // Parameters can not be abstract class types.
12696   // For record types, this is done by the AbstractClassUsageDiagnoser once
12697   // the class has been completely parsed.
12698   if (!CurContext->isRecord() &&
12699       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12700                              AbstractParamType))
12701     New->setInvalidDecl();
12702 
12703   // Parameter declarators cannot be interface types. All ObjC objects are
12704   // passed by reference.
12705   if (T->isObjCObjectType()) {
12706     SourceLocation TypeEndLoc =
12707         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12708     Diag(NameLoc,
12709          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12710       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12711     T = Context.getObjCObjectPointerType(T);
12712     New->setType(T);
12713   }
12714 
12715   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12716   // duration shall not be qualified by an address-space qualifier."
12717   // Since all parameters have automatic store duration, they can not have
12718   // an address space.
12719   if (T.getAddressSpace() != LangAS::Default &&
12720       // OpenCL allows function arguments declared to be an array of a type
12721       // to be qualified with an address space.
12722       !(getLangOpts().OpenCL &&
12723         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12724     Diag(NameLoc, diag::err_arg_with_address_space);
12725     New->setInvalidDecl();
12726   }
12727 
12728   return New;
12729 }
12730 
12731 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12732                                            SourceLocation LocAfterDecls) {
12733   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12734 
12735   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12736   // for a K&R function.
12737   if (!FTI.hasPrototype) {
12738     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12739       --i;
12740       if (FTI.Params[i].Param == nullptr) {
12741         SmallString<256> Code;
12742         llvm::raw_svector_ostream(Code)
12743             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12744         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12745             << FTI.Params[i].Ident
12746             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12747 
12748         // Implicitly declare the argument as type 'int' for lack of a better
12749         // type.
12750         AttributeFactory attrs;
12751         DeclSpec DS(attrs);
12752         const char* PrevSpec; // unused
12753         unsigned DiagID; // unused
12754         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12755                            DiagID, Context.getPrintingPolicy());
12756         // Use the identifier location for the type source range.
12757         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12758         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12759         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12760         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12761         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12762       }
12763     }
12764   }
12765 }
12766 
12767 Decl *
12768 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12769                               MultiTemplateParamsArg TemplateParameterLists,
12770                               SkipBodyInfo *SkipBody) {
12771   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12772   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12773   Scope *ParentScope = FnBodyScope->getParent();
12774 
12775   D.setFunctionDefinitionKind(FDK_Definition);
12776   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12777   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12778 }
12779 
12780 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12781   Consumer.HandleInlineFunctionDefinition(D);
12782 }
12783 
12784 static bool
12785 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12786                                 const FunctionDecl *&PossiblePrototype) {
12787   // Don't warn about invalid declarations.
12788   if (FD->isInvalidDecl())
12789     return false;
12790 
12791   // Or declarations that aren't global.
12792   if (!FD->isGlobal())
12793     return false;
12794 
12795   // Don't warn about C++ member functions.
12796   if (isa<CXXMethodDecl>(FD))
12797     return false;
12798 
12799   // Don't warn about 'main'.
12800   if (FD->isMain())
12801     return false;
12802 
12803   // Don't warn about inline functions.
12804   if (FD->isInlined())
12805     return false;
12806 
12807   // Don't warn about function templates.
12808   if (FD->getDescribedFunctionTemplate())
12809     return false;
12810 
12811   // Don't warn about function template specializations.
12812   if (FD->isFunctionTemplateSpecialization())
12813     return false;
12814 
12815   // Don't warn for OpenCL kernels.
12816   if (FD->hasAttr<OpenCLKernelAttr>())
12817     return false;
12818 
12819   // Don't warn on explicitly deleted functions.
12820   if (FD->isDeleted())
12821     return false;
12822 
12823   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12824        Prev; Prev = Prev->getPreviousDecl()) {
12825     // Ignore any declarations that occur in function or method
12826     // scope, because they aren't visible from the header.
12827     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12828       continue;
12829 
12830     PossiblePrototype = Prev;
12831     return Prev->getType()->isFunctionNoProtoType();
12832   }
12833 
12834   return true;
12835 }
12836 
12837 void
12838 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12839                                    const FunctionDecl *EffectiveDefinition,
12840                                    SkipBodyInfo *SkipBody) {
12841   const FunctionDecl *Definition = EffectiveDefinition;
12842   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12843     // If this is a friend function defined in a class template, it does not
12844     // have a body until it is used, nevertheless it is a definition, see
12845     // [temp.inst]p2:
12846     //
12847     // ... for the purpose of determining whether an instantiated redeclaration
12848     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12849     // corresponds to a definition in the template is considered to be a
12850     // definition.
12851     //
12852     // The following code must produce redefinition error:
12853     //
12854     //     template<typename T> struct C20 { friend void func_20() {} };
12855     //     C20<int> c20i;
12856     //     void func_20() {}
12857     //
12858     for (auto I : FD->redecls()) {
12859       if (I != FD && !I->isInvalidDecl() &&
12860           I->getFriendObjectKind() != Decl::FOK_None) {
12861         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12862           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12863             // A merged copy of the same function, instantiated as a member of
12864             // the same class, is OK.
12865             if (declaresSameEntity(OrigFD, Original) &&
12866                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12867                                    cast<Decl>(FD->getLexicalDeclContext())))
12868               continue;
12869           }
12870 
12871           if (Original->isThisDeclarationADefinition()) {
12872             Definition = I;
12873             break;
12874           }
12875         }
12876       }
12877     }
12878   }
12879 
12880   if (!Definition)
12881     // Similar to friend functions a friend function template may be a
12882     // definition and do not have a body if it is instantiated in a class
12883     // template.
12884     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12885       for (auto I : FTD->redecls()) {
12886         auto D = cast<FunctionTemplateDecl>(I);
12887         if (D != FTD) {
12888           assert(!D->isThisDeclarationADefinition() &&
12889                  "More than one definition in redeclaration chain");
12890           if (D->getFriendObjectKind() != Decl::FOK_None)
12891             if (FunctionTemplateDecl *FT =
12892                                        D->getInstantiatedFromMemberTemplate()) {
12893               if (FT->isThisDeclarationADefinition()) {
12894                 Definition = D->getTemplatedDecl();
12895                 break;
12896               }
12897             }
12898         }
12899       }
12900     }
12901 
12902   if (!Definition)
12903     return;
12904 
12905   if (canRedefineFunction(Definition, getLangOpts()))
12906     return;
12907 
12908   // Don't emit an error when this is redefinition of a typo-corrected
12909   // definition.
12910   if (TypoCorrectedFunctionDefinitions.count(Definition))
12911     return;
12912 
12913   // If we don't have a visible definition of the function, and it's inline or
12914   // a template, skip the new definition.
12915   if (SkipBody && !hasVisibleDefinition(Definition) &&
12916       (Definition->getFormalLinkage() == InternalLinkage ||
12917        Definition->isInlined() ||
12918        Definition->getDescribedFunctionTemplate() ||
12919        Definition->getNumTemplateParameterLists())) {
12920     SkipBody->ShouldSkip = true;
12921     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12922     if (auto *TD = Definition->getDescribedFunctionTemplate())
12923       makeMergedDefinitionVisible(TD);
12924     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12925     return;
12926   }
12927 
12928   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12929       Definition->getStorageClass() == SC_Extern)
12930     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12931         << FD->getDeclName() << getLangOpts().CPlusPlus;
12932   else
12933     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12934 
12935   Diag(Definition->getLocation(), diag::note_previous_definition);
12936   FD->setInvalidDecl();
12937 }
12938 
12939 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12940                                    Sema &S) {
12941   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12942 
12943   LambdaScopeInfo *LSI = S.PushLambdaScope();
12944   LSI->CallOperator = CallOperator;
12945   LSI->Lambda = LambdaClass;
12946   LSI->ReturnType = CallOperator->getReturnType();
12947   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12948 
12949   if (LCD == LCD_None)
12950     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12951   else if (LCD == LCD_ByCopy)
12952     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12953   else if (LCD == LCD_ByRef)
12954     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12955   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12956 
12957   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12958   LSI->Mutable = !CallOperator->isConst();
12959 
12960   // Add the captures to the LSI so they can be noted as already
12961   // captured within tryCaptureVar.
12962   auto I = LambdaClass->field_begin();
12963   for (const auto &C : LambdaClass->captures()) {
12964     if (C.capturesVariable()) {
12965       VarDecl *VD = C.getCapturedVar();
12966       if (VD->isInitCapture())
12967         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12968       QualType CaptureType = VD->getType();
12969       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12970       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12971           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12972           /*EllipsisLoc*/C.isPackExpansion()
12973                          ? C.getEllipsisLoc() : SourceLocation(),
12974           CaptureType, /*Invalid*/false);
12975 
12976     } else if (C.capturesThis()) {
12977       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
12978                           C.getCaptureKind() == LCK_StarThis);
12979     } else {
12980       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
12981                              I->getType());
12982     }
12983     ++I;
12984   }
12985 }
12986 
12987 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12988                                     SkipBodyInfo *SkipBody) {
12989   if (!D) {
12990     // Parsing the function declaration failed in some way. Push on a fake scope
12991     // anyway so we can try to parse the function body.
12992     PushFunctionScope();
12993     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12994     return D;
12995   }
12996 
12997   FunctionDecl *FD = nullptr;
12998 
12999   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13000     FD = FunTmpl->getTemplatedDecl();
13001   else
13002     FD = cast<FunctionDecl>(D);
13003 
13004   // Do not push if it is a lambda because one is already pushed when building
13005   // the lambda in ActOnStartOfLambdaDefinition().
13006   if (!isLambdaCallOperator(FD))
13007     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13008 
13009   // Check for defining attributes before the check for redefinition.
13010   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13011     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13012     FD->dropAttr<AliasAttr>();
13013     FD->setInvalidDecl();
13014   }
13015   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13016     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13017     FD->dropAttr<IFuncAttr>();
13018     FD->setInvalidDecl();
13019   }
13020 
13021   // See if this is a redefinition. If 'will have body' is already set, then
13022   // these checks were already performed when it was set.
13023   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13024     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13025 
13026     // If we're skipping the body, we're done. Don't enter the scope.
13027     if (SkipBody && SkipBody->ShouldSkip)
13028       return D;
13029   }
13030 
13031   // Mark this function as "will have a body eventually".  This lets users to
13032   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13033   // this function.
13034   FD->setWillHaveBody();
13035 
13036   // If we are instantiating a generic lambda call operator, push
13037   // a LambdaScopeInfo onto the function stack.  But use the information
13038   // that's already been calculated (ActOnLambdaExpr) to prime the current
13039   // LambdaScopeInfo.
13040   // When the template operator is being specialized, the LambdaScopeInfo,
13041   // has to be properly restored so that tryCaptureVariable doesn't try
13042   // and capture any new variables. In addition when calculating potential
13043   // captures during transformation of nested lambdas, it is necessary to
13044   // have the LSI properly restored.
13045   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13046     assert(inTemplateInstantiation() &&
13047            "There should be an active template instantiation on the stack "
13048            "when instantiating a generic lambda!");
13049     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13050   } else {
13051     // Enter a new function scope
13052     PushFunctionScope();
13053   }
13054 
13055   // Builtin functions cannot be defined.
13056   if (unsigned BuiltinID = FD->getBuiltinID()) {
13057     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13058         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13059       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13060       FD->setInvalidDecl();
13061     }
13062   }
13063 
13064   // The return type of a function definition must be complete
13065   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13066   QualType ResultType = FD->getReturnType();
13067   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13068       !FD->isInvalidDecl() &&
13069       RequireCompleteType(FD->getLocation(), ResultType,
13070                           diag::err_func_def_incomplete_result))
13071     FD->setInvalidDecl();
13072 
13073   if (FnBodyScope)
13074     PushDeclContext(FnBodyScope, FD);
13075 
13076   // Check the validity of our function parameters
13077   CheckParmsForFunctionDef(FD->parameters(),
13078                            /*CheckParameterNames=*/true);
13079 
13080   // Add non-parameter declarations already in the function to the current
13081   // scope.
13082   if (FnBodyScope) {
13083     for (Decl *NPD : FD->decls()) {
13084       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13085       if (!NonParmDecl)
13086         continue;
13087       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13088              "parameters should not be in newly created FD yet");
13089 
13090       // If the decl has a name, make it accessible in the current scope.
13091       if (NonParmDecl->getDeclName())
13092         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13093 
13094       // Similarly, dive into enums and fish their constants out, making them
13095       // accessible in this scope.
13096       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13097         for (auto *EI : ED->enumerators())
13098           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13099       }
13100     }
13101   }
13102 
13103   // Introduce our parameters into the function scope
13104   for (auto Param : FD->parameters()) {
13105     Param->setOwningFunction(FD);
13106 
13107     // If this has an identifier, add it to the scope stack.
13108     if (Param->getIdentifier() && FnBodyScope) {
13109       CheckShadow(FnBodyScope, Param);
13110 
13111       PushOnScopeChains(Param, FnBodyScope);
13112     }
13113   }
13114 
13115   // Ensure that the function's exception specification is instantiated.
13116   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13117     ResolveExceptionSpec(D->getLocation(), FPT);
13118 
13119   // dllimport cannot be applied to non-inline function definitions.
13120   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13121       !FD->isTemplateInstantiation()) {
13122     assert(!FD->hasAttr<DLLExportAttr>());
13123     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13124     FD->setInvalidDecl();
13125     return D;
13126   }
13127   // We want to attach documentation to original Decl (which might be
13128   // a function template).
13129   ActOnDocumentableDecl(D);
13130   if (getCurLexicalContext()->isObjCContainer() &&
13131       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13132       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13133     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13134 
13135   return D;
13136 }
13137 
13138 /// Given the set of return statements within a function body,
13139 /// compute the variables that are subject to the named return value
13140 /// optimization.
13141 ///
13142 /// Each of the variables that is subject to the named return value
13143 /// optimization will be marked as NRVO variables in the AST, and any
13144 /// return statement that has a marked NRVO variable as its NRVO candidate can
13145 /// use the named return value optimization.
13146 ///
13147 /// This function applies a very simplistic algorithm for NRVO: if every return
13148 /// statement in the scope of a variable has the same NRVO candidate, that
13149 /// candidate is an NRVO variable.
13150 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13151   ReturnStmt **Returns = Scope->Returns.data();
13152 
13153   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13154     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13155       if (!NRVOCandidate->isNRVOVariable())
13156         Returns[I]->setNRVOCandidate(nullptr);
13157     }
13158   }
13159 }
13160 
13161 bool Sema::canDelayFunctionBody(const Declarator &D) {
13162   // We can't delay parsing the body of a constexpr function template (yet).
13163   if (D.getDeclSpec().hasConstexprSpecifier())
13164     return false;
13165 
13166   // We can't delay parsing the body of a function template with a deduced
13167   // return type (yet).
13168   if (D.getDeclSpec().hasAutoTypeSpec()) {
13169     // If the placeholder introduces a non-deduced trailing return type,
13170     // we can still delay parsing it.
13171     if (D.getNumTypeObjects()) {
13172       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13173       if (Outer.Kind == DeclaratorChunk::Function &&
13174           Outer.Fun.hasTrailingReturnType()) {
13175         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13176         return Ty.isNull() || !Ty->isUndeducedType();
13177       }
13178     }
13179     return false;
13180   }
13181 
13182   return true;
13183 }
13184 
13185 bool Sema::canSkipFunctionBody(Decl *D) {
13186   // We cannot skip the body of a function (or function template) which is
13187   // constexpr, since we may need to evaluate its body in order to parse the
13188   // rest of the file.
13189   // We cannot skip the body of a function with an undeduced return type,
13190   // because any callers of that function need to know the type.
13191   if (const FunctionDecl *FD = D->getAsFunction()) {
13192     if (FD->isConstexpr())
13193       return false;
13194     // We can't simply call Type::isUndeducedType here, because inside template
13195     // auto can be deduced to a dependent type, which is not considered
13196     // "undeduced".
13197     if (FD->getReturnType()->getContainedDeducedType())
13198       return false;
13199   }
13200   return Consumer.shouldSkipFunctionBody(D);
13201 }
13202 
13203 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13204   if (!Decl)
13205     return nullptr;
13206   if (FunctionDecl *FD = Decl->getAsFunction())
13207     FD->setHasSkippedBody();
13208   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13209     MD->setHasSkippedBody();
13210   return Decl;
13211 }
13212 
13213 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13214   return ActOnFinishFunctionBody(D, BodyArg, false);
13215 }
13216 
13217 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13218 /// body.
13219 class ExitFunctionBodyRAII {
13220 public:
13221   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13222   ~ExitFunctionBodyRAII() {
13223     if (!IsLambda)
13224       S.PopExpressionEvaluationContext();
13225   }
13226 
13227 private:
13228   Sema &S;
13229   bool IsLambda = false;
13230 };
13231 
13232 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13233   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13234 
13235   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13236     if (EscapeInfo.count(BD))
13237       return EscapeInfo[BD];
13238 
13239     bool R = false;
13240     const BlockDecl *CurBD = BD;
13241 
13242     do {
13243       R = !CurBD->doesNotEscape();
13244       if (R)
13245         break;
13246       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13247     } while (CurBD);
13248 
13249     return EscapeInfo[BD] = R;
13250   };
13251 
13252   // If the location where 'self' is implicitly retained is inside a escaping
13253   // block, emit a diagnostic.
13254   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13255        S.ImplicitlyRetainedSelfLocs)
13256     if (IsOrNestedInEscapingBlock(P.second))
13257       S.Diag(P.first, diag::warn_implicitly_retains_self)
13258           << FixItHint::CreateInsertion(P.first, "self->");
13259 }
13260 
13261 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13262                                     bool IsInstantiation) {
13263   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13264 
13265   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13266   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13267 
13268   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13269     CheckCompletedCoroutineBody(FD, Body);
13270 
13271   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13272   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13273   // meant to pop the context added in ActOnStartOfFunctionDef().
13274   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13275 
13276   if (FD) {
13277     FD->setBody(Body);
13278     FD->setWillHaveBody(false);
13279 
13280     if (getLangOpts().CPlusPlus14) {
13281       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13282           FD->getReturnType()->isUndeducedType()) {
13283         // If the function has a deduced result type but contains no 'return'
13284         // statements, the result type as written must be exactly 'auto', and
13285         // the deduced result type is 'void'.
13286         if (!FD->getReturnType()->getAs<AutoType>()) {
13287           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13288               << FD->getReturnType();
13289           FD->setInvalidDecl();
13290         } else {
13291           // Substitute 'void' for the 'auto' in the type.
13292           TypeLoc ResultType = getReturnTypeLoc(FD);
13293           Context.adjustDeducedFunctionResultType(
13294               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13295         }
13296       }
13297     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13298       // In C++11, we don't use 'auto' deduction rules for lambda call
13299       // operators because we don't support return type deduction.
13300       auto *LSI = getCurLambda();
13301       if (LSI->HasImplicitReturnType) {
13302         deduceClosureReturnType(*LSI);
13303 
13304         // C++11 [expr.prim.lambda]p4:
13305         //   [...] if there are no return statements in the compound-statement
13306         //   [the deduced type is] the type void
13307         QualType RetType =
13308             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13309 
13310         // Update the return type to the deduced type.
13311         const FunctionProtoType *Proto =
13312             FD->getType()->getAs<FunctionProtoType>();
13313         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13314                                             Proto->getExtProtoInfo()));
13315       }
13316     }
13317 
13318     // If the function implicitly returns zero (like 'main') or is naked,
13319     // don't complain about missing return statements.
13320     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13321       WP.disableCheckFallThrough();
13322 
13323     // MSVC permits the use of pure specifier (=0) on function definition,
13324     // defined at class scope, warn about this non-standard construct.
13325     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13326       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13327 
13328     if (!FD->isInvalidDecl()) {
13329       // Don't diagnose unused parameters of defaulted or deleted functions.
13330       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13331         DiagnoseUnusedParameters(FD->parameters());
13332       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13333                                              FD->getReturnType(), FD);
13334 
13335       // If this is a structor, we need a vtable.
13336       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13337         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13338       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13339         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13340 
13341       // Try to apply the named return value optimization. We have to check
13342       // if we can do this here because lambdas keep return statements around
13343       // to deduce an implicit return type.
13344       if (FD->getReturnType()->isRecordType() &&
13345           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13346         computeNRVO(Body, getCurFunction());
13347     }
13348 
13349     // GNU warning -Wmissing-prototypes:
13350     //   Warn if a global function is defined without a previous
13351     //   prototype declaration. This warning is issued even if the
13352     //   definition itself provides a prototype. The aim is to detect
13353     //   global functions that fail to be declared in header files.
13354     const FunctionDecl *PossiblePrototype = nullptr;
13355     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13356       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13357 
13358       if (PossiblePrototype) {
13359         // We found a declaration that is not a prototype,
13360         // but that could be a zero-parameter prototype
13361         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13362           TypeLoc TL = TI->getTypeLoc();
13363           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13364             Diag(PossiblePrototype->getLocation(),
13365                  diag::note_declaration_not_a_prototype)
13366                 << (FD->getNumParams() != 0)
13367                 << (FD->getNumParams() == 0
13368                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13369                         : FixItHint{});
13370         }
13371       } else {
13372         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13373             << /* function */ 1
13374             << (FD->getStorageClass() == SC_None
13375                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13376                                                  "static ")
13377                     : FixItHint{});
13378       }
13379 
13380       // GNU warning -Wstrict-prototypes
13381       //   Warn if K&R function is defined without a previous declaration.
13382       //   This warning is issued only if the definition itself does not provide
13383       //   a prototype. Only K&R definitions do not provide a prototype.
13384       //   An empty list in a function declarator that is part of a definition
13385       //   of that function specifies that the function has no parameters
13386       //   (C99 6.7.5.3p14)
13387       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13388           !LangOpts.CPlusPlus) {
13389         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13390         TypeLoc TL = TI->getTypeLoc();
13391         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13392         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13393       }
13394     }
13395 
13396     // Warn on CPUDispatch with an actual body.
13397     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13398       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13399         if (!CmpndBody->body_empty())
13400           Diag(CmpndBody->body_front()->getBeginLoc(),
13401                diag::warn_dispatch_body_ignored);
13402 
13403     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13404       const CXXMethodDecl *KeyFunction;
13405       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13406           MD->isVirtual() &&
13407           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13408           MD == KeyFunction->getCanonicalDecl()) {
13409         // Update the key-function state if necessary for this ABI.
13410         if (FD->isInlined() &&
13411             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13412           Context.setNonKeyFunction(MD);
13413 
13414           // If the newly-chosen key function is already defined, then we
13415           // need to mark the vtable as used retroactively.
13416           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13417           const FunctionDecl *Definition;
13418           if (KeyFunction && KeyFunction->isDefined(Definition))
13419             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13420         } else {
13421           // We just defined they key function; mark the vtable as used.
13422           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13423         }
13424       }
13425     }
13426 
13427     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13428            "Function parsing confused");
13429   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13430     assert(MD == getCurMethodDecl() && "Method parsing confused");
13431     MD->setBody(Body);
13432     if (!MD->isInvalidDecl()) {
13433       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13434                                              MD->getReturnType(), MD);
13435 
13436       if (Body)
13437         computeNRVO(Body, getCurFunction());
13438     }
13439     if (getCurFunction()->ObjCShouldCallSuper) {
13440       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13441           << MD->getSelector().getAsString();
13442       getCurFunction()->ObjCShouldCallSuper = false;
13443     }
13444     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13445       const ObjCMethodDecl *InitMethod = nullptr;
13446       bool isDesignated =
13447           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13448       assert(isDesignated && InitMethod);
13449       (void)isDesignated;
13450 
13451       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13452         auto IFace = MD->getClassInterface();
13453         if (!IFace)
13454           return false;
13455         auto SuperD = IFace->getSuperClass();
13456         if (!SuperD)
13457           return false;
13458         return SuperD->getIdentifier() ==
13459             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13460       };
13461       // Don't issue this warning for unavailable inits or direct subclasses
13462       // of NSObject.
13463       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13464         Diag(MD->getLocation(),
13465              diag::warn_objc_designated_init_missing_super_call);
13466         Diag(InitMethod->getLocation(),
13467              diag::note_objc_designated_init_marked_here);
13468       }
13469       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13470     }
13471     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13472       // Don't issue this warning for unavaialable inits.
13473       if (!MD->isUnavailable())
13474         Diag(MD->getLocation(),
13475              diag::warn_objc_secondary_init_missing_init_call);
13476       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13477     }
13478 
13479     diagnoseImplicitlyRetainedSelf(*this);
13480   } else {
13481     // Parsing the function declaration failed in some way. Pop the fake scope
13482     // we pushed on.
13483     PopFunctionScopeInfo(ActivePolicy, dcl);
13484     return nullptr;
13485   }
13486 
13487   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13488     DiagnoseUnguardedAvailabilityViolations(dcl);
13489 
13490   assert(!getCurFunction()->ObjCShouldCallSuper &&
13491          "This should only be set for ObjC methods, which should have been "
13492          "handled in the block above.");
13493 
13494   // Verify and clean out per-function state.
13495   if (Body && (!FD || !FD->isDefaulted())) {
13496     // C++ constructors that have function-try-blocks can't have return
13497     // statements in the handlers of that block. (C++ [except.handle]p14)
13498     // Verify this.
13499     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13500       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13501 
13502     // Verify that gotos and switch cases don't jump into scopes illegally.
13503     if (getCurFunction()->NeedsScopeChecking() &&
13504         !PP.isCodeCompletionEnabled())
13505       DiagnoseInvalidJumps(Body);
13506 
13507     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13508       if (!Destructor->getParent()->isDependentType())
13509         CheckDestructor(Destructor);
13510 
13511       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13512                                              Destructor->getParent());
13513     }
13514 
13515     // If any errors have occurred, clear out any temporaries that may have
13516     // been leftover. This ensures that these temporaries won't be picked up for
13517     // deletion in some later function.
13518     if (getDiagnostics().hasErrorOccurred() ||
13519         getDiagnostics().getSuppressAllDiagnostics()) {
13520       DiscardCleanupsInEvaluationContext();
13521     }
13522     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13523         !isa<FunctionTemplateDecl>(dcl)) {
13524       // Since the body is valid, issue any analysis-based warnings that are
13525       // enabled.
13526       ActivePolicy = &WP;
13527     }
13528 
13529     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13530         (!CheckConstexprFunctionDecl(FD) ||
13531          !CheckConstexprFunctionBody(FD, Body)))
13532       FD->setInvalidDecl();
13533 
13534     if (FD && FD->hasAttr<NakedAttr>()) {
13535       for (const Stmt *S : Body->children()) {
13536         // Allow local register variables without initializer as they don't
13537         // require prologue.
13538         bool RegisterVariables = false;
13539         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13540           for (const auto *Decl : DS->decls()) {
13541             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13542               RegisterVariables =
13543                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13544               if (!RegisterVariables)
13545                 break;
13546             }
13547           }
13548         }
13549         if (RegisterVariables)
13550           continue;
13551         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13552           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13553           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13554           FD->setInvalidDecl();
13555           break;
13556         }
13557       }
13558     }
13559 
13560     assert(ExprCleanupObjects.size() ==
13561                ExprEvalContexts.back().NumCleanupObjects &&
13562            "Leftover temporaries in function");
13563     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13564     assert(MaybeODRUseExprs.empty() &&
13565            "Leftover expressions for odr-use checking");
13566   }
13567 
13568   if (!IsInstantiation)
13569     PopDeclContext();
13570 
13571   PopFunctionScopeInfo(ActivePolicy, dcl);
13572   // If any errors have occurred, clear out any temporaries that may have
13573   // been leftover. This ensures that these temporaries won't be picked up for
13574   // deletion in some later function.
13575   if (getDiagnostics().hasErrorOccurred()) {
13576     DiscardCleanupsInEvaluationContext();
13577   }
13578 
13579   return dcl;
13580 }
13581 
13582 /// When we finish delayed parsing of an attribute, we must attach it to the
13583 /// relevant Decl.
13584 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13585                                        ParsedAttributes &Attrs) {
13586   // Always attach attributes to the underlying decl.
13587   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13588     D = TD->getTemplatedDecl();
13589   ProcessDeclAttributeList(S, D, Attrs);
13590 
13591   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13592     if (Method->isStatic())
13593       checkThisInStaticMemberFunctionAttributes(Method);
13594 }
13595 
13596 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13597 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13598 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13599                                           IdentifierInfo &II, Scope *S) {
13600   // Find the scope in which the identifier is injected and the corresponding
13601   // DeclContext.
13602   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13603   // In that case, we inject the declaration into the translation unit scope
13604   // instead.
13605   Scope *BlockScope = S;
13606   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13607     BlockScope = BlockScope->getParent();
13608 
13609   Scope *ContextScope = BlockScope;
13610   while (!ContextScope->getEntity())
13611     ContextScope = ContextScope->getParent();
13612   ContextRAII SavedContext(*this, ContextScope->getEntity());
13613 
13614   // Before we produce a declaration for an implicitly defined
13615   // function, see whether there was a locally-scoped declaration of
13616   // this name as a function or variable. If so, use that
13617   // (non-visible) declaration, and complain about it.
13618   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13619   if (ExternCPrev) {
13620     // We still need to inject the function into the enclosing block scope so
13621     // that later (non-call) uses can see it.
13622     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13623 
13624     // C89 footnote 38:
13625     //   If in fact it is not defined as having type "function returning int",
13626     //   the behavior is undefined.
13627     if (!isa<FunctionDecl>(ExternCPrev) ||
13628         !Context.typesAreCompatible(
13629             cast<FunctionDecl>(ExternCPrev)->getType(),
13630             Context.getFunctionNoProtoType(Context.IntTy))) {
13631       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13632           << ExternCPrev << !getLangOpts().C99;
13633       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13634       return ExternCPrev;
13635     }
13636   }
13637 
13638   // Extension in C99.  Legal in C90, but warn about it.
13639   unsigned diag_id;
13640   if (II.getName().startswith("__builtin_"))
13641     diag_id = diag::warn_builtin_unknown;
13642   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13643   else if (getLangOpts().OpenCL)
13644     diag_id = diag::err_opencl_implicit_function_decl;
13645   else if (getLangOpts().C99)
13646     diag_id = diag::ext_implicit_function_decl;
13647   else
13648     diag_id = diag::warn_implicit_function_decl;
13649   Diag(Loc, diag_id) << &II;
13650 
13651   // If we found a prior declaration of this function, don't bother building
13652   // another one. We've already pushed that one into scope, so there's nothing
13653   // more to do.
13654   if (ExternCPrev)
13655     return ExternCPrev;
13656 
13657   // Because typo correction is expensive, only do it if the implicit
13658   // function declaration is going to be treated as an error.
13659   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13660     TypoCorrection Corrected;
13661     DeclFilterCCC<FunctionDecl> CCC{};
13662     if (S && (Corrected =
13663                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
13664                               S, nullptr, CCC, CTK_NonError)))
13665       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13666                    /*ErrorRecovery*/false);
13667   }
13668 
13669   // Set a Declarator for the implicit definition: int foo();
13670   const char *Dummy;
13671   AttributeFactory attrFactory;
13672   DeclSpec DS(attrFactory);
13673   unsigned DiagID;
13674   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13675                                   Context.getPrintingPolicy());
13676   (void)Error; // Silence warning.
13677   assert(!Error && "Error setting up implicit decl!");
13678   SourceLocation NoLoc;
13679   Declarator D(DS, DeclaratorContext::BlockContext);
13680   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13681                                              /*IsAmbiguous=*/false,
13682                                              /*LParenLoc=*/NoLoc,
13683                                              /*Params=*/nullptr,
13684                                              /*NumParams=*/0,
13685                                              /*EllipsisLoc=*/NoLoc,
13686                                              /*RParenLoc=*/NoLoc,
13687                                              /*RefQualifierIsLvalueRef=*/true,
13688                                              /*RefQualifierLoc=*/NoLoc,
13689                                              /*MutableLoc=*/NoLoc, EST_None,
13690                                              /*ESpecRange=*/SourceRange(),
13691                                              /*Exceptions=*/nullptr,
13692                                              /*ExceptionRanges=*/nullptr,
13693                                              /*NumExceptions=*/0,
13694                                              /*NoexceptExpr=*/nullptr,
13695                                              /*ExceptionSpecTokens=*/nullptr,
13696                                              /*DeclsInPrototype=*/None, Loc,
13697                                              Loc, D),
13698                 std::move(DS.getAttributes()), SourceLocation());
13699   D.SetIdentifier(&II, Loc);
13700 
13701   // Insert this function into the enclosing block scope.
13702   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13703   FD->setImplicit();
13704 
13705   AddKnownFunctionAttributes(FD);
13706 
13707   return FD;
13708 }
13709 
13710 /// Adds any function attributes that we know a priori based on
13711 /// the declaration of this function.
13712 ///
13713 /// These attributes can apply both to implicitly-declared builtins
13714 /// (like __builtin___printf_chk) or to library-declared functions
13715 /// like NSLog or printf.
13716 ///
13717 /// We need to check for duplicate attributes both here and where user-written
13718 /// attributes are applied to declarations.
13719 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13720   if (FD->isInvalidDecl())
13721     return;
13722 
13723   // If this is a built-in function, map its builtin attributes to
13724   // actual attributes.
13725   if (unsigned BuiltinID = FD->getBuiltinID()) {
13726     // Handle printf-formatting attributes.
13727     unsigned FormatIdx;
13728     bool HasVAListArg;
13729     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13730       if (!FD->hasAttr<FormatAttr>()) {
13731         const char *fmt = "printf";
13732         unsigned int NumParams = FD->getNumParams();
13733         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13734             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13735           fmt = "NSString";
13736         FD->addAttr(FormatAttr::CreateImplicit(Context,
13737                                                &Context.Idents.get(fmt),
13738                                                FormatIdx+1,
13739                                                HasVAListArg ? 0 : FormatIdx+2,
13740                                                FD->getLocation()));
13741       }
13742     }
13743     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13744                                              HasVAListArg)) {
13745      if (!FD->hasAttr<FormatAttr>())
13746        FD->addAttr(FormatAttr::CreateImplicit(Context,
13747                                               &Context.Idents.get("scanf"),
13748                                               FormatIdx+1,
13749                                               HasVAListArg ? 0 : FormatIdx+2,
13750                                               FD->getLocation()));
13751     }
13752 
13753     // Handle automatically recognized callbacks.
13754     SmallVector<int, 4> Encoding;
13755     if (!FD->hasAttr<CallbackAttr>() &&
13756         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13757       FD->addAttr(CallbackAttr::CreateImplicit(
13758           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13759 
13760     // Mark const if we don't care about errno and that is the only thing
13761     // preventing the function from being const. This allows IRgen to use LLVM
13762     // intrinsics for such functions.
13763     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13764         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13765       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13766 
13767     // We make "fma" on some platforms const because we know it does not set
13768     // errno in those environments even though it could set errno based on the
13769     // C standard.
13770     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13771     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13772         !FD->hasAttr<ConstAttr>()) {
13773       switch (BuiltinID) {
13774       case Builtin::BI__builtin_fma:
13775       case Builtin::BI__builtin_fmaf:
13776       case Builtin::BI__builtin_fmal:
13777       case Builtin::BIfma:
13778       case Builtin::BIfmaf:
13779       case Builtin::BIfmal:
13780         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13781         break;
13782       default:
13783         break;
13784       }
13785     }
13786 
13787     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13788         !FD->hasAttr<ReturnsTwiceAttr>())
13789       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13790                                          FD->getLocation()));
13791     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13792       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13793     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13794       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13795     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13796       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13797     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13798         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13799       // Add the appropriate attribute, depending on the CUDA compilation mode
13800       // and which target the builtin belongs to. For example, during host
13801       // compilation, aux builtins are __device__, while the rest are __host__.
13802       if (getLangOpts().CUDAIsDevice !=
13803           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13804         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13805       else
13806         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13807     }
13808   }
13809 
13810   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13811   // throw, add an implicit nothrow attribute to any extern "C" function we come
13812   // across.
13813   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13814       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13815     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13816     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13817       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13818   }
13819 
13820   IdentifierInfo *Name = FD->getIdentifier();
13821   if (!Name)
13822     return;
13823   if ((!getLangOpts().CPlusPlus &&
13824        FD->getDeclContext()->isTranslationUnit()) ||
13825       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13826        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13827        LinkageSpecDecl::lang_c)) {
13828     // Okay: this could be a libc/libm/Objective-C function we know
13829     // about.
13830   } else
13831     return;
13832 
13833   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13834     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13835     // target-specific builtins, perhaps?
13836     if (!FD->hasAttr<FormatAttr>())
13837       FD->addAttr(FormatAttr::CreateImplicit(Context,
13838                                              &Context.Idents.get("printf"), 2,
13839                                              Name->isStr("vasprintf") ? 0 : 3,
13840                                              FD->getLocation()));
13841   }
13842 
13843   if (Name->isStr("__CFStringMakeConstantString")) {
13844     // We already have a __builtin___CFStringMakeConstantString,
13845     // but builds that use -fno-constant-cfstrings don't go through that.
13846     if (!FD->hasAttr<FormatArgAttr>())
13847       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13848                                                 FD->getLocation()));
13849   }
13850 }
13851 
13852 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13853                                     TypeSourceInfo *TInfo) {
13854   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13855   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13856 
13857   if (!TInfo) {
13858     assert(D.isInvalidType() && "no declarator info for valid type");
13859     TInfo = Context.getTrivialTypeSourceInfo(T);
13860   }
13861 
13862   // Scope manipulation handled by caller.
13863   TypedefDecl *NewTD =
13864       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13865                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13866 
13867   // Bail out immediately if we have an invalid declaration.
13868   if (D.isInvalidType()) {
13869     NewTD->setInvalidDecl();
13870     return NewTD;
13871   }
13872 
13873   if (D.getDeclSpec().isModulePrivateSpecified()) {
13874     if (CurContext->isFunctionOrMethod())
13875       Diag(NewTD->getLocation(), diag::err_module_private_local)
13876         << 2 << NewTD->getDeclName()
13877         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13878         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13879     else
13880       NewTD->setModulePrivate();
13881   }
13882 
13883   // C++ [dcl.typedef]p8:
13884   //   If the typedef declaration defines an unnamed class (or
13885   //   enum), the first typedef-name declared by the declaration
13886   //   to be that class type (or enum type) is used to denote the
13887   //   class type (or enum type) for linkage purposes only.
13888   // We need to check whether the type was declared in the declaration.
13889   switch (D.getDeclSpec().getTypeSpecType()) {
13890   case TST_enum:
13891   case TST_struct:
13892   case TST_interface:
13893   case TST_union:
13894   case TST_class: {
13895     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13896     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13897     break;
13898   }
13899 
13900   default:
13901     break;
13902   }
13903 
13904   return NewTD;
13905 }
13906 
13907 /// Check that this is a valid underlying type for an enum declaration.
13908 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13909   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13910   QualType T = TI->getType();
13911 
13912   if (T->isDependentType())
13913     return false;
13914 
13915   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13916     if (BT->isInteger())
13917       return false;
13918 
13919   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13920   return true;
13921 }
13922 
13923 /// Check whether this is a valid redeclaration of a previous enumeration.
13924 /// \return true if the redeclaration was invalid.
13925 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13926                                   QualType EnumUnderlyingTy, bool IsFixed,
13927                                   const EnumDecl *Prev) {
13928   if (IsScoped != Prev->isScoped()) {
13929     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13930       << Prev->isScoped();
13931     Diag(Prev->getLocation(), diag::note_previous_declaration);
13932     return true;
13933   }
13934 
13935   if (IsFixed && Prev->isFixed()) {
13936     if (!EnumUnderlyingTy->isDependentType() &&
13937         !Prev->getIntegerType()->isDependentType() &&
13938         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13939                                         Prev->getIntegerType())) {
13940       // TODO: Highlight the underlying type of the redeclaration.
13941       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13942         << EnumUnderlyingTy << Prev->getIntegerType();
13943       Diag(Prev->getLocation(), diag::note_previous_declaration)
13944           << Prev->getIntegerTypeRange();
13945       return true;
13946     }
13947   } else if (IsFixed != Prev->isFixed()) {
13948     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13949       << Prev->isFixed();
13950     Diag(Prev->getLocation(), diag::note_previous_declaration);
13951     return true;
13952   }
13953 
13954   return false;
13955 }
13956 
13957 /// Get diagnostic %select index for tag kind for
13958 /// redeclaration diagnostic message.
13959 /// WARNING: Indexes apply to particular diagnostics only!
13960 ///
13961 /// \returns diagnostic %select index.
13962 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13963   switch (Tag) {
13964   case TTK_Struct: return 0;
13965   case TTK_Interface: return 1;
13966   case TTK_Class:  return 2;
13967   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13968   }
13969 }
13970 
13971 /// Determine if tag kind is a class-key compatible with
13972 /// class for redeclaration (class, struct, or __interface).
13973 ///
13974 /// \returns true iff the tag kind is compatible.
13975 static bool isClassCompatTagKind(TagTypeKind Tag)
13976 {
13977   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13978 }
13979 
13980 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13981                                              TagTypeKind TTK) {
13982   if (isa<TypedefDecl>(PrevDecl))
13983     return NTK_Typedef;
13984   else if (isa<TypeAliasDecl>(PrevDecl))
13985     return NTK_TypeAlias;
13986   else if (isa<ClassTemplateDecl>(PrevDecl))
13987     return NTK_Template;
13988   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13989     return NTK_TypeAliasTemplate;
13990   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13991     return NTK_TemplateTemplateArgument;
13992   switch (TTK) {
13993   case TTK_Struct:
13994   case TTK_Interface:
13995   case TTK_Class:
13996     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13997   case TTK_Union:
13998     return NTK_NonUnion;
13999   case TTK_Enum:
14000     return NTK_NonEnum;
14001   }
14002   llvm_unreachable("invalid TTK");
14003 }
14004 
14005 /// Determine whether a tag with a given kind is acceptable
14006 /// as a redeclaration of the given tag declaration.
14007 ///
14008 /// \returns true if the new tag kind is acceptable, false otherwise.
14009 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14010                                         TagTypeKind NewTag, bool isDefinition,
14011                                         SourceLocation NewTagLoc,
14012                                         const IdentifierInfo *Name) {
14013   // C++ [dcl.type.elab]p3:
14014   //   The class-key or enum keyword present in the
14015   //   elaborated-type-specifier shall agree in kind with the
14016   //   declaration to which the name in the elaborated-type-specifier
14017   //   refers. This rule also applies to the form of
14018   //   elaborated-type-specifier that declares a class-name or
14019   //   friend class since it can be construed as referring to the
14020   //   definition of the class. Thus, in any
14021   //   elaborated-type-specifier, the enum keyword shall be used to
14022   //   refer to an enumeration (7.2), the union class-key shall be
14023   //   used to refer to a union (clause 9), and either the class or
14024   //   struct class-key shall be used to refer to a class (clause 9)
14025   //   declared using the class or struct class-key.
14026   TagTypeKind OldTag = Previous->getTagKind();
14027   if (OldTag != NewTag &&
14028       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14029     return false;
14030 
14031   // Tags are compatible, but we might still want to warn on mismatched tags.
14032   // Non-class tags can't be mismatched at this point.
14033   if (!isClassCompatTagKind(NewTag))
14034     return true;
14035 
14036   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14037   // by our warning analysis. We don't want to warn about mismatches with (eg)
14038   // declarations in system headers that are designed to be specialized, but if
14039   // a user asks us to warn, we should warn if their code contains mismatched
14040   // declarations.
14041   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14042     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14043                                       Loc);
14044   };
14045   if (IsIgnoredLoc(NewTagLoc))
14046     return true;
14047 
14048   auto IsIgnored = [&](const TagDecl *Tag) {
14049     return IsIgnoredLoc(Tag->getLocation());
14050   };
14051   while (IsIgnored(Previous)) {
14052     Previous = Previous->getPreviousDecl();
14053     if (!Previous)
14054       return true;
14055     OldTag = Previous->getTagKind();
14056   }
14057 
14058   bool isTemplate = false;
14059   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14060     isTemplate = Record->getDescribedClassTemplate();
14061 
14062   if (inTemplateInstantiation()) {
14063     if (OldTag != NewTag) {
14064       // In a template instantiation, do not offer fix-its for tag mismatches
14065       // since they usually mess up the template instead of fixing the problem.
14066       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14067         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14068         << getRedeclDiagFromTagKind(OldTag);
14069       // FIXME: Note previous location?
14070     }
14071     return true;
14072   }
14073 
14074   if (isDefinition) {
14075     // On definitions, check all previous tags and issue a fix-it for each
14076     // one that doesn't match the current tag.
14077     if (Previous->getDefinition()) {
14078       // Don't suggest fix-its for redefinitions.
14079       return true;
14080     }
14081 
14082     bool previousMismatch = false;
14083     for (const TagDecl *I : Previous->redecls()) {
14084       if (I->getTagKind() != NewTag) {
14085         // Ignore previous declarations for which the warning was disabled.
14086         if (IsIgnored(I))
14087           continue;
14088 
14089         if (!previousMismatch) {
14090           previousMismatch = true;
14091           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14092             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14093             << getRedeclDiagFromTagKind(I->getTagKind());
14094         }
14095         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14096           << getRedeclDiagFromTagKind(NewTag)
14097           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14098                TypeWithKeyword::getTagTypeKindName(NewTag));
14099       }
14100     }
14101     return true;
14102   }
14103 
14104   // Identify the prevailing tag kind: this is the kind of the definition (if
14105   // there is a non-ignored definition), or otherwise the kind of the prior
14106   // (non-ignored) declaration.
14107   const TagDecl *PrevDef = Previous->getDefinition();
14108   if (PrevDef && IsIgnored(PrevDef))
14109     PrevDef = nullptr;
14110   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14111   if (Redecl->getTagKind() != NewTag) {
14112     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14113       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14114       << getRedeclDiagFromTagKind(OldTag);
14115     Diag(Redecl->getLocation(), diag::note_previous_use);
14116 
14117     // If there is a previous definition, suggest a fix-it.
14118     if (PrevDef) {
14119       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14120         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14121         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14122              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14123     }
14124   }
14125 
14126   return true;
14127 }
14128 
14129 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14130 /// from an outer enclosing namespace or file scope inside a friend declaration.
14131 /// This should provide the commented out code in the following snippet:
14132 ///   namespace N {
14133 ///     struct X;
14134 ///     namespace M {
14135 ///       struct Y { friend struct /*N::*/ X; };
14136 ///     }
14137 ///   }
14138 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14139                                          SourceLocation NameLoc) {
14140   // While the decl is in a namespace, do repeated lookup of that name and see
14141   // if we get the same namespace back.  If we do not, continue until
14142   // translation unit scope, at which point we have a fully qualified NNS.
14143   SmallVector<IdentifierInfo *, 4> Namespaces;
14144   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14145   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14146     // This tag should be declared in a namespace, which can only be enclosed by
14147     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14148     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14149     if (!Namespace || Namespace->isAnonymousNamespace())
14150       return FixItHint();
14151     IdentifierInfo *II = Namespace->getIdentifier();
14152     Namespaces.push_back(II);
14153     NamedDecl *Lookup = SemaRef.LookupSingleName(
14154         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14155     if (Lookup == Namespace)
14156       break;
14157   }
14158 
14159   // Once we have all the namespaces, reverse them to go outermost first, and
14160   // build an NNS.
14161   SmallString<64> Insertion;
14162   llvm::raw_svector_ostream OS(Insertion);
14163   if (DC->isTranslationUnit())
14164     OS << "::";
14165   std::reverse(Namespaces.begin(), Namespaces.end());
14166   for (auto *II : Namespaces)
14167     OS << II->getName() << "::";
14168   return FixItHint::CreateInsertion(NameLoc, Insertion);
14169 }
14170 
14171 /// Determine whether a tag originally declared in context \p OldDC can
14172 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14173 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14174 /// using-declaration).
14175 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14176                                          DeclContext *NewDC) {
14177   OldDC = OldDC->getRedeclContext();
14178   NewDC = NewDC->getRedeclContext();
14179 
14180   if (OldDC->Equals(NewDC))
14181     return true;
14182 
14183   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14184   // encloses the other).
14185   if (S.getLangOpts().MSVCCompat &&
14186       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14187     return true;
14188 
14189   return false;
14190 }
14191 
14192 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14193 /// former case, Name will be non-null.  In the later case, Name will be null.
14194 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14195 /// reference/declaration/definition of a tag.
14196 ///
14197 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14198 /// trailing-type-specifier) other than one in an alias-declaration.
14199 ///
14200 /// \param SkipBody If non-null, will be set to indicate if the caller should
14201 /// skip the definition of this tag and treat it as if it were a declaration.
14202 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14203                      SourceLocation KWLoc, CXXScopeSpec &SS,
14204                      IdentifierInfo *Name, SourceLocation NameLoc,
14205                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14206                      SourceLocation ModulePrivateLoc,
14207                      MultiTemplateParamsArg TemplateParameterLists,
14208                      bool &OwnedDecl, bool &IsDependent,
14209                      SourceLocation ScopedEnumKWLoc,
14210                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14211                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14212                      SkipBodyInfo *SkipBody) {
14213   // If this is not a definition, it must have a name.
14214   IdentifierInfo *OrigName = Name;
14215   assert((Name != nullptr || TUK == TUK_Definition) &&
14216          "Nameless record must be a definition!");
14217   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14218 
14219   OwnedDecl = false;
14220   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14221   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14222 
14223   // FIXME: Check member specializations more carefully.
14224   bool isMemberSpecialization = false;
14225   bool Invalid = false;
14226 
14227   // We only need to do this matching if we have template parameters
14228   // or a scope specifier, which also conveniently avoids this work
14229   // for non-C++ cases.
14230   if (TemplateParameterLists.size() > 0 ||
14231       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14232     if (TemplateParameterList *TemplateParams =
14233             MatchTemplateParametersToScopeSpecifier(
14234                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14235                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14236       if (Kind == TTK_Enum) {
14237         Diag(KWLoc, diag::err_enum_template);
14238         return nullptr;
14239       }
14240 
14241       if (TemplateParams->size() > 0) {
14242         // This is a declaration or definition of a class template (which may
14243         // be a member of another template).
14244 
14245         if (Invalid)
14246           return nullptr;
14247 
14248         OwnedDecl = false;
14249         DeclResult Result = CheckClassTemplate(
14250             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14251             AS, ModulePrivateLoc,
14252             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14253             TemplateParameterLists.data(), SkipBody);
14254         return Result.get();
14255       } else {
14256         // The "template<>" header is extraneous.
14257         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14258           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14259         isMemberSpecialization = true;
14260       }
14261     }
14262   }
14263 
14264   // Figure out the underlying type if this a enum declaration. We need to do
14265   // this early, because it's needed to detect if this is an incompatible
14266   // redeclaration.
14267   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14268   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14269 
14270   if (Kind == TTK_Enum) {
14271     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14272       // No underlying type explicitly specified, or we failed to parse the
14273       // type, default to int.
14274       EnumUnderlying = Context.IntTy.getTypePtr();
14275     } else if (UnderlyingType.get()) {
14276       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14277       // integral type; any cv-qualification is ignored.
14278       TypeSourceInfo *TI = nullptr;
14279       GetTypeFromParser(UnderlyingType.get(), &TI);
14280       EnumUnderlying = TI;
14281 
14282       if (CheckEnumUnderlyingType(TI))
14283         // Recover by falling back to int.
14284         EnumUnderlying = Context.IntTy.getTypePtr();
14285 
14286       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14287                                           UPPC_FixedUnderlyingType))
14288         EnumUnderlying = Context.IntTy.getTypePtr();
14289 
14290     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14291       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14292       // of 'int'. However, if this is an unfixed forward declaration, don't set
14293       // the underlying type unless the user enables -fms-compatibility. This
14294       // makes unfixed forward declared enums incomplete and is more conforming.
14295       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14296         EnumUnderlying = Context.IntTy.getTypePtr();
14297     }
14298   }
14299 
14300   DeclContext *SearchDC = CurContext;
14301   DeclContext *DC = CurContext;
14302   bool isStdBadAlloc = false;
14303   bool isStdAlignValT = false;
14304 
14305   RedeclarationKind Redecl = forRedeclarationInCurContext();
14306   if (TUK == TUK_Friend || TUK == TUK_Reference)
14307     Redecl = NotForRedeclaration;
14308 
14309   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14310   /// implemented asks for structural equivalence checking, the returned decl
14311   /// here is passed back to the parser, allowing the tag body to be parsed.
14312   auto createTagFromNewDecl = [&]() -> TagDecl * {
14313     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14314     // If there is an identifier, use the location of the identifier as the
14315     // location of the decl, otherwise use the location of the struct/union
14316     // keyword.
14317     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14318     TagDecl *New = nullptr;
14319 
14320     if (Kind == TTK_Enum) {
14321       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14322                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14323       // If this is an undefined enum, bail.
14324       if (TUK != TUK_Definition && !Invalid)
14325         return nullptr;
14326       if (EnumUnderlying) {
14327         EnumDecl *ED = cast<EnumDecl>(New);
14328         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14329           ED->setIntegerTypeSourceInfo(TI);
14330         else
14331           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14332         ED->setPromotionType(ED->getIntegerType());
14333       }
14334     } else { // struct/union
14335       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14336                                nullptr);
14337     }
14338 
14339     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14340       // Add alignment attributes if necessary; these attributes are checked
14341       // when the ASTContext lays out the structure.
14342       //
14343       // It is important for implementing the correct semantics that this
14344       // happen here (in ActOnTag). The #pragma pack stack is
14345       // maintained as a result of parser callbacks which can occur at
14346       // many points during the parsing of a struct declaration (because
14347       // the #pragma tokens are effectively skipped over during the
14348       // parsing of the struct).
14349       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14350         AddAlignmentAttributesForRecord(RD);
14351         AddMsStructLayoutForRecord(RD);
14352       }
14353     }
14354     New->setLexicalDeclContext(CurContext);
14355     return New;
14356   };
14357 
14358   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14359   if (Name && SS.isNotEmpty()) {
14360     // We have a nested-name tag ('struct foo::bar').
14361 
14362     // Check for invalid 'foo::'.
14363     if (SS.isInvalid()) {
14364       Name = nullptr;
14365       goto CreateNewDecl;
14366     }
14367 
14368     // If this is a friend or a reference to a class in a dependent
14369     // context, don't try to make a decl for it.
14370     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14371       DC = computeDeclContext(SS, false);
14372       if (!DC) {
14373         IsDependent = true;
14374         return nullptr;
14375       }
14376     } else {
14377       DC = computeDeclContext(SS, true);
14378       if (!DC) {
14379         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14380           << SS.getRange();
14381         return nullptr;
14382       }
14383     }
14384 
14385     if (RequireCompleteDeclContext(SS, DC))
14386       return nullptr;
14387 
14388     SearchDC = DC;
14389     // Look-up name inside 'foo::'.
14390     LookupQualifiedName(Previous, DC);
14391 
14392     if (Previous.isAmbiguous())
14393       return nullptr;
14394 
14395     if (Previous.empty()) {
14396       // Name lookup did not find anything. However, if the
14397       // nested-name-specifier refers to the current instantiation,
14398       // and that current instantiation has any dependent base
14399       // classes, we might find something at instantiation time: treat
14400       // this as a dependent elaborated-type-specifier.
14401       // But this only makes any sense for reference-like lookups.
14402       if (Previous.wasNotFoundInCurrentInstantiation() &&
14403           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14404         IsDependent = true;
14405         return nullptr;
14406       }
14407 
14408       // A tag 'foo::bar' must already exist.
14409       Diag(NameLoc, diag::err_not_tag_in_scope)
14410         << Kind << Name << DC << SS.getRange();
14411       Name = nullptr;
14412       Invalid = true;
14413       goto CreateNewDecl;
14414     }
14415   } else if (Name) {
14416     // C++14 [class.mem]p14:
14417     //   If T is the name of a class, then each of the following shall have a
14418     //   name different from T:
14419     //    -- every member of class T that is itself a type
14420     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14421         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14422       return nullptr;
14423 
14424     // If this is a named struct, check to see if there was a previous forward
14425     // declaration or definition.
14426     // FIXME: We're looking into outer scopes here, even when we
14427     // shouldn't be. Doing so can result in ambiguities that we
14428     // shouldn't be diagnosing.
14429     LookupName(Previous, S);
14430 
14431     // When declaring or defining a tag, ignore ambiguities introduced
14432     // by types using'ed into this scope.
14433     if (Previous.isAmbiguous() &&
14434         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14435       LookupResult::Filter F = Previous.makeFilter();
14436       while (F.hasNext()) {
14437         NamedDecl *ND = F.next();
14438         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14439                 SearchDC->getRedeclContext()))
14440           F.erase();
14441       }
14442       F.done();
14443     }
14444 
14445     // C++11 [namespace.memdef]p3:
14446     //   If the name in a friend declaration is neither qualified nor
14447     //   a template-id and the declaration is a function or an
14448     //   elaborated-type-specifier, the lookup to determine whether
14449     //   the entity has been previously declared shall not consider
14450     //   any scopes outside the innermost enclosing namespace.
14451     //
14452     // MSVC doesn't implement the above rule for types, so a friend tag
14453     // declaration may be a redeclaration of a type declared in an enclosing
14454     // scope.  They do implement this rule for friend functions.
14455     //
14456     // Does it matter that this should be by scope instead of by
14457     // semantic context?
14458     if (!Previous.empty() && TUK == TUK_Friend) {
14459       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14460       LookupResult::Filter F = Previous.makeFilter();
14461       bool FriendSawTagOutsideEnclosingNamespace = false;
14462       while (F.hasNext()) {
14463         NamedDecl *ND = F.next();
14464         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14465         if (DC->isFileContext() &&
14466             !EnclosingNS->Encloses(ND->getDeclContext())) {
14467           if (getLangOpts().MSVCCompat)
14468             FriendSawTagOutsideEnclosingNamespace = true;
14469           else
14470             F.erase();
14471         }
14472       }
14473       F.done();
14474 
14475       // Diagnose this MSVC extension in the easy case where lookup would have
14476       // unambiguously found something outside the enclosing namespace.
14477       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14478         NamedDecl *ND = Previous.getFoundDecl();
14479         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14480             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14481       }
14482     }
14483 
14484     // Note:  there used to be some attempt at recovery here.
14485     if (Previous.isAmbiguous())
14486       return nullptr;
14487 
14488     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14489       // FIXME: This makes sure that we ignore the contexts associated
14490       // with C structs, unions, and enums when looking for a matching
14491       // tag declaration or definition. See the similar lookup tweak
14492       // in Sema::LookupName; is there a better way to deal with this?
14493       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14494         SearchDC = SearchDC->getParent();
14495     }
14496   }
14497 
14498   if (Previous.isSingleResult() &&
14499       Previous.getFoundDecl()->isTemplateParameter()) {
14500     // Maybe we will complain about the shadowed template parameter.
14501     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14502     // Just pretend that we didn't see the previous declaration.
14503     Previous.clear();
14504   }
14505 
14506   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14507       DC->Equals(getStdNamespace())) {
14508     if (Name->isStr("bad_alloc")) {
14509       // This is a declaration of or a reference to "std::bad_alloc".
14510       isStdBadAlloc = true;
14511 
14512       // If std::bad_alloc has been implicitly declared (but made invisible to
14513       // name lookup), fill in this implicit declaration as the previous
14514       // declaration, so that the declarations get chained appropriately.
14515       if (Previous.empty() && StdBadAlloc)
14516         Previous.addDecl(getStdBadAlloc());
14517     } else if (Name->isStr("align_val_t")) {
14518       isStdAlignValT = true;
14519       if (Previous.empty() && StdAlignValT)
14520         Previous.addDecl(getStdAlignValT());
14521     }
14522   }
14523 
14524   // If we didn't find a previous declaration, and this is a reference
14525   // (or friend reference), move to the correct scope.  In C++, we
14526   // also need to do a redeclaration lookup there, just in case
14527   // there's a shadow friend decl.
14528   if (Name && Previous.empty() &&
14529       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14530     if (Invalid) goto CreateNewDecl;
14531     assert(SS.isEmpty());
14532 
14533     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14534       // C++ [basic.scope.pdecl]p5:
14535       //   -- for an elaborated-type-specifier of the form
14536       //
14537       //          class-key identifier
14538       //
14539       //      if the elaborated-type-specifier is used in the
14540       //      decl-specifier-seq or parameter-declaration-clause of a
14541       //      function defined in namespace scope, the identifier is
14542       //      declared as a class-name in the namespace that contains
14543       //      the declaration; otherwise, except as a friend
14544       //      declaration, the identifier is declared in the smallest
14545       //      non-class, non-function-prototype scope that contains the
14546       //      declaration.
14547       //
14548       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14549       // C structs and unions.
14550       //
14551       // It is an error in C++ to declare (rather than define) an enum
14552       // type, including via an elaborated type specifier.  We'll
14553       // diagnose that later; for now, declare the enum in the same
14554       // scope as we would have picked for any other tag type.
14555       //
14556       // GNU C also supports this behavior as part of its incomplete
14557       // enum types extension, while GNU C++ does not.
14558       //
14559       // Find the context where we'll be declaring the tag.
14560       // FIXME: We would like to maintain the current DeclContext as the
14561       // lexical context,
14562       SearchDC = getTagInjectionContext(SearchDC);
14563 
14564       // Find the scope where we'll be declaring the tag.
14565       S = getTagInjectionScope(S, getLangOpts());
14566     } else {
14567       assert(TUK == TUK_Friend);
14568       // C++ [namespace.memdef]p3:
14569       //   If a friend declaration in a non-local class first declares a
14570       //   class or function, the friend class or function is a member of
14571       //   the innermost enclosing namespace.
14572       SearchDC = SearchDC->getEnclosingNamespaceContext();
14573     }
14574 
14575     // In C++, we need to do a redeclaration lookup to properly
14576     // diagnose some problems.
14577     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14578     // hidden declaration so that we don't get ambiguity errors when using a
14579     // type declared by an elaborated-type-specifier.  In C that is not correct
14580     // and we should instead merge compatible types found by lookup.
14581     if (getLangOpts().CPlusPlus) {
14582       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14583       LookupQualifiedName(Previous, SearchDC);
14584     } else {
14585       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14586       LookupName(Previous, S);
14587     }
14588   }
14589 
14590   // If we have a known previous declaration to use, then use it.
14591   if (Previous.empty() && SkipBody && SkipBody->Previous)
14592     Previous.addDecl(SkipBody->Previous);
14593 
14594   if (!Previous.empty()) {
14595     NamedDecl *PrevDecl = Previous.getFoundDecl();
14596     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14597 
14598     // It's okay to have a tag decl in the same scope as a typedef
14599     // which hides a tag decl in the same scope.  Finding this
14600     // insanity with a redeclaration lookup can only actually happen
14601     // in C++.
14602     //
14603     // This is also okay for elaborated-type-specifiers, which is
14604     // technically forbidden by the current standard but which is
14605     // okay according to the likely resolution of an open issue;
14606     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14607     if (getLangOpts().CPlusPlus) {
14608       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14609         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14610           TagDecl *Tag = TT->getDecl();
14611           if (Tag->getDeclName() == Name &&
14612               Tag->getDeclContext()->getRedeclContext()
14613                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14614             PrevDecl = Tag;
14615             Previous.clear();
14616             Previous.addDecl(Tag);
14617             Previous.resolveKind();
14618           }
14619         }
14620       }
14621     }
14622 
14623     // If this is a redeclaration of a using shadow declaration, it must
14624     // declare a tag in the same context. In MSVC mode, we allow a
14625     // redefinition if either context is within the other.
14626     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14627       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14628       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14629           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14630           !(OldTag && isAcceptableTagRedeclContext(
14631                           *this, OldTag->getDeclContext(), SearchDC))) {
14632         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14633         Diag(Shadow->getTargetDecl()->getLocation(),
14634              diag::note_using_decl_target);
14635         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14636             << 0;
14637         // Recover by ignoring the old declaration.
14638         Previous.clear();
14639         goto CreateNewDecl;
14640       }
14641     }
14642 
14643     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14644       // If this is a use of a previous tag, or if the tag is already declared
14645       // in the same scope (so that the definition/declaration completes or
14646       // rementions the tag), reuse the decl.
14647       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14648           isDeclInScope(DirectPrevDecl, SearchDC, S,
14649                         SS.isNotEmpty() || isMemberSpecialization)) {
14650         // Make sure that this wasn't declared as an enum and now used as a
14651         // struct or something similar.
14652         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14653                                           TUK == TUK_Definition, KWLoc,
14654                                           Name)) {
14655           bool SafeToContinue
14656             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14657                Kind != TTK_Enum);
14658           if (SafeToContinue)
14659             Diag(KWLoc, diag::err_use_with_wrong_tag)
14660               << Name
14661               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14662                                               PrevTagDecl->getKindName());
14663           else
14664             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14665           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14666 
14667           if (SafeToContinue)
14668             Kind = PrevTagDecl->getTagKind();
14669           else {
14670             // Recover by making this an anonymous redefinition.
14671             Name = nullptr;
14672             Previous.clear();
14673             Invalid = true;
14674           }
14675         }
14676 
14677         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14678           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14679 
14680           // If this is an elaborated-type-specifier for a scoped enumeration,
14681           // the 'class' keyword is not necessary and not permitted.
14682           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14683             if (ScopedEnum)
14684               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14685                 << PrevEnum->isScoped()
14686                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14687             return PrevTagDecl;
14688           }
14689 
14690           QualType EnumUnderlyingTy;
14691           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14692             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14693           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14694             EnumUnderlyingTy = QualType(T, 0);
14695 
14696           // All conflicts with previous declarations are recovered by
14697           // returning the previous declaration, unless this is a definition,
14698           // in which case we want the caller to bail out.
14699           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14700                                      ScopedEnum, EnumUnderlyingTy,
14701                                      IsFixed, PrevEnum))
14702             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14703         }
14704 
14705         // C++11 [class.mem]p1:
14706         //   A member shall not be declared twice in the member-specification,
14707         //   except that a nested class or member class template can be declared
14708         //   and then later defined.
14709         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14710             S->isDeclScope(PrevDecl)) {
14711           Diag(NameLoc, diag::ext_member_redeclared);
14712           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14713         }
14714 
14715         if (!Invalid) {
14716           // If this is a use, just return the declaration we found, unless
14717           // we have attributes.
14718           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14719             if (!Attrs.empty()) {
14720               // FIXME: Diagnose these attributes. For now, we create a new
14721               // declaration to hold them.
14722             } else if (TUK == TUK_Reference &&
14723                        (PrevTagDecl->getFriendObjectKind() ==
14724                             Decl::FOK_Undeclared ||
14725                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14726                        SS.isEmpty()) {
14727               // This declaration is a reference to an existing entity, but
14728               // has different visibility from that entity: it either makes
14729               // a friend visible or it makes a type visible in a new module.
14730               // In either case, create a new declaration. We only do this if
14731               // the declaration would have meant the same thing if no prior
14732               // declaration were found, that is, if it was found in the same
14733               // scope where we would have injected a declaration.
14734               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14735                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14736                 return PrevTagDecl;
14737               // This is in the injected scope, create a new declaration in
14738               // that scope.
14739               S = getTagInjectionScope(S, getLangOpts());
14740             } else {
14741               return PrevTagDecl;
14742             }
14743           }
14744 
14745           // Diagnose attempts to redefine a tag.
14746           if (TUK == TUK_Definition) {
14747             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14748               // If we're defining a specialization and the previous definition
14749               // is from an implicit instantiation, don't emit an error
14750               // here; we'll catch this in the general case below.
14751               bool IsExplicitSpecializationAfterInstantiation = false;
14752               if (isMemberSpecialization) {
14753                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14754                   IsExplicitSpecializationAfterInstantiation =
14755                     RD->getTemplateSpecializationKind() !=
14756                     TSK_ExplicitSpecialization;
14757                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14758                   IsExplicitSpecializationAfterInstantiation =
14759                     ED->getTemplateSpecializationKind() !=
14760                     TSK_ExplicitSpecialization;
14761               }
14762 
14763               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14764               // not keep more that one definition around (merge them). However,
14765               // ensure the decl passes the structural compatibility check in
14766               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14767               NamedDecl *Hidden = nullptr;
14768               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14769                 // There is a definition of this tag, but it is not visible. We
14770                 // explicitly make use of C++'s one definition rule here, and
14771                 // assume that this definition is identical to the hidden one
14772                 // we already have. Make the existing definition visible and
14773                 // use it in place of this one.
14774                 if (!getLangOpts().CPlusPlus) {
14775                   // Postpone making the old definition visible until after we
14776                   // complete parsing the new one and do the structural
14777                   // comparison.
14778                   SkipBody->CheckSameAsPrevious = true;
14779                   SkipBody->New = createTagFromNewDecl();
14780                   SkipBody->Previous = Def;
14781                   return Def;
14782                 } else {
14783                   SkipBody->ShouldSkip = true;
14784                   SkipBody->Previous = Def;
14785                   makeMergedDefinitionVisible(Hidden);
14786                   // Carry on and handle it like a normal definition. We'll
14787                   // skip starting the definitiion later.
14788                 }
14789               } else if (!IsExplicitSpecializationAfterInstantiation) {
14790                 // A redeclaration in function prototype scope in C isn't
14791                 // visible elsewhere, so merely issue a warning.
14792                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14793                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14794                 else
14795                   Diag(NameLoc, diag::err_redefinition) << Name;
14796                 notePreviousDefinition(Def,
14797                                        NameLoc.isValid() ? NameLoc : KWLoc);
14798                 // If this is a redefinition, recover by making this
14799                 // struct be anonymous, which will make any later
14800                 // references get the previous definition.
14801                 Name = nullptr;
14802                 Previous.clear();
14803                 Invalid = true;
14804               }
14805             } else {
14806               // If the type is currently being defined, complain
14807               // about a nested redefinition.
14808               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14809               if (TD->isBeingDefined()) {
14810                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14811                 Diag(PrevTagDecl->getLocation(),
14812                      diag::note_previous_definition);
14813                 Name = nullptr;
14814                 Previous.clear();
14815                 Invalid = true;
14816               }
14817             }
14818 
14819             // Okay, this is definition of a previously declared or referenced
14820             // tag. We're going to create a new Decl for it.
14821           }
14822 
14823           // Okay, we're going to make a redeclaration.  If this is some kind
14824           // of reference, make sure we build the redeclaration in the same DC
14825           // as the original, and ignore the current access specifier.
14826           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14827             SearchDC = PrevTagDecl->getDeclContext();
14828             AS = AS_none;
14829           }
14830         }
14831         // If we get here we have (another) forward declaration or we
14832         // have a definition.  Just create a new decl.
14833 
14834       } else {
14835         // If we get here, this is a definition of a new tag type in a nested
14836         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14837         // new decl/type.  We set PrevDecl to NULL so that the entities
14838         // have distinct types.
14839         Previous.clear();
14840       }
14841       // If we get here, we're going to create a new Decl. If PrevDecl
14842       // is non-NULL, it's a definition of the tag declared by
14843       // PrevDecl. If it's NULL, we have a new definition.
14844 
14845     // Otherwise, PrevDecl is not a tag, but was found with tag
14846     // lookup.  This is only actually possible in C++, where a few
14847     // things like templates still live in the tag namespace.
14848     } else {
14849       // Use a better diagnostic if an elaborated-type-specifier
14850       // found the wrong kind of type on the first
14851       // (non-redeclaration) lookup.
14852       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14853           !Previous.isForRedeclaration()) {
14854         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14855         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14856                                                        << Kind;
14857         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14858         Invalid = true;
14859 
14860       // Otherwise, only diagnose if the declaration is in scope.
14861       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14862                                 SS.isNotEmpty() || isMemberSpecialization)) {
14863         // do nothing
14864 
14865       // Diagnose implicit declarations introduced by elaborated types.
14866       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14867         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14868         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14869         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14870         Invalid = true;
14871 
14872       // Otherwise it's a declaration.  Call out a particularly common
14873       // case here.
14874       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14875         unsigned Kind = 0;
14876         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14877         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14878           << Name << Kind << TND->getUnderlyingType();
14879         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14880         Invalid = true;
14881 
14882       // Otherwise, diagnose.
14883       } else {
14884         // The tag name clashes with something else in the target scope,
14885         // issue an error and recover by making this tag be anonymous.
14886         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14887         notePreviousDefinition(PrevDecl, NameLoc);
14888         Name = nullptr;
14889         Invalid = true;
14890       }
14891 
14892       // The existing declaration isn't relevant to us; we're in a
14893       // new scope, so clear out the previous declaration.
14894       Previous.clear();
14895     }
14896   }
14897 
14898 CreateNewDecl:
14899 
14900   TagDecl *PrevDecl = nullptr;
14901   if (Previous.isSingleResult())
14902     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14903 
14904   // If there is an identifier, use the location of the identifier as the
14905   // location of the decl, otherwise use the location of the struct/union
14906   // keyword.
14907   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14908 
14909   // Otherwise, create a new declaration. If there is a previous
14910   // declaration of the same entity, the two will be linked via
14911   // PrevDecl.
14912   TagDecl *New;
14913 
14914   if (Kind == TTK_Enum) {
14915     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14916     // enum X { A, B, C } D;    D should chain to X.
14917     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14918                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14919                            ScopedEnumUsesClassTag, IsFixed);
14920 
14921     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14922       StdAlignValT = cast<EnumDecl>(New);
14923 
14924     // If this is an undefined enum, warn.
14925     if (TUK != TUK_Definition && !Invalid) {
14926       TagDecl *Def;
14927       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14928         // C++0x: 7.2p2: opaque-enum-declaration.
14929         // Conflicts are diagnosed above. Do nothing.
14930       }
14931       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14932         Diag(Loc, diag::ext_forward_ref_enum_def)
14933           << New;
14934         Diag(Def->getLocation(), diag::note_previous_definition);
14935       } else {
14936         unsigned DiagID = diag::ext_forward_ref_enum;
14937         if (getLangOpts().MSVCCompat)
14938           DiagID = diag::ext_ms_forward_ref_enum;
14939         else if (getLangOpts().CPlusPlus)
14940           DiagID = diag::err_forward_ref_enum;
14941         Diag(Loc, DiagID);
14942       }
14943     }
14944 
14945     if (EnumUnderlying) {
14946       EnumDecl *ED = cast<EnumDecl>(New);
14947       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14948         ED->setIntegerTypeSourceInfo(TI);
14949       else
14950         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14951       ED->setPromotionType(ED->getIntegerType());
14952       assert(ED->isComplete() && "enum with type should be complete");
14953     }
14954   } else {
14955     // struct/union/class
14956 
14957     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14958     // struct X { int A; } D;    D should chain to X.
14959     if (getLangOpts().CPlusPlus) {
14960       // FIXME: Look for a way to use RecordDecl for simple structs.
14961       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14962                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14963 
14964       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14965         StdBadAlloc = cast<CXXRecordDecl>(New);
14966     } else
14967       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14968                                cast_or_null<RecordDecl>(PrevDecl));
14969   }
14970 
14971   // C++11 [dcl.type]p3:
14972   //   A type-specifier-seq shall not define a class or enumeration [...].
14973   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14974       TUK == TUK_Definition) {
14975     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14976       << Context.getTagDeclType(New);
14977     Invalid = true;
14978   }
14979 
14980   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14981       DC->getDeclKind() == Decl::Enum) {
14982     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14983       << Context.getTagDeclType(New);
14984     Invalid = true;
14985   }
14986 
14987   // Maybe add qualifier info.
14988   if (SS.isNotEmpty()) {
14989     if (SS.isSet()) {
14990       // If this is either a declaration or a definition, check the
14991       // nested-name-specifier against the current context.
14992       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14993           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14994                                        isMemberSpecialization))
14995         Invalid = true;
14996 
14997       New->setQualifierInfo(SS.getWithLocInContext(Context));
14998       if (TemplateParameterLists.size() > 0) {
14999         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15000       }
15001     }
15002     else
15003       Invalid = true;
15004   }
15005 
15006   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15007     // Add alignment attributes if necessary; these attributes are checked when
15008     // the ASTContext lays out the structure.
15009     //
15010     // It is important for implementing the correct semantics that this
15011     // happen here (in ActOnTag). The #pragma pack stack is
15012     // maintained as a result of parser callbacks which can occur at
15013     // many points during the parsing of a struct declaration (because
15014     // the #pragma tokens are effectively skipped over during the
15015     // parsing of the struct).
15016     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15017       AddAlignmentAttributesForRecord(RD);
15018       AddMsStructLayoutForRecord(RD);
15019     }
15020   }
15021 
15022   if (ModulePrivateLoc.isValid()) {
15023     if (isMemberSpecialization)
15024       Diag(New->getLocation(), diag::err_module_private_specialization)
15025         << 2
15026         << FixItHint::CreateRemoval(ModulePrivateLoc);
15027     // __module_private__ does not apply to local classes. However, we only
15028     // diagnose this as an error when the declaration specifiers are
15029     // freestanding. Here, we just ignore the __module_private__.
15030     else if (!SearchDC->isFunctionOrMethod())
15031       New->setModulePrivate();
15032   }
15033 
15034   // If this is a specialization of a member class (of a class template),
15035   // check the specialization.
15036   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15037     Invalid = true;
15038 
15039   // If we're declaring or defining a tag in function prototype scope in C,
15040   // note that this type can only be used within the function and add it to
15041   // the list of decls to inject into the function definition scope.
15042   if ((Name || Kind == TTK_Enum) &&
15043       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15044     if (getLangOpts().CPlusPlus) {
15045       // C++ [dcl.fct]p6:
15046       //   Types shall not be defined in return or parameter types.
15047       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15048         Diag(Loc, diag::err_type_defined_in_param_type)
15049             << Name;
15050         Invalid = true;
15051       }
15052     } else if (!PrevDecl) {
15053       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15054     }
15055   }
15056 
15057   if (Invalid)
15058     New->setInvalidDecl();
15059 
15060   // Set the lexical context. If the tag has a C++ scope specifier, the
15061   // lexical context will be different from the semantic context.
15062   New->setLexicalDeclContext(CurContext);
15063 
15064   // Mark this as a friend decl if applicable.
15065   // In Microsoft mode, a friend declaration also acts as a forward
15066   // declaration so we always pass true to setObjectOfFriendDecl to make
15067   // the tag name visible.
15068   if (TUK == TUK_Friend)
15069     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15070 
15071   // Set the access specifier.
15072   if (!Invalid && SearchDC->isRecord())
15073     SetMemberAccessSpecifier(New, PrevDecl, AS);
15074 
15075   if (PrevDecl)
15076     CheckRedeclarationModuleOwnership(New, PrevDecl);
15077 
15078   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15079     New->startDefinition();
15080 
15081   ProcessDeclAttributeList(S, New, Attrs);
15082   AddPragmaAttributes(S, New);
15083 
15084   // If this has an identifier, add it to the scope stack.
15085   if (TUK == TUK_Friend) {
15086     // We might be replacing an existing declaration in the lookup tables;
15087     // if so, borrow its access specifier.
15088     if (PrevDecl)
15089       New->setAccess(PrevDecl->getAccess());
15090 
15091     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15092     DC->makeDeclVisibleInContext(New);
15093     if (Name) // can be null along some error paths
15094       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15095         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15096   } else if (Name) {
15097     S = getNonFieldDeclScope(S);
15098     PushOnScopeChains(New, S, true);
15099   } else {
15100     CurContext->addDecl(New);
15101   }
15102 
15103   // If this is the C FILE type, notify the AST context.
15104   if (IdentifierInfo *II = New->getIdentifier())
15105     if (!New->isInvalidDecl() &&
15106         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15107         II->isStr("FILE"))
15108       Context.setFILEDecl(New);
15109 
15110   if (PrevDecl)
15111     mergeDeclAttributes(New, PrevDecl);
15112 
15113   // If there's a #pragma GCC visibility in scope, set the visibility of this
15114   // record.
15115   AddPushedVisibilityAttribute(New);
15116 
15117   if (isMemberSpecialization && !New->isInvalidDecl())
15118     CompleteMemberSpecialization(New, Previous);
15119 
15120   OwnedDecl = true;
15121   // In C++, don't return an invalid declaration. We can't recover well from
15122   // the cases where we make the type anonymous.
15123   if (Invalid && getLangOpts().CPlusPlus) {
15124     if (New->isBeingDefined())
15125       if (auto RD = dyn_cast<RecordDecl>(New))
15126         RD->completeDefinition();
15127     return nullptr;
15128   } else if (SkipBody && SkipBody->ShouldSkip) {
15129     return SkipBody->Previous;
15130   } else {
15131     return New;
15132   }
15133 }
15134 
15135 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15136   AdjustDeclIfTemplate(TagD);
15137   TagDecl *Tag = cast<TagDecl>(TagD);
15138 
15139   // Enter the tag context.
15140   PushDeclContext(S, Tag);
15141 
15142   ActOnDocumentableDecl(TagD);
15143 
15144   // If there's a #pragma GCC visibility in scope, set the visibility of this
15145   // record.
15146   AddPushedVisibilityAttribute(Tag);
15147 }
15148 
15149 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15150                                     SkipBodyInfo &SkipBody) {
15151   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15152     return false;
15153 
15154   // Make the previous decl visible.
15155   makeMergedDefinitionVisible(SkipBody.Previous);
15156   return true;
15157 }
15158 
15159 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15160   assert(isa<ObjCContainerDecl>(IDecl) &&
15161          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15162   DeclContext *OCD = cast<DeclContext>(IDecl);
15163   assert(getContainingDC(OCD) == CurContext &&
15164       "The next DeclContext should be lexically contained in the current one.");
15165   CurContext = OCD;
15166   return IDecl;
15167 }
15168 
15169 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15170                                            SourceLocation FinalLoc,
15171                                            bool IsFinalSpelledSealed,
15172                                            SourceLocation LBraceLoc) {
15173   AdjustDeclIfTemplate(TagD);
15174   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15175 
15176   FieldCollector->StartClass();
15177 
15178   if (!Record->getIdentifier())
15179     return;
15180 
15181   if (FinalLoc.isValid())
15182     Record->addAttr(new (Context)
15183                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15184 
15185   // C++ [class]p2:
15186   //   [...] The class-name is also inserted into the scope of the
15187   //   class itself; this is known as the injected-class-name. For
15188   //   purposes of access checking, the injected-class-name is treated
15189   //   as if it were a public member name.
15190   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15191       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15192       Record->getLocation(), Record->getIdentifier(),
15193       /*PrevDecl=*/nullptr,
15194       /*DelayTypeCreation=*/true);
15195   Context.getTypeDeclType(InjectedClassName, Record);
15196   InjectedClassName->setImplicit();
15197   InjectedClassName->setAccess(AS_public);
15198   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15199       InjectedClassName->setDescribedClassTemplate(Template);
15200   PushOnScopeChains(InjectedClassName, S);
15201   assert(InjectedClassName->isInjectedClassName() &&
15202          "Broken injected-class-name");
15203 }
15204 
15205 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15206                                     SourceRange BraceRange) {
15207   AdjustDeclIfTemplate(TagD);
15208   TagDecl *Tag = cast<TagDecl>(TagD);
15209   Tag->setBraceRange(BraceRange);
15210 
15211   // Make sure we "complete" the definition even it is invalid.
15212   if (Tag->isBeingDefined()) {
15213     assert(Tag->isInvalidDecl() && "We should already have completed it");
15214     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15215       RD->completeDefinition();
15216   }
15217 
15218   if (isa<CXXRecordDecl>(Tag)) {
15219     FieldCollector->FinishClass();
15220   }
15221 
15222   // Exit this scope of this tag's definition.
15223   PopDeclContext();
15224 
15225   if (getCurLexicalContext()->isObjCContainer() &&
15226       Tag->getDeclContext()->isFileContext())
15227     Tag->setTopLevelDeclInObjCContainer();
15228 
15229   // Notify the consumer that we've defined a tag.
15230   if (!Tag->isInvalidDecl())
15231     Consumer.HandleTagDeclDefinition(Tag);
15232 }
15233 
15234 void Sema::ActOnObjCContainerFinishDefinition() {
15235   // Exit this scope of this interface definition.
15236   PopDeclContext();
15237 }
15238 
15239 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15240   assert(DC == CurContext && "Mismatch of container contexts");
15241   OriginalLexicalContext = DC;
15242   ActOnObjCContainerFinishDefinition();
15243 }
15244 
15245 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15246   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15247   OriginalLexicalContext = nullptr;
15248 }
15249 
15250 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15251   AdjustDeclIfTemplate(TagD);
15252   TagDecl *Tag = cast<TagDecl>(TagD);
15253   Tag->setInvalidDecl();
15254 
15255   // Make sure we "complete" the definition even it is invalid.
15256   if (Tag->isBeingDefined()) {
15257     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15258       RD->completeDefinition();
15259   }
15260 
15261   // We're undoing ActOnTagStartDefinition here, not
15262   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15263   // the FieldCollector.
15264 
15265   PopDeclContext();
15266 }
15267 
15268 // Note that FieldName may be null for anonymous bitfields.
15269 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15270                                 IdentifierInfo *FieldName,
15271                                 QualType FieldTy, bool IsMsStruct,
15272                                 Expr *BitWidth, bool *ZeroWidth) {
15273   // Default to true; that shouldn't confuse checks for emptiness
15274   if (ZeroWidth)
15275     *ZeroWidth = true;
15276 
15277   // C99 6.7.2.1p4 - verify the field type.
15278   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15279   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15280     // Handle incomplete types with specific error.
15281     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15282       return ExprError();
15283     if (FieldName)
15284       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15285         << FieldName << FieldTy << BitWidth->getSourceRange();
15286     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15287       << FieldTy << BitWidth->getSourceRange();
15288   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15289                                              UPPC_BitFieldWidth))
15290     return ExprError();
15291 
15292   // If the bit-width is type- or value-dependent, don't try to check
15293   // it now.
15294   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15295     return BitWidth;
15296 
15297   llvm::APSInt Value;
15298   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15299   if (ICE.isInvalid())
15300     return ICE;
15301   BitWidth = ICE.get();
15302 
15303   if (Value != 0 && ZeroWidth)
15304     *ZeroWidth = false;
15305 
15306   // Zero-width bitfield is ok for anonymous field.
15307   if (Value == 0 && FieldName)
15308     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15309 
15310   if (Value.isSigned() && Value.isNegative()) {
15311     if (FieldName)
15312       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15313                << FieldName << Value.toString(10);
15314     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15315       << Value.toString(10);
15316   }
15317 
15318   if (!FieldTy->isDependentType()) {
15319     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15320     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15321     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15322 
15323     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15324     // ABI.
15325     bool CStdConstraintViolation =
15326         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15327     bool MSBitfieldViolation =
15328         Value.ugt(TypeStorageSize) &&
15329         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15330     if (CStdConstraintViolation || MSBitfieldViolation) {
15331       unsigned DiagWidth =
15332           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15333       if (FieldName)
15334         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15335                << FieldName << (unsigned)Value.getZExtValue()
15336                << !CStdConstraintViolation << DiagWidth;
15337 
15338       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15339              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15340              << DiagWidth;
15341     }
15342 
15343     // Warn on types where the user might conceivably expect to get all
15344     // specified bits as value bits: that's all integral types other than
15345     // 'bool'.
15346     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15347       if (FieldName)
15348         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15349             << FieldName << (unsigned)Value.getZExtValue()
15350             << (unsigned)TypeWidth;
15351       else
15352         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15353             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15354     }
15355   }
15356 
15357   return BitWidth;
15358 }
15359 
15360 /// ActOnField - Each field of a C struct/union is passed into this in order
15361 /// to create a FieldDecl object for it.
15362 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15363                        Declarator &D, Expr *BitfieldWidth) {
15364   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15365                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15366                                /*InitStyle=*/ICIS_NoInit, AS_public);
15367   return Res;
15368 }
15369 
15370 /// HandleField - Analyze a field of a C struct or a C++ data member.
15371 ///
15372 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15373                              SourceLocation DeclStart,
15374                              Declarator &D, Expr *BitWidth,
15375                              InClassInitStyle InitStyle,
15376                              AccessSpecifier AS) {
15377   if (D.isDecompositionDeclarator()) {
15378     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15379     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15380       << Decomp.getSourceRange();
15381     return nullptr;
15382   }
15383 
15384   IdentifierInfo *II = D.getIdentifier();
15385   SourceLocation Loc = DeclStart;
15386   if (II) Loc = D.getIdentifierLoc();
15387 
15388   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15389   QualType T = TInfo->getType();
15390   if (getLangOpts().CPlusPlus) {
15391     CheckExtraCXXDefaultArguments(D);
15392 
15393     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15394                                         UPPC_DataMemberType)) {
15395       D.setInvalidType();
15396       T = Context.IntTy;
15397       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15398     }
15399   }
15400 
15401   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15402 
15403   if (D.getDeclSpec().isInlineSpecified())
15404     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15405         << getLangOpts().CPlusPlus17;
15406   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15407     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15408          diag::err_invalid_thread)
15409       << DeclSpec::getSpecifierName(TSCS);
15410 
15411   // Check to see if this name was declared as a member previously
15412   NamedDecl *PrevDecl = nullptr;
15413   LookupResult Previous(*this, II, Loc, LookupMemberName,
15414                         ForVisibleRedeclaration);
15415   LookupName(Previous, S);
15416   switch (Previous.getResultKind()) {
15417     case LookupResult::Found:
15418     case LookupResult::FoundUnresolvedValue:
15419       PrevDecl = Previous.getAsSingle<NamedDecl>();
15420       break;
15421 
15422     case LookupResult::FoundOverloaded:
15423       PrevDecl = Previous.getRepresentativeDecl();
15424       break;
15425 
15426     case LookupResult::NotFound:
15427     case LookupResult::NotFoundInCurrentInstantiation:
15428     case LookupResult::Ambiguous:
15429       break;
15430   }
15431   Previous.suppressDiagnostics();
15432 
15433   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15434     // Maybe we will complain about the shadowed template parameter.
15435     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15436     // Just pretend that we didn't see the previous declaration.
15437     PrevDecl = nullptr;
15438   }
15439 
15440   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15441     PrevDecl = nullptr;
15442 
15443   bool Mutable
15444     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15445   SourceLocation TSSL = D.getBeginLoc();
15446   FieldDecl *NewFD
15447     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15448                      TSSL, AS, PrevDecl, &D);
15449 
15450   if (NewFD->isInvalidDecl())
15451     Record->setInvalidDecl();
15452 
15453   if (D.getDeclSpec().isModulePrivateSpecified())
15454     NewFD->setModulePrivate();
15455 
15456   if (NewFD->isInvalidDecl() && PrevDecl) {
15457     // Don't introduce NewFD into scope; there's already something
15458     // with the same name in the same scope.
15459   } else if (II) {
15460     PushOnScopeChains(NewFD, S);
15461   } else
15462     Record->addDecl(NewFD);
15463 
15464   return NewFD;
15465 }
15466 
15467 /// Build a new FieldDecl and check its well-formedness.
15468 ///
15469 /// This routine builds a new FieldDecl given the fields name, type,
15470 /// record, etc. \p PrevDecl should refer to any previous declaration
15471 /// with the same name and in the same scope as the field to be
15472 /// created.
15473 ///
15474 /// \returns a new FieldDecl.
15475 ///
15476 /// \todo The Declarator argument is a hack. It will be removed once
15477 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15478                                 TypeSourceInfo *TInfo,
15479                                 RecordDecl *Record, SourceLocation Loc,
15480                                 bool Mutable, Expr *BitWidth,
15481                                 InClassInitStyle InitStyle,
15482                                 SourceLocation TSSL,
15483                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15484                                 Declarator *D) {
15485   IdentifierInfo *II = Name.getAsIdentifierInfo();
15486   bool InvalidDecl = false;
15487   if (D) InvalidDecl = D->isInvalidType();
15488 
15489   // If we receive a broken type, recover by assuming 'int' and
15490   // marking this declaration as invalid.
15491   if (T.isNull()) {
15492     InvalidDecl = true;
15493     T = Context.IntTy;
15494   }
15495 
15496   QualType EltTy = Context.getBaseElementType(T);
15497   if (!EltTy->isDependentType()) {
15498     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15499       // Fields of incomplete type force their record to be invalid.
15500       Record->setInvalidDecl();
15501       InvalidDecl = true;
15502     } else {
15503       NamedDecl *Def;
15504       EltTy->isIncompleteType(&Def);
15505       if (Def && Def->isInvalidDecl()) {
15506         Record->setInvalidDecl();
15507         InvalidDecl = true;
15508       }
15509     }
15510   }
15511 
15512   // TR 18037 does not allow fields to be declared with address space
15513   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15514       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15515     Diag(Loc, diag::err_field_with_address_space);
15516     Record->setInvalidDecl();
15517     InvalidDecl = true;
15518   }
15519 
15520   if (LangOpts.OpenCL) {
15521     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15522     // used as structure or union field: image, sampler, event or block types.
15523     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15524         T->isBlockPointerType()) {
15525       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15526       Record->setInvalidDecl();
15527       InvalidDecl = true;
15528     }
15529     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15530     if (BitWidth) {
15531       Diag(Loc, diag::err_opencl_bitfields);
15532       InvalidDecl = true;
15533     }
15534   }
15535 
15536   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15537   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15538       T.hasQualifiers()) {
15539     InvalidDecl = true;
15540     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15541   }
15542 
15543   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15544   // than a variably modified type.
15545   if (!InvalidDecl && T->isVariablyModifiedType()) {
15546     bool SizeIsNegative;
15547     llvm::APSInt Oversized;
15548 
15549     TypeSourceInfo *FixedTInfo =
15550       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15551                                                     SizeIsNegative,
15552                                                     Oversized);
15553     if (FixedTInfo) {
15554       Diag(Loc, diag::warn_illegal_constant_array_size);
15555       TInfo = FixedTInfo;
15556       T = FixedTInfo->getType();
15557     } else {
15558       if (SizeIsNegative)
15559         Diag(Loc, diag::err_typecheck_negative_array_size);
15560       else if (Oversized.getBoolValue())
15561         Diag(Loc, diag::err_array_too_large)
15562           << Oversized.toString(10);
15563       else
15564         Diag(Loc, diag::err_typecheck_field_variable_size);
15565       InvalidDecl = true;
15566     }
15567   }
15568 
15569   // Fields can not have abstract class types
15570   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15571                                              diag::err_abstract_type_in_decl,
15572                                              AbstractFieldType))
15573     InvalidDecl = true;
15574 
15575   bool ZeroWidth = false;
15576   if (InvalidDecl)
15577     BitWidth = nullptr;
15578   // If this is declared as a bit-field, check the bit-field.
15579   if (BitWidth) {
15580     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15581                               &ZeroWidth).get();
15582     if (!BitWidth) {
15583       InvalidDecl = true;
15584       BitWidth = nullptr;
15585       ZeroWidth = false;
15586     }
15587   }
15588 
15589   // Check that 'mutable' is consistent with the type of the declaration.
15590   if (!InvalidDecl && Mutable) {
15591     unsigned DiagID = 0;
15592     if (T->isReferenceType())
15593       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15594                                         : diag::err_mutable_reference;
15595     else if (T.isConstQualified())
15596       DiagID = diag::err_mutable_const;
15597 
15598     if (DiagID) {
15599       SourceLocation ErrLoc = Loc;
15600       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15601         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15602       Diag(ErrLoc, DiagID);
15603       if (DiagID != diag::ext_mutable_reference) {
15604         Mutable = false;
15605         InvalidDecl = true;
15606       }
15607     }
15608   }
15609 
15610   // C++11 [class.union]p8 (DR1460):
15611   //   At most one variant member of a union may have a
15612   //   brace-or-equal-initializer.
15613   if (InitStyle != ICIS_NoInit)
15614     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15615 
15616   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15617                                        BitWidth, Mutable, InitStyle);
15618   if (InvalidDecl)
15619     NewFD->setInvalidDecl();
15620 
15621   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15622     Diag(Loc, diag::err_duplicate_member) << II;
15623     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15624     NewFD->setInvalidDecl();
15625   }
15626 
15627   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15628     if (Record->isUnion()) {
15629       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15630         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15631         if (RDecl->getDefinition()) {
15632           // C++ [class.union]p1: An object of a class with a non-trivial
15633           // constructor, a non-trivial copy constructor, a non-trivial
15634           // destructor, or a non-trivial copy assignment operator
15635           // cannot be a member of a union, nor can an array of such
15636           // objects.
15637           if (CheckNontrivialField(NewFD))
15638             NewFD->setInvalidDecl();
15639         }
15640       }
15641 
15642       // C++ [class.union]p1: If a union contains a member of reference type,
15643       // the program is ill-formed, except when compiling with MSVC extensions
15644       // enabled.
15645       if (EltTy->isReferenceType()) {
15646         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15647                                     diag::ext_union_member_of_reference_type :
15648                                     diag::err_union_member_of_reference_type)
15649           << NewFD->getDeclName() << EltTy;
15650         if (!getLangOpts().MicrosoftExt)
15651           NewFD->setInvalidDecl();
15652       }
15653     }
15654   }
15655 
15656   // FIXME: We need to pass in the attributes given an AST
15657   // representation, not a parser representation.
15658   if (D) {
15659     // FIXME: The current scope is almost... but not entirely... correct here.
15660     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15661 
15662     if (NewFD->hasAttrs())
15663       CheckAlignasUnderalignment(NewFD);
15664   }
15665 
15666   // In auto-retain/release, infer strong retension for fields of
15667   // retainable type.
15668   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15669     NewFD->setInvalidDecl();
15670 
15671   if (T.isObjCGCWeak())
15672     Diag(Loc, diag::warn_attribute_weak_on_field);
15673 
15674   NewFD->setAccess(AS);
15675   return NewFD;
15676 }
15677 
15678 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15679   assert(FD);
15680   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15681 
15682   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15683     return false;
15684 
15685   QualType EltTy = Context.getBaseElementType(FD->getType());
15686   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15687     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15688     if (RDecl->getDefinition()) {
15689       // We check for copy constructors before constructors
15690       // because otherwise we'll never get complaints about
15691       // copy constructors.
15692 
15693       CXXSpecialMember member = CXXInvalid;
15694       // We're required to check for any non-trivial constructors. Since the
15695       // implicit default constructor is suppressed if there are any
15696       // user-declared constructors, we just need to check that there is a
15697       // trivial default constructor and a trivial copy constructor. (We don't
15698       // worry about move constructors here, since this is a C++98 check.)
15699       if (RDecl->hasNonTrivialCopyConstructor())
15700         member = CXXCopyConstructor;
15701       else if (!RDecl->hasTrivialDefaultConstructor())
15702         member = CXXDefaultConstructor;
15703       else if (RDecl->hasNonTrivialCopyAssignment())
15704         member = CXXCopyAssignment;
15705       else if (RDecl->hasNonTrivialDestructor())
15706         member = CXXDestructor;
15707 
15708       if (member != CXXInvalid) {
15709         if (!getLangOpts().CPlusPlus11 &&
15710             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15711           // Objective-C++ ARC: it is an error to have a non-trivial field of
15712           // a union. However, system headers in Objective-C programs
15713           // occasionally have Objective-C lifetime objects within unions,
15714           // and rather than cause the program to fail, we make those
15715           // members unavailable.
15716           SourceLocation Loc = FD->getLocation();
15717           if (getSourceManager().isInSystemHeader(Loc)) {
15718             if (!FD->hasAttr<UnavailableAttr>())
15719               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15720                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15721             return false;
15722           }
15723         }
15724 
15725         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15726                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15727                diag::err_illegal_union_or_anon_struct_member)
15728           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15729         DiagnoseNontrivial(RDecl, member);
15730         return !getLangOpts().CPlusPlus11;
15731       }
15732     }
15733   }
15734 
15735   return false;
15736 }
15737 
15738 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15739 ///  AST enum value.
15740 static ObjCIvarDecl::AccessControl
15741 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15742   switch (ivarVisibility) {
15743   default: llvm_unreachable("Unknown visitibility kind");
15744   case tok::objc_private: return ObjCIvarDecl::Private;
15745   case tok::objc_public: return ObjCIvarDecl::Public;
15746   case tok::objc_protected: return ObjCIvarDecl::Protected;
15747   case tok::objc_package: return ObjCIvarDecl::Package;
15748   }
15749 }
15750 
15751 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15752 /// in order to create an IvarDecl object for it.
15753 Decl *Sema::ActOnIvar(Scope *S,
15754                                 SourceLocation DeclStart,
15755                                 Declarator &D, Expr *BitfieldWidth,
15756                                 tok::ObjCKeywordKind Visibility) {
15757 
15758   IdentifierInfo *II = D.getIdentifier();
15759   Expr *BitWidth = (Expr*)BitfieldWidth;
15760   SourceLocation Loc = DeclStart;
15761   if (II) Loc = D.getIdentifierLoc();
15762 
15763   // FIXME: Unnamed fields can be handled in various different ways, for
15764   // example, unnamed unions inject all members into the struct namespace!
15765 
15766   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15767   QualType T = TInfo->getType();
15768 
15769   if (BitWidth) {
15770     // 6.7.2.1p3, 6.7.2.1p4
15771     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15772     if (!BitWidth)
15773       D.setInvalidType();
15774   } else {
15775     // Not a bitfield.
15776 
15777     // validate II.
15778 
15779   }
15780   if (T->isReferenceType()) {
15781     Diag(Loc, diag::err_ivar_reference_type);
15782     D.setInvalidType();
15783   }
15784   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15785   // than a variably modified type.
15786   else if (T->isVariablyModifiedType()) {
15787     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15788     D.setInvalidType();
15789   }
15790 
15791   // Get the visibility (access control) for this ivar.
15792   ObjCIvarDecl::AccessControl ac =
15793     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15794                                         : ObjCIvarDecl::None;
15795   // Must set ivar's DeclContext to its enclosing interface.
15796   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15797   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15798     return nullptr;
15799   ObjCContainerDecl *EnclosingContext;
15800   if (ObjCImplementationDecl *IMPDecl =
15801       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15802     if (LangOpts.ObjCRuntime.isFragile()) {
15803     // Case of ivar declared in an implementation. Context is that of its class.
15804       EnclosingContext = IMPDecl->getClassInterface();
15805       assert(EnclosingContext && "Implementation has no class interface!");
15806     }
15807     else
15808       EnclosingContext = EnclosingDecl;
15809   } else {
15810     if (ObjCCategoryDecl *CDecl =
15811         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15812       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15813         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15814         return nullptr;
15815       }
15816     }
15817     EnclosingContext = EnclosingDecl;
15818   }
15819 
15820   // Construct the decl.
15821   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15822                                              DeclStart, Loc, II, T,
15823                                              TInfo, ac, (Expr *)BitfieldWidth);
15824 
15825   if (II) {
15826     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15827                                            ForVisibleRedeclaration);
15828     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15829         && !isa<TagDecl>(PrevDecl)) {
15830       Diag(Loc, diag::err_duplicate_member) << II;
15831       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15832       NewID->setInvalidDecl();
15833     }
15834   }
15835 
15836   // Process attributes attached to the ivar.
15837   ProcessDeclAttributes(S, NewID, D);
15838 
15839   if (D.isInvalidType())
15840     NewID->setInvalidDecl();
15841 
15842   // In ARC, infer 'retaining' for ivars of retainable type.
15843   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15844     NewID->setInvalidDecl();
15845 
15846   if (D.getDeclSpec().isModulePrivateSpecified())
15847     NewID->setModulePrivate();
15848 
15849   if (II) {
15850     // FIXME: When interfaces are DeclContexts, we'll need to add
15851     // these to the interface.
15852     S->AddDecl(NewID);
15853     IdResolver.AddDecl(NewID);
15854   }
15855 
15856   if (LangOpts.ObjCRuntime.isNonFragile() &&
15857       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15858     Diag(Loc, diag::warn_ivars_in_interface);
15859 
15860   return NewID;
15861 }
15862 
15863 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15864 /// class and class extensions. For every class \@interface and class
15865 /// extension \@interface, if the last ivar is a bitfield of any type,
15866 /// then add an implicit `char :0` ivar to the end of that interface.
15867 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15868                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15869   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15870     return;
15871 
15872   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15873   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15874 
15875   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15876     return;
15877   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15878   if (!ID) {
15879     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15880       if (!CD->IsClassExtension())
15881         return;
15882     }
15883     // No need to add this to end of @implementation.
15884     else
15885       return;
15886   }
15887   // All conditions are met. Add a new bitfield to the tail end of ivars.
15888   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15889   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15890 
15891   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15892                               DeclLoc, DeclLoc, nullptr,
15893                               Context.CharTy,
15894                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15895                                                                DeclLoc),
15896                               ObjCIvarDecl::Private, BW,
15897                               true);
15898   AllIvarDecls.push_back(Ivar);
15899 }
15900 
15901 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15902                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15903                        SourceLocation RBrac,
15904                        const ParsedAttributesView &Attrs) {
15905   assert(EnclosingDecl && "missing record or interface decl");
15906 
15907   // If this is an Objective-C @implementation or category and we have
15908   // new fields here we should reset the layout of the interface since
15909   // it will now change.
15910   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15911     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15912     switch (DC->getKind()) {
15913     default: break;
15914     case Decl::ObjCCategory:
15915       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15916       break;
15917     case Decl::ObjCImplementation:
15918       Context.
15919         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15920       break;
15921     }
15922   }
15923 
15924   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15925   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15926 
15927   // Start counting up the number of named members; make sure to include
15928   // members of anonymous structs and unions in the total.
15929   unsigned NumNamedMembers = 0;
15930   if (Record) {
15931     for (const auto *I : Record->decls()) {
15932       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15933         if (IFD->getDeclName())
15934           ++NumNamedMembers;
15935     }
15936   }
15937 
15938   // Verify that all the fields are okay.
15939   SmallVector<FieldDecl*, 32> RecFields;
15940 
15941   bool ObjCFieldLifetimeErrReported = false;
15942   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15943        i != end; ++i) {
15944     FieldDecl *FD = cast<FieldDecl>(*i);
15945 
15946     // Get the type for the field.
15947     const Type *FDTy = FD->getType().getTypePtr();
15948 
15949     if (!FD->isAnonymousStructOrUnion()) {
15950       // Remember all fields written by the user.
15951       RecFields.push_back(FD);
15952     }
15953 
15954     // If the field is already invalid for some reason, don't emit more
15955     // diagnostics about it.
15956     if (FD->isInvalidDecl()) {
15957       EnclosingDecl->setInvalidDecl();
15958       continue;
15959     }
15960 
15961     // C99 6.7.2.1p2:
15962     //   A structure or union shall not contain a member with
15963     //   incomplete or function type (hence, a structure shall not
15964     //   contain an instance of itself, but may contain a pointer to
15965     //   an instance of itself), except that the last member of a
15966     //   structure with more than one named member may have incomplete
15967     //   array type; such a structure (and any union containing,
15968     //   possibly recursively, a member that is such a structure)
15969     //   shall not be a member of a structure or an element of an
15970     //   array.
15971     bool IsLastField = (i + 1 == Fields.end());
15972     if (FDTy->isFunctionType()) {
15973       // Field declared as a function.
15974       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15975         << FD->getDeclName();
15976       FD->setInvalidDecl();
15977       EnclosingDecl->setInvalidDecl();
15978       continue;
15979     } else if (FDTy->isIncompleteArrayType() &&
15980                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15981       if (Record) {
15982         // Flexible array member.
15983         // Microsoft and g++ is more permissive regarding flexible array.
15984         // It will accept flexible array in union and also
15985         // as the sole element of a struct/class.
15986         unsigned DiagID = 0;
15987         if (!Record->isUnion() && !IsLastField) {
15988           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15989             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15990           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15991           FD->setInvalidDecl();
15992           EnclosingDecl->setInvalidDecl();
15993           continue;
15994         } else if (Record->isUnion())
15995           DiagID = getLangOpts().MicrosoftExt
15996                        ? diag::ext_flexible_array_union_ms
15997                        : getLangOpts().CPlusPlus
15998                              ? diag::ext_flexible_array_union_gnu
15999                              : diag::err_flexible_array_union;
16000         else if (NumNamedMembers < 1)
16001           DiagID = getLangOpts().MicrosoftExt
16002                        ? diag::ext_flexible_array_empty_aggregate_ms
16003                        : getLangOpts().CPlusPlus
16004                              ? diag::ext_flexible_array_empty_aggregate_gnu
16005                              : diag::err_flexible_array_empty_aggregate;
16006 
16007         if (DiagID)
16008           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16009                                           << Record->getTagKind();
16010         // While the layout of types that contain virtual bases is not specified
16011         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16012         // virtual bases after the derived members.  This would make a flexible
16013         // array member declared at the end of an object not adjacent to the end
16014         // of the type.
16015         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16016           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16017               << FD->getDeclName() << Record->getTagKind();
16018         if (!getLangOpts().C99)
16019           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16020             << FD->getDeclName() << Record->getTagKind();
16021 
16022         // If the element type has a non-trivial destructor, we would not
16023         // implicitly destroy the elements, so disallow it for now.
16024         //
16025         // FIXME: GCC allows this. We should probably either implicitly delete
16026         // the destructor of the containing class, or just allow this.
16027         QualType BaseElem = Context.getBaseElementType(FD->getType());
16028         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16029           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16030             << FD->getDeclName() << FD->getType();
16031           FD->setInvalidDecl();
16032           EnclosingDecl->setInvalidDecl();
16033           continue;
16034         }
16035         // Okay, we have a legal flexible array member at the end of the struct.
16036         Record->setHasFlexibleArrayMember(true);
16037       } else {
16038         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16039         // unless they are followed by another ivar. That check is done
16040         // elsewhere, after synthesized ivars are known.
16041       }
16042     } else if (!FDTy->isDependentType() &&
16043                RequireCompleteType(FD->getLocation(), FD->getType(),
16044                                    diag::err_field_incomplete)) {
16045       // Incomplete type
16046       FD->setInvalidDecl();
16047       EnclosingDecl->setInvalidDecl();
16048       continue;
16049     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16050       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16051         // A type which contains a flexible array member is considered to be a
16052         // flexible array member.
16053         Record->setHasFlexibleArrayMember(true);
16054         if (!Record->isUnion()) {
16055           // If this is a struct/class and this is not the last element, reject
16056           // it.  Note that GCC supports variable sized arrays in the middle of
16057           // structures.
16058           if (!IsLastField)
16059             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16060               << FD->getDeclName() << FD->getType();
16061           else {
16062             // We support flexible arrays at the end of structs in
16063             // other structs as an extension.
16064             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16065               << FD->getDeclName();
16066           }
16067         }
16068       }
16069       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16070           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16071                                  diag::err_abstract_type_in_decl,
16072                                  AbstractIvarType)) {
16073         // Ivars can not have abstract class types
16074         FD->setInvalidDecl();
16075       }
16076       if (Record && FDTTy->getDecl()->hasObjectMember())
16077         Record->setHasObjectMember(true);
16078       if (Record && FDTTy->getDecl()->hasVolatileMember())
16079         Record->setHasVolatileMember(true);
16080       if (Record && Record->isUnion() &&
16081           FD->getType().isNonTrivialPrimitiveCType(Context))
16082         Diag(FD->getLocation(),
16083              diag::err_nontrivial_primitive_type_in_union);
16084     } else if (FDTy->isObjCObjectType()) {
16085       /// A field cannot be an Objective-c object
16086       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16087         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16088       QualType T = Context.getObjCObjectPointerType(FD->getType());
16089       FD->setType(T);
16090     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
16091                Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
16092                !getLangOpts().CPlusPlus) {
16093       // It's an error in ARC or Weak if a field has lifetime.
16094       // We don't want to report this in a system header, though,
16095       // so we just make the field unavailable.
16096       // FIXME: that's really not sufficient; we need to make the type
16097       // itself invalid to, say, initialize or copy.
16098       QualType T = FD->getType();
16099       if (T.hasNonTrivialObjCLifetime()) {
16100         SourceLocation loc = FD->getLocation();
16101         if (getSourceManager().isInSystemHeader(loc)) {
16102           if (!FD->hasAttr<UnavailableAttr>()) {
16103             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16104                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
16105           }
16106         } else {
16107           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
16108             << T->isBlockPointerType() << Record->getTagKind();
16109         }
16110         ObjCFieldLifetimeErrReported = true;
16111       }
16112     } else if (getLangOpts().ObjC &&
16113                getLangOpts().getGC() != LangOptions::NonGC &&
16114                Record && !Record->hasObjectMember()) {
16115       if (FD->getType()->isObjCObjectPointerType() ||
16116           FD->getType().isObjCGCStrong())
16117         Record->setHasObjectMember(true);
16118       else if (Context.getAsArrayType(FD->getType())) {
16119         QualType BaseType = Context.getBaseElementType(FD->getType());
16120         if (BaseType->isRecordType() &&
16121             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16122           Record->setHasObjectMember(true);
16123         else if (BaseType->isObjCObjectPointerType() ||
16124                  BaseType.isObjCGCStrong())
16125                Record->setHasObjectMember(true);
16126       }
16127     }
16128 
16129     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16130       QualType FT = FD->getType();
16131       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
16132         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16133       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16134       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
16135         Record->setNonTrivialToPrimitiveCopy(true);
16136       if (FT.isDestructedType()) {
16137         Record->setNonTrivialToPrimitiveDestroy(true);
16138         Record->setParamDestroyedInCallee(true);
16139       }
16140 
16141       if (const auto *RT = FT->getAs<RecordType>()) {
16142         if (RT->getDecl()->getArgPassingRestrictions() ==
16143             RecordDecl::APK_CanNeverPassInRegs)
16144           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16145       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16146         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16147     }
16148 
16149     if (Record && FD->getType().isVolatileQualified())
16150       Record->setHasVolatileMember(true);
16151     // Keep track of the number of named members.
16152     if (FD->getIdentifier())
16153       ++NumNamedMembers;
16154   }
16155 
16156   // Okay, we successfully defined 'Record'.
16157   if (Record) {
16158     bool Completed = false;
16159     if (CXXRecord) {
16160       if (!CXXRecord->isInvalidDecl()) {
16161         // Set access bits correctly on the directly-declared conversions.
16162         for (CXXRecordDecl::conversion_iterator
16163                I = CXXRecord->conversion_begin(),
16164                E = CXXRecord->conversion_end(); I != E; ++I)
16165           I.setAccess((*I)->getAccess());
16166       }
16167 
16168       if (!CXXRecord->isDependentType()) {
16169         // Add any implicitly-declared members to this class.
16170         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16171 
16172         if (!CXXRecord->isInvalidDecl()) {
16173           // If we have virtual base classes, we may end up finding multiple
16174           // final overriders for a given virtual function. Check for this
16175           // problem now.
16176           if (CXXRecord->getNumVBases()) {
16177             CXXFinalOverriderMap FinalOverriders;
16178             CXXRecord->getFinalOverriders(FinalOverriders);
16179 
16180             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16181                                              MEnd = FinalOverriders.end();
16182                  M != MEnd; ++M) {
16183               for (OverridingMethods::iterator SO = M->second.begin(),
16184                                             SOEnd = M->second.end();
16185                    SO != SOEnd; ++SO) {
16186                 assert(SO->second.size() > 0 &&
16187                        "Virtual function without overriding functions?");
16188                 if (SO->second.size() == 1)
16189                   continue;
16190 
16191                 // C++ [class.virtual]p2:
16192                 //   In a derived class, if a virtual member function of a base
16193                 //   class subobject has more than one final overrider the
16194                 //   program is ill-formed.
16195                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16196                   << (const NamedDecl *)M->first << Record;
16197                 Diag(M->first->getLocation(),
16198                      diag::note_overridden_virtual_function);
16199                 for (OverridingMethods::overriding_iterator
16200                           OM = SO->second.begin(),
16201                        OMEnd = SO->second.end();
16202                      OM != OMEnd; ++OM)
16203                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16204                     << (const NamedDecl *)M->first << OM->Method->getParent();
16205 
16206                 Record->setInvalidDecl();
16207               }
16208             }
16209             CXXRecord->completeDefinition(&FinalOverriders);
16210             Completed = true;
16211           }
16212         }
16213       }
16214     }
16215 
16216     if (!Completed)
16217       Record->completeDefinition();
16218 
16219     // Handle attributes before checking the layout.
16220     ProcessDeclAttributeList(S, Record, Attrs);
16221 
16222     // We may have deferred checking for a deleted destructor. Check now.
16223     if (CXXRecord) {
16224       auto *Dtor = CXXRecord->getDestructor();
16225       if (Dtor && Dtor->isImplicit() &&
16226           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16227         CXXRecord->setImplicitDestructorIsDeleted();
16228         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16229       }
16230     }
16231 
16232     if (Record->hasAttrs()) {
16233       CheckAlignasUnderalignment(Record);
16234 
16235       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16236         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16237                                            IA->getRange(), IA->getBestCase(),
16238                                            IA->getSemanticSpelling());
16239     }
16240 
16241     // Check if the structure/union declaration is a type that can have zero
16242     // size in C. For C this is a language extension, for C++ it may cause
16243     // compatibility problems.
16244     bool CheckForZeroSize;
16245     if (!getLangOpts().CPlusPlus) {
16246       CheckForZeroSize = true;
16247     } else {
16248       // For C++ filter out types that cannot be referenced in C code.
16249       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16250       CheckForZeroSize =
16251           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16252           !CXXRecord->isDependentType() &&
16253           CXXRecord->isCLike();
16254     }
16255     if (CheckForZeroSize) {
16256       bool ZeroSize = true;
16257       bool IsEmpty = true;
16258       unsigned NonBitFields = 0;
16259       for (RecordDecl::field_iterator I = Record->field_begin(),
16260                                       E = Record->field_end();
16261            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16262         IsEmpty = false;
16263         if (I->isUnnamedBitfield()) {
16264           if (!I->isZeroLengthBitField(Context))
16265             ZeroSize = false;
16266         } else {
16267           ++NonBitFields;
16268           QualType FieldType = I->getType();
16269           if (FieldType->isIncompleteType() ||
16270               !Context.getTypeSizeInChars(FieldType).isZero())
16271             ZeroSize = false;
16272         }
16273       }
16274 
16275       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16276       // allowed in C++, but warn if its declaration is inside
16277       // extern "C" block.
16278       if (ZeroSize) {
16279         Diag(RecLoc, getLangOpts().CPlusPlus ?
16280                          diag::warn_zero_size_struct_union_in_extern_c :
16281                          diag::warn_zero_size_struct_union_compat)
16282           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16283       }
16284 
16285       // Structs without named members are extension in C (C99 6.7.2.1p7),
16286       // but are accepted by GCC.
16287       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16288         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16289                                diag::ext_no_named_members_in_struct_union)
16290           << Record->isUnion();
16291       }
16292     }
16293   } else {
16294     ObjCIvarDecl **ClsFields =
16295       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16296     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16297       ID->setEndOfDefinitionLoc(RBrac);
16298       // Add ivar's to class's DeclContext.
16299       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16300         ClsFields[i]->setLexicalDeclContext(ID);
16301         ID->addDecl(ClsFields[i]);
16302       }
16303       // Must enforce the rule that ivars in the base classes may not be
16304       // duplicates.
16305       if (ID->getSuperClass())
16306         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16307     } else if (ObjCImplementationDecl *IMPDecl =
16308                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16309       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16310       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16311         // Ivar declared in @implementation never belongs to the implementation.
16312         // Only it is in implementation's lexical context.
16313         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16314       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16315       IMPDecl->setIvarLBraceLoc(LBrac);
16316       IMPDecl->setIvarRBraceLoc(RBrac);
16317     } else if (ObjCCategoryDecl *CDecl =
16318                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16319       // case of ivars in class extension; all other cases have been
16320       // reported as errors elsewhere.
16321       // FIXME. Class extension does not have a LocEnd field.
16322       // CDecl->setLocEnd(RBrac);
16323       // Add ivar's to class extension's DeclContext.
16324       // Diagnose redeclaration of private ivars.
16325       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16326       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16327         if (IDecl) {
16328           if (const ObjCIvarDecl *ClsIvar =
16329               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16330             Diag(ClsFields[i]->getLocation(),
16331                  diag::err_duplicate_ivar_declaration);
16332             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16333             continue;
16334           }
16335           for (const auto *Ext : IDecl->known_extensions()) {
16336             if (const ObjCIvarDecl *ClsExtIvar
16337                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16338               Diag(ClsFields[i]->getLocation(),
16339                    diag::err_duplicate_ivar_declaration);
16340               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16341               continue;
16342             }
16343           }
16344         }
16345         ClsFields[i]->setLexicalDeclContext(CDecl);
16346         CDecl->addDecl(ClsFields[i]);
16347       }
16348       CDecl->setIvarLBraceLoc(LBrac);
16349       CDecl->setIvarRBraceLoc(RBrac);
16350     }
16351   }
16352 }
16353 
16354 /// Determine whether the given integral value is representable within
16355 /// the given type T.
16356 static bool isRepresentableIntegerValue(ASTContext &Context,
16357                                         llvm::APSInt &Value,
16358                                         QualType T) {
16359   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16360          "Integral type required!");
16361   unsigned BitWidth = Context.getIntWidth(T);
16362 
16363   if (Value.isUnsigned() || Value.isNonNegative()) {
16364     if (T->isSignedIntegerOrEnumerationType())
16365       --BitWidth;
16366     return Value.getActiveBits() <= BitWidth;
16367   }
16368   return Value.getMinSignedBits() <= BitWidth;
16369 }
16370 
16371 // Given an integral type, return the next larger integral type
16372 // (or a NULL type of no such type exists).
16373 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16374   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16375   // enum checking below.
16376   assert((T->isIntegralType(Context) ||
16377          T->isEnumeralType()) && "Integral type required!");
16378   const unsigned NumTypes = 4;
16379   QualType SignedIntegralTypes[NumTypes] = {
16380     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16381   };
16382   QualType UnsignedIntegralTypes[NumTypes] = {
16383     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16384     Context.UnsignedLongLongTy
16385   };
16386 
16387   unsigned BitWidth = Context.getTypeSize(T);
16388   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16389                                                         : UnsignedIntegralTypes;
16390   for (unsigned I = 0; I != NumTypes; ++I)
16391     if (Context.getTypeSize(Types[I]) > BitWidth)
16392       return Types[I];
16393 
16394   return QualType();
16395 }
16396 
16397 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16398                                           EnumConstantDecl *LastEnumConst,
16399                                           SourceLocation IdLoc,
16400                                           IdentifierInfo *Id,
16401                                           Expr *Val) {
16402   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16403   llvm::APSInt EnumVal(IntWidth);
16404   QualType EltTy;
16405 
16406   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16407     Val = nullptr;
16408 
16409   if (Val)
16410     Val = DefaultLvalueConversion(Val).get();
16411 
16412   if (Val) {
16413     if (Enum->isDependentType() || Val->isTypeDependent())
16414       EltTy = Context.DependentTy;
16415     else {
16416       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16417           !getLangOpts().MSVCCompat) {
16418         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16419         // constant-expression in the enumerator-definition shall be a converted
16420         // constant expression of the underlying type.
16421         EltTy = Enum->getIntegerType();
16422         ExprResult Converted =
16423           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16424                                            CCEK_Enumerator);
16425         if (Converted.isInvalid())
16426           Val = nullptr;
16427         else
16428           Val = Converted.get();
16429       } else if (!Val->isValueDependent() &&
16430                  !(Val = VerifyIntegerConstantExpression(Val,
16431                                                          &EnumVal).get())) {
16432         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16433       } else {
16434         if (Enum->isComplete()) {
16435           EltTy = Enum->getIntegerType();
16436 
16437           // In Obj-C and Microsoft mode, require the enumeration value to be
16438           // representable in the underlying type of the enumeration. In C++11,
16439           // we perform a non-narrowing conversion as part of converted constant
16440           // expression checking.
16441           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16442             if (getLangOpts().MSVCCompat) {
16443               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16444               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16445             } else
16446               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16447           } else
16448             Val = ImpCastExprToType(Val, EltTy,
16449                                     EltTy->isBooleanType() ?
16450                                     CK_IntegralToBoolean : CK_IntegralCast)
16451                     .get();
16452         } else if (getLangOpts().CPlusPlus) {
16453           // C++11 [dcl.enum]p5:
16454           //   If the underlying type is not fixed, the type of each enumerator
16455           //   is the type of its initializing value:
16456           //     - If an initializer is specified for an enumerator, the
16457           //       initializing value has the same type as the expression.
16458           EltTy = Val->getType();
16459         } else {
16460           // C99 6.7.2.2p2:
16461           //   The expression that defines the value of an enumeration constant
16462           //   shall be an integer constant expression that has a value
16463           //   representable as an int.
16464 
16465           // Complain if the value is not representable in an int.
16466           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16467             Diag(IdLoc, diag::ext_enum_value_not_int)
16468               << EnumVal.toString(10) << Val->getSourceRange()
16469               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16470           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16471             // Force the type of the expression to 'int'.
16472             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16473           }
16474           EltTy = Val->getType();
16475         }
16476       }
16477     }
16478   }
16479 
16480   if (!Val) {
16481     if (Enum->isDependentType())
16482       EltTy = Context.DependentTy;
16483     else if (!LastEnumConst) {
16484       // C++0x [dcl.enum]p5:
16485       //   If the underlying type is not fixed, the type of each enumerator
16486       //   is the type of its initializing value:
16487       //     - If no initializer is specified for the first enumerator, the
16488       //       initializing value has an unspecified integral type.
16489       //
16490       // GCC uses 'int' for its unspecified integral type, as does
16491       // C99 6.7.2.2p3.
16492       if (Enum->isFixed()) {
16493         EltTy = Enum->getIntegerType();
16494       }
16495       else {
16496         EltTy = Context.IntTy;
16497       }
16498     } else {
16499       // Assign the last value + 1.
16500       EnumVal = LastEnumConst->getInitVal();
16501       ++EnumVal;
16502       EltTy = LastEnumConst->getType();
16503 
16504       // Check for overflow on increment.
16505       if (EnumVal < LastEnumConst->getInitVal()) {
16506         // C++0x [dcl.enum]p5:
16507         //   If the underlying type is not fixed, the type of each enumerator
16508         //   is the type of its initializing value:
16509         //
16510         //     - Otherwise the type of the initializing value is the same as
16511         //       the type of the initializing value of the preceding enumerator
16512         //       unless the incremented value is not representable in that type,
16513         //       in which case the type is an unspecified integral type
16514         //       sufficient to contain the incremented value. If no such type
16515         //       exists, the program is ill-formed.
16516         QualType T = getNextLargerIntegralType(Context, EltTy);
16517         if (T.isNull() || Enum->isFixed()) {
16518           // There is no integral type larger enough to represent this
16519           // value. Complain, then allow the value to wrap around.
16520           EnumVal = LastEnumConst->getInitVal();
16521           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16522           ++EnumVal;
16523           if (Enum->isFixed())
16524             // When the underlying type is fixed, this is ill-formed.
16525             Diag(IdLoc, diag::err_enumerator_wrapped)
16526               << EnumVal.toString(10)
16527               << EltTy;
16528           else
16529             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16530               << EnumVal.toString(10);
16531         } else {
16532           EltTy = T;
16533         }
16534 
16535         // Retrieve the last enumerator's value, extent that type to the
16536         // type that is supposed to be large enough to represent the incremented
16537         // value, then increment.
16538         EnumVal = LastEnumConst->getInitVal();
16539         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16540         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16541         ++EnumVal;
16542 
16543         // If we're not in C++, diagnose the overflow of enumerator values,
16544         // which in C99 means that the enumerator value is not representable in
16545         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16546         // permits enumerator values that are representable in some larger
16547         // integral type.
16548         if (!getLangOpts().CPlusPlus && !T.isNull())
16549           Diag(IdLoc, diag::warn_enum_value_overflow);
16550       } else if (!getLangOpts().CPlusPlus &&
16551                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16552         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16553         Diag(IdLoc, diag::ext_enum_value_not_int)
16554           << EnumVal.toString(10) << 1;
16555       }
16556     }
16557   }
16558 
16559   if (!EltTy->isDependentType()) {
16560     // Make the enumerator value match the signedness and size of the
16561     // enumerator's type.
16562     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16563     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16564   }
16565 
16566   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16567                                   Val, EnumVal);
16568 }
16569 
16570 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16571                                                 SourceLocation IILoc) {
16572   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16573       !getLangOpts().CPlusPlus)
16574     return SkipBodyInfo();
16575 
16576   // We have an anonymous enum definition. Look up the first enumerator to
16577   // determine if we should merge the definition with an existing one and
16578   // skip the body.
16579   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16580                                          forRedeclarationInCurContext());
16581   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16582   if (!PrevECD)
16583     return SkipBodyInfo();
16584 
16585   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16586   NamedDecl *Hidden;
16587   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16588     SkipBodyInfo Skip;
16589     Skip.Previous = Hidden;
16590     return Skip;
16591   }
16592 
16593   return SkipBodyInfo();
16594 }
16595 
16596 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16597                               SourceLocation IdLoc, IdentifierInfo *Id,
16598                               const ParsedAttributesView &Attrs,
16599                               SourceLocation EqualLoc, Expr *Val) {
16600   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16601   EnumConstantDecl *LastEnumConst =
16602     cast_or_null<EnumConstantDecl>(lastEnumConst);
16603 
16604   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16605   // we find one that is.
16606   S = getNonFieldDeclScope(S);
16607 
16608   // Verify that there isn't already something declared with this name in this
16609   // scope.
16610   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16611   LookupName(R, S);
16612   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16613 
16614   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16615     // Maybe we will complain about the shadowed template parameter.
16616     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16617     // Just pretend that we didn't see the previous declaration.
16618     PrevDecl = nullptr;
16619   }
16620 
16621   // C++ [class.mem]p15:
16622   // If T is the name of a class, then each of the following shall have a name
16623   // different from T:
16624   // - every enumerator of every member of class T that is an unscoped
16625   // enumerated type
16626   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16627     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16628                             DeclarationNameInfo(Id, IdLoc));
16629 
16630   EnumConstantDecl *New =
16631     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16632   if (!New)
16633     return nullptr;
16634 
16635   if (PrevDecl) {
16636     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16637       // Check for other kinds of shadowing not already handled.
16638       CheckShadow(New, PrevDecl, R);
16639     }
16640 
16641     // When in C++, we may get a TagDecl with the same name; in this case the
16642     // enum constant will 'hide' the tag.
16643     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16644            "Received TagDecl when not in C++!");
16645     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16646       if (isa<EnumConstantDecl>(PrevDecl))
16647         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16648       else
16649         Diag(IdLoc, diag::err_redefinition) << Id;
16650       notePreviousDefinition(PrevDecl, IdLoc);
16651       return nullptr;
16652     }
16653   }
16654 
16655   // Process attributes.
16656   ProcessDeclAttributeList(S, New, Attrs);
16657   AddPragmaAttributes(S, New);
16658 
16659   // Register this decl in the current scope stack.
16660   New->setAccess(TheEnumDecl->getAccess());
16661   PushOnScopeChains(New, S);
16662 
16663   ActOnDocumentableDecl(New);
16664 
16665   return New;
16666 }
16667 
16668 // Returns true when the enum initial expression does not trigger the
16669 // duplicate enum warning.  A few common cases are exempted as follows:
16670 // Element2 = Element1
16671 // Element2 = Element1 + 1
16672 // Element2 = Element1 - 1
16673 // Where Element2 and Element1 are from the same enum.
16674 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16675   Expr *InitExpr = ECD->getInitExpr();
16676   if (!InitExpr)
16677     return true;
16678   InitExpr = InitExpr->IgnoreImpCasts();
16679 
16680   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16681     if (!BO->isAdditiveOp())
16682       return true;
16683     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16684     if (!IL)
16685       return true;
16686     if (IL->getValue() != 1)
16687       return true;
16688 
16689     InitExpr = BO->getLHS();
16690   }
16691 
16692   // This checks if the elements are from the same enum.
16693   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16694   if (!DRE)
16695     return true;
16696 
16697   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16698   if (!EnumConstant)
16699     return true;
16700 
16701   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16702       Enum)
16703     return true;
16704 
16705   return false;
16706 }
16707 
16708 // Emits a warning when an element is implicitly set a value that
16709 // a previous element has already been set to.
16710 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16711                                         EnumDecl *Enum, QualType EnumType) {
16712   // Avoid anonymous enums
16713   if (!Enum->getIdentifier())
16714     return;
16715 
16716   // Only check for small enums.
16717   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16718     return;
16719 
16720   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16721     return;
16722 
16723   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16724   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16725 
16726   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16727   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16728 
16729   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16730   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16731     llvm::APSInt Val = D->getInitVal();
16732     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16733   };
16734 
16735   DuplicatesVector DupVector;
16736   ValueToVectorMap EnumMap;
16737 
16738   // Populate the EnumMap with all values represented by enum constants without
16739   // an initializer.
16740   for (auto *Element : Elements) {
16741     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16742 
16743     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16744     // this constant.  Skip this enum since it may be ill-formed.
16745     if (!ECD) {
16746       return;
16747     }
16748 
16749     // Constants with initalizers are handled in the next loop.
16750     if (ECD->getInitExpr())
16751       continue;
16752 
16753     // Duplicate values are handled in the next loop.
16754     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16755   }
16756 
16757   if (EnumMap.size() == 0)
16758     return;
16759 
16760   // Create vectors for any values that has duplicates.
16761   for (auto *Element : Elements) {
16762     // The last loop returned if any constant was null.
16763     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16764     if (!ValidDuplicateEnum(ECD, Enum))
16765       continue;
16766 
16767     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16768     if (Iter == EnumMap.end())
16769       continue;
16770 
16771     DeclOrVector& Entry = Iter->second;
16772     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16773       // Ensure constants are different.
16774       if (D == ECD)
16775         continue;
16776 
16777       // Create new vector and push values onto it.
16778       auto Vec = llvm::make_unique<ECDVector>();
16779       Vec->push_back(D);
16780       Vec->push_back(ECD);
16781 
16782       // Update entry to point to the duplicates vector.
16783       Entry = Vec.get();
16784 
16785       // Store the vector somewhere we can consult later for quick emission of
16786       // diagnostics.
16787       DupVector.emplace_back(std::move(Vec));
16788       continue;
16789     }
16790 
16791     ECDVector *Vec = Entry.get<ECDVector*>();
16792     // Make sure constants are not added more than once.
16793     if (*Vec->begin() == ECD)
16794       continue;
16795 
16796     Vec->push_back(ECD);
16797   }
16798 
16799   // Emit diagnostics.
16800   for (const auto &Vec : DupVector) {
16801     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16802 
16803     // Emit warning for one enum constant.
16804     auto *FirstECD = Vec->front();
16805     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16806       << FirstECD << FirstECD->getInitVal().toString(10)
16807       << FirstECD->getSourceRange();
16808 
16809     // Emit one note for each of the remaining enum constants with
16810     // the same value.
16811     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16812       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16813         << ECD << ECD->getInitVal().toString(10)
16814         << ECD->getSourceRange();
16815   }
16816 }
16817 
16818 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16819                              bool AllowMask) const {
16820   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16821   assert(ED->isCompleteDefinition() && "expected enum definition");
16822 
16823   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16824   llvm::APInt &FlagBits = R.first->second;
16825 
16826   if (R.second) {
16827     for (auto *E : ED->enumerators()) {
16828       const auto &EVal = E->getInitVal();
16829       // Only single-bit enumerators introduce new flag values.
16830       if (EVal.isPowerOf2())
16831         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16832     }
16833   }
16834 
16835   // A value is in a flag enum if either its bits are a subset of the enum's
16836   // flag bits (the first condition) or we are allowing masks and the same is
16837   // true of its complement (the second condition). When masks are allowed, we
16838   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16839   //
16840   // While it's true that any value could be used as a mask, the assumption is
16841   // that a mask will have all of the insignificant bits set. Anything else is
16842   // likely a logic error.
16843   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16844   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16845 }
16846 
16847 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16848                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16849                          const ParsedAttributesView &Attrs) {
16850   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16851   QualType EnumType = Context.getTypeDeclType(Enum);
16852 
16853   ProcessDeclAttributeList(S, Enum, Attrs);
16854 
16855   if (Enum->isDependentType()) {
16856     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16857       EnumConstantDecl *ECD =
16858         cast_or_null<EnumConstantDecl>(Elements[i]);
16859       if (!ECD) continue;
16860 
16861       ECD->setType(EnumType);
16862     }
16863 
16864     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16865     return;
16866   }
16867 
16868   // TODO: If the result value doesn't fit in an int, it must be a long or long
16869   // long value.  ISO C does not support this, but GCC does as an extension,
16870   // emit a warning.
16871   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16872   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16873   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16874 
16875   // Verify that all the values are okay, compute the size of the values, and
16876   // reverse the list.
16877   unsigned NumNegativeBits = 0;
16878   unsigned NumPositiveBits = 0;
16879 
16880   // Keep track of whether all elements have type int.
16881   bool AllElementsInt = true;
16882 
16883   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16884     EnumConstantDecl *ECD =
16885       cast_or_null<EnumConstantDecl>(Elements[i]);
16886     if (!ECD) continue;  // Already issued a diagnostic.
16887 
16888     const llvm::APSInt &InitVal = ECD->getInitVal();
16889 
16890     // Keep track of the size of positive and negative values.
16891     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16892       NumPositiveBits = std::max(NumPositiveBits,
16893                                  (unsigned)InitVal.getActiveBits());
16894     else
16895       NumNegativeBits = std::max(NumNegativeBits,
16896                                  (unsigned)InitVal.getMinSignedBits());
16897 
16898     // Keep track of whether every enum element has type int (very common).
16899     if (AllElementsInt)
16900       AllElementsInt = ECD->getType() == Context.IntTy;
16901   }
16902 
16903   // Figure out the type that should be used for this enum.
16904   QualType BestType;
16905   unsigned BestWidth;
16906 
16907   // C++0x N3000 [conv.prom]p3:
16908   //   An rvalue of an unscoped enumeration type whose underlying
16909   //   type is not fixed can be converted to an rvalue of the first
16910   //   of the following types that can represent all the values of
16911   //   the enumeration: int, unsigned int, long int, unsigned long
16912   //   int, long long int, or unsigned long long int.
16913   // C99 6.4.4.3p2:
16914   //   An identifier declared as an enumeration constant has type int.
16915   // The C99 rule is modified by a gcc extension
16916   QualType BestPromotionType;
16917 
16918   bool Packed = Enum->hasAttr<PackedAttr>();
16919   // -fshort-enums is the equivalent to specifying the packed attribute on all
16920   // enum definitions.
16921   if (LangOpts.ShortEnums)
16922     Packed = true;
16923 
16924   // If the enum already has a type because it is fixed or dictated by the
16925   // target, promote that type instead of analyzing the enumerators.
16926   if (Enum->isComplete()) {
16927     BestType = Enum->getIntegerType();
16928     if (BestType->isPromotableIntegerType())
16929       BestPromotionType = Context.getPromotedIntegerType(BestType);
16930     else
16931       BestPromotionType = BestType;
16932 
16933     BestWidth = Context.getIntWidth(BestType);
16934   }
16935   else if (NumNegativeBits) {
16936     // If there is a negative value, figure out the smallest integer type (of
16937     // int/long/longlong) that fits.
16938     // If it's packed, check also if it fits a char or a short.
16939     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16940       BestType = Context.SignedCharTy;
16941       BestWidth = CharWidth;
16942     } else if (Packed && NumNegativeBits <= ShortWidth &&
16943                NumPositiveBits < ShortWidth) {
16944       BestType = Context.ShortTy;
16945       BestWidth = ShortWidth;
16946     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16947       BestType = Context.IntTy;
16948       BestWidth = IntWidth;
16949     } else {
16950       BestWidth = Context.getTargetInfo().getLongWidth();
16951 
16952       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16953         BestType = Context.LongTy;
16954       } else {
16955         BestWidth = Context.getTargetInfo().getLongLongWidth();
16956 
16957         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16958           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16959         BestType = Context.LongLongTy;
16960       }
16961     }
16962     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16963   } else {
16964     // If there is no negative value, figure out the smallest type that fits
16965     // all of the enumerator values.
16966     // If it's packed, check also if it fits a char or a short.
16967     if (Packed && NumPositiveBits <= CharWidth) {
16968       BestType = Context.UnsignedCharTy;
16969       BestPromotionType = Context.IntTy;
16970       BestWidth = CharWidth;
16971     } else if (Packed && NumPositiveBits <= ShortWidth) {
16972       BestType = Context.UnsignedShortTy;
16973       BestPromotionType = Context.IntTy;
16974       BestWidth = ShortWidth;
16975     } else if (NumPositiveBits <= IntWidth) {
16976       BestType = Context.UnsignedIntTy;
16977       BestWidth = IntWidth;
16978       BestPromotionType
16979         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16980                            ? Context.UnsignedIntTy : Context.IntTy;
16981     } else if (NumPositiveBits <=
16982                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16983       BestType = Context.UnsignedLongTy;
16984       BestPromotionType
16985         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16986                            ? Context.UnsignedLongTy : Context.LongTy;
16987     } else {
16988       BestWidth = Context.getTargetInfo().getLongLongWidth();
16989       assert(NumPositiveBits <= BestWidth &&
16990              "How could an initializer get larger than ULL?");
16991       BestType = Context.UnsignedLongLongTy;
16992       BestPromotionType
16993         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16994                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16995     }
16996   }
16997 
16998   // Loop over all of the enumerator constants, changing their types to match
16999   // the type of the enum if needed.
17000   for (auto *D : Elements) {
17001     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17002     if (!ECD) continue;  // Already issued a diagnostic.
17003 
17004     // Standard C says the enumerators have int type, but we allow, as an
17005     // extension, the enumerators to be larger than int size.  If each
17006     // enumerator value fits in an int, type it as an int, otherwise type it the
17007     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17008     // that X has type 'int', not 'unsigned'.
17009 
17010     // Determine whether the value fits into an int.
17011     llvm::APSInt InitVal = ECD->getInitVal();
17012 
17013     // If it fits into an integer type, force it.  Otherwise force it to match
17014     // the enum decl type.
17015     QualType NewTy;
17016     unsigned NewWidth;
17017     bool NewSign;
17018     if (!getLangOpts().CPlusPlus &&
17019         !Enum->isFixed() &&
17020         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17021       NewTy = Context.IntTy;
17022       NewWidth = IntWidth;
17023       NewSign = true;
17024     } else if (ECD->getType() == BestType) {
17025       // Already the right type!
17026       if (getLangOpts().CPlusPlus)
17027         // C++ [dcl.enum]p4: Following the closing brace of an
17028         // enum-specifier, each enumerator has the type of its
17029         // enumeration.
17030         ECD->setType(EnumType);
17031       continue;
17032     } else {
17033       NewTy = BestType;
17034       NewWidth = BestWidth;
17035       NewSign = BestType->isSignedIntegerOrEnumerationType();
17036     }
17037 
17038     // Adjust the APSInt value.
17039     InitVal = InitVal.extOrTrunc(NewWidth);
17040     InitVal.setIsSigned(NewSign);
17041     ECD->setInitVal(InitVal);
17042 
17043     // Adjust the Expr initializer and type.
17044     if (ECD->getInitExpr() &&
17045         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17046       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17047                                                 CK_IntegralCast,
17048                                                 ECD->getInitExpr(),
17049                                                 /*base paths*/ nullptr,
17050                                                 VK_RValue));
17051     if (getLangOpts().CPlusPlus)
17052       // C++ [dcl.enum]p4: Following the closing brace of an
17053       // enum-specifier, each enumerator has the type of its
17054       // enumeration.
17055       ECD->setType(EnumType);
17056     else
17057       ECD->setType(NewTy);
17058   }
17059 
17060   Enum->completeDefinition(BestType, BestPromotionType,
17061                            NumPositiveBits, NumNegativeBits);
17062 
17063   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17064 
17065   if (Enum->isClosedFlag()) {
17066     for (Decl *D : Elements) {
17067       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17068       if (!ECD) continue;  // Already issued a diagnostic.
17069 
17070       llvm::APSInt InitVal = ECD->getInitVal();
17071       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17072           !IsValueInFlagEnum(Enum, InitVal, true))
17073         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17074           << ECD << Enum;
17075     }
17076   }
17077 
17078   // Now that the enum type is defined, ensure it's not been underaligned.
17079   if (Enum->hasAttrs())
17080     CheckAlignasUnderalignment(Enum);
17081 }
17082 
17083 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17084                                   SourceLocation StartLoc,
17085                                   SourceLocation EndLoc) {
17086   StringLiteral *AsmString = cast<StringLiteral>(expr);
17087 
17088   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17089                                                    AsmString, StartLoc,
17090                                                    EndLoc);
17091   CurContext->addDecl(New);
17092   return New;
17093 }
17094 
17095 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17096                                       IdentifierInfo* AliasName,
17097                                       SourceLocation PragmaLoc,
17098                                       SourceLocation NameLoc,
17099                                       SourceLocation AliasNameLoc) {
17100   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17101                                          LookupOrdinaryName);
17102   AsmLabelAttr *Attr =
17103       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17104 
17105   // If a declaration that:
17106   // 1) declares a function or a variable
17107   // 2) has external linkage
17108   // already exists, add a label attribute to it.
17109   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17110     if (isDeclExternC(PrevDecl))
17111       PrevDecl->addAttr(Attr);
17112     else
17113       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17114           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17115   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17116   } else
17117     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17118 }
17119 
17120 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17121                              SourceLocation PragmaLoc,
17122                              SourceLocation NameLoc) {
17123   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17124 
17125   if (PrevDecl) {
17126     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17127   } else {
17128     (void)WeakUndeclaredIdentifiers.insert(
17129       std::pair<IdentifierInfo*,WeakInfo>
17130         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17131   }
17132 }
17133 
17134 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17135                                 IdentifierInfo* AliasName,
17136                                 SourceLocation PragmaLoc,
17137                                 SourceLocation NameLoc,
17138                                 SourceLocation AliasNameLoc) {
17139   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17140                                     LookupOrdinaryName);
17141   WeakInfo W = WeakInfo(Name, NameLoc);
17142 
17143   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17144     if (!PrevDecl->hasAttr<AliasAttr>())
17145       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17146         DeclApplyPragmaWeak(TUScope, ND, W);
17147   } else {
17148     (void)WeakUndeclaredIdentifiers.insert(
17149       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17150   }
17151 }
17152 
17153 Decl *Sema::getObjCDeclContext() const {
17154   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17155 }
17156