xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp (revision e2eeea75eb8b6dd50c1298067a0655880d186734)
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/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw_wchar_t:
145   case tok::kw_bool:
146   case tok::kw___underlying_type:
147   case tok::kw___auto_type:
148     return true;
149 
150   case tok::annot_typename:
151   case tok::kw_char16_t:
152   case tok::kw_char32_t:
153   case tok::kw_typeof:
154   case tok::annot_decltype:
155   case tok::kw_decltype:
156     return getLangOpts().CPlusPlus;
157 
158   case tok::kw_char8_t:
159     return getLangOpts().Char8;
160 
161   default:
162     break;
163   }
164 
165   return false;
166 }
167 
168 namespace {
169 enum class UnqualifiedTypeNameLookupResult {
170   NotFound,
171   FoundNonType,
172   FoundType
173 };
174 } // end anonymous namespace
175 
176 /// Tries to perform unqualified lookup of the type decls in bases for
177 /// dependent class.
178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179 /// type decl, \a FoundType if only type decls are found.
180 static UnqualifiedTypeNameLookupResult
181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182                                 SourceLocation NameLoc,
183                                 const CXXRecordDecl *RD) {
184   if (!RD->hasDefinition())
185     return UnqualifiedTypeNameLookupResult::NotFound;
186   // Look for type decls in base classes.
187   UnqualifiedTypeNameLookupResult FoundTypeDecl =
188       UnqualifiedTypeNameLookupResult::NotFound;
189   for (const auto &Base : RD->bases()) {
190     const CXXRecordDecl *BaseRD = nullptr;
191     if (auto *BaseTT = Base.getType()->getAs<TagType>())
192       BaseRD = BaseTT->getAsCXXRecordDecl();
193     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194       // Look for type decls in dependent base classes that have known primary
195       // templates.
196       if (!TST || !TST->isDependentType())
197         continue;
198       auto *TD = TST->getTemplateName().getAsTemplateDecl();
199       if (!TD)
200         continue;
201       if (auto *BasePrimaryTemplate =
202           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204           BaseRD = BasePrimaryTemplate;
205         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206           if (const ClassTemplatePartialSpecializationDecl *PS =
207                   CTD->findPartialSpecialization(Base.getType()))
208             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209               BaseRD = PS;
210         }
211       }
212     }
213     if (BaseRD) {
214       for (NamedDecl *ND : BaseRD->lookup(&II)) {
215         if (!isa<TypeDecl>(ND))
216           return UnqualifiedTypeNameLookupResult::FoundNonType;
217         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218       }
219       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221         case UnqualifiedTypeNameLookupResult::FoundNonType:
222           return UnqualifiedTypeNameLookupResult::FoundNonType;
223         case UnqualifiedTypeNameLookupResult::FoundType:
224           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225           break;
226         case UnqualifiedTypeNameLookupResult::NotFound:
227           break;
228         }
229       }
230     }
231   }
232 
233   return FoundTypeDecl;
234 }
235 
236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237                                                       const IdentifierInfo &II,
238                                                       SourceLocation NameLoc) {
239   // Lookup in the parent class template context, if any.
240   const CXXRecordDecl *RD = nullptr;
241   UnqualifiedTypeNameLookupResult FoundTypeDecl =
242       UnqualifiedTypeNameLookupResult::NotFound;
243   for (DeclContext *DC = S.CurContext;
244        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245        DC = DC->getParent()) {
246     // Look for type decls in dependent base classes that have known primary
247     // templates.
248     RD = dyn_cast<CXXRecordDecl>(DC);
249     if (RD && RD->getDescribedClassTemplate())
250       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251   }
252   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253     return nullptr;
254 
255   // We found some types in dependent base classes.  Recover as if the user
256   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
257   // lookup during template instantiation.
258   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
259 
260   ASTContext &Context = S.Context;
261   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262                                           cast<Type>(Context.getRecordType(RD)));
263   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264 
265   CXXScopeSpec SS;
266   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267 
268   TypeLocBuilder Builder;
269   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270   DepTL.setNameLoc(NameLoc);
271   DepTL.setElaboratedKeywordLoc(SourceLocation());
272   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274 }
275 
276 /// If the identifier refers to a type name within this scope,
277 /// return the declaration of that type.
278 ///
279 /// This routine performs ordinary name lookup of the identifier II
280 /// within the given scope, with optional C++ scope specifier SS, to
281 /// determine whether the name refers to a type. If so, returns an
282 /// opaque pointer (actually a QualType) corresponding to that
283 /// type. Otherwise, returns NULL.
284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285                              Scope *S, CXXScopeSpec *SS,
286                              bool isClassName, bool HasTrailingDot,
287                              ParsedType ObjectTypePtr,
288                              bool IsCtorOrDtorName,
289                              bool WantNontrivialTypeSourceInfo,
290                              bool IsClassTemplateDeductionContext,
291                              IdentifierInfo **CorrectedII) {
292   // FIXME: Consider allowing this outside C++1z mode as an extension.
293   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295                               !isClassName && !HasTrailingDot;
296 
297   // Determine where we will perform name lookup.
298   DeclContext *LookupCtx = nullptr;
299   if (ObjectTypePtr) {
300     QualType ObjectType = ObjectTypePtr.get();
301     if (ObjectType->isRecordType())
302       LookupCtx = computeDeclContext(ObjectType);
303   } else if (SS && SS->isNotEmpty()) {
304     LookupCtx = computeDeclContext(*SS, false);
305 
306     if (!LookupCtx) {
307       if (isDependentScopeSpecifier(*SS)) {
308         // C++ [temp.res]p3:
309         //   A qualified-id that refers to a type and in which the
310         //   nested-name-specifier depends on a template-parameter (14.6.2)
311         //   shall be prefixed by the keyword typename to indicate that the
312         //   qualified-id denotes a type, forming an
313         //   elaborated-type-specifier (7.1.5.3).
314         //
315         // We therefore do not perform any name lookup if the result would
316         // refer to a member of an unknown specialization.
317         if (!isClassName && !IsCtorOrDtorName)
318           return nullptr;
319 
320         // We know from the grammar that this name refers to a type,
321         // so build a dependent node to describe the type.
322         if (WantNontrivialTypeSourceInfo)
323           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324 
325         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327                                        II, NameLoc);
328         return ParsedType::make(T);
329       }
330 
331       return nullptr;
332     }
333 
334     if (!LookupCtx->isDependentContext() &&
335         RequireCompleteDeclContext(*SS, LookupCtx))
336       return nullptr;
337   }
338 
339   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340   // lookup for class-names.
341   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342                                       LookupOrdinaryName;
343   LookupResult Result(*this, &II, NameLoc, Kind);
344   if (LookupCtx) {
345     // Perform "qualified" name lookup into the declaration context we
346     // computed, which is either the type of the base of a member access
347     // expression or the declaration context associated with a prior
348     // nested-name-specifier.
349     LookupQualifiedName(Result, LookupCtx);
350 
351     if (ObjectTypePtr && Result.empty()) {
352       // C++ [basic.lookup.classref]p3:
353       //   If the unqualified-id is ~type-name, the type-name is looked up
354       //   in the context of the entire postfix-expression. If the type T of
355       //   the object expression is of a class type C, the type-name is also
356       //   looked up in the scope of class C. At least one of the lookups shall
357       //   find a name that refers to (possibly cv-qualified) T.
358       LookupName(Result, S);
359     }
360   } else {
361     // Perform unqualified name lookup.
362     LookupName(Result, S);
363 
364     // For unqualified lookup in a class template in MSVC mode, look into
365     // dependent base classes where the primary class template is known.
366     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367       if (ParsedType TypeInBase =
368               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369         return TypeInBase;
370     }
371   }
372 
373   NamedDecl *IIDecl = nullptr;
374   switch (Result.getResultKind()) {
375   case LookupResult::NotFound:
376   case LookupResult::NotFoundInCurrentInstantiation:
377     if (CorrectedII) {
378       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379                                AllowDeducedTemplate);
380       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381                                               S, SS, CCC, CTK_ErrorRecovery);
382       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383       TemplateTy Template;
384       bool MemberOfUnknownSpecialization;
385       UnqualifiedId TemplateName;
386       TemplateName.setIdentifier(NewII, NameLoc);
387       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388       CXXScopeSpec NewSS, *NewSSPtr = SS;
389       if (SS && NNS) {
390         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391         NewSSPtr = &NewSS;
392       }
393       if (Correction && (NNS || NewII != &II) &&
394           // Ignore a correction to a template type as the to-be-corrected
395           // identifier is not a template (typo correction for template names
396           // is handled elsewhere).
397           !(getLangOpts().CPlusPlus && NewSSPtr &&
398             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399                            Template, MemberOfUnknownSpecialization))) {
400         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401                                     isClassName, HasTrailingDot, ObjectTypePtr,
402                                     IsCtorOrDtorName,
403                                     WantNontrivialTypeSourceInfo,
404                                     IsClassTemplateDeductionContext);
405         if (Ty) {
406           diagnoseTypo(Correction,
407                        PDiag(diag::err_unknown_type_or_class_name_suggest)
408                          << Result.getLookupName() << isClassName);
409           if (SS && NNS)
410             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411           *CorrectedII = NewII;
412           return Ty;
413         }
414       }
415     }
416     // If typo correction failed or was not performed, fall through
417     LLVM_FALLTHROUGH;
418   case LookupResult::FoundOverloaded:
419   case LookupResult::FoundUnresolvedValue:
420     Result.suppressDiagnostics();
421     return nullptr;
422 
423   case LookupResult::Ambiguous:
424     // Recover from type-hiding ambiguities by hiding the type.  We'll
425     // do the lookup again when looking for an object, and we can
426     // diagnose the error then.  If we don't do this, then the error
427     // about hiding the type will be immediately followed by an error
428     // that only makes sense if the identifier was treated like a type.
429     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430       Result.suppressDiagnostics();
431       return nullptr;
432     }
433 
434     // Look to see if we have a type anywhere in the list of results.
435     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436          Res != ResEnd; ++Res) {
437       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
438           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
439         if (!IIDecl ||
440             (*Res)->getLocation().getRawEncoding() <
441               IIDecl->getLocation().getRawEncoding())
442           IIDecl = *Res;
443       }
444     }
445 
446     if (!IIDecl) {
447       // None of the entities we found is a type, so there is no way
448       // to even assume that the result is a type. In this case, don't
449       // complain about the ambiguity. The parser will either try to
450       // perform this lookup again (e.g., as an object name), which
451       // will produce the ambiguity, or will complain that it expected
452       // a type name.
453       Result.suppressDiagnostics();
454       return nullptr;
455     }
456 
457     // We found a type within the ambiguous lookup; diagnose the
458     // ambiguity and then return that type. This might be the right
459     // answer, or it might not be, but it suppresses any attempt to
460     // perform the name lookup again.
461     break;
462 
463   case LookupResult::Found:
464     IIDecl = Result.getFoundDecl();
465     break;
466   }
467 
468   assert(IIDecl && "Didn't find decl");
469 
470   QualType T;
471   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
472     // C++ [class.qual]p2: A lookup that would find the injected-class-name
473     // instead names the constructors of the class, except when naming a class.
474     // This is ill-formed when we're not actually forming a ctor or dtor name.
475     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
476     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
477     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
478         FoundRD->isInjectedClassName() &&
479         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
480       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
481           << &II << /*Type*/1;
482 
483     DiagnoseUseOfDecl(IIDecl, NameLoc);
484 
485     T = Context.getTypeDeclType(TD);
486     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
487   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
488     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
489     if (!HasTrailingDot)
490       T = Context.getObjCInterfaceType(IDecl);
491   } else if (AllowDeducedTemplate) {
492     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
493       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
494                                                        QualType(), false);
495   }
496 
497   if (T.isNull()) {
498     // If it's not plausibly a type, suppress diagnostics.
499     Result.suppressDiagnostics();
500     return nullptr;
501   }
502 
503   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
504   // constructor or destructor name (in such a case, the scope specifier
505   // will be attached to the enclosing Expr or Decl node).
506   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
507       !isa<ObjCInterfaceDecl>(IIDecl)) {
508     if (WantNontrivialTypeSourceInfo) {
509       // Construct a type with type-source information.
510       TypeLocBuilder Builder;
511       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
512 
513       T = getElaboratedType(ETK_None, *SS, T);
514       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
515       ElabTL.setElaboratedKeywordLoc(SourceLocation());
516       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
517       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
518     } else {
519       T = getElaboratedType(ETK_None, *SS, T);
520     }
521   }
522 
523   return ParsedType::make(T);
524 }
525 
526 // Builds a fake NNS for the given decl context.
527 static NestedNameSpecifier *
528 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
529   for (;; DC = DC->getLookupParent()) {
530     DC = DC->getPrimaryContext();
531     auto *ND = dyn_cast<NamespaceDecl>(DC);
532     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
533       return NestedNameSpecifier::Create(Context, nullptr, ND);
534     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
535       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
536                                          RD->getTypeForDecl());
537     else if (isa<TranslationUnitDecl>(DC))
538       return NestedNameSpecifier::GlobalSpecifier(Context);
539   }
540   llvm_unreachable("something isn't in TU scope?");
541 }
542 
543 /// Find the parent class with dependent bases of the innermost enclosing method
544 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
545 /// up allowing unqualified dependent type names at class-level, which MSVC
546 /// correctly rejects.
547 static const CXXRecordDecl *
548 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
549   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
550     DC = DC->getPrimaryContext();
551     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
552       if (MD->getParent()->hasAnyDependentBases())
553         return MD->getParent();
554   }
555   return nullptr;
556 }
557 
558 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
559                                           SourceLocation NameLoc,
560                                           bool IsTemplateTypeArg) {
561   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
562 
563   NestedNameSpecifier *NNS = nullptr;
564   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
565     // If we weren't able to parse a default template argument, delay lookup
566     // until instantiation time by making a non-dependent DependentTypeName. We
567     // pretend we saw a NestedNameSpecifier referring to the current scope, and
568     // lookup is retried.
569     // FIXME: This hurts our diagnostic quality, since we get errors like "no
570     // type named 'Foo' in 'current_namespace'" when the user didn't write any
571     // name specifiers.
572     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
573     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
574   } else if (const CXXRecordDecl *RD =
575                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
576     // Build a DependentNameType that will perform lookup into RD at
577     // instantiation time.
578     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
579                                       RD->getTypeForDecl());
580 
581     // Diagnose that this identifier was undeclared, and retry the lookup during
582     // template instantiation.
583     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
584                                                                       << RD;
585   } else {
586     // This is not a situation that we should recover from.
587     return ParsedType();
588   }
589 
590   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
591 
592   // Build type location information.  We synthesized the qualifier, so we have
593   // to build a fake NestedNameSpecifierLoc.
594   NestedNameSpecifierLocBuilder NNSLocBuilder;
595   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
596   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
597 
598   TypeLocBuilder Builder;
599   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
600   DepTL.setNameLoc(NameLoc);
601   DepTL.setElaboratedKeywordLoc(SourceLocation());
602   DepTL.setQualifierLoc(QualifierLoc);
603   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
604 }
605 
606 /// isTagName() - This method is called *for error recovery purposes only*
607 /// to determine if the specified name is a valid tag name ("struct foo").  If
608 /// so, this returns the TST for the tag corresponding to it (TST_enum,
609 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
610 /// cases in C where the user forgot to specify the tag.
611 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
612   // Do a tag name lookup in this scope.
613   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
614   LookupName(R, S, false);
615   R.suppressDiagnostics();
616   if (R.getResultKind() == LookupResult::Found)
617     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
618       switch (TD->getTagKind()) {
619       case TTK_Struct: return DeclSpec::TST_struct;
620       case TTK_Interface: return DeclSpec::TST_interface;
621       case TTK_Union:  return DeclSpec::TST_union;
622       case TTK_Class:  return DeclSpec::TST_class;
623       case TTK_Enum:   return DeclSpec::TST_enum;
624       }
625     }
626 
627   return DeclSpec::TST_unspecified;
628 }
629 
630 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
631 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
632 /// then downgrade the missing typename error to a warning.
633 /// This is needed for MSVC compatibility; Example:
634 /// @code
635 /// template<class T> class A {
636 /// public:
637 ///   typedef int TYPE;
638 /// };
639 /// template<class T> class B : public A<T> {
640 /// public:
641 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
642 /// };
643 /// @endcode
644 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
645   if (CurContext->isRecord()) {
646     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
647       return true;
648 
649     const Type *Ty = SS->getScopeRep()->getAsType();
650 
651     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
652     for (const auto &Base : RD->bases())
653       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
654         return true;
655     return S->isFunctionPrototypeScope();
656   }
657   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
658 }
659 
660 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
661                                    SourceLocation IILoc,
662                                    Scope *S,
663                                    CXXScopeSpec *SS,
664                                    ParsedType &SuggestedType,
665                                    bool IsTemplateName) {
666   // Don't report typename errors for editor placeholders.
667   if (II->isEditorPlaceholder())
668     return;
669   // We don't have anything to suggest (yet).
670   SuggestedType = nullptr;
671 
672   // There may have been a typo in the name of the type. Look up typo
673   // results, in case we have something that we can suggest.
674   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
675                            /*AllowTemplates=*/IsTemplateName,
676                            /*AllowNonTemplates=*/!IsTemplateName);
677   if (TypoCorrection Corrected =
678           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
679                       CCC, CTK_ErrorRecovery)) {
680     // FIXME: Support error recovery for the template-name case.
681     bool CanRecover = !IsTemplateName;
682     if (Corrected.isKeyword()) {
683       // We corrected to a keyword.
684       diagnoseTypo(Corrected,
685                    PDiag(IsTemplateName ? diag::err_no_template_suggest
686                                         : diag::err_unknown_typename_suggest)
687                        << II);
688       II = Corrected.getCorrectionAsIdentifierInfo();
689     } else {
690       // We found a similarly-named type or interface; suggest that.
691       if (!SS || !SS->isSet()) {
692         diagnoseTypo(Corrected,
693                      PDiag(IsTemplateName ? diag::err_no_template_suggest
694                                           : diag::err_unknown_typename_suggest)
695                          << II, CanRecover);
696       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
697         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
698         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
699                                 II->getName().equals(CorrectedStr);
700         diagnoseTypo(Corrected,
701                      PDiag(IsTemplateName
702                                ? diag::err_no_member_template_suggest
703                                : diag::err_unknown_nested_typename_suggest)
704                          << II << DC << DroppedSpecifier << SS->getRange(),
705                      CanRecover);
706       } else {
707         llvm_unreachable("could not have corrected a typo here");
708       }
709 
710       if (!CanRecover)
711         return;
712 
713       CXXScopeSpec tmpSS;
714       if (Corrected.getCorrectionSpecifier())
715         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
716                           SourceRange(IILoc));
717       // FIXME: Support class template argument deduction here.
718       SuggestedType =
719           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
720                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
721                       /*IsCtorOrDtorName=*/false,
722                       /*WantNontrivialTypeSourceInfo=*/true);
723     }
724     return;
725   }
726 
727   if (getLangOpts().CPlusPlus && !IsTemplateName) {
728     // See if II is a class template that the user forgot to pass arguments to.
729     UnqualifiedId Name;
730     Name.setIdentifier(II, IILoc);
731     CXXScopeSpec EmptySS;
732     TemplateTy TemplateResult;
733     bool MemberOfUnknownSpecialization;
734     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
735                        Name, nullptr, true, TemplateResult,
736                        MemberOfUnknownSpecialization) == TNK_Type_template) {
737       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
738       return;
739     }
740   }
741 
742   // FIXME: Should we move the logic that tries to recover from a missing tag
743   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
744 
745   if (!SS || (!SS->isSet() && !SS->isInvalid()))
746     Diag(IILoc, IsTemplateName ? diag::err_no_template
747                                : diag::err_unknown_typename)
748         << II;
749   else if (DeclContext *DC = computeDeclContext(*SS, false))
750     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
751                                : diag::err_typename_nested_not_found)
752         << II << DC << SS->getRange();
753   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
754     SuggestedType =
755         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
756   } else if (isDependentScopeSpecifier(*SS)) {
757     unsigned DiagID = diag::err_typename_missing;
758     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
759       DiagID = diag::ext_typename_missing;
760 
761     Diag(SS->getRange().getBegin(), DiagID)
762       << SS->getScopeRep() << II->getName()
763       << SourceRange(SS->getRange().getBegin(), IILoc)
764       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
765     SuggestedType = ActOnTypenameType(S, SourceLocation(),
766                                       *SS, *II, IILoc).get();
767   } else {
768     assert(SS && SS->isInvalid() &&
769            "Invalid scope specifier has already been diagnosed");
770   }
771 }
772 
773 /// Determine whether the given result set contains either a type name
774 /// or
775 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
776   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
777                        NextToken.is(tok::less);
778 
779   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
780     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
781       return true;
782 
783     if (CheckTemplate && isa<TemplateDecl>(*I))
784       return true;
785   }
786 
787   return false;
788 }
789 
790 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
791                                     Scope *S, CXXScopeSpec &SS,
792                                     IdentifierInfo *&Name,
793                                     SourceLocation NameLoc) {
794   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
795   SemaRef.LookupParsedName(R, S, &SS);
796   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
797     StringRef FixItTagName;
798     switch (Tag->getTagKind()) {
799       case TTK_Class:
800         FixItTagName = "class ";
801         break;
802 
803       case TTK_Enum:
804         FixItTagName = "enum ";
805         break;
806 
807       case TTK_Struct:
808         FixItTagName = "struct ";
809         break;
810 
811       case TTK_Interface:
812         FixItTagName = "__interface ";
813         break;
814 
815       case TTK_Union:
816         FixItTagName = "union ";
817         break;
818     }
819 
820     StringRef TagName = FixItTagName.drop_back();
821     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
822       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
823       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
824 
825     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
826          I != IEnd; ++I)
827       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
828         << Name << TagName;
829 
830     // Replace lookup results with just the tag decl.
831     Result.clear(Sema::LookupTagName);
832     SemaRef.LookupParsedName(Result, S, &SS);
833     return true;
834   }
835 
836   return false;
837 }
838 
839 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
840 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
841                                   QualType T, SourceLocation NameLoc) {
842   ASTContext &Context = S.Context;
843 
844   TypeLocBuilder Builder;
845   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
846 
847   T = S.getElaboratedType(ETK_None, SS, T);
848   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
849   ElabTL.setElaboratedKeywordLoc(SourceLocation());
850   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
851   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
852 }
853 
854 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
855                                             IdentifierInfo *&Name,
856                                             SourceLocation NameLoc,
857                                             const Token &NextToken,
858                                             CorrectionCandidateCallback *CCC) {
859   DeclarationNameInfo NameInfo(Name, NameLoc);
860   ObjCMethodDecl *CurMethod = getCurMethodDecl();
861 
862   assert(NextToken.isNot(tok::coloncolon) &&
863          "parse nested name specifiers before calling ClassifyName");
864   if (getLangOpts().CPlusPlus && SS.isSet() &&
865       isCurrentClassName(*Name, S, &SS)) {
866     // Per [class.qual]p2, this names the constructors of SS, not the
867     // injected-class-name. We don't have a classification for that.
868     // There's not much point caching this result, since the parser
869     // will reject it later.
870     return NameClassification::Unknown();
871   }
872 
873   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
874   LookupParsedName(Result, S, &SS, !CurMethod);
875 
876   if (SS.isInvalid())
877     return NameClassification::Error();
878 
879   // For unqualified lookup in a class template in MSVC mode, look into
880   // dependent base classes where the primary class template is known.
881   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
882     if (ParsedType TypeInBase =
883             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
884       return TypeInBase;
885   }
886 
887   // Perform lookup for Objective-C instance variables (including automatically
888   // synthesized instance variables), if we're in an Objective-C method.
889   // FIXME: This lookup really, really needs to be folded in to the normal
890   // unqualified lookup mechanism.
891   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
892     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
893     if (Ivar.isInvalid())
894       return NameClassification::Error();
895     if (Ivar.isUsable())
896       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
897 
898     // We defer builtin creation until after ivar lookup inside ObjC methods.
899     if (Result.empty())
900       LookupBuiltin(Result);
901   }
902 
903   bool SecondTry = false;
904   bool IsFilteredTemplateName = false;
905 
906 Corrected:
907   switch (Result.getResultKind()) {
908   case LookupResult::NotFound:
909     // If an unqualified-id is followed by a '(', then we have a function
910     // call.
911     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
912       // In C++, this is an ADL-only call.
913       // FIXME: Reference?
914       if (getLangOpts().CPlusPlus)
915         return NameClassification::UndeclaredNonType();
916 
917       // C90 6.3.2.2:
918       //   If the expression that precedes the parenthesized argument list in a
919       //   function call consists solely of an identifier, and if no
920       //   declaration is visible for this identifier, the identifier is
921       //   implicitly declared exactly as if, in the innermost block containing
922       //   the function call, the declaration
923       //
924       //     extern int identifier ();
925       //
926       //   appeared.
927       //
928       // We also allow this in C99 as an extension.
929       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
930         return NameClassification::NonType(D);
931     }
932 
933     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
934       // In C++20 onwards, this could be an ADL-only call to a function
935       // template, and we're required to assume that this is a template name.
936       //
937       // FIXME: Find a way to still do typo correction in this case.
938       TemplateName Template =
939           Context.getAssumedTemplateName(NameInfo.getName());
940       return NameClassification::UndeclaredTemplate(Template);
941     }
942 
943     // In C, we first see whether there is a tag type by the same name, in
944     // which case it's likely that the user just forgot to write "enum",
945     // "struct", or "union".
946     if (!getLangOpts().CPlusPlus && !SecondTry &&
947         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
948       break;
949     }
950 
951     // Perform typo correction to determine if there is another name that is
952     // close to this name.
953     if (!SecondTry && CCC) {
954       SecondTry = true;
955       if (TypoCorrection Corrected =
956               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
957                           &SS, *CCC, CTK_ErrorRecovery)) {
958         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
959         unsigned QualifiedDiag = diag::err_no_member_suggest;
960 
961         NamedDecl *FirstDecl = Corrected.getFoundDecl();
962         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
963         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
964             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
965           UnqualifiedDiag = diag::err_no_template_suggest;
966           QualifiedDiag = diag::err_no_member_template_suggest;
967         } else if (UnderlyingFirstDecl &&
968                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
969                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
970                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
971           UnqualifiedDiag = diag::err_unknown_typename_suggest;
972           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
973         }
974 
975         if (SS.isEmpty()) {
976           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
977         } else {// FIXME: is this even reachable? Test it.
978           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
979           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
980                                   Name->getName().equals(CorrectedStr);
981           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
982                                     << Name << computeDeclContext(SS, false)
983                                     << DroppedSpecifier << SS.getRange());
984         }
985 
986         // Update the name, so that the caller has the new name.
987         Name = Corrected.getCorrectionAsIdentifierInfo();
988 
989         // Typo correction corrected to a keyword.
990         if (Corrected.isKeyword())
991           return Name;
992 
993         // Also update the LookupResult...
994         // FIXME: This should probably go away at some point
995         Result.clear();
996         Result.setLookupName(Corrected.getCorrection());
997         if (FirstDecl)
998           Result.addDecl(FirstDecl);
999 
1000         // If we found an Objective-C instance variable, let
1001         // LookupInObjCMethod build the appropriate expression to
1002         // reference the ivar.
1003         // FIXME: This is a gross hack.
1004         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1005           DeclResult R =
1006               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1007           if (R.isInvalid())
1008             return NameClassification::Error();
1009           if (R.isUsable())
1010             return NameClassification::NonType(Ivar);
1011         }
1012 
1013         goto Corrected;
1014       }
1015     }
1016 
1017     // We failed to correct; just fall through and let the parser deal with it.
1018     Result.suppressDiagnostics();
1019     return NameClassification::Unknown();
1020 
1021   case LookupResult::NotFoundInCurrentInstantiation: {
1022     // We performed name lookup into the current instantiation, and there were
1023     // dependent bases, so we treat this result the same way as any other
1024     // dependent nested-name-specifier.
1025 
1026     // C++ [temp.res]p2:
1027     //   A name used in a template declaration or definition and that is
1028     //   dependent on a template-parameter is assumed not to name a type
1029     //   unless the applicable name lookup finds a type name or the name is
1030     //   qualified by the keyword typename.
1031     //
1032     // FIXME: If the next token is '<', we might want to ask the parser to
1033     // perform some heroics to see if we actually have a
1034     // template-argument-list, which would indicate a missing 'template'
1035     // keyword here.
1036     return NameClassification::DependentNonType();
1037   }
1038 
1039   case LookupResult::Found:
1040   case LookupResult::FoundOverloaded:
1041   case LookupResult::FoundUnresolvedValue:
1042     break;
1043 
1044   case LookupResult::Ambiguous:
1045     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1046         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047                                       /*AllowDependent=*/false)) {
1048       // C++ [temp.local]p3:
1049       //   A lookup that finds an injected-class-name (10.2) can result in an
1050       //   ambiguity in certain cases (for example, if it is found in more than
1051       //   one base class). If all of the injected-class-names that are found
1052       //   refer to specializations of the same class template, and if the name
1053       //   is followed by a template-argument-list, the reference refers to the
1054       //   class template itself and not a specialization thereof, and is not
1055       //   ambiguous.
1056       //
1057       // This filtering can make an ambiguous result into an unambiguous one,
1058       // so try again after filtering out template names.
1059       FilterAcceptableTemplateNames(Result);
1060       if (!Result.isAmbiguous()) {
1061         IsFilteredTemplateName = true;
1062         break;
1063       }
1064     }
1065 
1066     // Diagnose the ambiguity and return an error.
1067     return NameClassification::Error();
1068   }
1069 
1070   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1071       (IsFilteredTemplateName ||
1072        hasAnyAcceptableTemplateNames(
1073            Result, /*AllowFunctionTemplates=*/true,
1074            /*AllowDependent=*/false,
1075            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1076                getLangOpts().CPlusPlus20))) {
1077     // C++ [temp.names]p3:
1078     //   After name lookup (3.4) finds that a name is a template-name or that
1079     //   an operator-function-id or a literal- operator-id refers to a set of
1080     //   overloaded functions any member of which is a function template if
1081     //   this is followed by a <, the < is always taken as the delimiter of a
1082     //   template-argument-list and never as the less-than operator.
1083     // C++2a [temp.names]p2:
1084     //   A name is also considered to refer to a template if it is an
1085     //   unqualified-id followed by a < and name lookup finds either one
1086     //   or more functions or finds nothing.
1087     if (!IsFilteredTemplateName)
1088       FilterAcceptableTemplateNames(Result);
1089 
1090     bool IsFunctionTemplate;
1091     bool IsVarTemplate;
1092     TemplateName Template;
1093     if (Result.end() - Result.begin() > 1) {
1094       IsFunctionTemplate = true;
1095       Template = Context.getOverloadedTemplateName(Result.begin(),
1096                                                    Result.end());
1097     } else if (!Result.empty()) {
1098       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1099           *Result.begin(), /*AllowFunctionTemplates=*/true,
1100           /*AllowDependent=*/false));
1101       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1102       IsVarTemplate = isa<VarTemplateDecl>(TD);
1103 
1104       if (SS.isNotEmpty())
1105         Template =
1106             Context.getQualifiedTemplateName(SS.getScopeRep(),
1107                                              /*TemplateKeyword=*/false, TD);
1108       else
1109         Template = TemplateName(TD);
1110     } else {
1111       // All results were non-template functions. This is a function template
1112       // name.
1113       IsFunctionTemplate = true;
1114       Template = Context.getAssumedTemplateName(NameInfo.getName());
1115     }
1116 
1117     if (IsFunctionTemplate) {
1118       // Function templates always go through overload resolution, at which
1119       // point we'll perform the various checks (e.g., accessibility) we need
1120       // to based on which function we selected.
1121       Result.suppressDiagnostics();
1122 
1123       return NameClassification::FunctionTemplate(Template);
1124     }
1125 
1126     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1127                          : NameClassification::TypeTemplate(Template);
1128   }
1129 
1130   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1131   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1132     DiagnoseUseOfDecl(Type, NameLoc);
1133     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1134     QualType T = Context.getTypeDeclType(Type);
1135     if (SS.isNotEmpty())
1136       return buildNestedType(*this, SS, T, NameLoc);
1137     return ParsedType::make(T);
1138   }
1139 
1140   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1141   if (!Class) {
1142     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1143     if (ObjCCompatibleAliasDecl *Alias =
1144             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1145       Class = Alias->getClassInterface();
1146   }
1147 
1148   if (Class) {
1149     DiagnoseUseOfDecl(Class, NameLoc);
1150 
1151     if (NextToken.is(tok::period)) {
1152       // Interface. <something> is parsed as a property reference expression.
1153       // Just return "unknown" as a fall-through for now.
1154       Result.suppressDiagnostics();
1155       return NameClassification::Unknown();
1156     }
1157 
1158     QualType T = Context.getObjCInterfaceType(Class);
1159     return ParsedType::make(T);
1160   }
1161 
1162   if (isa<ConceptDecl>(FirstDecl))
1163     return NameClassification::Concept(
1164         TemplateName(cast<TemplateDecl>(FirstDecl)));
1165 
1166   // We can have a type template here if we're classifying a template argument.
1167   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1168       !isa<VarTemplateDecl>(FirstDecl))
1169     return NameClassification::TypeTemplate(
1170         TemplateName(cast<TemplateDecl>(FirstDecl)));
1171 
1172   // Check for a tag type hidden by a non-type decl in a few cases where it
1173   // seems likely a type is wanted instead of the non-type that was found.
1174   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1175   if ((NextToken.is(tok::identifier) ||
1176        (NextIsOp &&
1177         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1178       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1179     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1180     DiagnoseUseOfDecl(Type, NameLoc);
1181     QualType T = Context.getTypeDeclType(Type);
1182     if (SS.isNotEmpty())
1183       return buildNestedType(*this, SS, T, NameLoc);
1184     return ParsedType::make(T);
1185   }
1186 
1187   // FIXME: This is context-dependent. We need to defer building the member
1188   // expression until the classification is consumed.
1189   if (FirstDecl->isCXXClassMember())
1190     return NameClassification::ContextIndependentExpr(
1191         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1192                                         S));
1193 
1194   // If we already know which single declaration is referenced, just annotate
1195   // that declaration directly.
1196   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1197   if (Result.isSingleResult() && !ADL)
1198     return NameClassification::NonType(Result.getRepresentativeDecl());
1199 
1200   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1201   // context in which we performed classification, so it's safe to do now.
1202   return NameClassification::ContextIndependentExpr(
1203       BuildDeclarationNameExpr(SS, Result, ADL));
1204 }
1205 
1206 ExprResult
1207 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1208                                              SourceLocation NameLoc) {
1209   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1210   CXXScopeSpec SS;
1211   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1212   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1213 }
1214 
1215 ExprResult
1216 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1217                                             IdentifierInfo *Name,
1218                                             SourceLocation NameLoc,
1219                                             bool IsAddressOfOperand) {
1220   DeclarationNameInfo NameInfo(Name, NameLoc);
1221   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1222                                     NameInfo, IsAddressOfOperand,
1223                                     /*TemplateArgs=*/nullptr);
1224 }
1225 
1226 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1227                                               NamedDecl *Found,
1228                                               SourceLocation NameLoc,
1229                                               const Token &NextToken) {
1230   if (getCurMethodDecl() && SS.isEmpty())
1231     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1232       return BuildIvarRefExpr(S, NameLoc, Ivar);
1233 
1234   // Reconstruct the lookup result.
1235   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1236   Result.addDecl(Found);
1237   Result.resolveKind();
1238 
1239   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1240   return BuildDeclarationNameExpr(SS, Result, ADL);
1241 }
1242 
1243 Sema::TemplateNameKindForDiagnostics
1244 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1245   auto *TD = Name.getAsTemplateDecl();
1246   if (!TD)
1247     return TemplateNameKindForDiagnostics::DependentTemplate;
1248   if (isa<ClassTemplateDecl>(TD))
1249     return TemplateNameKindForDiagnostics::ClassTemplate;
1250   if (isa<FunctionTemplateDecl>(TD))
1251     return TemplateNameKindForDiagnostics::FunctionTemplate;
1252   if (isa<VarTemplateDecl>(TD))
1253     return TemplateNameKindForDiagnostics::VarTemplate;
1254   if (isa<TypeAliasTemplateDecl>(TD))
1255     return TemplateNameKindForDiagnostics::AliasTemplate;
1256   if (isa<TemplateTemplateParmDecl>(TD))
1257     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1258   if (isa<ConceptDecl>(TD))
1259     return TemplateNameKindForDiagnostics::Concept;
1260   return TemplateNameKindForDiagnostics::DependentTemplate;
1261 }
1262 
1263 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1264   assert(DC->getLexicalParent() == CurContext &&
1265       "The next DeclContext should be lexically contained in the current one.");
1266   CurContext = DC;
1267   S->setEntity(DC);
1268 }
1269 
1270 void Sema::PopDeclContext() {
1271   assert(CurContext && "DeclContext imbalance!");
1272 
1273   CurContext = CurContext->getLexicalParent();
1274   assert(CurContext && "Popped translation unit!");
1275 }
1276 
1277 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1278                                                                     Decl *D) {
1279   // Unlike PushDeclContext, the context to which we return is not necessarily
1280   // the containing DC of TD, because the new context will be some pre-existing
1281   // TagDecl definition instead of a fresh one.
1282   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1283   CurContext = cast<TagDecl>(D)->getDefinition();
1284   assert(CurContext && "skipping definition of undefined tag");
1285   // Start lookups from the parent of the current context; we don't want to look
1286   // into the pre-existing complete definition.
1287   S->setEntity(CurContext->getLookupParent());
1288   return Result;
1289 }
1290 
1291 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1292   CurContext = static_cast<decltype(CurContext)>(Context);
1293 }
1294 
1295 /// EnterDeclaratorContext - Used when we must lookup names in the context
1296 /// of a declarator's nested name specifier.
1297 ///
1298 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1299   // C++0x [basic.lookup.unqual]p13:
1300   //   A name used in the definition of a static data member of class
1301   //   X (after the qualified-id of the static member) is looked up as
1302   //   if the name was used in a member function of X.
1303   // C++0x [basic.lookup.unqual]p14:
1304   //   If a variable member of a namespace is defined outside of the
1305   //   scope of its namespace then any name used in the definition of
1306   //   the variable member (after the declarator-id) is looked up as
1307   //   if the definition of the variable member occurred in its
1308   //   namespace.
1309   // Both of these imply that we should push a scope whose context
1310   // is the semantic context of the declaration.  We can't use
1311   // PushDeclContext here because that context is not necessarily
1312   // lexically contained in the current context.  Fortunately,
1313   // the containing scope should have the appropriate information.
1314 
1315   assert(!S->getEntity() && "scope already has entity");
1316 
1317 #ifndef NDEBUG
1318   Scope *Ancestor = S->getParent();
1319   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1320   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1321 #endif
1322 
1323   CurContext = DC;
1324   S->setEntity(DC);
1325 
1326   if (S->getParent()->isTemplateParamScope()) {
1327     // Also set the corresponding entities for all immediately-enclosing
1328     // template parameter scopes.
1329     EnterTemplatedContext(S->getParent(), DC);
1330   }
1331 }
1332 
1333 void Sema::ExitDeclaratorContext(Scope *S) {
1334   assert(S->getEntity() == CurContext && "Context imbalance!");
1335 
1336   // Switch back to the lexical context.  The safety of this is
1337   // enforced by an assert in EnterDeclaratorContext.
1338   Scope *Ancestor = S->getParent();
1339   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1340   CurContext = Ancestor->getEntity();
1341 
1342   // We don't need to do anything with the scope, which is going to
1343   // disappear.
1344 }
1345 
1346 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1347   assert(S->isTemplateParamScope() &&
1348          "expected to be initializing a template parameter scope");
1349 
1350   // C++20 [temp.local]p7:
1351   //   In the definition of a member of a class template that appears outside
1352   //   of the class template definition, the name of a member of the class
1353   //   template hides the name of a template-parameter of any enclosing class
1354   //   templates (but not a template-parameter of the member if the member is a
1355   //   class or function template).
1356   // C++20 [temp.local]p9:
1357   //   In the definition of a class template or in the definition of a member
1358   //   of such a template that appears outside of the template definition, for
1359   //   each non-dependent base class (13.8.2.1), if the name of the base class
1360   //   or the name of a member of the base class is the same as the name of a
1361   //   template-parameter, the base class name or member name hides the
1362   //   template-parameter name (6.4.10).
1363   //
1364   // This means that a template parameter scope should be searched immediately
1365   // after searching the DeclContext for which it is a template parameter
1366   // scope. For example, for
1367   //   template<typename T> template<typename U> template<typename V>
1368   //     void N::A<T>::B<U>::f(...)
1369   // we search V then B<U> (and base classes) then U then A<T> (and base
1370   // classes) then T then N then ::.
1371   unsigned ScopeDepth = getTemplateDepth(S);
1372   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1373     DeclContext *SearchDCAfterScope = DC;
1374     for (; DC; DC = DC->getLookupParent()) {
1375       if (const TemplateParameterList *TPL =
1376               cast<Decl>(DC)->getDescribedTemplateParams()) {
1377         unsigned DCDepth = TPL->getDepth() + 1;
1378         if (DCDepth > ScopeDepth)
1379           continue;
1380         if (ScopeDepth == DCDepth)
1381           SearchDCAfterScope = DC = DC->getLookupParent();
1382         break;
1383       }
1384     }
1385     S->setLookupEntity(SearchDCAfterScope);
1386   }
1387 }
1388 
1389 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1390   // We assume that the caller has already called
1391   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1392   FunctionDecl *FD = D->getAsFunction();
1393   if (!FD)
1394     return;
1395 
1396   // Same implementation as PushDeclContext, but enters the context
1397   // from the lexical parent, rather than the top-level class.
1398   assert(CurContext == FD->getLexicalParent() &&
1399     "The next DeclContext should be lexically contained in the current one.");
1400   CurContext = FD;
1401   S->setEntity(CurContext);
1402 
1403   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1404     ParmVarDecl *Param = FD->getParamDecl(P);
1405     // If the parameter has an identifier, then add it to the scope
1406     if (Param->getIdentifier()) {
1407       S->AddDecl(Param);
1408       IdResolver.AddDecl(Param);
1409     }
1410   }
1411 }
1412 
1413 void Sema::ActOnExitFunctionContext() {
1414   // Same implementation as PopDeclContext, but returns to the lexical parent,
1415   // rather than the top-level class.
1416   assert(CurContext && "DeclContext imbalance!");
1417   CurContext = CurContext->getLexicalParent();
1418   assert(CurContext && "Popped translation unit!");
1419 }
1420 
1421 /// Determine whether we allow overloading of the function
1422 /// PrevDecl with another declaration.
1423 ///
1424 /// This routine determines whether overloading is possible, not
1425 /// whether some new function is actually an overload. It will return
1426 /// true in C++ (where we can always provide overloads) or, as an
1427 /// extension, in C when the previous function is already an
1428 /// overloaded function declaration or has the "overloadable"
1429 /// attribute.
1430 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1431                                        ASTContext &Context,
1432                                        const FunctionDecl *New) {
1433   if (Context.getLangOpts().CPlusPlus)
1434     return true;
1435 
1436   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1437     return true;
1438 
1439   return Previous.getResultKind() == LookupResult::Found &&
1440          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1441           New->hasAttr<OverloadableAttr>());
1442 }
1443 
1444 /// Add this decl to the scope shadowed decl chains.
1445 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1446   // Move up the scope chain until we find the nearest enclosing
1447   // non-transparent context. The declaration will be introduced into this
1448   // scope.
1449   while (S->getEntity() && S->getEntity()->isTransparentContext())
1450     S = S->getParent();
1451 
1452   // Add scoped declarations into their context, so that they can be
1453   // found later. Declarations without a context won't be inserted
1454   // into any context.
1455   if (AddToContext)
1456     CurContext->addDecl(D);
1457 
1458   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1459   // are function-local declarations.
1460   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1461       !D->getDeclContext()->getRedeclContext()->Equals(
1462         D->getLexicalDeclContext()->getRedeclContext()) &&
1463       !D->getLexicalDeclContext()->isFunctionOrMethod())
1464     return;
1465 
1466   // Template instantiations should also not be pushed into scope.
1467   if (isa<FunctionDecl>(D) &&
1468       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1469     return;
1470 
1471   // If this replaces anything in the current scope,
1472   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1473                                IEnd = IdResolver.end();
1474   for (; I != IEnd; ++I) {
1475     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1476       S->RemoveDecl(*I);
1477       IdResolver.RemoveDecl(*I);
1478 
1479       // Should only need to replace one decl.
1480       break;
1481     }
1482   }
1483 
1484   S->AddDecl(D);
1485 
1486   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1487     // Implicitly-generated labels may end up getting generated in an order that
1488     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1489     // the label at the appropriate place in the identifier chain.
1490     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1491       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1492       if (IDC == CurContext) {
1493         if (!S->isDeclScope(*I))
1494           continue;
1495       } else if (IDC->Encloses(CurContext))
1496         break;
1497     }
1498 
1499     IdResolver.InsertDeclAfter(I, D);
1500   } else {
1501     IdResolver.AddDecl(D);
1502   }
1503 }
1504 
1505 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1506                          bool AllowInlineNamespace) {
1507   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1508 }
1509 
1510 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1511   DeclContext *TargetDC = DC->getPrimaryContext();
1512   do {
1513     if (DeclContext *ScopeDC = S->getEntity())
1514       if (ScopeDC->getPrimaryContext() == TargetDC)
1515         return S;
1516   } while ((S = S->getParent()));
1517 
1518   return nullptr;
1519 }
1520 
1521 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1522                                             DeclContext*,
1523                                             ASTContext&);
1524 
1525 /// Filters out lookup results that don't fall within the given scope
1526 /// as determined by isDeclInScope.
1527 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1528                                 bool ConsiderLinkage,
1529                                 bool AllowInlineNamespace) {
1530   LookupResult::Filter F = R.makeFilter();
1531   while (F.hasNext()) {
1532     NamedDecl *D = F.next();
1533 
1534     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1535       continue;
1536 
1537     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1538       continue;
1539 
1540     F.erase();
1541   }
1542 
1543   F.done();
1544 }
1545 
1546 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1547 /// have compatible owning modules.
1548 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1549   // FIXME: The Modules TS is not clear about how friend declarations are
1550   // to be treated. It's not meaningful to have different owning modules for
1551   // linkage in redeclarations of the same entity, so for now allow the
1552   // redeclaration and change the owning modules to match.
1553   if (New->getFriendObjectKind() &&
1554       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1555     New->setLocalOwningModule(Old->getOwningModule());
1556     makeMergedDefinitionVisible(New);
1557     return false;
1558   }
1559 
1560   Module *NewM = New->getOwningModule();
1561   Module *OldM = Old->getOwningModule();
1562 
1563   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1564     NewM = NewM->Parent;
1565   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1566     OldM = OldM->Parent;
1567 
1568   if (NewM == OldM)
1569     return false;
1570 
1571   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1572   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1573   if (NewIsModuleInterface || OldIsModuleInterface) {
1574     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1575     //   if a declaration of D [...] appears in the purview of a module, all
1576     //   other such declarations shall appear in the purview of the same module
1577     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1578       << New
1579       << NewIsModuleInterface
1580       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1581       << OldIsModuleInterface
1582       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1583     Diag(Old->getLocation(), diag::note_previous_declaration);
1584     New->setInvalidDecl();
1585     return true;
1586   }
1587 
1588   return false;
1589 }
1590 
1591 static bool isUsingDecl(NamedDecl *D) {
1592   return isa<UsingShadowDecl>(D) ||
1593          isa<UnresolvedUsingTypenameDecl>(D) ||
1594          isa<UnresolvedUsingValueDecl>(D);
1595 }
1596 
1597 /// Removes using shadow declarations from the lookup results.
1598 static void RemoveUsingDecls(LookupResult &R) {
1599   LookupResult::Filter F = R.makeFilter();
1600   while (F.hasNext())
1601     if (isUsingDecl(F.next()))
1602       F.erase();
1603 
1604   F.done();
1605 }
1606 
1607 /// Check for this common pattern:
1608 /// @code
1609 /// class S {
1610 ///   S(const S&); // DO NOT IMPLEMENT
1611 ///   void operator=(const S&); // DO NOT IMPLEMENT
1612 /// };
1613 /// @endcode
1614 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1615   // FIXME: Should check for private access too but access is set after we get
1616   // the decl here.
1617   if (D->doesThisDeclarationHaveABody())
1618     return false;
1619 
1620   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1621     return CD->isCopyConstructor();
1622   return D->isCopyAssignmentOperator();
1623 }
1624 
1625 // We need this to handle
1626 //
1627 // typedef struct {
1628 //   void *foo() { return 0; }
1629 // } A;
1630 //
1631 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1632 // for example. If 'A', foo will have external linkage. If we have '*A',
1633 // foo will have no linkage. Since we can't know until we get to the end
1634 // of the typedef, this function finds out if D might have non-external linkage.
1635 // Callers should verify at the end of the TU if it D has external linkage or
1636 // not.
1637 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1638   const DeclContext *DC = D->getDeclContext();
1639   while (!DC->isTranslationUnit()) {
1640     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1641       if (!RD->hasNameForLinkage())
1642         return true;
1643     }
1644     DC = DC->getParent();
1645   }
1646 
1647   return !D->isExternallyVisible();
1648 }
1649 
1650 // FIXME: This needs to be refactored; some other isInMainFile users want
1651 // these semantics.
1652 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1653   if (S.TUKind != TU_Complete)
1654     return false;
1655   return S.SourceMgr.isInMainFile(Loc);
1656 }
1657 
1658 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1659   assert(D);
1660 
1661   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1662     return false;
1663 
1664   // Ignore all entities declared within templates, and out-of-line definitions
1665   // of members of class templates.
1666   if (D->getDeclContext()->isDependentContext() ||
1667       D->getLexicalDeclContext()->isDependentContext())
1668     return false;
1669 
1670   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1671     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1672       return false;
1673     // A non-out-of-line declaration of a member specialization was implicitly
1674     // instantiated; it's the out-of-line declaration that we're interested in.
1675     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1676         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1677       return false;
1678 
1679     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1680       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1681         return false;
1682     } else {
1683       // 'static inline' functions are defined in headers; don't warn.
1684       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1685         return false;
1686     }
1687 
1688     if (FD->doesThisDeclarationHaveABody() &&
1689         Context.DeclMustBeEmitted(FD))
1690       return false;
1691   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1692     // Constants and utility variables are defined in headers with internal
1693     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1694     // like "inline".)
1695     if (!isMainFileLoc(*this, VD->getLocation()))
1696       return false;
1697 
1698     if (Context.DeclMustBeEmitted(VD))
1699       return false;
1700 
1701     if (VD->isStaticDataMember() &&
1702         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1703       return false;
1704     if (VD->isStaticDataMember() &&
1705         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1706         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1707       return false;
1708 
1709     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1710       return false;
1711   } else {
1712     return false;
1713   }
1714 
1715   // Only warn for unused decls internal to the translation unit.
1716   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1717   // for inline functions defined in the main source file, for instance.
1718   return mightHaveNonExternalLinkage(D);
1719 }
1720 
1721 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1722   if (!D)
1723     return;
1724 
1725   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1726     const FunctionDecl *First = FD->getFirstDecl();
1727     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1728       return; // First should already be in the vector.
1729   }
1730 
1731   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1732     const VarDecl *First = VD->getFirstDecl();
1733     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1734       return; // First should already be in the vector.
1735   }
1736 
1737   if (ShouldWarnIfUnusedFileScopedDecl(D))
1738     UnusedFileScopedDecls.push_back(D);
1739 }
1740 
1741 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1742   if (D->isInvalidDecl())
1743     return false;
1744 
1745   bool Referenced = false;
1746   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1747     // For a decomposition declaration, warn if none of the bindings are
1748     // referenced, instead of if the variable itself is referenced (which
1749     // it is, by the bindings' expressions).
1750     for (auto *BD : DD->bindings()) {
1751       if (BD->isReferenced()) {
1752         Referenced = true;
1753         break;
1754       }
1755     }
1756   } else if (!D->getDeclName()) {
1757     return false;
1758   } else if (D->isReferenced() || D->isUsed()) {
1759     Referenced = true;
1760   }
1761 
1762   if (Referenced || D->hasAttr<UnusedAttr>() ||
1763       D->hasAttr<ObjCPreciseLifetimeAttr>())
1764     return false;
1765 
1766   if (isa<LabelDecl>(D))
1767     return true;
1768 
1769   // Except for labels, we only care about unused decls that are local to
1770   // functions.
1771   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1772   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1773     // For dependent types, the diagnostic is deferred.
1774     WithinFunction =
1775         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1776   if (!WithinFunction)
1777     return false;
1778 
1779   if (isa<TypedefNameDecl>(D))
1780     return true;
1781 
1782   // White-list anything that isn't a local variable.
1783   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1784     return false;
1785 
1786   // Types of valid local variables should be complete, so this should succeed.
1787   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1788 
1789     // White-list anything with an __attribute__((unused)) type.
1790     const auto *Ty = VD->getType().getTypePtr();
1791 
1792     // Only look at the outermost level of typedef.
1793     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1794       if (TT->getDecl()->hasAttr<UnusedAttr>())
1795         return false;
1796     }
1797 
1798     // If we failed to complete the type for some reason, or if the type is
1799     // dependent, don't diagnose the variable.
1800     if (Ty->isIncompleteType() || Ty->isDependentType())
1801       return false;
1802 
1803     // Look at the element type to ensure that the warning behaviour is
1804     // consistent for both scalars and arrays.
1805     Ty = Ty->getBaseElementTypeUnsafe();
1806 
1807     if (const TagType *TT = Ty->getAs<TagType>()) {
1808       const TagDecl *Tag = TT->getDecl();
1809       if (Tag->hasAttr<UnusedAttr>())
1810         return false;
1811 
1812       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1813         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1814           return false;
1815 
1816         if (const Expr *Init = VD->getInit()) {
1817           if (const ExprWithCleanups *Cleanups =
1818                   dyn_cast<ExprWithCleanups>(Init))
1819             Init = Cleanups->getSubExpr();
1820           const CXXConstructExpr *Construct =
1821             dyn_cast<CXXConstructExpr>(Init);
1822           if (Construct && !Construct->isElidable()) {
1823             CXXConstructorDecl *CD = Construct->getConstructor();
1824             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1825                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1826               return false;
1827           }
1828 
1829           // Suppress the warning if we don't know how this is constructed, and
1830           // it could possibly be non-trivial constructor.
1831           if (Init->isTypeDependent())
1832             for (const CXXConstructorDecl *Ctor : RD->ctors())
1833               if (!Ctor->isTrivial())
1834                 return false;
1835         }
1836       }
1837     }
1838 
1839     // TODO: __attribute__((unused)) templates?
1840   }
1841 
1842   return true;
1843 }
1844 
1845 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1846                                      FixItHint &Hint) {
1847   if (isa<LabelDecl>(D)) {
1848     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1849         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1850         true);
1851     if (AfterColon.isInvalid())
1852       return;
1853     Hint = FixItHint::CreateRemoval(
1854         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1855   }
1856 }
1857 
1858 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1859   if (D->getTypeForDecl()->isDependentType())
1860     return;
1861 
1862   for (auto *TmpD : D->decls()) {
1863     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1864       DiagnoseUnusedDecl(T);
1865     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1866       DiagnoseUnusedNestedTypedefs(R);
1867   }
1868 }
1869 
1870 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1871 /// unless they are marked attr(unused).
1872 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1873   if (!ShouldDiagnoseUnusedDecl(D))
1874     return;
1875 
1876   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1877     // typedefs can be referenced later on, so the diagnostics are emitted
1878     // at end-of-translation-unit.
1879     UnusedLocalTypedefNameCandidates.insert(TD);
1880     return;
1881   }
1882 
1883   FixItHint Hint;
1884   GenerateFixForUnusedDecl(D, Context, Hint);
1885 
1886   unsigned DiagID;
1887   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1888     DiagID = diag::warn_unused_exception_param;
1889   else if (isa<LabelDecl>(D))
1890     DiagID = diag::warn_unused_label;
1891   else
1892     DiagID = diag::warn_unused_variable;
1893 
1894   Diag(D->getLocation(), DiagID) << D << Hint;
1895 }
1896 
1897 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1898   // Verify that we have no forward references left.  If so, there was a goto
1899   // or address of a label taken, but no definition of it.  Label fwd
1900   // definitions are indicated with a null substmt which is also not a resolved
1901   // MS inline assembly label name.
1902   bool Diagnose = false;
1903   if (L->isMSAsmLabel())
1904     Diagnose = !L->isResolvedMSAsmLabel();
1905   else
1906     Diagnose = L->getStmt() == nullptr;
1907   if (Diagnose)
1908     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1909 }
1910 
1911 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1912   S->mergeNRVOIntoParent();
1913 
1914   if (S->decl_empty()) return;
1915   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1916          "Scope shouldn't contain decls!");
1917 
1918   for (auto *TmpD : S->decls()) {
1919     assert(TmpD && "This decl didn't get pushed??");
1920 
1921     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1922     NamedDecl *D = cast<NamedDecl>(TmpD);
1923 
1924     // Diagnose unused variables in this scope.
1925     if (!S->hasUnrecoverableErrorOccurred()) {
1926       DiagnoseUnusedDecl(D);
1927       if (const auto *RD = dyn_cast<RecordDecl>(D))
1928         DiagnoseUnusedNestedTypedefs(RD);
1929     }
1930 
1931     if (!D->getDeclName()) continue;
1932 
1933     // If this was a forward reference to a label, verify it was defined.
1934     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1935       CheckPoppedLabel(LD, *this);
1936 
1937     // Remove this name from our lexical scope, and warn on it if we haven't
1938     // already.
1939     IdResolver.RemoveDecl(D);
1940     auto ShadowI = ShadowingDecls.find(D);
1941     if (ShadowI != ShadowingDecls.end()) {
1942       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1943         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1944             << D << FD << FD->getParent();
1945         Diag(FD->getLocation(), diag::note_previous_declaration);
1946       }
1947       ShadowingDecls.erase(ShadowI);
1948     }
1949   }
1950 }
1951 
1952 /// Look for an Objective-C class in the translation unit.
1953 ///
1954 /// \param Id The name of the Objective-C class we're looking for. If
1955 /// typo-correction fixes this name, the Id will be updated
1956 /// to the fixed name.
1957 ///
1958 /// \param IdLoc The location of the name in the translation unit.
1959 ///
1960 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1961 /// if there is no class with the given name.
1962 ///
1963 /// \returns The declaration of the named Objective-C class, or NULL if the
1964 /// class could not be found.
1965 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1966                                               SourceLocation IdLoc,
1967                                               bool DoTypoCorrection) {
1968   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1969   // creation from this context.
1970   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1971 
1972   if (!IDecl && DoTypoCorrection) {
1973     // Perform typo correction at the given location, but only if we
1974     // find an Objective-C class name.
1975     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1976     if (TypoCorrection C =
1977             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1978                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1979       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1980       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1981       Id = IDecl->getIdentifier();
1982     }
1983   }
1984   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1985   // This routine must always return a class definition, if any.
1986   if (Def && Def->getDefinition())
1987       Def = Def->getDefinition();
1988   return Def;
1989 }
1990 
1991 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1992 /// from S, where a non-field would be declared. This routine copes
1993 /// with the difference between C and C++ scoping rules in structs and
1994 /// unions. For example, the following code is well-formed in C but
1995 /// ill-formed in C++:
1996 /// @code
1997 /// struct S6 {
1998 ///   enum { BAR } e;
1999 /// };
2000 ///
2001 /// void test_S6() {
2002 ///   struct S6 a;
2003 ///   a.e = BAR;
2004 /// }
2005 /// @endcode
2006 /// For the declaration of BAR, this routine will return a different
2007 /// scope. The scope S will be the scope of the unnamed enumeration
2008 /// within S6. In C++, this routine will return the scope associated
2009 /// with S6, because the enumeration's scope is a transparent
2010 /// context but structures can contain non-field names. In C, this
2011 /// routine will return the translation unit scope, since the
2012 /// enumeration's scope is a transparent context and structures cannot
2013 /// contain non-field names.
2014 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2015   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2016          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2017          (S->isClassScope() && !getLangOpts().CPlusPlus))
2018     S = S->getParent();
2019   return S;
2020 }
2021 
2022 /// Looks up the declaration of "struct objc_super" and
2023 /// saves it for later use in building builtin declaration of
2024 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2025 /// pre-existing declaration exists no action takes place.
2026 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2027                                         IdentifierInfo *II) {
2028   if (!II->isStr("objc_msgSendSuper"))
2029     return;
2030   ASTContext &Context = ThisSema.Context;
2031 
2032   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2033                       SourceLocation(), Sema::LookupTagName);
2034   ThisSema.LookupName(Result, S);
2035   if (Result.getResultKind() == LookupResult::Found)
2036     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2037       Context.setObjCSuperType(Context.getTagDeclType(TD));
2038 }
2039 
2040 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2041                                ASTContext::GetBuiltinTypeError Error) {
2042   switch (Error) {
2043   case ASTContext::GE_None:
2044     return "";
2045   case ASTContext::GE_Missing_type:
2046     return BuiltinInfo.getHeaderName(ID);
2047   case ASTContext::GE_Missing_stdio:
2048     return "stdio.h";
2049   case ASTContext::GE_Missing_setjmp:
2050     return "setjmp.h";
2051   case ASTContext::GE_Missing_ucontext:
2052     return "ucontext.h";
2053   }
2054   llvm_unreachable("unhandled error kind");
2055 }
2056 
2057 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2058                                   unsigned ID, SourceLocation Loc) {
2059   DeclContext *Parent = Context.getTranslationUnitDecl();
2060 
2061   if (getLangOpts().CPlusPlus) {
2062     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2063         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2064     CLinkageDecl->setImplicit();
2065     Parent->addDecl(CLinkageDecl);
2066     Parent = CLinkageDecl;
2067   }
2068 
2069   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2070                                            /*TInfo=*/nullptr, SC_Extern, false,
2071                                            Type->isFunctionProtoType());
2072   New->setImplicit();
2073   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2074 
2075   // Create Decl objects for each parameter, adding them to the
2076   // FunctionDecl.
2077   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2078     SmallVector<ParmVarDecl *, 16> Params;
2079     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2080       ParmVarDecl *parm = ParmVarDecl::Create(
2081           Context, New, SourceLocation(), SourceLocation(), nullptr,
2082           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2083       parm->setScopeInfo(0, i);
2084       Params.push_back(parm);
2085     }
2086     New->setParams(Params);
2087   }
2088 
2089   AddKnownFunctionAttributes(New);
2090   return New;
2091 }
2092 
2093 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2094 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2095 /// if we're creating this built-in in anticipation of redeclaring the
2096 /// built-in.
2097 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2098                                      Scope *S, bool ForRedeclaration,
2099                                      SourceLocation Loc) {
2100   LookupPredefedObjCSuperType(*this, S, II);
2101 
2102   ASTContext::GetBuiltinTypeError Error;
2103   QualType R = Context.GetBuiltinType(ID, Error);
2104   if (Error) {
2105     if (!ForRedeclaration)
2106       return nullptr;
2107 
2108     // If we have a builtin without an associated type we should not emit a
2109     // warning when we were not able to find a type for it.
2110     if (Error == ASTContext::GE_Missing_type)
2111       return nullptr;
2112 
2113     // If we could not find a type for setjmp it is because the jmp_buf type was
2114     // not defined prior to the setjmp declaration.
2115     if (Error == ASTContext::GE_Missing_setjmp) {
2116       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2117           << Context.BuiltinInfo.getName(ID);
2118       return nullptr;
2119     }
2120 
2121     // Generally, we emit a warning that the declaration requires the
2122     // appropriate header.
2123     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2124         << getHeaderName(Context.BuiltinInfo, ID, Error)
2125         << Context.BuiltinInfo.getName(ID);
2126     return nullptr;
2127   }
2128 
2129   if (!ForRedeclaration &&
2130       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2131        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2132     Diag(Loc, diag::ext_implicit_lib_function_decl)
2133         << Context.BuiltinInfo.getName(ID) << R;
2134     if (Context.BuiltinInfo.getHeaderName(ID) &&
2135         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2136       Diag(Loc, diag::note_include_header_or_declare)
2137           << Context.BuiltinInfo.getHeaderName(ID)
2138           << Context.BuiltinInfo.getName(ID);
2139   }
2140 
2141   if (R.isNull())
2142     return nullptr;
2143 
2144   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2145   RegisterLocallyScopedExternCDecl(New, S);
2146 
2147   // TUScope is the translation-unit scope to insert this function into.
2148   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2149   // relate Scopes to DeclContexts, and probably eliminate CurContext
2150   // entirely, but we're not there yet.
2151   DeclContext *SavedContext = CurContext;
2152   CurContext = New->getDeclContext();
2153   PushOnScopeChains(New, TUScope);
2154   CurContext = SavedContext;
2155   return New;
2156 }
2157 
2158 /// Typedef declarations don't have linkage, but they still denote the same
2159 /// entity if their types are the same.
2160 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2161 /// isSameEntity.
2162 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2163                                                      TypedefNameDecl *Decl,
2164                                                      LookupResult &Previous) {
2165   // This is only interesting when modules are enabled.
2166   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2167     return;
2168 
2169   // Empty sets are uninteresting.
2170   if (Previous.empty())
2171     return;
2172 
2173   LookupResult::Filter Filter = Previous.makeFilter();
2174   while (Filter.hasNext()) {
2175     NamedDecl *Old = Filter.next();
2176 
2177     // Non-hidden declarations are never ignored.
2178     if (S.isVisible(Old))
2179       continue;
2180 
2181     // Declarations of the same entity are not ignored, even if they have
2182     // different linkages.
2183     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2184       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2185                                 Decl->getUnderlyingType()))
2186         continue;
2187 
2188       // If both declarations give a tag declaration a typedef name for linkage
2189       // purposes, then they declare the same entity.
2190       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2191           Decl->getAnonDeclWithTypedefName())
2192         continue;
2193     }
2194 
2195     Filter.erase();
2196   }
2197 
2198   Filter.done();
2199 }
2200 
2201 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2202   QualType OldType;
2203   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2204     OldType = OldTypedef->getUnderlyingType();
2205   else
2206     OldType = Context.getTypeDeclType(Old);
2207   QualType NewType = New->getUnderlyingType();
2208 
2209   if (NewType->isVariablyModifiedType()) {
2210     // Must not redefine a typedef with a variably-modified type.
2211     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2212     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2213       << Kind << NewType;
2214     if (Old->getLocation().isValid())
2215       notePreviousDefinition(Old, New->getLocation());
2216     New->setInvalidDecl();
2217     return true;
2218   }
2219 
2220   if (OldType != NewType &&
2221       !OldType->isDependentType() &&
2222       !NewType->isDependentType() &&
2223       !Context.hasSameType(OldType, NewType)) {
2224     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2225     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2226       << Kind << NewType << OldType;
2227     if (Old->getLocation().isValid())
2228       notePreviousDefinition(Old, New->getLocation());
2229     New->setInvalidDecl();
2230     return true;
2231   }
2232   return false;
2233 }
2234 
2235 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2236 /// same name and scope as a previous declaration 'Old'.  Figure out
2237 /// how to resolve this situation, merging decls or emitting
2238 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2239 ///
2240 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2241                                 LookupResult &OldDecls) {
2242   // If the new decl is known invalid already, don't bother doing any
2243   // merging checks.
2244   if (New->isInvalidDecl()) return;
2245 
2246   // Allow multiple definitions for ObjC built-in typedefs.
2247   // FIXME: Verify the underlying types are equivalent!
2248   if (getLangOpts().ObjC) {
2249     const IdentifierInfo *TypeID = New->getIdentifier();
2250     switch (TypeID->getLength()) {
2251     default: break;
2252     case 2:
2253       {
2254         if (!TypeID->isStr("id"))
2255           break;
2256         QualType T = New->getUnderlyingType();
2257         if (!T->isPointerType())
2258           break;
2259         if (!T->isVoidPointerType()) {
2260           QualType PT = T->castAs<PointerType>()->getPointeeType();
2261           if (!PT->isStructureType())
2262             break;
2263         }
2264         Context.setObjCIdRedefinitionType(T);
2265         // Install the built-in type for 'id', ignoring the current definition.
2266         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2267         return;
2268       }
2269     case 5:
2270       if (!TypeID->isStr("Class"))
2271         break;
2272       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2273       // Install the built-in type for 'Class', ignoring the current definition.
2274       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2275       return;
2276     case 3:
2277       if (!TypeID->isStr("SEL"))
2278         break;
2279       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2280       // Install the built-in type for 'SEL', ignoring the current definition.
2281       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2282       return;
2283     }
2284     // Fall through - the typedef name was not a builtin type.
2285   }
2286 
2287   // Verify the old decl was also a type.
2288   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2289   if (!Old) {
2290     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2291       << New->getDeclName();
2292 
2293     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2294     if (OldD->getLocation().isValid())
2295       notePreviousDefinition(OldD, New->getLocation());
2296 
2297     return New->setInvalidDecl();
2298   }
2299 
2300   // If the old declaration is invalid, just give up here.
2301   if (Old->isInvalidDecl())
2302     return New->setInvalidDecl();
2303 
2304   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2305     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2306     auto *NewTag = New->getAnonDeclWithTypedefName();
2307     NamedDecl *Hidden = nullptr;
2308     if (OldTag && NewTag &&
2309         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2310         !hasVisibleDefinition(OldTag, &Hidden)) {
2311       // There is a definition of this tag, but it is not visible. Use it
2312       // instead of our tag.
2313       New->setTypeForDecl(OldTD->getTypeForDecl());
2314       if (OldTD->isModed())
2315         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2316                                     OldTD->getUnderlyingType());
2317       else
2318         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2319 
2320       // Make the old tag definition visible.
2321       makeMergedDefinitionVisible(Hidden);
2322 
2323       // If this was an unscoped enumeration, yank all of its enumerators
2324       // out of the scope.
2325       if (isa<EnumDecl>(NewTag)) {
2326         Scope *EnumScope = getNonFieldDeclScope(S);
2327         for (auto *D : NewTag->decls()) {
2328           auto *ED = cast<EnumConstantDecl>(D);
2329           assert(EnumScope->isDeclScope(ED));
2330           EnumScope->RemoveDecl(ED);
2331           IdResolver.RemoveDecl(ED);
2332           ED->getLexicalDeclContext()->removeDecl(ED);
2333         }
2334       }
2335     }
2336   }
2337 
2338   // If the typedef types are not identical, reject them in all languages and
2339   // with any extensions enabled.
2340   if (isIncompatibleTypedef(Old, New))
2341     return;
2342 
2343   // The types match.  Link up the redeclaration chain and merge attributes if
2344   // the old declaration was a typedef.
2345   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2346     New->setPreviousDecl(Typedef);
2347     mergeDeclAttributes(New, Old);
2348   }
2349 
2350   if (getLangOpts().MicrosoftExt)
2351     return;
2352 
2353   if (getLangOpts().CPlusPlus) {
2354     // C++ [dcl.typedef]p2:
2355     //   In a given non-class scope, a typedef specifier can be used to
2356     //   redefine the name of any type declared in that scope to refer
2357     //   to the type to which it already refers.
2358     if (!isa<CXXRecordDecl>(CurContext))
2359       return;
2360 
2361     // C++0x [dcl.typedef]p4:
2362     //   In a given class scope, a typedef specifier can be used to redefine
2363     //   any class-name declared in that scope that is not also a typedef-name
2364     //   to refer to the type to which it already refers.
2365     //
2366     // This wording came in via DR424, which was a correction to the
2367     // wording in DR56, which accidentally banned code like:
2368     //
2369     //   struct S {
2370     //     typedef struct A { } A;
2371     //   };
2372     //
2373     // in the C++03 standard. We implement the C++0x semantics, which
2374     // allow the above but disallow
2375     //
2376     //   struct S {
2377     //     typedef int I;
2378     //     typedef int I;
2379     //   };
2380     //
2381     // since that was the intent of DR56.
2382     if (!isa<TypedefNameDecl>(Old))
2383       return;
2384 
2385     Diag(New->getLocation(), diag::err_redefinition)
2386       << New->getDeclName();
2387     notePreviousDefinition(Old, New->getLocation());
2388     return New->setInvalidDecl();
2389   }
2390 
2391   // Modules always permit redefinition of typedefs, as does C11.
2392   if (getLangOpts().Modules || getLangOpts().C11)
2393     return;
2394 
2395   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2396   // is normally mapped to an error, but can be controlled with
2397   // -Wtypedef-redefinition.  If either the original or the redefinition is
2398   // in a system header, don't emit this for compatibility with GCC.
2399   if (getDiagnostics().getSuppressSystemWarnings() &&
2400       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2401       (Old->isImplicit() ||
2402        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2403        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2404     return;
2405 
2406   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2407     << New->getDeclName();
2408   notePreviousDefinition(Old, New->getLocation());
2409 }
2410 
2411 /// DeclhasAttr - returns true if decl Declaration already has the target
2412 /// attribute.
2413 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2414   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2415   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2416   for (const auto *i : D->attrs())
2417     if (i->getKind() == A->getKind()) {
2418       if (Ann) {
2419         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2420           return true;
2421         continue;
2422       }
2423       // FIXME: Don't hardcode this check
2424       if (OA && isa<OwnershipAttr>(i))
2425         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2426       return true;
2427     }
2428 
2429   return false;
2430 }
2431 
2432 static bool isAttributeTargetADefinition(Decl *D) {
2433   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2434     return VD->isThisDeclarationADefinition();
2435   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2436     return TD->isCompleteDefinition() || TD->isBeingDefined();
2437   return true;
2438 }
2439 
2440 /// Merge alignment attributes from \p Old to \p New, taking into account the
2441 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2442 ///
2443 /// \return \c true if any attributes were added to \p New.
2444 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2445   // Look for alignas attributes on Old, and pick out whichever attribute
2446   // specifies the strictest alignment requirement.
2447   AlignedAttr *OldAlignasAttr = nullptr;
2448   AlignedAttr *OldStrictestAlignAttr = nullptr;
2449   unsigned OldAlign = 0;
2450   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2451     // FIXME: We have no way of representing inherited dependent alignments
2452     // in a case like:
2453     //   template<int A, int B> struct alignas(A) X;
2454     //   template<int A, int B> struct alignas(B) X {};
2455     // For now, we just ignore any alignas attributes which are not on the
2456     // definition in such a case.
2457     if (I->isAlignmentDependent())
2458       return false;
2459 
2460     if (I->isAlignas())
2461       OldAlignasAttr = I;
2462 
2463     unsigned Align = I->getAlignment(S.Context);
2464     if (Align > OldAlign) {
2465       OldAlign = Align;
2466       OldStrictestAlignAttr = I;
2467     }
2468   }
2469 
2470   // Look for alignas attributes on New.
2471   AlignedAttr *NewAlignasAttr = nullptr;
2472   unsigned NewAlign = 0;
2473   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2474     if (I->isAlignmentDependent())
2475       return false;
2476 
2477     if (I->isAlignas())
2478       NewAlignasAttr = I;
2479 
2480     unsigned Align = I->getAlignment(S.Context);
2481     if (Align > NewAlign)
2482       NewAlign = Align;
2483   }
2484 
2485   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2486     // Both declarations have 'alignas' attributes. We require them to match.
2487     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2488     // fall short. (If two declarations both have alignas, they must both match
2489     // every definition, and so must match each other if there is a definition.)
2490 
2491     // If either declaration only contains 'alignas(0)' specifiers, then it
2492     // specifies the natural alignment for the type.
2493     if (OldAlign == 0 || NewAlign == 0) {
2494       QualType Ty;
2495       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2496         Ty = VD->getType();
2497       else
2498         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2499 
2500       if (OldAlign == 0)
2501         OldAlign = S.Context.getTypeAlign(Ty);
2502       if (NewAlign == 0)
2503         NewAlign = S.Context.getTypeAlign(Ty);
2504     }
2505 
2506     if (OldAlign != NewAlign) {
2507       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2508         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2509         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2510       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2511     }
2512   }
2513 
2514   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2515     // C++11 [dcl.align]p6:
2516     //   if any declaration of an entity has an alignment-specifier,
2517     //   every defining declaration of that entity shall specify an
2518     //   equivalent alignment.
2519     // C11 6.7.5/7:
2520     //   If the definition of an object does not have an alignment
2521     //   specifier, any other declaration of that object shall also
2522     //   have no alignment specifier.
2523     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2524       << OldAlignasAttr;
2525     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2526       << OldAlignasAttr;
2527   }
2528 
2529   bool AnyAdded = false;
2530 
2531   // Ensure we have an attribute representing the strictest alignment.
2532   if (OldAlign > NewAlign) {
2533     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2534     Clone->setInherited(true);
2535     New->addAttr(Clone);
2536     AnyAdded = true;
2537   }
2538 
2539   // Ensure we have an alignas attribute if the old declaration had one.
2540   if (OldAlignasAttr && !NewAlignasAttr &&
2541       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2542     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2543     Clone->setInherited(true);
2544     New->addAttr(Clone);
2545     AnyAdded = true;
2546   }
2547 
2548   return AnyAdded;
2549 }
2550 
2551 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2552                                const InheritableAttr *Attr,
2553                                Sema::AvailabilityMergeKind AMK) {
2554   // This function copies an attribute Attr from a previous declaration to the
2555   // new declaration D if the new declaration doesn't itself have that attribute
2556   // yet or if that attribute allows duplicates.
2557   // If you're adding a new attribute that requires logic different from
2558   // "use explicit attribute on decl if present, else use attribute from
2559   // previous decl", for example if the attribute needs to be consistent
2560   // between redeclarations, you need to call a custom merge function here.
2561   InheritableAttr *NewAttr = nullptr;
2562   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2563     NewAttr = S.mergeAvailabilityAttr(
2564         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2565         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2566         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2567         AA->getPriority());
2568   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2569     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2570   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2571     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2572   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2573     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2574   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2575     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2576   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2577     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2578                                 FA->getFirstArg());
2579   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2580     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2581   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2582     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2583   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2584     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2585                                        IA->getInheritanceModel());
2586   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2587     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2588                                       &S.Context.Idents.get(AA->getSpelling()));
2589   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2590            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2591             isa<CUDAGlobalAttr>(Attr))) {
2592     // CUDA target attributes are part of function signature for
2593     // overloading purposes and must not be merged.
2594     return false;
2595   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2596     NewAttr = S.mergeMinSizeAttr(D, *MA);
2597   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2598     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2599   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2600     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2601   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2602     NewAttr = S.mergeCommonAttr(D, *CommonA);
2603   else if (isa<AlignedAttr>(Attr))
2604     // AlignedAttrs are handled separately, because we need to handle all
2605     // such attributes on a declaration at the same time.
2606     NewAttr = nullptr;
2607   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2608            (AMK == Sema::AMK_Override ||
2609             AMK == Sema::AMK_ProtocolImplementation))
2610     NewAttr = nullptr;
2611   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2612     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2613   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2614     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2615   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2616     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2617   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2618     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2619   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2620     NewAttr = S.mergeImportNameAttr(D, *INA);
2621   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2622     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2623 
2624   if (NewAttr) {
2625     NewAttr->setInherited(true);
2626     D->addAttr(NewAttr);
2627     if (isa<MSInheritanceAttr>(NewAttr))
2628       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2629     return true;
2630   }
2631 
2632   return false;
2633 }
2634 
2635 static const NamedDecl *getDefinition(const Decl *D) {
2636   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2637     return TD->getDefinition();
2638   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2639     const VarDecl *Def = VD->getDefinition();
2640     if (Def)
2641       return Def;
2642     return VD->getActingDefinition();
2643   }
2644   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2645     return FD->getDefinition();
2646   return nullptr;
2647 }
2648 
2649 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2650   for (const auto *Attribute : D->attrs())
2651     if (Attribute->getKind() == Kind)
2652       return true;
2653   return false;
2654 }
2655 
2656 /// checkNewAttributesAfterDef - If we already have a definition, check that
2657 /// there are no new attributes in this declaration.
2658 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2659   if (!New->hasAttrs())
2660     return;
2661 
2662   const NamedDecl *Def = getDefinition(Old);
2663   if (!Def || Def == New)
2664     return;
2665 
2666   AttrVec &NewAttributes = New->getAttrs();
2667   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2668     const Attr *NewAttribute = NewAttributes[I];
2669 
2670     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2671       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2672         Sema::SkipBodyInfo SkipBody;
2673         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2674 
2675         // If we're skipping this definition, drop the "alias" attribute.
2676         if (SkipBody.ShouldSkip) {
2677           NewAttributes.erase(NewAttributes.begin() + I);
2678           --E;
2679           continue;
2680         }
2681       } else {
2682         VarDecl *VD = cast<VarDecl>(New);
2683         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2684                                 VarDecl::TentativeDefinition
2685                             ? diag::err_alias_after_tentative
2686                             : diag::err_redefinition;
2687         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2688         if (Diag == diag::err_redefinition)
2689           S.notePreviousDefinition(Def, VD->getLocation());
2690         else
2691           S.Diag(Def->getLocation(), diag::note_previous_definition);
2692         VD->setInvalidDecl();
2693       }
2694       ++I;
2695       continue;
2696     }
2697 
2698     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2699       // Tentative definitions are only interesting for the alias check above.
2700       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2701         ++I;
2702         continue;
2703       }
2704     }
2705 
2706     if (hasAttribute(Def, NewAttribute->getKind())) {
2707       ++I;
2708       continue; // regular attr merging will take care of validating this.
2709     }
2710 
2711     if (isa<C11NoReturnAttr>(NewAttribute)) {
2712       // C's _Noreturn is allowed to be added to a function after it is defined.
2713       ++I;
2714       continue;
2715     } else if (isa<UuidAttr>(NewAttribute)) {
2716       // msvc will allow a subsequent definition to add an uuid to a class
2717       ++I;
2718       continue;
2719     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2720       if (AA->isAlignas()) {
2721         // C++11 [dcl.align]p6:
2722         //   if any declaration of an entity has an alignment-specifier,
2723         //   every defining declaration of that entity shall specify an
2724         //   equivalent alignment.
2725         // C11 6.7.5/7:
2726         //   If the definition of an object does not have an alignment
2727         //   specifier, any other declaration of that object shall also
2728         //   have no alignment specifier.
2729         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2730           << AA;
2731         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2732           << AA;
2733         NewAttributes.erase(NewAttributes.begin() + I);
2734         --E;
2735         continue;
2736       }
2737     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2738       // If there is a C definition followed by a redeclaration with this
2739       // attribute then there are two different definitions. In C++, prefer the
2740       // standard diagnostics.
2741       if (!S.getLangOpts().CPlusPlus) {
2742         S.Diag(NewAttribute->getLocation(),
2743                diag::err_loader_uninitialized_redeclaration);
2744         S.Diag(Def->getLocation(), diag::note_previous_definition);
2745         NewAttributes.erase(NewAttributes.begin() + I);
2746         --E;
2747         continue;
2748       }
2749     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2750                cast<VarDecl>(New)->isInline() &&
2751                !cast<VarDecl>(New)->isInlineSpecified()) {
2752       // Don't warn about applying selectany to implicitly inline variables.
2753       // Older compilers and language modes would require the use of selectany
2754       // to make such variables inline, and it would have no effect if we
2755       // honored it.
2756       ++I;
2757       continue;
2758     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2759       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2760       // declarations after defintions.
2761       ++I;
2762       continue;
2763     }
2764 
2765     S.Diag(NewAttribute->getLocation(),
2766            diag::warn_attribute_precede_definition);
2767     S.Diag(Def->getLocation(), diag::note_previous_definition);
2768     NewAttributes.erase(NewAttributes.begin() + I);
2769     --E;
2770   }
2771 }
2772 
2773 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2774                                      const ConstInitAttr *CIAttr,
2775                                      bool AttrBeforeInit) {
2776   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2777 
2778   // Figure out a good way to write this specifier on the old declaration.
2779   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2780   // enough of the attribute list spelling information to extract that without
2781   // heroics.
2782   std::string SuitableSpelling;
2783   if (S.getLangOpts().CPlusPlus20)
2784     SuitableSpelling = std::string(
2785         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2786   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2787     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2788         InsertLoc, {tok::l_square, tok::l_square,
2789                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2790                     S.PP.getIdentifierInfo("require_constant_initialization"),
2791                     tok::r_square, tok::r_square}));
2792   if (SuitableSpelling.empty())
2793     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2794         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2795                     S.PP.getIdentifierInfo("require_constant_initialization"),
2796                     tok::r_paren, tok::r_paren}));
2797   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2798     SuitableSpelling = "constinit";
2799   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2800     SuitableSpelling = "[[clang::require_constant_initialization]]";
2801   if (SuitableSpelling.empty())
2802     SuitableSpelling = "__attribute__((require_constant_initialization))";
2803   SuitableSpelling += " ";
2804 
2805   if (AttrBeforeInit) {
2806     // extern constinit int a;
2807     // int a = 0; // error (missing 'constinit'), accepted as extension
2808     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2809     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2810         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2811     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2812   } else {
2813     // int a = 0;
2814     // constinit extern int a; // error (missing 'constinit')
2815     S.Diag(CIAttr->getLocation(),
2816            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2817                                  : diag::warn_require_const_init_added_too_late)
2818         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2819     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2820         << CIAttr->isConstinit()
2821         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2822   }
2823 }
2824 
2825 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2826 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2827                                AvailabilityMergeKind AMK) {
2828   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2829     UsedAttr *NewAttr = OldAttr->clone(Context);
2830     NewAttr->setInherited(true);
2831     New->addAttr(NewAttr);
2832   }
2833 
2834   if (!Old->hasAttrs() && !New->hasAttrs())
2835     return;
2836 
2837   // [dcl.constinit]p1:
2838   //   If the [constinit] specifier is applied to any declaration of a
2839   //   variable, it shall be applied to the initializing declaration.
2840   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2841   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2842   if (bool(OldConstInit) != bool(NewConstInit)) {
2843     const auto *OldVD = cast<VarDecl>(Old);
2844     auto *NewVD = cast<VarDecl>(New);
2845 
2846     // Find the initializing declaration. Note that we might not have linked
2847     // the new declaration into the redeclaration chain yet.
2848     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2849     if (!InitDecl &&
2850         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2851       InitDecl = NewVD;
2852 
2853     if (InitDecl == NewVD) {
2854       // This is the initializing declaration. If it would inherit 'constinit',
2855       // that's ill-formed. (Note that we do not apply this to the attribute
2856       // form).
2857       if (OldConstInit && OldConstInit->isConstinit())
2858         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2859                                  /*AttrBeforeInit=*/true);
2860     } else if (NewConstInit) {
2861       // This is the first time we've been told that this declaration should
2862       // have a constant initializer. If we already saw the initializing
2863       // declaration, this is too late.
2864       if (InitDecl && InitDecl != NewVD) {
2865         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2866                                  /*AttrBeforeInit=*/false);
2867         NewVD->dropAttr<ConstInitAttr>();
2868       }
2869     }
2870   }
2871 
2872   // Attributes declared post-definition are currently ignored.
2873   checkNewAttributesAfterDef(*this, New, Old);
2874 
2875   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2876     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2877       if (!OldA->isEquivalent(NewA)) {
2878         // This redeclaration changes __asm__ label.
2879         Diag(New->getLocation(), diag::err_different_asm_label);
2880         Diag(OldA->getLocation(), diag::note_previous_declaration);
2881       }
2882     } else if (Old->isUsed()) {
2883       // This redeclaration adds an __asm__ label to a declaration that has
2884       // already been ODR-used.
2885       Diag(New->getLocation(), diag::err_late_asm_label_name)
2886         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2887     }
2888   }
2889 
2890   // Re-declaration cannot add abi_tag's.
2891   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2892     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2893       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2894         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2895                       NewTag) == OldAbiTagAttr->tags_end()) {
2896           Diag(NewAbiTagAttr->getLocation(),
2897                diag::err_new_abi_tag_on_redeclaration)
2898               << NewTag;
2899           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2900         }
2901       }
2902     } else {
2903       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2904       Diag(Old->getLocation(), diag::note_previous_declaration);
2905     }
2906   }
2907 
2908   // This redeclaration adds a section attribute.
2909   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2910     if (auto *VD = dyn_cast<VarDecl>(New)) {
2911       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2912         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2913         Diag(Old->getLocation(), diag::note_previous_declaration);
2914       }
2915     }
2916   }
2917 
2918   // Redeclaration adds code-seg attribute.
2919   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2920   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2921       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2922     Diag(New->getLocation(), diag::warn_mismatched_section)
2923          << 0 /*codeseg*/;
2924     Diag(Old->getLocation(), diag::note_previous_declaration);
2925   }
2926 
2927   if (!Old->hasAttrs())
2928     return;
2929 
2930   bool foundAny = New->hasAttrs();
2931 
2932   // Ensure that any moving of objects within the allocated map is done before
2933   // we process them.
2934   if (!foundAny) New->setAttrs(AttrVec());
2935 
2936   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2937     // Ignore deprecated/unavailable/availability attributes if requested.
2938     AvailabilityMergeKind LocalAMK = AMK_None;
2939     if (isa<DeprecatedAttr>(I) ||
2940         isa<UnavailableAttr>(I) ||
2941         isa<AvailabilityAttr>(I)) {
2942       switch (AMK) {
2943       case AMK_None:
2944         continue;
2945 
2946       case AMK_Redeclaration:
2947       case AMK_Override:
2948       case AMK_ProtocolImplementation:
2949         LocalAMK = AMK;
2950         break;
2951       }
2952     }
2953 
2954     // Already handled.
2955     if (isa<UsedAttr>(I))
2956       continue;
2957 
2958     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2959       foundAny = true;
2960   }
2961 
2962   if (mergeAlignedAttrs(*this, New, Old))
2963     foundAny = true;
2964 
2965   if (!foundAny) New->dropAttrs();
2966 }
2967 
2968 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2969 /// to the new one.
2970 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2971                                      const ParmVarDecl *oldDecl,
2972                                      Sema &S) {
2973   // C++11 [dcl.attr.depend]p2:
2974   //   The first declaration of a function shall specify the
2975   //   carries_dependency attribute for its declarator-id if any declaration
2976   //   of the function specifies the carries_dependency attribute.
2977   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2978   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2979     S.Diag(CDA->getLocation(),
2980            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2981     // Find the first declaration of the parameter.
2982     // FIXME: Should we build redeclaration chains for function parameters?
2983     const FunctionDecl *FirstFD =
2984       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2985     const ParmVarDecl *FirstVD =
2986       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2987     S.Diag(FirstVD->getLocation(),
2988            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2989   }
2990 
2991   if (!oldDecl->hasAttrs())
2992     return;
2993 
2994   bool foundAny = newDecl->hasAttrs();
2995 
2996   // Ensure that any moving of objects within the allocated map is
2997   // done before we process them.
2998   if (!foundAny) newDecl->setAttrs(AttrVec());
2999 
3000   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3001     if (!DeclHasAttr(newDecl, I)) {
3002       InheritableAttr *newAttr =
3003         cast<InheritableParamAttr>(I->clone(S.Context));
3004       newAttr->setInherited(true);
3005       newDecl->addAttr(newAttr);
3006       foundAny = true;
3007     }
3008   }
3009 
3010   if (!foundAny) newDecl->dropAttrs();
3011 }
3012 
3013 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3014                                 const ParmVarDecl *OldParam,
3015                                 Sema &S) {
3016   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3017     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3018       if (*Oldnullability != *Newnullability) {
3019         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3020           << DiagNullabilityKind(
3021                *Newnullability,
3022                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3023                 != 0))
3024           << DiagNullabilityKind(
3025                *Oldnullability,
3026                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3027                 != 0));
3028         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3029       }
3030     } else {
3031       QualType NewT = NewParam->getType();
3032       NewT = S.Context.getAttributedType(
3033                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3034                          NewT, NewT);
3035       NewParam->setType(NewT);
3036     }
3037   }
3038 }
3039 
3040 namespace {
3041 
3042 /// Used in MergeFunctionDecl to keep track of function parameters in
3043 /// C.
3044 struct GNUCompatibleParamWarning {
3045   ParmVarDecl *OldParm;
3046   ParmVarDecl *NewParm;
3047   QualType PromotedType;
3048 };
3049 
3050 } // end anonymous namespace
3051 
3052 // Determine whether the previous declaration was a definition, implicit
3053 // declaration, or a declaration.
3054 template <typename T>
3055 static std::pair<diag::kind, SourceLocation>
3056 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3057   diag::kind PrevDiag;
3058   SourceLocation OldLocation = Old->getLocation();
3059   if (Old->isThisDeclarationADefinition())
3060     PrevDiag = diag::note_previous_definition;
3061   else if (Old->isImplicit()) {
3062     PrevDiag = diag::note_previous_implicit_declaration;
3063     if (OldLocation.isInvalid())
3064       OldLocation = New->getLocation();
3065   } else
3066     PrevDiag = diag::note_previous_declaration;
3067   return std::make_pair(PrevDiag, OldLocation);
3068 }
3069 
3070 /// canRedefineFunction - checks if a function can be redefined. Currently,
3071 /// only extern inline functions can be redefined, and even then only in
3072 /// GNU89 mode.
3073 static bool canRedefineFunction(const FunctionDecl *FD,
3074                                 const LangOptions& LangOpts) {
3075   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3076           !LangOpts.CPlusPlus &&
3077           FD->isInlineSpecified() &&
3078           FD->getStorageClass() == SC_Extern);
3079 }
3080 
3081 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3082   const AttributedType *AT = T->getAs<AttributedType>();
3083   while (AT && !AT->isCallingConv())
3084     AT = AT->getModifiedType()->getAs<AttributedType>();
3085   return AT;
3086 }
3087 
3088 template <typename T>
3089 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3090   const DeclContext *DC = Old->getDeclContext();
3091   if (DC->isRecord())
3092     return false;
3093 
3094   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3095   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3096     return true;
3097   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3098     return true;
3099   return false;
3100 }
3101 
3102 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3103 static bool isExternC(VarTemplateDecl *) { return false; }
3104 
3105 /// Check whether a redeclaration of an entity introduced by a
3106 /// using-declaration is valid, given that we know it's not an overload
3107 /// (nor a hidden tag declaration).
3108 template<typename ExpectedDecl>
3109 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3110                                    ExpectedDecl *New) {
3111   // C++11 [basic.scope.declarative]p4:
3112   //   Given a set of declarations in a single declarative region, each of
3113   //   which specifies the same unqualified name,
3114   //   -- they shall all refer to the same entity, or all refer to functions
3115   //      and function templates; or
3116   //   -- exactly one declaration shall declare a class name or enumeration
3117   //      name that is not a typedef name and the other declarations shall all
3118   //      refer to the same variable or enumerator, or all refer to functions
3119   //      and function templates; in this case the class name or enumeration
3120   //      name is hidden (3.3.10).
3121 
3122   // C++11 [namespace.udecl]p14:
3123   //   If a function declaration in namespace scope or block scope has the
3124   //   same name and the same parameter-type-list as a function introduced
3125   //   by a using-declaration, and the declarations do not declare the same
3126   //   function, the program is ill-formed.
3127 
3128   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3129   if (Old &&
3130       !Old->getDeclContext()->getRedeclContext()->Equals(
3131           New->getDeclContext()->getRedeclContext()) &&
3132       !(isExternC(Old) && isExternC(New)))
3133     Old = nullptr;
3134 
3135   if (!Old) {
3136     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3137     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3138     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3139     return true;
3140   }
3141   return false;
3142 }
3143 
3144 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3145                                             const FunctionDecl *B) {
3146   assert(A->getNumParams() == B->getNumParams());
3147 
3148   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3149     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3150     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3151     if (AttrA == AttrB)
3152       return true;
3153     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3154            AttrA->isDynamic() == AttrB->isDynamic();
3155   };
3156 
3157   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3158 }
3159 
3160 /// If necessary, adjust the semantic declaration context for a qualified
3161 /// declaration to name the correct inline namespace within the qualifier.
3162 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3163                                                DeclaratorDecl *OldD) {
3164   // The only case where we need to update the DeclContext is when
3165   // redeclaration lookup for a qualified name finds a declaration
3166   // in an inline namespace within the context named by the qualifier:
3167   //
3168   //   inline namespace N { int f(); }
3169   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3170   //
3171   // For unqualified declarations, the semantic context *can* change
3172   // along the redeclaration chain (for local extern declarations,
3173   // extern "C" declarations, and friend declarations in particular).
3174   if (!NewD->getQualifier())
3175     return;
3176 
3177   // NewD is probably already in the right context.
3178   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3179   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3180   if (NamedDC->Equals(SemaDC))
3181     return;
3182 
3183   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3184           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3185          "unexpected context for redeclaration");
3186 
3187   auto *LexDC = NewD->getLexicalDeclContext();
3188   auto FixSemaDC = [=](NamedDecl *D) {
3189     if (!D)
3190       return;
3191     D->setDeclContext(SemaDC);
3192     D->setLexicalDeclContext(LexDC);
3193   };
3194 
3195   FixSemaDC(NewD);
3196   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3197     FixSemaDC(FD->getDescribedFunctionTemplate());
3198   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3199     FixSemaDC(VD->getDescribedVarTemplate());
3200 }
3201 
3202 /// MergeFunctionDecl - We just parsed a function 'New' from
3203 /// declarator D which has the same name and scope as a previous
3204 /// declaration 'Old'.  Figure out how to resolve this situation,
3205 /// merging decls or emitting diagnostics as appropriate.
3206 ///
3207 /// In C++, New and Old must be declarations that are not
3208 /// overloaded. Use IsOverload to determine whether New and Old are
3209 /// overloaded, and to select the Old declaration that New should be
3210 /// merged with.
3211 ///
3212 /// Returns true if there was an error, false otherwise.
3213 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3214                              Scope *S, bool MergeTypeWithOld) {
3215   // Verify the old decl was also a function.
3216   FunctionDecl *Old = OldD->getAsFunction();
3217   if (!Old) {
3218     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3219       if (New->getFriendObjectKind()) {
3220         Diag(New->getLocation(), diag::err_using_decl_friend);
3221         Diag(Shadow->getTargetDecl()->getLocation(),
3222              diag::note_using_decl_target);
3223         Diag(Shadow->getUsingDecl()->getLocation(),
3224              diag::note_using_decl) << 0;
3225         return true;
3226       }
3227 
3228       // Check whether the two declarations might declare the same function.
3229       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3230         return true;
3231       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3232     } else {
3233       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3234         << New->getDeclName();
3235       notePreviousDefinition(OldD, New->getLocation());
3236       return true;
3237     }
3238   }
3239 
3240   // If the old declaration is invalid, just give up here.
3241   if (Old->isInvalidDecl())
3242     return true;
3243 
3244   // Disallow redeclaration of some builtins.
3245   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3246     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3247     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3248         << Old << Old->getType();
3249     return true;
3250   }
3251 
3252   diag::kind PrevDiag;
3253   SourceLocation OldLocation;
3254   std::tie(PrevDiag, OldLocation) =
3255       getNoteDiagForInvalidRedeclaration(Old, New);
3256 
3257   // Don't complain about this if we're in GNU89 mode and the old function
3258   // is an extern inline function.
3259   // Don't complain about specializations. They are not supposed to have
3260   // storage classes.
3261   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3262       New->getStorageClass() == SC_Static &&
3263       Old->hasExternalFormalLinkage() &&
3264       !New->getTemplateSpecializationInfo() &&
3265       !canRedefineFunction(Old, getLangOpts())) {
3266     if (getLangOpts().MicrosoftExt) {
3267       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3268       Diag(OldLocation, PrevDiag);
3269     } else {
3270       Diag(New->getLocation(), diag::err_static_non_static) << New;
3271       Diag(OldLocation, PrevDiag);
3272       return true;
3273     }
3274   }
3275 
3276   if (New->hasAttr<InternalLinkageAttr>() &&
3277       !Old->hasAttr<InternalLinkageAttr>()) {
3278     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3279         << New->getDeclName();
3280     notePreviousDefinition(Old, New->getLocation());
3281     New->dropAttr<InternalLinkageAttr>();
3282   }
3283 
3284   if (CheckRedeclarationModuleOwnership(New, Old))
3285     return true;
3286 
3287   if (!getLangOpts().CPlusPlus) {
3288     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3289     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3290       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3291         << New << OldOvl;
3292 
3293       // Try our best to find a decl that actually has the overloadable
3294       // attribute for the note. In most cases (e.g. programs with only one
3295       // broken declaration/definition), this won't matter.
3296       //
3297       // FIXME: We could do this if we juggled some extra state in
3298       // OverloadableAttr, rather than just removing it.
3299       const Decl *DiagOld = Old;
3300       if (OldOvl) {
3301         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3302           const auto *A = D->getAttr<OverloadableAttr>();
3303           return A && !A->isImplicit();
3304         });
3305         // If we've implicitly added *all* of the overloadable attrs to this
3306         // chain, emitting a "previous redecl" note is pointless.
3307         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3308       }
3309 
3310       if (DiagOld)
3311         Diag(DiagOld->getLocation(),
3312              diag::note_attribute_overloadable_prev_overload)
3313           << OldOvl;
3314 
3315       if (OldOvl)
3316         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3317       else
3318         New->dropAttr<OverloadableAttr>();
3319     }
3320   }
3321 
3322   // If a function is first declared with a calling convention, but is later
3323   // declared or defined without one, all following decls assume the calling
3324   // convention of the first.
3325   //
3326   // It's OK if a function is first declared without a calling convention,
3327   // but is later declared or defined with the default calling convention.
3328   //
3329   // To test if either decl has an explicit calling convention, we look for
3330   // AttributedType sugar nodes on the type as written.  If they are missing or
3331   // were canonicalized away, we assume the calling convention was implicit.
3332   //
3333   // Note also that we DO NOT return at this point, because we still have
3334   // other tests to run.
3335   QualType OldQType = Context.getCanonicalType(Old->getType());
3336   QualType NewQType = Context.getCanonicalType(New->getType());
3337   const FunctionType *OldType = cast<FunctionType>(OldQType);
3338   const FunctionType *NewType = cast<FunctionType>(NewQType);
3339   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3340   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3341   bool RequiresAdjustment = false;
3342 
3343   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3344     FunctionDecl *First = Old->getFirstDecl();
3345     const FunctionType *FT =
3346         First->getType().getCanonicalType()->castAs<FunctionType>();
3347     FunctionType::ExtInfo FI = FT->getExtInfo();
3348     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3349     if (!NewCCExplicit) {
3350       // Inherit the CC from the previous declaration if it was specified
3351       // there but not here.
3352       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3353       RequiresAdjustment = true;
3354     } else if (Old->getBuiltinID()) {
3355       // Builtin attribute isn't propagated to the new one yet at this point,
3356       // so we check if the old one is a builtin.
3357 
3358       // Calling Conventions on a Builtin aren't really useful and setting a
3359       // default calling convention and cdecl'ing some builtin redeclarations is
3360       // common, so warn and ignore the calling convention on the redeclaration.
3361       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3362           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3363           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3364       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3365       RequiresAdjustment = true;
3366     } else {
3367       // Calling conventions aren't compatible, so complain.
3368       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3369       Diag(New->getLocation(), diag::err_cconv_change)
3370         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3371         << !FirstCCExplicit
3372         << (!FirstCCExplicit ? "" :
3373             FunctionType::getNameForCallConv(FI.getCC()));
3374 
3375       // Put the note on the first decl, since it is the one that matters.
3376       Diag(First->getLocation(), diag::note_previous_declaration);
3377       return true;
3378     }
3379   }
3380 
3381   // FIXME: diagnose the other way around?
3382   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3383     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3384     RequiresAdjustment = true;
3385   }
3386 
3387   // Merge regparm attribute.
3388   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3389       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3390     if (NewTypeInfo.getHasRegParm()) {
3391       Diag(New->getLocation(), diag::err_regparm_mismatch)
3392         << NewType->getRegParmType()
3393         << OldType->getRegParmType();
3394       Diag(OldLocation, diag::note_previous_declaration);
3395       return true;
3396     }
3397 
3398     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3399     RequiresAdjustment = true;
3400   }
3401 
3402   // Merge ns_returns_retained attribute.
3403   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3404     if (NewTypeInfo.getProducesResult()) {
3405       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3406           << "'ns_returns_retained'";
3407       Diag(OldLocation, diag::note_previous_declaration);
3408       return true;
3409     }
3410 
3411     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3412     RequiresAdjustment = true;
3413   }
3414 
3415   if (OldTypeInfo.getNoCallerSavedRegs() !=
3416       NewTypeInfo.getNoCallerSavedRegs()) {
3417     if (NewTypeInfo.getNoCallerSavedRegs()) {
3418       AnyX86NoCallerSavedRegistersAttr *Attr =
3419         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3420       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3421       Diag(OldLocation, diag::note_previous_declaration);
3422       return true;
3423     }
3424 
3425     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3426     RequiresAdjustment = true;
3427   }
3428 
3429   if (RequiresAdjustment) {
3430     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3431     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3432     New->setType(QualType(AdjustedType, 0));
3433     NewQType = Context.getCanonicalType(New->getType());
3434   }
3435 
3436   // If this redeclaration makes the function inline, we may need to add it to
3437   // UndefinedButUsed.
3438   if (!Old->isInlined() && New->isInlined() &&
3439       !New->hasAttr<GNUInlineAttr>() &&
3440       !getLangOpts().GNUInline &&
3441       Old->isUsed(false) &&
3442       !Old->isDefined() && !New->isThisDeclarationADefinition())
3443     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3444                                            SourceLocation()));
3445 
3446   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3447   // about it.
3448   if (New->hasAttr<GNUInlineAttr>() &&
3449       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3450     UndefinedButUsed.erase(Old->getCanonicalDecl());
3451   }
3452 
3453   // If pass_object_size params don't match up perfectly, this isn't a valid
3454   // redeclaration.
3455   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3456       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3457     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3458         << New->getDeclName();
3459     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3460     return true;
3461   }
3462 
3463   if (getLangOpts().CPlusPlus) {
3464     // C++1z [over.load]p2
3465     //   Certain function declarations cannot be overloaded:
3466     //     -- Function declarations that differ only in the return type,
3467     //        the exception specification, or both cannot be overloaded.
3468 
3469     // Check the exception specifications match. This may recompute the type of
3470     // both Old and New if it resolved exception specifications, so grab the
3471     // types again after this. Because this updates the type, we do this before
3472     // any of the other checks below, which may update the "de facto" NewQType
3473     // but do not necessarily update the type of New.
3474     if (CheckEquivalentExceptionSpec(Old, New))
3475       return true;
3476     OldQType = Context.getCanonicalType(Old->getType());
3477     NewQType = Context.getCanonicalType(New->getType());
3478 
3479     // Go back to the type source info to compare the declared return types,
3480     // per C++1y [dcl.type.auto]p13:
3481     //   Redeclarations or specializations of a function or function template
3482     //   with a declared return type that uses a placeholder type shall also
3483     //   use that placeholder, not a deduced type.
3484     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3485     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3486     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3487         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3488                                        OldDeclaredReturnType)) {
3489       QualType ResQT;
3490       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3491           OldDeclaredReturnType->isObjCObjectPointerType())
3492         // FIXME: This does the wrong thing for a deduced return type.
3493         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3494       if (ResQT.isNull()) {
3495         if (New->isCXXClassMember() && New->isOutOfLine())
3496           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3497               << New << New->getReturnTypeSourceRange();
3498         else
3499           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3500               << New->getReturnTypeSourceRange();
3501         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3502                                     << Old->getReturnTypeSourceRange();
3503         return true;
3504       }
3505       else
3506         NewQType = ResQT;
3507     }
3508 
3509     QualType OldReturnType = OldType->getReturnType();
3510     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3511     if (OldReturnType != NewReturnType) {
3512       // If this function has a deduced return type and has already been
3513       // defined, copy the deduced value from the old declaration.
3514       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3515       if (OldAT && OldAT->isDeduced()) {
3516         New->setType(
3517             SubstAutoType(New->getType(),
3518                           OldAT->isDependentType() ? Context.DependentTy
3519                                                    : OldAT->getDeducedType()));
3520         NewQType = Context.getCanonicalType(
3521             SubstAutoType(NewQType,
3522                           OldAT->isDependentType() ? Context.DependentTy
3523                                                    : OldAT->getDeducedType()));
3524       }
3525     }
3526 
3527     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3528     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3529     if (OldMethod && NewMethod) {
3530       // Preserve triviality.
3531       NewMethod->setTrivial(OldMethod->isTrivial());
3532 
3533       // MSVC allows explicit template specialization at class scope:
3534       // 2 CXXMethodDecls referring to the same function will be injected.
3535       // We don't want a redeclaration error.
3536       bool IsClassScopeExplicitSpecialization =
3537                               OldMethod->isFunctionTemplateSpecialization() &&
3538                               NewMethod->isFunctionTemplateSpecialization();
3539       bool isFriend = NewMethod->getFriendObjectKind();
3540 
3541       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3542           !IsClassScopeExplicitSpecialization) {
3543         //    -- Member function declarations with the same name and the
3544         //       same parameter types cannot be overloaded if any of them
3545         //       is a static member function declaration.
3546         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3547           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3548           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3549           return true;
3550         }
3551 
3552         // C++ [class.mem]p1:
3553         //   [...] A member shall not be declared twice in the
3554         //   member-specification, except that a nested class or member
3555         //   class template can be declared and then later defined.
3556         if (!inTemplateInstantiation()) {
3557           unsigned NewDiag;
3558           if (isa<CXXConstructorDecl>(OldMethod))
3559             NewDiag = diag::err_constructor_redeclared;
3560           else if (isa<CXXDestructorDecl>(NewMethod))
3561             NewDiag = diag::err_destructor_redeclared;
3562           else if (isa<CXXConversionDecl>(NewMethod))
3563             NewDiag = diag::err_conv_function_redeclared;
3564           else
3565             NewDiag = diag::err_member_redeclared;
3566 
3567           Diag(New->getLocation(), NewDiag);
3568         } else {
3569           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3570             << New << New->getType();
3571         }
3572         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3573         return true;
3574 
3575       // Complain if this is an explicit declaration of a special
3576       // member that was initially declared implicitly.
3577       //
3578       // As an exception, it's okay to befriend such methods in order
3579       // to permit the implicit constructor/destructor/operator calls.
3580       } else if (OldMethod->isImplicit()) {
3581         if (isFriend) {
3582           NewMethod->setImplicit();
3583         } else {
3584           Diag(NewMethod->getLocation(),
3585                diag::err_definition_of_implicitly_declared_member)
3586             << New << getSpecialMember(OldMethod);
3587           return true;
3588         }
3589       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3590         Diag(NewMethod->getLocation(),
3591              diag::err_definition_of_explicitly_defaulted_member)
3592           << getSpecialMember(OldMethod);
3593         return true;
3594       }
3595     }
3596 
3597     // C++11 [dcl.attr.noreturn]p1:
3598     //   The first declaration of a function shall specify the noreturn
3599     //   attribute if any declaration of that function specifies the noreturn
3600     //   attribute.
3601     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3602     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3603       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3604       Diag(Old->getFirstDecl()->getLocation(),
3605            diag::note_noreturn_missing_first_decl);
3606     }
3607 
3608     // C++11 [dcl.attr.depend]p2:
3609     //   The first declaration of a function shall specify the
3610     //   carries_dependency attribute for its declarator-id if any declaration
3611     //   of the function specifies the carries_dependency attribute.
3612     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3613     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3614       Diag(CDA->getLocation(),
3615            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3616       Diag(Old->getFirstDecl()->getLocation(),
3617            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3618     }
3619 
3620     // (C++98 8.3.5p3):
3621     //   All declarations for a function shall agree exactly in both the
3622     //   return type and the parameter-type-list.
3623     // We also want to respect all the extended bits except noreturn.
3624 
3625     // noreturn should now match unless the old type info didn't have it.
3626     QualType OldQTypeForComparison = OldQType;
3627     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3628       auto *OldType = OldQType->castAs<FunctionProtoType>();
3629       const FunctionType *OldTypeForComparison
3630         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3631       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3632       assert(OldQTypeForComparison.isCanonical());
3633     }
3634 
3635     if (haveIncompatibleLanguageLinkages(Old, New)) {
3636       // As a special case, retain the language linkage from previous
3637       // declarations of a friend function as an extension.
3638       //
3639       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3640       // and is useful because there's otherwise no way to specify language
3641       // linkage within class scope.
3642       //
3643       // Check cautiously as the friend object kind isn't yet complete.
3644       if (New->getFriendObjectKind() != Decl::FOK_None) {
3645         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3646         Diag(OldLocation, PrevDiag);
3647       } else {
3648         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3649         Diag(OldLocation, PrevDiag);
3650         return true;
3651       }
3652     }
3653 
3654     // If the function types are compatible, merge the declarations. Ignore the
3655     // exception specifier because it was already checked above in
3656     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3657     // about incompatible types under -fms-compatibility.
3658     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3659                                                          NewQType))
3660       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3661 
3662     // If the types are imprecise (due to dependent constructs in friends or
3663     // local extern declarations), it's OK if they differ. We'll check again
3664     // during instantiation.
3665     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3666       return false;
3667 
3668     // Fall through for conflicting redeclarations and redefinitions.
3669   }
3670 
3671   // C: Function types need to be compatible, not identical. This handles
3672   // duplicate function decls like "void f(int); void f(enum X);" properly.
3673   if (!getLangOpts().CPlusPlus &&
3674       Context.typesAreCompatible(OldQType, NewQType)) {
3675     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3676     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3677     const FunctionProtoType *OldProto = nullptr;
3678     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3679         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3680       // The old declaration provided a function prototype, but the
3681       // new declaration does not. Merge in the prototype.
3682       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3683       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3684       NewQType =
3685           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3686                                   OldProto->getExtProtoInfo());
3687       New->setType(NewQType);
3688       New->setHasInheritedPrototype();
3689 
3690       // Synthesize parameters with the same types.
3691       SmallVector<ParmVarDecl*, 16> Params;
3692       for (const auto &ParamType : OldProto->param_types()) {
3693         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3694                                                  SourceLocation(), nullptr,
3695                                                  ParamType, /*TInfo=*/nullptr,
3696                                                  SC_None, nullptr);
3697         Param->setScopeInfo(0, Params.size());
3698         Param->setImplicit();
3699         Params.push_back(Param);
3700       }
3701 
3702       New->setParams(Params);
3703     }
3704 
3705     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3706   }
3707 
3708   // Check if the function types are compatible when pointer size address
3709   // spaces are ignored.
3710   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3711     return false;
3712 
3713   // GNU C permits a K&R definition to follow a prototype declaration
3714   // if the declared types of the parameters in the K&R definition
3715   // match the types in the prototype declaration, even when the
3716   // promoted types of the parameters from the K&R definition differ
3717   // from the types in the prototype. GCC then keeps the types from
3718   // the prototype.
3719   //
3720   // If a variadic prototype is followed by a non-variadic K&R definition,
3721   // the K&R definition becomes variadic.  This is sort of an edge case, but
3722   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3723   // C99 6.9.1p8.
3724   if (!getLangOpts().CPlusPlus &&
3725       Old->hasPrototype() && !New->hasPrototype() &&
3726       New->getType()->getAs<FunctionProtoType>() &&
3727       Old->getNumParams() == New->getNumParams()) {
3728     SmallVector<QualType, 16> ArgTypes;
3729     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3730     const FunctionProtoType *OldProto
3731       = Old->getType()->getAs<FunctionProtoType>();
3732     const FunctionProtoType *NewProto
3733       = New->getType()->getAs<FunctionProtoType>();
3734 
3735     // Determine whether this is the GNU C extension.
3736     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3737                                                NewProto->getReturnType());
3738     bool LooseCompatible = !MergedReturn.isNull();
3739     for (unsigned Idx = 0, End = Old->getNumParams();
3740          LooseCompatible && Idx != End; ++Idx) {
3741       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3742       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3743       if (Context.typesAreCompatible(OldParm->getType(),
3744                                      NewProto->getParamType(Idx))) {
3745         ArgTypes.push_back(NewParm->getType());
3746       } else if (Context.typesAreCompatible(OldParm->getType(),
3747                                             NewParm->getType(),
3748                                             /*CompareUnqualified=*/true)) {
3749         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3750                                            NewProto->getParamType(Idx) };
3751         Warnings.push_back(Warn);
3752         ArgTypes.push_back(NewParm->getType());
3753       } else
3754         LooseCompatible = false;
3755     }
3756 
3757     if (LooseCompatible) {
3758       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3759         Diag(Warnings[Warn].NewParm->getLocation(),
3760              diag::ext_param_promoted_not_compatible_with_prototype)
3761           << Warnings[Warn].PromotedType
3762           << Warnings[Warn].OldParm->getType();
3763         if (Warnings[Warn].OldParm->getLocation().isValid())
3764           Diag(Warnings[Warn].OldParm->getLocation(),
3765                diag::note_previous_declaration);
3766       }
3767 
3768       if (MergeTypeWithOld)
3769         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3770                                              OldProto->getExtProtoInfo()));
3771       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3772     }
3773 
3774     // Fall through to diagnose conflicting types.
3775   }
3776 
3777   // A function that has already been declared has been redeclared or
3778   // defined with a different type; show an appropriate diagnostic.
3779 
3780   // If the previous declaration was an implicitly-generated builtin
3781   // declaration, then at the very least we should use a specialized note.
3782   unsigned BuiltinID;
3783   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3784     // If it's actually a library-defined builtin function like 'malloc'
3785     // or 'printf', just warn about the incompatible redeclaration.
3786     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3787       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3788       Diag(OldLocation, diag::note_previous_builtin_declaration)
3789         << Old << Old->getType();
3790       return false;
3791     }
3792 
3793     PrevDiag = diag::note_previous_builtin_declaration;
3794   }
3795 
3796   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3797   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3798   return true;
3799 }
3800 
3801 /// Completes the merge of two function declarations that are
3802 /// known to be compatible.
3803 ///
3804 /// This routine handles the merging of attributes and other
3805 /// properties of function declarations from the old declaration to
3806 /// the new declaration, once we know that New is in fact a
3807 /// redeclaration of Old.
3808 ///
3809 /// \returns false
3810 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3811                                         Scope *S, bool MergeTypeWithOld) {
3812   // Merge the attributes
3813   mergeDeclAttributes(New, Old);
3814 
3815   // Merge "pure" flag.
3816   if (Old->isPure())
3817     New->setPure();
3818 
3819   // Merge "used" flag.
3820   if (Old->getMostRecentDecl()->isUsed(false))
3821     New->setIsUsed();
3822 
3823   // Merge attributes from the parameters.  These can mismatch with K&R
3824   // declarations.
3825   if (New->getNumParams() == Old->getNumParams())
3826       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3827         ParmVarDecl *NewParam = New->getParamDecl(i);
3828         ParmVarDecl *OldParam = Old->getParamDecl(i);
3829         mergeParamDeclAttributes(NewParam, OldParam, *this);
3830         mergeParamDeclTypes(NewParam, OldParam, *this);
3831       }
3832 
3833   if (getLangOpts().CPlusPlus)
3834     return MergeCXXFunctionDecl(New, Old, S);
3835 
3836   // Merge the function types so the we get the composite types for the return
3837   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3838   // was visible.
3839   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3840   if (!Merged.isNull() && MergeTypeWithOld)
3841     New->setType(Merged);
3842 
3843   return false;
3844 }
3845 
3846 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3847                                 ObjCMethodDecl *oldMethod) {
3848   // Merge the attributes, including deprecated/unavailable
3849   AvailabilityMergeKind MergeKind =
3850     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3851       ? AMK_ProtocolImplementation
3852       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3853                                                        : AMK_Override;
3854 
3855   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3856 
3857   // Merge attributes from the parameters.
3858   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3859                                        oe = oldMethod->param_end();
3860   for (ObjCMethodDecl::param_iterator
3861          ni = newMethod->param_begin(), ne = newMethod->param_end();
3862        ni != ne && oi != oe; ++ni, ++oi)
3863     mergeParamDeclAttributes(*ni, *oi, *this);
3864 
3865   CheckObjCMethodOverride(newMethod, oldMethod);
3866 }
3867 
3868 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3869   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3870 
3871   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3872          ? diag::err_redefinition_different_type
3873          : diag::err_redeclaration_different_type)
3874     << New->getDeclName() << New->getType() << Old->getType();
3875 
3876   diag::kind PrevDiag;
3877   SourceLocation OldLocation;
3878   std::tie(PrevDiag, OldLocation)
3879     = getNoteDiagForInvalidRedeclaration(Old, New);
3880   S.Diag(OldLocation, PrevDiag);
3881   New->setInvalidDecl();
3882 }
3883 
3884 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3885 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3886 /// emitting diagnostics as appropriate.
3887 ///
3888 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3889 /// to here in AddInitializerToDecl. We can't check them before the initializer
3890 /// is attached.
3891 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3892                              bool MergeTypeWithOld) {
3893   if (New->isInvalidDecl() || Old->isInvalidDecl())
3894     return;
3895 
3896   QualType MergedT;
3897   if (getLangOpts().CPlusPlus) {
3898     if (New->getType()->isUndeducedType()) {
3899       // We don't know what the new type is until the initializer is attached.
3900       return;
3901     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3902       // These could still be something that needs exception specs checked.
3903       return MergeVarDeclExceptionSpecs(New, Old);
3904     }
3905     // C++ [basic.link]p10:
3906     //   [...] the types specified by all declarations referring to a given
3907     //   object or function shall be identical, except that declarations for an
3908     //   array object can specify array types that differ by the presence or
3909     //   absence of a major array bound (8.3.4).
3910     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3911       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3912       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3913 
3914       // We are merging a variable declaration New into Old. If it has an array
3915       // bound, and that bound differs from Old's bound, we should diagnose the
3916       // mismatch.
3917       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3918         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3919              PrevVD = PrevVD->getPreviousDecl()) {
3920           QualType PrevVDTy = PrevVD->getType();
3921           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3922             continue;
3923 
3924           if (!Context.hasSameType(New->getType(), PrevVDTy))
3925             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3926         }
3927       }
3928 
3929       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3930         if (Context.hasSameType(OldArray->getElementType(),
3931                                 NewArray->getElementType()))
3932           MergedT = New->getType();
3933       }
3934       // FIXME: Check visibility. New is hidden but has a complete type. If New
3935       // has no array bound, it should not inherit one from Old, if Old is not
3936       // visible.
3937       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3938         if (Context.hasSameType(OldArray->getElementType(),
3939                                 NewArray->getElementType()))
3940           MergedT = Old->getType();
3941       }
3942     }
3943     else if (New->getType()->isObjCObjectPointerType() &&
3944                Old->getType()->isObjCObjectPointerType()) {
3945       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3946                                               Old->getType());
3947     }
3948   } else {
3949     // C 6.2.7p2:
3950     //   All declarations that refer to the same object or function shall have
3951     //   compatible type.
3952     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3953   }
3954   if (MergedT.isNull()) {
3955     // It's OK if we couldn't merge types if either type is dependent, for a
3956     // block-scope variable. In other cases (static data members of class
3957     // templates, variable templates, ...), we require the types to be
3958     // equivalent.
3959     // FIXME: The C++ standard doesn't say anything about this.
3960     if ((New->getType()->isDependentType() ||
3961          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3962       // If the old type was dependent, we can't merge with it, so the new type
3963       // becomes dependent for now. We'll reproduce the original type when we
3964       // instantiate the TypeSourceInfo for the variable.
3965       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3966         New->setType(Context.DependentTy);
3967       return;
3968     }
3969     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3970   }
3971 
3972   // Don't actually update the type on the new declaration if the old
3973   // declaration was an extern declaration in a different scope.
3974   if (MergeTypeWithOld)
3975     New->setType(MergedT);
3976 }
3977 
3978 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3979                                   LookupResult &Previous) {
3980   // C11 6.2.7p4:
3981   //   For an identifier with internal or external linkage declared
3982   //   in a scope in which a prior declaration of that identifier is
3983   //   visible, if the prior declaration specifies internal or
3984   //   external linkage, the type of the identifier at the later
3985   //   declaration becomes the composite type.
3986   //
3987   // If the variable isn't visible, we do not merge with its type.
3988   if (Previous.isShadowed())
3989     return false;
3990 
3991   if (S.getLangOpts().CPlusPlus) {
3992     // C++11 [dcl.array]p3:
3993     //   If there is a preceding declaration of the entity in the same
3994     //   scope in which the bound was specified, an omitted array bound
3995     //   is taken to be the same as in that earlier declaration.
3996     return NewVD->isPreviousDeclInSameBlockScope() ||
3997            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3998             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3999   } else {
4000     // If the old declaration was function-local, don't merge with its
4001     // type unless we're in the same function.
4002     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4003            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4004   }
4005 }
4006 
4007 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4008 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4009 /// situation, merging decls or emitting diagnostics as appropriate.
4010 ///
4011 /// Tentative definition rules (C99 6.9.2p2) are checked by
4012 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4013 /// definitions here, since the initializer hasn't been attached.
4014 ///
4015 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4016   // If the new decl is already invalid, don't do any other checking.
4017   if (New->isInvalidDecl())
4018     return;
4019 
4020   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4021     return;
4022 
4023   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4024 
4025   // Verify the old decl was also a variable or variable template.
4026   VarDecl *Old = nullptr;
4027   VarTemplateDecl *OldTemplate = nullptr;
4028   if (Previous.isSingleResult()) {
4029     if (NewTemplate) {
4030       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4031       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4032 
4033       if (auto *Shadow =
4034               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4035         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4036           return New->setInvalidDecl();
4037     } else {
4038       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4039 
4040       if (auto *Shadow =
4041               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4042         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4043           return New->setInvalidDecl();
4044     }
4045   }
4046   if (!Old) {
4047     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4048         << New->getDeclName();
4049     notePreviousDefinition(Previous.getRepresentativeDecl(),
4050                            New->getLocation());
4051     return New->setInvalidDecl();
4052   }
4053 
4054   // Ensure the template parameters are compatible.
4055   if (NewTemplate &&
4056       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4057                                       OldTemplate->getTemplateParameters(),
4058                                       /*Complain=*/true, TPL_TemplateMatch))
4059     return New->setInvalidDecl();
4060 
4061   // C++ [class.mem]p1:
4062   //   A member shall not be declared twice in the member-specification [...]
4063   //
4064   // Here, we need only consider static data members.
4065   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4066     Diag(New->getLocation(), diag::err_duplicate_member)
4067       << New->getIdentifier();
4068     Diag(Old->getLocation(), diag::note_previous_declaration);
4069     New->setInvalidDecl();
4070   }
4071 
4072   mergeDeclAttributes(New, Old);
4073   // Warn if an already-declared variable is made a weak_import in a subsequent
4074   // declaration
4075   if (New->hasAttr<WeakImportAttr>() &&
4076       Old->getStorageClass() == SC_None &&
4077       !Old->hasAttr<WeakImportAttr>()) {
4078     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4079     notePreviousDefinition(Old, New->getLocation());
4080     // Remove weak_import attribute on new declaration.
4081     New->dropAttr<WeakImportAttr>();
4082   }
4083 
4084   if (New->hasAttr<InternalLinkageAttr>() &&
4085       !Old->hasAttr<InternalLinkageAttr>()) {
4086     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4087         << New->getDeclName();
4088     notePreviousDefinition(Old, New->getLocation());
4089     New->dropAttr<InternalLinkageAttr>();
4090   }
4091 
4092   // Merge the types.
4093   VarDecl *MostRecent = Old->getMostRecentDecl();
4094   if (MostRecent != Old) {
4095     MergeVarDeclTypes(New, MostRecent,
4096                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4097     if (New->isInvalidDecl())
4098       return;
4099   }
4100 
4101   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4102   if (New->isInvalidDecl())
4103     return;
4104 
4105   diag::kind PrevDiag;
4106   SourceLocation OldLocation;
4107   std::tie(PrevDiag, OldLocation) =
4108       getNoteDiagForInvalidRedeclaration(Old, New);
4109 
4110   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4111   if (New->getStorageClass() == SC_Static &&
4112       !New->isStaticDataMember() &&
4113       Old->hasExternalFormalLinkage()) {
4114     if (getLangOpts().MicrosoftExt) {
4115       Diag(New->getLocation(), diag::ext_static_non_static)
4116           << New->getDeclName();
4117       Diag(OldLocation, PrevDiag);
4118     } else {
4119       Diag(New->getLocation(), diag::err_static_non_static)
4120           << New->getDeclName();
4121       Diag(OldLocation, PrevDiag);
4122       return New->setInvalidDecl();
4123     }
4124   }
4125   // C99 6.2.2p4:
4126   //   For an identifier declared with the storage-class specifier
4127   //   extern in a scope in which a prior declaration of that
4128   //   identifier is visible,23) if the prior declaration specifies
4129   //   internal or external linkage, the linkage of the identifier at
4130   //   the later declaration is the same as the linkage specified at
4131   //   the prior declaration. If no prior declaration is visible, or
4132   //   if the prior declaration specifies no linkage, then the
4133   //   identifier has external linkage.
4134   if (New->hasExternalStorage() && Old->hasLinkage())
4135     /* Okay */;
4136   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4137            !New->isStaticDataMember() &&
4138            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4139     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4140     Diag(OldLocation, PrevDiag);
4141     return New->setInvalidDecl();
4142   }
4143 
4144   // Check if extern is followed by non-extern and vice-versa.
4145   if (New->hasExternalStorage() &&
4146       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4147     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4148     Diag(OldLocation, PrevDiag);
4149     return New->setInvalidDecl();
4150   }
4151   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4152       !New->hasExternalStorage()) {
4153     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4154     Diag(OldLocation, PrevDiag);
4155     return New->setInvalidDecl();
4156   }
4157 
4158   if (CheckRedeclarationModuleOwnership(New, Old))
4159     return;
4160 
4161   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4162 
4163   // FIXME: The test for external storage here seems wrong? We still
4164   // need to check for mismatches.
4165   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4166       // Don't complain about out-of-line definitions of static members.
4167       !(Old->getLexicalDeclContext()->isRecord() &&
4168         !New->getLexicalDeclContext()->isRecord())) {
4169     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4170     Diag(OldLocation, PrevDiag);
4171     return New->setInvalidDecl();
4172   }
4173 
4174   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4175     if (VarDecl *Def = Old->getDefinition()) {
4176       // C++1z [dcl.fcn.spec]p4:
4177       //   If the definition of a variable appears in a translation unit before
4178       //   its first declaration as inline, the program is ill-formed.
4179       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4180       Diag(Def->getLocation(), diag::note_previous_definition);
4181     }
4182   }
4183 
4184   // If this redeclaration makes the variable inline, we may need to add it to
4185   // UndefinedButUsed.
4186   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4187       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4188     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4189                                            SourceLocation()));
4190 
4191   if (New->getTLSKind() != Old->getTLSKind()) {
4192     if (!Old->getTLSKind()) {
4193       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4194       Diag(OldLocation, PrevDiag);
4195     } else if (!New->getTLSKind()) {
4196       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4197       Diag(OldLocation, PrevDiag);
4198     } else {
4199       // Do not allow redeclaration to change the variable between requiring
4200       // static and dynamic initialization.
4201       // FIXME: GCC allows this, but uses the TLS keyword on the first
4202       // declaration to determine the kind. Do we need to be compatible here?
4203       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4204         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4205       Diag(OldLocation, PrevDiag);
4206     }
4207   }
4208 
4209   // C++ doesn't have tentative definitions, so go right ahead and check here.
4210   if (getLangOpts().CPlusPlus &&
4211       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4212     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4213         Old->getCanonicalDecl()->isConstexpr()) {
4214       // This definition won't be a definition any more once it's been merged.
4215       Diag(New->getLocation(),
4216            diag::warn_deprecated_redundant_constexpr_static_def);
4217     } else if (VarDecl *Def = Old->getDefinition()) {
4218       if (checkVarDeclRedefinition(Def, New))
4219         return;
4220     }
4221   }
4222 
4223   if (haveIncompatibleLanguageLinkages(Old, New)) {
4224     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4225     Diag(OldLocation, PrevDiag);
4226     New->setInvalidDecl();
4227     return;
4228   }
4229 
4230   // Merge "used" flag.
4231   if (Old->getMostRecentDecl()->isUsed(false))
4232     New->setIsUsed();
4233 
4234   // Keep a chain of previous declarations.
4235   New->setPreviousDecl(Old);
4236   if (NewTemplate)
4237     NewTemplate->setPreviousDecl(OldTemplate);
4238   adjustDeclContextForDeclaratorDecl(New, Old);
4239 
4240   // Inherit access appropriately.
4241   New->setAccess(Old->getAccess());
4242   if (NewTemplate)
4243     NewTemplate->setAccess(New->getAccess());
4244 
4245   if (Old->isInline())
4246     New->setImplicitlyInline();
4247 }
4248 
4249 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4250   SourceManager &SrcMgr = getSourceManager();
4251   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4252   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4253   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4254   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4255   auto &HSI = PP.getHeaderSearchInfo();
4256   StringRef HdrFilename =
4257       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4258 
4259   auto noteFromModuleOrInclude = [&](Module *Mod,
4260                                      SourceLocation IncLoc) -> bool {
4261     // Redefinition errors with modules are common with non modular mapped
4262     // headers, example: a non-modular header H in module A that also gets
4263     // included directly in a TU. Pointing twice to the same header/definition
4264     // is confusing, try to get better diagnostics when modules is on.
4265     if (IncLoc.isValid()) {
4266       if (Mod) {
4267         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4268             << HdrFilename.str() << Mod->getFullModuleName();
4269         if (!Mod->DefinitionLoc.isInvalid())
4270           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4271               << Mod->getFullModuleName();
4272       } else {
4273         Diag(IncLoc, diag::note_redefinition_include_same_file)
4274             << HdrFilename.str();
4275       }
4276       return true;
4277     }
4278 
4279     return false;
4280   };
4281 
4282   // Is it the same file and same offset? Provide more information on why
4283   // this leads to a redefinition error.
4284   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4285     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4286     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4287     bool EmittedDiag =
4288         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4289     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4290 
4291     // If the header has no guards, emit a note suggesting one.
4292     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4293       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4294 
4295     if (EmittedDiag)
4296       return;
4297   }
4298 
4299   // Redefinition coming from different files or couldn't do better above.
4300   if (Old->getLocation().isValid())
4301     Diag(Old->getLocation(), diag::note_previous_definition);
4302 }
4303 
4304 /// We've just determined that \p Old and \p New both appear to be definitions
4305 /// of the same variable. Either diagnose or fix the problem.
4306 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4307   if (!hasVisibleDefinition(Old) &&
4308       (New->getFormalLinkage() == InternalLinkage ||
4309        New->isInline() ||
4310        New->getDescribedVarTemplate() ||
4311        New->getNumTemplateParameterLists() ||
4312        New->getDeclContext()->isDependentContext())) {
4313     // The previous definition is hidden, and multiple definitions are
4314     // permitted (in separate TUs). Demote this to a declaration.
4315     New->demoteThisDefinitionToDeclaration();
4316 
4317     // Make the canonical definition visible.
4318     if (auto *OldTD = Old->getDescribedVarTemplate())
4319       makeMergedDefinitionVisible(OldTD);
4320     makeMergedDefinitionVisible(Old);
4321     return false;
4322   } else {
4323     Diag(New->getLocation(), diag::err_redefinition) << New;
4324     notePreviousDefinition(Old, New->getLocation());
4325     New->setInvalidDecl();
4326     return true;
4327   }
4328 }
4329 
4330 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4331 /// no declarator (e.g. "struct foo;") is parsed.
4332 Decl *
4333 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4334                                  RecordDecl *&AnonRecord) {
4335   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4336                                     AnonRecord);
4337 }
4338 
4339 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4340 // disambiguate entities defined in different scopes.
4341 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4342 // compatibility.
4343 // We will pick our mangling number depending on which version of MSVC is being
4344 // targeted.
4345 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4346   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4347              ? S->getMSCurManglingNumber()
4348              : S->getMSLastManglingNumber();
4349 }
4350 
4351 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4352   if (!Context.getLangOpts().CPlusPlus)
4353     return;
4354 
4355   if (isa<CXXRecordDecl>(Tag->getParent())) {
4356     // If this tag is the direct child of a class, number it if
4357     // it is anonymous.
4358     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4359       return;
4360     MangleNumberingContext &MCtx =
4361         Context.getManglingNumberContext(Tag->getParent());
4362     Context.setManglingNumber(
4363         Tag, MCtx.getManglingNumber(
4364                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4365     return;
4366   }
4367 
4368   // If this tag isn't a direct child of a class, number it if it is local.
4369   MangleNumberingContext *MCtx;
4370   Decl *ManglingContextDecl;
4371   std::tie(MCtx, ManglingContextDecl) =
4372       getCurrentMangleNumberContext(Tag->getDeclContext());
4373   if (MCtx) {
4374     Context.setManglingNumber(
4375         Tag, MCtx->getManglingNumber(
4376                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4377   }
4378 }
4379 
4380 namespace {
4381 struct NonCLikeKind {
4382   enum {
4383     None,
4384     BaseClass,
4385     DefaultMemberInit,
4386     Lambda,
4387     Friend,
4388     OtherMember,
4389     Invalid,
4390   } Kind = None;
4391   SourceRange Range;
4392 
4393   explicit operator bool() { return Kind != None; }
4394 };
4395 }
4396 
4397 /// Determine whether a class is C-like, according to the rules of C++
4398 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4399 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4400   if (RD->isInvalidDecl())
4401     return {NonCLikeKind::Invalid, {}};
4402 
4403   // C++ [dcl.typedef]p9: [P1766R1]
4404   //   An unnamed class with a typedef name for linkage purposes shall not
4405   //
4406   //    -- have any base classes
4407   if (RD->getNumBases())
4408     return {NonCLikeKind::BaseClass,
4409             SourceRange(RD->bases_begin()->getBeginLoc(),
4410                         RD->bases_end()[-1].getEndLoc())};
4411   bool Invalid = false;
4412   for (Decl *D : RD->decls()) {
4413     // Don't complain about things we already diagnosed.
4414     if (D->isInvalidDecl()) {
4415       Invalid = true;
4416       continue;
4417     }
4418 
4419     //  -- have any [...] default member initializers
4420     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4421       if (FD->hasInClassInitializer()) {
4422         auto *Init = FD->getInClassInitializer();
4423         return {NonCLikeKind::DefaultMemberInit,
4424                 Init ? Init->getSourceRange() : D->getSourceRange()};
4425       }
4426       continue;
4427     }
4428 
4429     // FIXME: We don't allow friend declarations. This violates the wording of
4430     // P1766, but not the intent.
4431     if (isa<FriendDecl>(D))
4432       return {NonCLikeKind::Friend, D->getSourceRange()};
4433 
4434     //  -- declare any members other than non-static data members, member
4435     //     enumerations, or member classes,
4436     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4437         isa<EnumDecl>(D))
4438       continue;
4439     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4440     if (!MemberRD) {
4441       if (D->isImplicit())
4442         continue;
4443       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4444     }
4445 
4446     //  -- contain a lambda-expression,
4447     if (MemberRD->isLambda())
4448       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4449 
4450     //  and all member classes shall also satisfy these requirements
4451     //  (recursively).
4452     if (MemberRD->isThisDeclarationADefinition()) {
4453       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4454         return Kind;
4455     }
4456   }
4457 
4458   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4459 }
4460 
4461 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4462                                         TypedefNameDecl *NewTD) {
4463   if (TagFromDeclSpec->isInvalidDecl())
4464     return;
4465 
4466   // Do nothing if the tag already has a name for linkage purposes.
4467   if (TagFromDeclSpec->hasNameForLinkage())
4468     return;
4469 
4470   // A well-formed anonymous tag must always be a TUK_Definition.
4471   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4472 
4473   // The type must match the tag exactly;  no qualifiers allowed.
4474   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4475                            Context.getTagDeclType(TagFromDeclSpec))) {
4476     if (getLangOpts().CPlusPlus)
4477       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4478     return;
4479   }
4480 
4481   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4482   //   An unnamed class with a typedef name for linkage purposes shall [be
4483   //   C-like].
4484   //
4485   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4486   // shouldn't happen, but there are constructs that the language rule doesn't
4487   // disallow for which we can't reasonably avoid computing linkage early.
4488   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4489   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4490                              : NonCLikeKind();
4491   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4492   if (NonCLike || ChangesLinkage) {
4493     if (NonCLike.Kind == NonCLikeKind::Invalid)
4494       return;
4495 
4496     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4497     if (ChangesLinkage) {
4498       // If the linkage changes, we can't accept this as an extension.
4499       if (NonCLike.Kind == NonCLikeKind::None)
4500         DiagID = diag::err_typedef_changes_linkage;
4501       else
4502         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4503     }
4504 
4505     SourceLocation FixitLoc =
4506         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4507     llvm::SmallString<40> TextToInsert;
4508     TextToInsert += ' ';
4509     TextToInsert += NewTD->getIdentifier()->getName();
4510 
4511     Diag(FixitLoc, DiagID)
4512       << isa<TypeAliasDecl>(NewTD)
4513       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4514     if (NonCLike.Kind != NonCLikeKind::None) {
4515       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4516         << NonCLike.Kind - 1 << NonCLike.Range;
4517     }
4518     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4519       << NewTD << isa<TypeAliasDecl>(NewTD);
4520 
4521     if (ChangesLinkage)
4522       return;
4523   }
4524 
4525   // Otherwise, set this as the anon-decl typedef for the tag.
4526   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4527 }
4528 
4529 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4530   switch (T) {
4531   case DeclSpec::TST_class:
4532     return 0;
4533   case DeclSpec::TST_struct:
4534     return 1;
4535   case DeclSpec::TST_interface:
4536     return 2;
4537   case DeclSpec::TST_union:
4538     return 3;
4539   case DeclSpec::TST_enum:
4540     return 4;
4541   default:
4542     llvm_unreachable("unexpected type specifier");
4543   }
4544 }
4545 
4546 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4547 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4548 /// parameters to cope with template friend declarations.
4549 Decl *
4550 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4551                                  MultiTemplateParamsArg TemplateParams,
4552                                  bool IsExplicitInstantiation,
4553                                  RecordDecl *&AnonRecord) {
4554   Decl *TagD = nullptr;
4555   TagDecl *Tag = nullptr;
4556   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4557       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4558       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4559       DS.getTypeSpecType() == DeclSpec::TST_union ||
4560       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4561     TagD = DS.getRepAsDecl();
4562 
4563     if (!TagD) // We probably had an error
4564       return nullptr;
4565 
4566     // Note that the above type specs guarantee that the
4567     // type rep is a Decl, whereas in many of the others
4568     // it's a Type.
4569     if (isa<TagDecl>(TagD))
4570       Tag = cast<TagDecl>(TagD);
4571     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4572       Tag = CTD->getTemplatedDecl();
4573   }
4574 
4575   if (Tag) {
4576     handleTagNumbering(Tag, S);
4577     Tag->setFreeStanding();
4578     if (Tag->isInvalidDecl())
4579       return Tag;
4580   }
4581 
4582   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4583     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4584     // or incomplete types shall not be restrict-qualified."
4585     if (TypeQuals & DeclSpec::TQ_restrict)
4586       Diag(DS.getRestrictSpecLoc(),
4587            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4588            << DS.getSourceRange();
4589   }
4590 
4591   if (DS.isInlineSpecified())
4592     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4593         << getLangOpts().CPlusPlus17;
4594 
4595   if (DS.hasConstexprSpecifier()) {
4596     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4597     // and definitions of functions and variables.
4598     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4599     // the declaration of a function or function template
4600     if (Tag)
4601       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4602           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4603           << DS.getConstexprSpecifier();
4604     else
4605       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4606           << DS.getConstexprSpecifier();
4607     // Don't emit warnings after this error.
4608     return TagD;
4609   }
4610 
4611   DiagnoseFunctionSpecifiers(DS);
4612 
4613   if (DS.isFriendSpecified()) {
4614     // If we're dealing with a decl but not a TagDecl, assume that
4615     // whatever routines created it handled the friendship aspect.
4616     if (TagD && !Tag)
4617       return nullptr;
4618     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4619   }
4620 
4621   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4622   bool IsExplicitSpecialization =
4623     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4624   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4625       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4626       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4627     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4628     // nested-name-specifier unless it is an explicit instantiation
4629     // or an explicit specialization.
4630     //
4631     // FIXME: We allow class template partial specializations here too, per the
4632     // obvious intent of DR1819.
4633     //
4634     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4635     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4636         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4637     return nullptr;
4638   }
4639 
4640   // Track whether this decl-specifier declares anything.
4641   bool DeclaresAnything = true;
4642 
4643   // Handle anonymous struct definitions.
4644   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4645     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4646         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4647       if (getLangOpts().CPlusPlus ||
4648           Record->getDeclContext()->isRecord()) {
4649         // If CurContext is a DeclContext that can contain statements,
4650         // RecursiveASTVisitor won't visit the decls that
4651         // BuildAnonymousStructOrUnion() will put into CurContext.
4652         // Also store them here so that they can be part of the
4653         // DeclStmt that gets created in this case.
4654         // FIXME: Also return the IndirectFieldDecls created by
4655         // BuildAnonymousStructOr union, for the same reason?
4656         if (CurContext->isFunctionOrMethod())
4657           AnonRecord = Record;
4658         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4659                                            Context.getPrintingPolicy());
4660       }
4661 
4662       DeclaresAnything = false;
4663     }
4664   }
4665 
4666   // C11 6.7.2.1p2:
4667   //   A struct-declaration that does not declare an anonymous structure or
4668   //   anonymous union shall contain a struct-declarator-list.
4669   //
4670   // This rule also existed in C89 and C99; the grammar for struct-declaration
4671   // did not permit a struct-declaration without a struct-declarator-list.
4672   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4673       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4674     // Check for Microsoft C extension: anonymous struct/union member.
4675     // Handle 2 kinds of anonymous struct/union:
4676     //   struct STRUCT;
4677     //   union UNION;
4678     // and
4679     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4680     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4681     if ((Tag && Tag->getDeclName()) ||
4682         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4683       RecordDecl *Record = nullptr;
4684       if (Tag)
4685         Record = dyn_cast<RecordDecl>(Tag);
4686       else if (const RecordType *RT =
4687                    DS.getRepAsType().get()->getAsStructureType())
4688         Record = RT->getDecl();
4689       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4690         Record = UT->getDecl();
4691 
4692       if (Record && getLangOpts().MicrosoftExt) {
4693         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4694             << Record->isUnion() << DS.getSourceRange();
4695         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4696       }
4697 
4698       DeclaresAnything = false;
4699     }
4700   }
4701 
4702   // Skip all the checks below if we have a type error.
4703   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4704       (TagD && TagD->isInvalidDecl()))
4705     return TagD;
4706 
4707   if (getLangOpts().CPlusPlus &&
4708       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4709     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4710       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4711           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4712         DeclaresAnything = false;
4713 
4714   if (!DS.isMissingDeclaratorOk()) {
4715     // Customize diagnostic for a typedef missing a name.
4716     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4717       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4718           << DS.getSourceRange();
4719     else
4720       DeclaresAnything = false;
4721   }
4722 
4723   if (DS.isModulePrivateSpecified() &&
4724       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4725     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4726       << Tag->getTagKind()
4727       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4728 
4729   ActOnDocumentableDecl(TagD);
4730 
4731   // C 6.7/2:
4732   //   A declaration [...] shall declare at least a declarator [...], a tag,
4733   //   or the members of an enumeration.
4734   // C++ [dcl.dcl]p3:
4735   //   [If there are no declarators], and except for the declaration of an
4736   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4737   //   names into the program, or shall redeclare a name introduced by a
4738   //   previous declaration.
4739   if (!DeclaresAnything) {
4740     // In C, we allow this as a (popular) extension / bug. Don't bother
4741     // producing further diagnostics for redundant qualifiers after this.
4742     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4743     return TagD;
4744   }
4745 
4746   // C++ [dcl.stc]p1:
4747   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4748   //   init-declarator-list of the declaration shall not be empty.
4749   // C++ [dcl.fct.spec]p1:
4750   //   If a cv-qualifier appears in a decl-specifier-seq, the
4751   //   init-declarator-list of the declaration shall not be empty.
4752   //
4753   // Spurious qualifiers here appear to be valid in C.
4754   unsigned DiagID = diag::warn_standalone_specifier;
4755   if (getLangOpts().CPlusPlus)
4756     DiagID = diag::ext_standalone_specifier;
4757 
4758   // Note that a linkage-specification sets a storage class, but
4759   // 'extern "C" struct foo;' is actually valid and not theoretically
4760   // useless.
4761   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4762     if (SCS == DeclSpec::SCS_mutable)
4763       // Since mutable is not a viable storage class specifier in C, there is
4764       // no reason to treat it as an extension. Instead, diagnose as an error.
4765       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4766     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4767       Diag(DS.getStorageClassSpecLoc(), DiagID)
4768         << DeclSpec::getSpecifierName(SCS);
4769   }
4770 
4771   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4772     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4773       << DeclSpec::getSpecifierName(TSCS);
4774   if (DS.getTypeQualifiers()) {
4775     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4776       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4777     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4778       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4779     // Restrict is covered above.
4780     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4781       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4782     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4783       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4784   }
4785 
4786   // Warn about ignored type attributes, for example:
4787   // __attribute__((aligned)) struct A;
4788   // Attributes should be placed after tag to apply to type declaration.
4789   if (!DS.getAttributes().empty()) {
4790     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4791     if (TypeSpecType == DeclSpec::TST_class ||
4792         TypeSpecType == DeclSpec::TST_struct ||
4793         TypeSpecType == DeclSpec::TST_interface ||
4794         TypeSpecType == DeclSpec::TST_union ||
4795         TypeSpecType == DeclSpec::TST_enum) {
4796       for (const ParsedAttr &AL : DS.getAttributes())
4797         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4798             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4799     }
4800   }
4801 
4802   return TagD;
4803 }
4804 
4805 /// We are trying to inject an anonymous member into the given scope;
4806 /// check if there's an existing declaration that can't be overloaded.
4807 ///
4808 /// \return true if this is a forbidden redeclaration
4809 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4810                                          Scope *S,
4811                                          DeclContext *Owner,
4812                                          DeclarationName Name,
4813                                          SourceLocation NameLoc,
4814                                          bool IsUnion) {
4815   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4816                  Sema::ForVisibleRedeclaration);
4817   if (!SemaRef.LookupName(R, S)) return false;
4818 
4819   // Pick a representative declaration.
4820   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4821   assert(PrevDecl && "Expected a non-null Decl");
4822 
4823   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4824     return false;
4825 
4826   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4827     << IsUnion << Name;
4828   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4829 
4830   return true;
4831 }
4832 
4833 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4834 /// anonymous struct or union AnonRecord into the owning context Owner
4835 /// and scope S. This routine will be invoked just after we realize
4836 /// that an unnamed union or struct is actually an anonymous union or
4837 /// struct, e.g.,
4838 ///
4839 /// @code
4840 /// union {
4841 ///   int i;
4842 ///   float f;
4843 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4844 ///    // f into the surrounding scope.x
4845 /// @endcode
4846 ///
4847 /// This routine is recursive, injecting the names of nested anonymous
4848 /// structs/unions into the owning context and scope as well.
4849 static bool
4850 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4851                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4852                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4853   bool Invalid = false;
4854 
4855   // Look every FieldDecl and IndirectFieldDecl with a name.
4856   for (auto *D : AnonRecord->decls()) {
4857     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4858         cast<NamedDecl>(D)->getDeclName()) {
4859       ValueDecl *VD = cast<ValueDecl>(D);
4860       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4861                                        VD->getLocation(),
4862                                        AnonRecord->isUnion())) {
4863         // C++ [class.union]p2:
4864         //   The names of the members of an anonymous union shall be
4865         //   distinct from the names of any other entity in the
4866         //   scope in which the anonymous union is declared.
4867         Invalid = true;
4868       } else {
4869         // C++ [class.union]p2:
4870         //   For the purpose of name lookup, after the anonymous union
4871         //   definition, the members of the anonymous union are
4872         //   considered to have been defined in the scope in which the
4873         //   anonymous union is declared.
4874         unsigned OldChainingSize = Chaining.size();
4875         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4876           Chaining.append(IF->chain_begin(), IF->chain_end());
4877         else
4878           Chaining.push_back(VD);
4879 
4880         assert(Chaining.size() >= 2);
4881         NamedDecl **NamedChain =
4882           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4883         for (unsigned i = 0; i < Chaining.size(); i++)
4884           NamedChain[i] = Chaining[i];
4885 
4886         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4887             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4888             VD->getType(), {NamedChain, Chaining.size()});
4889 
4890         for (const auto *Attr : VD->attrs())
4891           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4892 
4893         IndirectField->setAccess(AS);
4894         IndirectField->setImplicit();
4895         SemaRef.PushOnScopeChains(IndirectField, S);
4896 
4897         // That includes picking up the appropriate access specifier.
4898         if (AS != AS_none) IndirectField->setAccess(AS);
4899 
4900         Chaining.resize(OldChainingSize);
4901       }
4902     }
4903   }
4904 
4905   return Invalid;
4906 }
4907 
4908 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4909 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4910 /// illegal input values are mapped to SC_None.
4911 static StorageClass
4912 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4913   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4914   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4915          "Parser allowed 'typedef' as storage class VarDecl.");
4916   switch (StorageClassSpec) {
4917   case DeclSpec::SCS_unspecified:    return SC_None;
4918   case DeclSpec::SCS_extern:
4919     if (DS.isExternInLinkageSpec())
4920       return SC_None;
4921     return SC_Extern;
4922   case DeclSpec::SCS_static:         return SC_Static;
4923   case DeclSpec::SCS_auto:           return SC_Auto;
4924   case DeclSpec::SCS_register:       return SC_Register;
4925   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4926     // Illegal SCSs map to None: error reporting is up to the caller.
4927   case DeclSpec::SCS_mutable:        // Fall through.
4928   case DeclSpec::SCS_typedef:        return SC_None;
4929   }
4930   llvm_unreachable("unknown storage class specifier");
4931 }
4932 
4933 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4934   assert(Record->hasInClassInitializer());
4935 
4936   for (const auto *I : Record->decls()) {
4937     const auto *FD = dyn_cast<FieldDecl>(I);
4938     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4939       FD = IFD->getAnonField();
4940     if (FD && FD->hasInClassInitializer())
4941       return FD->getLocation();
4942   }
4943 
4944   llvm_unreachable("couldn't find in-class initializer");
4945 }
4946 
4947 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4948                                       SourceLocation DefaultInitLoc) {
4949   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4950     return;
4951 
4952   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4953   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4954 }
4955 
4956 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4957                                       CXXRecordDecl *AnonUnion) {
4958   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4959     return;
4960 
4961   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4962 }
4963 
4964 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4965 /// anonymous structure or union. Anonymous unions are a C++ feature
4966 /// (C++ [class.union]) and a C11 feature; anonymous structures
4967 /// are a C11 feature and GNU C++ extension.
4968 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4969                                         AccessSpecifier AS,
4970                                         RecordDecl *Record,
4971                                         const PrintingPolicy &Policy) {
4972   DeclContext *Owner = Record->getDeclContext();
4973 
4974   // Diagnose whether this anonymous struct/union is an extension.
4975   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4976     Diag(Record->getLocation(), diag::ext_anonymous_union);
4977   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4978     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4979   else if (!Record->isUnion() && !getLangOpts().C11)
4980     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4981 
4982   // C and C++ require different kinds of checks for anonymous
4983   // structs/unions.
4984   bool Invalid = false;
4985   if (getLangOpts().CPlusPlus) {
4986     const char *PrevSpec = nullptr;
4987     if (Record->isUnion()) {
4988       // C++ [class.union]p6:
4989       // C++17 [class.union.anon]p2:
4990       //   Anonymous unions declared in a named namespace or in the
4991       //   global namespace shall be declared static.
4992       unsigned DiagID;
4993       DeclContext *OwnerScope = Owner->getRedeclContext();
4994       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4995           (OwnerScope->isTranslationUnit() ||
4996            (OwnerScope->isNamespace() &&
4997             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4998         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4999           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5000 
5001         // Recover by adding 'static'.
5002         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5003                                PrevSpec, DiagID, Policy);
5004       }
5005       // C++ [class.union]p6:
5006       //   A storage class is not allowed in a declaration of an
5007       //   anonymous union in a class scope.
5008       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5009                isa<RecordDecl>(Owner)) {
5010         Diag(DS.getStorageClassSpecLoc(),
5011              diag::err_anonymous_union_with_storage_spec)
5012           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5013 
5014         // Recover by removing the storage specifier.
5015         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5016                                SourceLocation(),
5017                                PrevSpec, DiagID, Context.getPrintingPolicy());
5018       }
5019     }
5020 
5021     // Ignore const/volatile/restrict qualifiers.
5022     if (DS.getTypeQualifiers()) {
5023       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5024         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5025           << Record->isUnion() << "const"
5026           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5027       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5028         Diag(DS.getVolatileSpecLoc(),
5029              diag::ext_anonymous_struct_union_qualified)
5030           << Record->isUnion() << "volatile"
5031           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5032       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5033         Diag(DS.getRestrictSpecLoc(),
5034              diag::ext_anonymous_struct_union_qualified)
5035           << Record->isUnion() << "restrict"
5036           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5037       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5038         Diag(DS.getAtomicSpecLoc(),
5039              diag::ext_anonymous_struct_union_qualified)
5040           << Record->isUnion() << "_Atomic"
5041           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5042       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5043         Diag(DS.getUnalignedSpecLoc(),
5044              diag::ext_anonymous_struct_union_qualified)
5045           << Record->isUnion() << "__unaligned"
5046           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5047 
5048       DS.ClearTypeQualifiers();
5049     }
5050 
5051     // C++ [class.union]p2:
5052     //   The member-specification of an anonymous union shall only
5053     //   define non-static data members. [Note: nested types and
5054     //   functions cannot be declared within an anonymous union. ]
5055     for (auto *Mem : Record->decls()) {
5056       // Ignore invalid declarations; we already diagnosed them.
5057       if (Mem->isInvalidDecl())
5058         continue;
5059 
5060       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5061         // C++ [class.union]p3:
5062         //   An anonymous union shall not have private or protected
5063         //   members (clause 11).
5064         assert(FD->getAccess() != AS_none);
5065         if (FD->getAccess() != AS_public) {
5066           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5067             << Record->isUnion() << (FD->getAccess() == AS_protected);
5068           Invalid = true;
5069         }
5070 
5071         // C++ [class.union]p1
5072         //   An object of a class with a non-trivial constructor, a non-trivial
5073         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5074         //   assignment operator cannot be a member of a union, nor can an
5075         //   array of such objects.
5076         if (CheckNontrivialField(FD))
5077           Invalid = true;
5078       } else if (Mem->isImplicit()) {
5079         // Any implicit members are fine.
5080       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5081         // This is a type that showed up in an
5082         // elaborated-type-specifier inside the anonymous struct or
5083         // union, but which actually declares a type outside of the
5084         // anonymous struct or union. It's okay.
5085       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5086         if (!MemRecord->isAnonymousStructOrUnion() &&
5087             MemRecord->getDeclName()) {
5088           // Visual C++ allows type definition in anonymous struct or union.
5089           if (getLangOpts().MicrosoftExt)
5090             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5091               << Record->isUnion();
5092           else {
5093             // This is a nested type declaration.
5094             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5095               << Record->isUnion();
5096             Invalid = true;
5097           }
5098         } else {
5099           // This is an anonymous type definition within another anonymous type.
5100           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5101           // not part of standard C++.
5102           Diag(MemRecord->getLocation(),
5103                diag::ext_anonymous_record_with_anonymous_type)
5104             << Record->isUnion();
5105         }
5106       } else if (isa<AccessSpecDecl>(Mem)) {
5107         // Any access specifier is fine.
5108       } else if (isa<StaticAssertDecl>(Mem)) {
5109         // In C++1z, static_assert declarations are also fine.
5110       } else {
5111         // We have something that isn't a non-static data
5112         // member. Complain about it.
5113         unsigned DK = diag::err_anonymous_record_bad_member;
5114         if (isa<TypeDecl>(Mem))
5115           DK = diag::err_anonymous_record_with_type;
5116         else if (isa<FunctionDecl>(Mem))
5117           DK = diag::err_anonymous_record_with_function;
5118         else if (isa<VarDecl>(Mem))
5119           DK = diag::err_anonymous_record_with_static;
5120 
5121         // Visual C++ allows type definition in anonymous struct or union.
5122         if (getLangOpts().MicrosoftExt &&
5123             DK == diag::err_anonymous_record_with_type)
5124           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5125             << Record->isUnion();
5126         else {
5127           Diag(Mem->getLocation(), DK) << Record->isUnion();
5128           Invalid = true;
5129         }
5130       }
5131     }
5132 
5133     // C++11 [class.union]p8 (DR1460):
5134     //   At most one variant member of a union may have a
5135     //   brace-or-equal-initializer.
5136     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5137         Owner->isRecord())
5138       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5139                                 cast<CXXRecordDecl>(Record));
5140   }
5141 
5142   if (!Record->isUnion() && !Owner->isRecord()) {
5143     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5144       << getLangOpts().CPlusPlus;
5145     Invalid = true;
5146   }
5147 
5148   // C++ [dcl.dcl]p3:
5149   //   [If there are no declarators], and except for the declaration of an
5150   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5151   //   names into the program
5152   // C++ [class.mem]p2:
5153   //   each such member-declaration shall either declare at least one member
5154   //   name of the class or declare at least one unnamed bit-field
5155   //
5156   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5157   if (getLangOpts().CPlusPlus && Record->field_empty())
5158     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5159 
5160   // Mock up a declarator.
5161   Declarator Dc(DS, DeclaratorContext::MemberContext);
5162   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5163   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5164 
5165   // Create a declaration for this anonymous struct/union.
5166   NamedDecl *Anon = nullptr;
5167   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5168     Anon = FieldDecl::Create(
5169         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5170         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5171         /*BitWidth=*/nullptr, /*Mutable=*/false,
5172         /*InitStyle=*/ICIS_NoInit);
5173     Anon->setAccess(AS);
5174     ProcessDeclAttributes(S, Anon, Dc);
5175 
5176     if (getLangOpts().CPlusPlus)
5177       FieldCollector->Add(cast<FieldDecl>(Anon));
5178   } else {
5179     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5180     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5181     if (SCSpec == DeclSpec::SCS_mutable) {
5182       // mutable can only appear on non-static class members, so it's always
5183       // an error here
5184       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5185       Invalid = true;
5186       SC = SC_None;
5187     }
5188 
5189     assert(DS.getAttributes().empty() && "No attribute expected");
5190     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5191                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5192                            Context.getTypeDeclType(Record), TInfo, SC);
5193 
5194     // Default-initialize the implicit variable. This initialization will be
5195     // trivial in almost all cases, except if a union member has an in-class
5196     // initializer:
5197     //   union { int n = 0; };
5198     ActOnUninitializedDecl(Anon);
5199   }
5200   Anon->setImplicit();
5201 
5202   // Mark this as an anonymous struct/union type.
5203   Record->setAnonymousStructOrUnion(true);
5204 
5205   // Add the anonymous struct/union object to the current
5206   // context. We'll be referencing this object when we refer to one of
5207   // its members.
5208   Owner->addDecl(Anon);
5209 
5210   // Inject the members of the anonymous struct/union into the owning
5211   // context and into the identifier resolver chain for name lookup
5212   // purposes.
5213   SmallVector<NamedDecl*, 2> Chain;
5214   Chain.push_back(Anon);
5215 
5216   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5217     Invalid = true;
5218 
5219   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5220     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5221       MangleNumberingContext *MCtx;
5222       Decl *ManglingContextDecl;
5223       std::tie(MCtx, ManglingContextDecl) =
5224           getCurrentMangleNumberContext(NewVD->getDeclContext());
5225       if (MCtx) {
5226         Context.setManglingNumber(
5227             NewVD, MCtx->getManglingNumber(
5228                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5229         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5230       }
5231     }
5232   }
5233 
5234   if (Invalid)
5235     Anon->setInvalidDecl();
5236 
5237   return Anon;
5238 }
5239 
5240 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5241 /// Microsoft C anonymous structure.
5242 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5243 /// Example:
5244 ///
5245 /// struct A { int a; };
5246 /// struct B { struct A; int b; };
5247 ///
5248 /// void foo() {
5249 ///   B var;
5250 ///   var.a = 3;
5251 /// }
5252 ///
5253 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5254                                            RecordDecl *Record) {
5255   assert(Record && "expected a record!");
5256 
5257   // Mock up a declarator.
5258   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5259   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5260   assert(TInfo && "couldn't build declarator info for anonymous struct");
5261 
5262   auto *ParentDecl = cast<RecordDecl>(CurContext);
5263   QualType RecTy = Context.getTypeDeclType(Record);
5264 
5265   // Create a declaration for this anonymous struct.
5266   NamedDecl *Anon =
5267       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5268                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5269                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5270                         /*InitStyle=*/ICIS_NoInit);
5271   Anon->setImplicit();
5272 
5273   // Add the anonymous struct object to the current context.
5274   CurContext->addDecl(Anon);
5275 
5276   // Inject the members of the anonymous struct into the current
5277   // context and into the identifier resolver chain for name lookup
5278   // purposes.
5279   SmallVector<NamedDecl*, 2> Chain;
5280   Chain.push_back(Anon);
5281 
5282   RecordDecl *RecordDef = Record->getDefinition();
5283   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5284                                diag::err_field_incomplete_or_sizeless) ||
5285       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5286                                           AS_none, Chain)) {
5287     Anon->setInvalidDecl();
5288     ParentDecl->setInvalidDecl();
5289   }
5290 
5291   return Anon;
5292 }
5293 
5294 /// GetNameForDeclarator - Determine the full declaration name for the
5295 /// given Declarator.
5296 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5297   return GetNameFromUnqualifiedId(D.getName());
5298 }
5299 
5300 /// Retrieves the declaration name from a parsed unqualified-id.
5301 DeclarationNameInfo
5302 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5303   DeclarationNameInfo NameInfo;
5304   NameInfo.setLoc(Name.StartLocation);
5305 
5306   switch (Name.getKind()) {
5307 
5308   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5309   case UnqualifiedIdKind::IK_Identifier:
5310     NameInfo.setName(Name.Identifier);
5311     return NameInfo;
5312 
5313   case UnqualifiedIdKind::IK_DeductionGuideName: {
5314     // C++ [temp.deduct.guide]p3:
5315     //   The simple-template-id shall name a class template specialization.
5316     //   The template-name shall be the same identifier as the template-name
5317     //   of the simple-template-id.
5318     // These together intend to imply that the template-name shall name a
5319     // class template.
5320     // FIXME: template<typename T> struct X {};
5321     //        template<typename T> using Y = X<T>;
5322     //        Y(int) -> Y<int>;
5323     //   satisfies these rules but does not name a class template.
5324     TemplateName TN = Name.TemplateName.get().get();
5325     auto *Template = TN.getAsTemplateDecl();
5326     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5327       Diag(Name.StartLocation,
5328            diag::err_deduction_guide_name_not_class_template)
5329         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5330       if (Template)
5331         Diag(Template->getLocation(), diag::note_template_decl_here);
5332       return DeclarationNameInfo();
5333     }
5334 
5335     NameInfo.setName(
5336         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5337     return NameInfo;
5338   }
5339 
5340   case UnqualifiedIdKind::IK_OperatorFunctionId:
5341     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5342                                            Name.OperatorFunctionId.Operator));
5343     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5344       = Name.OperatorFunctionId.SymbolLocations[0];
5345     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5346       = Name.EndLocation.getRawEncoding();
5347     return NameInfo;
5348 
5349   case UnqualifiedIdKind::IK_LiteralOperatorId:
5350     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5351                                                            Name.Identifier));
5352     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5353     return NameInfo;
5354 
5355   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5356     TypeSourceInfo *TInfo;
5357     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5358     if (Ty.isNull())
5359       return DeclarationNameInfo();
5360     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5361                                                Context.getCanonicalType(Ty)));
5362     NameInfo.setNamedTypeInfo(TInfo);
5363     return NameInfo;
5364   }
5365 
5366   case UnqualifiedIdKind::IK_ConstructorName: {
5367     TypeSourceInfo *TInfo;
5368     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5369     if (Ty.isNull())
5370       return DeclarationNameInfo();
5371     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5372                                               Context.getCanonicalType(Ty)));
5373     NameInfo.setNamedTypeInfo(TInfo);
5374     return NameInfo;
5375   }
5376 
5377   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5378     // In well-formed code, we can only have a constructor
5379     // template-id that refers to the current context, so go there
5380     // to find the actual type being constructed.
5381     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5382     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5383       return DeclarationNameInfo();
5384 
5385     // Determine the type of the class being constructed.
5386     QualType CurClassType = Context.getTypeDeclType(CurClass);
5387 
5388     // FIXME: Check two things: that the template-id names the same type as
5389     // CurClassType, and that the template-id does not occur when the name
5390     // was qualified.
5391 
5392     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5393                                     Context.getCanonicalType(CurClassType)));
5394     // FIXME: should we retrieve TypeSourceInfo?
5395     NameInfo.setNamedTypeInfo(nullptr);
5396     return NameInfo;
5397   }
5398 
5399   case UnqualifiedIdKind::IK_DestructorName: {
5400     TypeSourceInfo *TInfo;
5401     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5402     if (Ty.isNull())
5403       return DeclarationNameInfo();
5404     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5405                                               Context.getCanonicalType(Ty)));
5406     NameInfo.setNamedTypeInfo(TInfo);
5407     return NameInfo;
5408   }
5409 
5410   case UnqualifiedIdKind::IK_TemplateId: {
5411     TemplateName TName = Name.TemplateId->Template.get();
5412     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5413     return Context.getNameForTemplate(TName, TNameLoc);
5414   }
5415 
5416   } // switch (Name.getKind())
5417 
5418   llvm_unreachable("Unknown name kind");
5419 }
5420 
5421 static QualType getCoreType(QualType Ty) {
5422   do {
5423     if (Ty->isPointerType() || Ty->isReferenceType())
5424       Ty = Ty->getPointeeType();
5425     else if (Ty->isArrayType())
5426       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5427     else
5428       return Ty.withoutLocalFastQualifiers();
5429   } while (true);
5430 }
5431 
5432 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5433 /// and Definition have "nearly" matching parameters. This heuristic is
5434 /// used to improve diagnostics in the case where an out-of-line function
5435 /// definition doesn't match any declaration within the class or namespace.
5436 /// Also sets Params to the list of indices to the parameters that differ
5437 /// between the declaration and the definition. If hasSimilarParameters
5438 /// returns true and Params is empty, then all of the parameters match.
5439 static bool hasSimilarParameters(ASTContext &Context,
5440                                      FunctionDecl *Declaration,
5441                                      FunctionDecl *Definition,
5442                                      SmallVectorImpl<unsigned> &Params) {
5443   Params.clear();
5444   if (Declaration->param_size() != Definition->param_size())
5445     return false;
5446   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5447     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5448     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5449 
5450     // The parameter types are identical
5451     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5452       continue;
5453 
5454     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5455     QualType DefParamBaseTy = getCoreType(DefParamTy);
5456     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5457     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5458 
5459     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5460         (DeclTyName && DeclTyName == DefTyName))
5461       Params.push_back(Idx);
5462     else  // The two parameters aren't even close
5463       return false;
5464   }
5465 
5466   return true;
5467 }
5468 
5469 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5470 /// declarator needs to be rebuilt in the current instantiation.
5471 /// Any bits of declarator which appear before the name are valid for
5472 /// consideration here.  That's specifically the type in the decl spec
5473 /// and the base type in any member-pointer chunks.
5474 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5475                                                     DeclarationName Name) {
5476   // The types we specifically need to rebuild are:
5477   //   - typenames, typeofs, and decltypes
5478   //   - types which will become injected class names
5479   // Of course, we also need to rebuild any type referencing such a
5480   // type.  It's safest to just say "dependent", but we call out a
5481   // few cases here.
5482 
5483   DeclSpec &DS = D.getMutableDeclSpec();
5484   switch (DS.getTypeSpecType()) {
5485   case DeclSpec::TST_typename:
5486   case DeclSpec::TST_typeofType:
5487   case DeclSpec::TST_underlyingType:
5488   case DeclSpec::TST_atomic: {
5489     // Grab the type from the parser.
5490     TypeSourceInfo *TSI = nullptr;
5491     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5492     if (T.isNull() || !T->isDependentType()) break;
5493 
5494     // Make sure there's a type source info.  This isn't really much
5495     // of a waste; most dependent types should have type source info
5496     // attached already.
5497     if (!TSI)
5498       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5499 
5500     // Rebuild the type in the current instantiation.
5501     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5502     if (!TSI) return true;
5503 
5504     // Store the new type back in the decl spec.
5505     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5506     DS.UpdateTypeRep(LocType);
5507     break;
5508   }
5509 
5510   case DeclSpec::TST_decltype:
5511   case DeclSpec::TST_typeofExpr: {
5512     Expr *E = DS.getRepAsExpr();
5513     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5514     if (Result.isInvalid()) return true;
5515     DS.UpdateExprRep(Result.get());
5516     break;
5517   }
5518 
5519   default:
5520     // Nothing to do for these decl specs.
5521     break;
5522   }
5523 
5524   // It doesn't matter what order we do this in.
5525   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5526     DeclaratorChunk &Chunk = D.getTypeObject(I);
5527 
5528     // The only type information in the declarator which can come
5529     // before the declaration name is the base type of a member
5530     // pointer.
5531     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5532       continue;
5533 
5534     // Rebuild the scope specifier in-place.
5535     CXXScopeSpec &SS = Chunk.Mem.Scope();
5536     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5537       return true;
5538   }
5539 
5540   return false;
5541 }
5542 
5543 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5544   D.setFunctionDefinitionKind(FDK_Declaration);
5545   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5546 
5547   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5548       Dcl && Dcl->getDeclContext()->isFileContext())
5549     Dcl->setTopLevelDeclInObjCContainer();
5550 
5551   if (getLangOpts().OpenCL)
5552     setCurrentOpenCLExtensionForDecl(Dcl);
5553 
5554   return Dcl;
5555 }
5556 
5557 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5558 ///   If T is the name of a class, then each of the following shall have a
5559 ///   name different from T:
5560 ///     - every static data member of class T;
5561 ///     - every member function of class T
5562 ///     - every member of class T that is itself a type;
5563 /// \returns true if the declaration name violates these rules.
5564 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5565                                    DeclarationNameInfo NameInfo) {
5566   DeclarationName Name = NameInfo.getName();
5567 
5568   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5569   while (Record && Record->isAnonymousStructOrUnion())
5570     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5571   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5572     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5573     return true;
5574   }
5575 
5576   return false;
5577 }
5578 
5579 /// Diagnose a declaration whose declarator-id has the given
5580 /// nested-name-specifier.
5581 ///
5582 /// \param SS The nested-name-specifier of the declarator-id.
5583 ///
5584 /// \param DC The declaration context to which the nested-name-specifier
5585 /// resolves.
5586 ///
5587 /// \param Name The name of the entity being declared.
5588 ///
5589 /// \param Loc The location of the name of the entity being declared.
5590 ///
5591 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5592 /// we're declaring an explicit / partial specialization / instantiation.
5593 ///
5594 /// \returns true if we cannot safely recover from this error, false otherwise.
5595 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5596                                         DeclarationName Name,
5597                                         SourceLocation Loc, bool IsTemplateId) {
5598   DeclContext *Cur = CurContext;
5599   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5600     Cur = Cur->getParent();
5601 
5602   // If the user provided a superfluous scope specifier that refers back to the
5603   // class in which the entity is already declared, diagnose and ignore it.
5604   //
5605   // class X {
5606   //   void X::f();
5607   // };
5608   //
5609   // Note, it was once ill-formed to give redundant qualification in all
5610   // contexts, but that rule was removed by DR482.
5611   if (Cur->Equals(DC)) {
5612     if (Cur->isRecord()) {
5613       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5614                                       : diag::err_member_extra_qualification)
5615         << Name << FixItHint::CreateRemoval(SS.getRange());
5616       SS.clear();
5617     } else {
5618       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5619     }
5620     return false;
5621   }
5622 
5623   // Check whether the qualifying scope encloses the scope of the original
5624   // declaration. For a template-id, we perform the checks in
5625   // CheckTemplateSpecializationScope.
5626   if (!Cur->Encloses(DC) && !IsTemplateId) {
5627     if (Cur->isRecord())
5628       Diag(Loc, diag::err_member_qualification)
5629         << Name << SS.getRange();
5630     else if (isa<TranslationUnitDecl>(DC))
5631       Diag(Loc, diag::err_invalid_declarator_global_scope)
5632         << Name << SS.getRange();
5633     else if (isa<FunctionDecl>(Cur))
5634       Diag(Loc, diag::err_invalid_declarator_in_function)
5635         << Name << SS.getRange();
5636     else if (isa<BlockDecl>(Cur))
5637       Diag(Loc, diag::err_invalid_declarator_in_block)
5638         << Name << SS.getRange();
5639     else
5640       Diag(Loc, diag::err_invalid_declarator_scope)
5641       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5642 
5643     return true;
5644   }
5645 
5646   if (Cur->isRecord()) {
5647     // Cannot qualify members within a class.
5648     Diag(Loc, diag::err_member_qualification)
5649       << Name << SS.getRange();
5650     SS.clear();
5651 
5652     // C++ constructors and destructors with incorrect scopes can break
5653     // our AST invariants by having the wrong underlying types. If
5654     // that's the case, then drop this declaration entirely.
5655     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5656          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5657         !Context.hasSameType(Name.getCXXNameType(),
5658                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5659       return true;
5660 
5661     return false;
5662   }
5663 
5664   // C++11 [dcl.meaning]p1:
5665   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5666   //   not begin with a decltype-specifer"
5667   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5668   while (SpecLoc.getPrefix())
5669     SpecLoc = SpecLoc.getPrefix();
5670   if (dyn_cast_or_null<DecltypeType>(
5671         SpecLoc.getNestedNameSpecifier()->getAsType()))
5672     Diag(Loc, diag::err_decltype_in_declarator)
5673       << SpecLoc.getTypeLoc().getSourceRange();
5674 
5675   return false;
5676 }
5677 
5678 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5679                                   MultiTemplateParamsArg TemplateParamLists) {
5680   // TODO: consider using NameInfo for diagnostic.
5681   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5682   DeclarationName Name = NameInfo.getName();
5683 
5684   // All of these full declarators require an identifier.  If it doesn't have
5685   // one, the ParsedFreeStandingDeclSpec action should be used.
5686   if (D.isDecompositionDeclarator()) {
5687     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5688   } else if (!Name) {
5689     if (!D.isInvalidType())  // Reject this if we think it is valid.
5690       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5691           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5692     return nullptr;
5693   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5694     return nullptr;
5695 
5696   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5697   // we find one that is.
5698   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5699          (S->getFlags() & Scope::TemplateParamScope) != 0)
5700     S = S->getParent();
5701 
5702   DeclContext *DC = CurContext;
5703   if (D.getCXXScopeSpec().isInvalid())
5704     D.setInvalidType();
5705   else if (D.getCXXScopeSpec().isSet()) {
5706     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5707                                         UPPC_DeclarationQualifier))
5708       return nullptr;
5709 
5710     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5711     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5712     if (!DC || isa<EnumDecl>(DC)) {
5713       // If we could not compute the declaration context, it's because the
5714       // declaration context is dependent but does not refer to a class,
5715       // class template, or class template partial specialization. Complain
5716       // and return early, to avoid the coming semantic disaster.
5717       Diag(D.getIdentifierLoc(),
5718            diag::err_template_qualified_declarator_no_match)
5719         << D.getCXXScopeSpec().getScopeRep()
5720         << D.getCXXScopeSpec().getRange();
5721       return nullptr;
5722     }
5723     bool IsDependentContext = DC->isDependentContext();
5724 
5725     if (!IsDependentContext &&
5726         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5727       return nullptr;
5728 
5729     // If a class is incomplete, do not parse entities inside it.
5730     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5731       Diag(D.getIdentifierLoc(),
5732            diag::err_member_def_undefined_record)
5733         << Name << DC << D.getCXXScopeSpec().getRange();
5734       return nullptr;
5735     }
5736     if (!D.getDeclSpec().isFriendSpecified()) {
5737       if (diagnoseQualifiedDeclaration(
5738               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5739               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5740         if (DC->isRecord())
5741           return nullptr;
5742 
5743         D.setInvalidType();
5744       }
5745     }
5746 
5747     // Check whether we need to rebuild the type of the given
5748     // declaration in the current instantiation.
5749     if (EnteringContext && IsDependentContext &&
5750         TemplateParamLists.size() != 0) {
5751       ContextRAII SavedContext(*this, DC);
5752       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5753         D.setInvalidType();
5754     }
5755   }
5756 
5757   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5758   QualType R = TInfo->getType();
5759 
5760   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5761                                       UPPC_DeclarationType))
5762     D.setInvalidType();
5763 
5764   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5765                         forRedeclarationInCurContext());
5766 
5767   // See if this is a redefinition of a variable in the same scope.
5768   if (!D.getCXXScopeSpec().isSet()) {
5769     bool IsLinkageLookup = false;
5770     bool CreateBuiltins = false;
5771 
5772     // If the declaration we're planning to build will be a function
5773     // or object with linkage, then look for another declaration with
5774     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5775     //
5776     // If the declaration we're planning to build will be declared with
5777     // external linkage in the translation unit, create any builtin with
5778     // the same name.
5779     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5780       /* Do nothing*/;
5781     else if (CurContext->isFunctionOrMethod() &&
5782              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5783               R->isFunctionType())) {
5784       IsLinkageLookup = true;
5785       CreateBuiltins =
5786           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5787     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5788                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5789       CreateBuiltins = true;
5790 
5791     if (IsLinkageLookup) {
5792       Previous.clear(LookupRedeclarationWithLinkage);
5793       Previous.setRedeclarationKind(ForExternalRedeclaration);
5794     }
5795 
5796     LookupName(Previous, S, CreateBuiltins);
5797   } else { // Something like "int foo::x;"
5798     LookupQualifiedName(Previous, DC);
5799 
5800     // C++ [dcl.meaning]p1:
5801     //   When the declarator-id is qualified, the declaration shall refer to a
5802     //  previously declared member of the class or namespace to which the
5803     //  qualifier refers (or, in the case of a namespace, of an element of the
5804     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5805     //  thereof; [...]
5806     //
5807     // Note that we already checked the context above, and that we do not have
5808     // enough information to make sure that Previous contains the declaration
5809     // we want to match. For example, given:
5810     //
5811     //   class X {
5812     //     void f();
5813     //     void f(float);
5814     //   };
5815     //
5816     //   void X::f(int) { } // ill-formed
5817     //
5818     // In this case, Previous will point to the overload set
5819     // containing the two f's declared in X, but neither of them
5820     // matches.
5821 
5822     // C++ [dcl.meaning]p1:
5823     //   [...] the member shall not merely have been introduced by a
5824     //   using-declaration in the scope of the class or namespace nominated by
5825     //   the nested-name-specifier of the declarator-id.
5826     RemoveUsingDecls(Previous);
5827   }
5828 
5829   if (Previous.isSingleResult() &&
5830       Previous.getFoundDecl()->isTemplateParameter()) {
5831     // Maybe we will complain about the shadowed template parameter.
5832     if (!D.isInvalidType())
5833       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5834                                       Previous.getFoundDecl());
5835 
5836     // Just pretend that we didn't see the previous declaration.
5837     Previous.clear();
5838   }
5839 
5840   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5841     // Forget that the previous declaration is the injected-class-name.
5842     Previous.clear();
5843 
5844   // In C++, the previous declaration we find might be a tag type
5845   // (class or enum). In this case, the new declaration will hide the
5846   // tag type. Note that this applies to functions, function templates, and
5847   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5848   if (Previous.isSingleTagDecl() &&
5849       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5850       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5851     Previous.clear();
5852 
5853   // Check that there are no default arguments other than in the parameters
5854   // of a function declaration (C++ only).
5855   if (getLangOpts().CPlusPlus)
5856     CheckExtraCXXDefaultArguments(D);
5857 
5858   NamedDecl *New;
5859 
5860   bool AddToScope = true;
5861   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5862     if (TemplateParamLists.size()) {
5863       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5864       return nullptr;
5865     }
5866 
5867     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5868   } else if (R->isFunctionType()) {
5869     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5870                                   TemplateParamLists,
5871                                   AddToScope);
5872   } else {
5873     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5874                                   AddToScope);
5875   }
5876 
5877   if (!New)
5878     return nullptr;
5879 
5880   // If this has an identifier and is not a function template specialization,
5881   // add it to the scope stack.
5882   if (New->getDeclName() && AddToScope)
5883     PushOnScopeChains(New, S);
5884 
5885   if (isInOpenMPDeclareTargetContext())
5886     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5887 
5888   return New;
5889 }
5890 
5891 /// Helper method to turn variable array types into constant array
5892 /// types in certain situations which would otherwise be errors (for
5893 /// GCC compatibility).
5894 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5895                                                     ASTContext &Context,
5896                                                     bool &SizeIsNegative,
5897                                                     llvm::APSInt &Oversized) {
5898   // This method tries to turn a variable array into a constant
5899   // array even when the size isn't an ICE.  This is necessary
5900   // for compatibility with code that depends on gcc's buggy
5901   // constant expression folding, like struct {char x[(int)(char*)2];}
5902   SizeIsNegative = false;
5903   Oversized = 0;
5904 
5905   if (T->isDependentType())
5906     return QualType();
5907 
5908   QualifierCollector Qs;
5909   const Type *Ty = Qs.strip(T);
5910 
5911   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5912     QualType Pointee = PTy->getPointeeType();
5913     QualType FixedType =
5914         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5915                                             Oversized);
5916     if (FixedType.isNull()) return FixedType;
5917     FixedType = Context.getPointerType(FixedType);
5918     return Qs.apply(Context, FixedType);
5919   }
5920   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5921     QualType Inner = PTy->getInnerType();
5922     QualType FixedType =
5923         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5924                                             Oversized);
5925     if (FixedType.isNull()) return FixedType;
5926     FixedType = Context.getParenType(FixedType);
5927     return Qs.apply(Context, FixedType);
5928   }
5929 
5930   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5931   if (!VLATy)
5932     return QualType();
5933   // FIXME: We should probably handle this case
5934   if (VLATy->getElementType()->isVariablyModifiedType())
5935     return QualType();
5936 
5937   Expr::EvalResult Result;
5938   if (!VLATy->getSizeExpr() ||
5939       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5940     return QualType();
5941 
5942   llvm::APSInt Res = Result.Val.getInt();
5943 
5944   // Check whether the array size is negative.
5945   if (Res.isSigned() && Res.isNegative()) {
5946     SizeIsNegative = true;
5947     return QualType();
5948   }
5949 
5950   // Check whether the array is too large to be addressed.
5951   unsigned ActiveSizeBits
5952     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5953                                               Res);
5954   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5955     Oversized = Res;
5956     return QualType();
5957   }
5958 
5959   return Context.getConstantArrayType(
5960       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5961 }
5962 
5963 static void
5964 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5965   SrcTL = SrcTL.getUnqualifiedLoc();
5966   DstTL = DstTL.getUnqualifiedLoc();
5967   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5968     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5969     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5970                                       DstPTL.getPointeeLoc());
5971     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5972     return;
5973   }
5974   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5975     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5976     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5977                                       DstPTL.getInnerLoc());
5978     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5979     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5980     return;
5981   }
5982   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5983   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5984   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5985   TypeLoc DstElemTL = DstATL.getElementLoc();
5986   DstElemTL.initializeFullCopy(SrcElemTL);
5987   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5988   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5989   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5990 }
5991 
5992 /// Helper method to turn variable array types into constant array
5993 /// types in certain situations which would otherwise be errors (for
5994 /// GCC compatibility).
5995 static TypeSourceInfo*
5996 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5997                                               ASTContext &Context,
5998                                               bool &SizeIsNegative,
5999                                               llvm::APSInt &Oversized) {
6000   QualType FixedTy
6001     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6002                                           SizeIsNegative, Oversized);
6003   if (FixedTy.isNull())
6004     return nullptr;
6005   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6006   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6007                                     FixedTInfo->getTypeLoc());
6008   return FixedTInfo;
6009 }
6010 
6011 /// Register the given locally-scoped extern "C" declaration so
6012 /// that it can be found later for redeclarations. We include any extern "C"
6013 /// declaration that is not visible in the translation unit here, not just
6014 /// function-scope declarations.
6015 void
6016 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6017   if (!getLangOpts().CPlusPlus &&
6018       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6019     // Don't need to track declarations in the TU in C.
6020     return;
6021 
6022   // Note that we have a locally-scoped external with this name.
6023   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6024 }
6025 
6026 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6027   // FIXME: We can have multiple results via __attribute__((overloadable)).
6028   auto Result = Context.getExternCContextDecl()->lookup(Name);
6029   return Result.empty() ? nullptr : *Result.begin();
6030 }
6031 
6032 /// Diagnose function specifiers on a declaration of an identifier that
6033 /// does not identify a function.
6034 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6035   // FIXME: We should probably indicate the identifier in question to avoid
6036   // confusion for constructs like "virtual int a(), b;"
6037   if (DS.isVirtualSpecified())
6038     Diag(DS.getVirtualSpecLoc(),
6039          diag::err_virtual_non_function);
6040 
6041   if (DS.hasExplicitSpecifier())
6042     Diag(DS.getExplicitSpecLoc(),
6043          diag::err_explicit_non_function);
6044 
6045   if (DS.isNoreturnSpecified())
6046     Diag(DS.getNoreturnSpecLoc(),
6047          diag::err_noreturn_non_function);
6048 }
6049 
6050 NamedDecl*
6051 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6052                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6053   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6054   if (D.getCXXScopeSpec().isSet()) {
6055     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6056       << D.getCXXScopeSpec().getRange();
6057     D.setInvalidType();
6058     // Pretend we didn't see the scope specifier.
6059     DC = CurContext;
6060     Previous.clear();
6061   }
6062 
6063   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6064 
6065   if (D.getDeclSpec().isInlineSpecified())
6066     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6067         << getLangOpts().CPlusPlus17;
6068   if (D.getDeclSpec().hasConstexprSpecifier())
6069     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6070         << 1 << D.getDeclSpec().getConstexprSpecifier();
6071 
6072   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6073     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6074       Diag(D.getName().StartLocation,
6075            diag::err_deduction_guide_invalid_specifier)
6076           << "typedef";
6077     else
6078       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6079           << D.getName().getSourceRange();
6080     return nullptr;
6081   }
6082 
6083   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6084   if (!NewTD) return nullptr;
6085 
6086   // Handle attributes prior to checking for duplicates in MergeVarDecl
6087   ProcessDeclAttributes(S, NewTD, D);
6088 
6089   CheckTypedefForVariablyModifiedType(S, NewTD);
6090 
6091   bool Redeclaration = D.isRedeclaration();
6092   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6093   D.setRedeclaration(Redeclaration);
6094   return ND;
6095 }
6096 
6097 void
6098 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6099   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6100   // then it shall have block scope.
6101   // Note that variably modified types must be fixed before merging the decl so
6102   // that redeclarations will match.
6103   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6104   QualType T = TInfo->getType();
6105   if (T->isVariablyModifiedType()) {
6106     setFunctionHasBranchProtectedScope();
6107 
6108     if (S->getFnParent() == nullptr) {
6109       bool SizeIsNegative;
6110       llvm::APSInt Oversized;
6111       TypeSourceInfo *FixedTInfo =
6112         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6113                                                       SizeIsNegative,
6114                                                       Oversized);
6115       if (FixedTInfo) {
6116         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6117         NewTD->setTypeSourceInfo(FixedTInfo);
6118       } else {
6119         if (SizeIsNegative)
6120           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6121         else if (T->isVariableArrayType())
6122           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6123         else if (Oversized.getBoolValue())
6124           Diag(NewTD->getLocation(), diag::err_array_too_large)
6125             << Oversized.toString(10);
6126         else
6127           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6128         NewTD->setInvalidDecl();
6129       }
6130     }
6131   }
6132 }
6133 
6134 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6135 /// declares a typedef-name, either using the 'typedef' type specifier or via
6136 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6137 NamedDecl*
6138 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6139                            LookupResult &Previous, bool &Redeclaration) {
6140 
6141   // Find the shadowed declaration before filtering for scope.
6142   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6143 
6144   // Merge the decl with the existing one if appropriate. If the decl is
6145   // in an outer scope, it isn't the same thing.
6146   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6147                        /*AllowInlineNamespace*/false);
6148   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6149   if (!Previous.empty()) {
6150     Redeclaration = true;
6151     MergeTypedefNameDecl(S, NewTD, Previous);
6152   } else {
6153     inferGslPointerAttribute(NewTD);
6154   }
6155 
6156   if (ShadowedDecl && !Redeclaration)
6157     CheckShadow(NewTD, ShadowedDecl, Previous);
6158 
6159   // If this is the C FILE type, notify the AST context.
6160   if (IdentifierInfo *II = NewTD->getIdentifier())
6161     if (!NewTD->isInvalidDecl() &&
6162         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6163       if (II->isStr("FILE"))
6164         Context.setFILEDecl(NewTD);
6165       else if (II->isStr("jmp_buf"))
6166         Context.setjmp_bufDecl(NewTD);
6167       else if (II->isStr("sigjmp_buf"))
6168         Context.setsigjmp_bufDecl(NewTD);
6169       else if (II->isStr("ucontext_t"))
6170         Context.setucontext_tDecl(NewTD);
6171     }
6172 
6173   return NewTD;
6174 }
6175 
6176 /// Determines whether the given declaration is an out-of-scope
6177 /// previous declaration.
6178 ///
6179 /// This routine should be invoked when name lookup has found a
6180 /// previous declaration (PrevDecl) that is not in the scope where a
6181 /// new declaration by the same name is being introduced. If the new
6182 /// declaration occurs in a local scope, previous declarations with
6183 /// linkage may still be considered previous declarations (C99
6184 /// 6.2.2p4-5, C++ [basic.link]p6).
6185 ///
6186 /// \param PrevDecl the previous declaration found by name
6187 /// lookup
6188 ///
6189 /// \param DC the context in which the new declaration is being
6190 /// declared.
6191 ///
6192 /// \returns true if PrevDecl is an out-of-scope previous declaration
6193 /// for a new delcaration with the same name.
6194 static bool
6195 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6196                                 ASTContext &Context) {
6197   if (!PrevDecl)
6198     return false;
6199 
6200   if (!PrevDecl->hasLinkage())
6201     return false;
6202 
6203   if (Context.getLangOpts().CPlusPlus) {
6204     // C++ [basic.link]p6:
6205     //   If there is a visible declaration of an entity with linkage
6206     //   having the same name and type, ignoring entities declared
6207     //   outside the innermost enclosing namespace scope, the block
6208     //   scope declaration declares that same entity and receives the
6209     //   linkage of the previous declaration.
6210     DeclContext *OuterContext = DC->getRedeclContext();
6211     if (!OuterContext->isFunctionOrMethod())
6212       // This rule only applies to block-scope declarations.
6213       return false;
6214 
6215     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6216     if (PrevOuterContext->isRecord())
6217       // We found a member function: ignore it.
6218       return false;
6219 
6220     // Find the innermost enclosing namespace for the new and
6221     // previous declarations.
6222     OuterContext = OuterContext->getEnclosingNamespaceContext();
6223     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6224 
6225     // The previous declaration is in a different namespace, so it
6226     // isn't the same function.
6227     if (!OuterContext->Equals(PrevOuterContext))
6228       return false;
6229   }
6230 
6231   return true;
6232 }
6233 
6234 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6235   CXXScopeSpec &SS = D.getCXXScopeSpec();
6236   if (!SS.isSet()) return;
6237   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6238 }
6239 
6240 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6241   QualType type = decl->getType();
6242   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6243   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6244     // Various kinds of declaration aren't allowed to be __autoreleasing.
6245     unsigned kind = -1U;
6246     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6247       if (var->hasAttr<BlocksAttr>())
6248         kind = 0; // __block
6249       else if (!var->hasLocalStorage())
6250         kind = 1; // global
6251     } else if (isa<ObjCIvarDecl>(decl)) {
6252       kind = 3; // ivar
6253     } else if (isa<FieldDecl>(decl)) {
6254       kind = 2; // field
6255     }
6256 
6257     if (kind != -1U) {
6258       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6259         << kind;
6260     }
6261   } else if (lifetime == Qualifiers::OCL_None) {
6262     // Try to infer lifetime.
6263     if (!type->isObjCLifetimeType())
6264       return false;
6265 
6266     lifetime = type->getObjCARCImplicitLifetime();
6267     type = Context.getLifetimeQualifiedType(type, lifetime);
6268     decl->setType(type);
6269   }
6270 
6271   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6272     // Thread-local variables cannot have lifetime.
6273     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6274         var->getTLSKind()) {
6275       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6276         << var->getType();
6277       return true;
6278     }
6279   }
6280 
6281   return false;
6282 }
6283 
6284 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6285   if (Decl->getType().hasAddressSpace())
6286     return;
6287   if (Decl->getType()->isDependentType())
6288     return;
6289   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6290     QualType Type = Var->getType();
6291     if (Type->isSamplerT() || Type->isVoidType())
6292       return;
6293     LangAS ImplAS = LangAS::opencl_private;
6294     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6295         Var->hasGlobalStorage())
6296       ImplAS = LangAS::opencl_global;
6297     // If the original type from a decayed type is an array type and that array
6298     // type has no address space yet, deduce it now.
6299     if (auto DT = dyn_cast<DecayedType>(Type)) {
6300       auto OrigTy = DT->getOriginalType();
6301       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6302         // Add the address space to the original array type and then propagate
6303         // that to the element type through `getAsArrayType`.
6304         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6305         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6306         // Re-generate the decayed type.
6307         Type = Context.getDecayedType(OrigTy);
6308       }
6309     }
6310     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6311     // Apply any qualifiers (including address space) from the array type to
6312     // the element type. This implements C99 6.7.3p8: "If the specification of
6313     // an array type includes any type qualifiers, the element type is so
6314     // qualified, not the array type."
6315     if (Type->isArrayType())
6316       Type = QualType(Context.getAsArrayType(Type), 0);
6317     Decl->setType(Type);
6318   }
6319 }
6320 
6321 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6322   // Ensure that an auto decl is deduced otherwise the checks below might cache
6323   // the wrong linkage.
6324   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6325 
6326   // 'weak' only applies to declarations with external linkage.
6327   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6328     if (!ND.isExternallyVisible()) {
6329       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6330       ND.dropAttr<WeakAttr>();
6331     }
6332   }
6333   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6334     if (ND.isExternallyVisible()) {
6335       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6336       ND.dropAttr<WeakRefAttr>();
6337       ND.dropAttr<AliasAttr>();
6338     }
6339   }
6340 
6341   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6342     if (VD->hasInit()) {
6343       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6344         assert(VD->isThisDeclarationADefinition() &&
6345                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6346         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6347         VD->dropAttr<AliasAttr>();
6348       }
6349     }
6350   }
6351 
6352   // 'selectany' only applies to externally visible variable declarations.
6353   // It does not apply to functions.
6354   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6355     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6356       S.Diag(Attr->getLocation(),
6357              diag::err_attribute_selectany_non_extern_data);
6358       ND.dropAttr<SelectAnyAttr>();
6359     }
6360   }
6361 
6362   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6363     auto *VD = dyn_cast<VarDecl>(&ND);
6364     bool IsAnonymousNS = false;
6365     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6366     if (VD) {
6367       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6368       while (NS && !IsAnonymousNS) {
6369         IsAnonymousNS = NS->isAnonymousNamespace();
6370         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6371       }
6372     }
6373     // dll attributes require external linkage. Static locals may have external
6374     // linkage but still cannot be explicitly imported or exported.
6375     // In Microsoft mode, a variable defined in anonymous namespace must have
6376     // external linkage in order to be exported.
6377     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6378     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6379         (!AnonNSInMicrosoftMode &&
6380          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6381       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6382         << &ND << Attr;
6383       ND.setInvalidDecl();
6384     }
6385   }
6386 
6387   // Virtual functions cannot be marked as 'notail'.
6388   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6389     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6390       if (MD->isVirtual()) {
6391         S.Diag(ND.getLocation(),
6392                diag::err_invalid_attribute_on_virtual_function)
6393             << Attr;
6394         ND.dropAttr<NotTailCalledAttr>();
6395       }
6396 
6397   // Check the attributes on the function type, if any.
6398   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6399     // Don't declare this variable in the second operand of the for-statement;
6400     // GCC miscompiles that by ending its lifetime before evaluating the
6401     // third operand. See gcc.gnu.org/PR86769.
6402     AttributedTypeLoc ATL;
6403     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6404          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6405          TL = ATL.getModifiedLoc()) {
6406       // The [[lifetimebound]] attribute can be applied to the implicit object
6407       // parameter of a non-static member function (other than a ctor or dtor)
6408       // by applying it to the function type.
6409       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6410         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6411         if (!MD || MD->isStatic()) {
6412           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6413               << !MD << A->getRange();
6414         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6415           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6416               << isa<CXXDestructorDecl>(MD) << A->getRange();
6417         }
6418       }
6419     }
6420   }
6421 }
6422 
6423 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6424                                            NamedDecl *NewDecl,
6425                                            bool IsSpecialization,
6426                                            bool IsDefinition) {
6427   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6428     return;
6429 
6430   bool IsTemplate = false;
6431   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6432     OldDecl = OldTD->getTemplatedDecl();
6433     IsTemplate = true;
6434     if (!IsSpecialization)
6435       IsDefinition = false;
6436   }
6437   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6438     NewDecl = NewTD->getTemplatedDecl();
6439     IsTemplate = true;
6440   }
6441 
6442   if (!OldDecl || !NewDecl)
6443     return;
6444 
6445   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6446   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6447   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6448   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6449 
6450   // dllimport and dllexport are inheritable attributes so we have to exclude
6451   // inherited attribute instances.
6452   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6453                     (NewExportAttr && !NewExportAttr->isInherited());
6454 
6455   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6456   // the only exception being explicit specializations.
6457   // Implicitly generated declarations are also excluded for now because there
6458   // is no other way to switch these to use dllimport or dllexport.
6459   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6460 
6461   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6462     // Allow with a warning for free functions and global variables.
6463     bool JustWarn = false;
6464     if (!OldDecl->isCXXClassMember()) {
6465       auto *VD = dyn_cast<VarDecl>(OldDecl);
6466       if (VD && !VD->getDescribedVarTemplate())
6467         JustWarn = true;
6468       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6469       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6470         JustWarn = true;
6471     }
6472 
6473     // We cannot change a declaration that's been used because IR has already
6474     // been emitted. Dllimported functions will still work though (modulo
6475     // address equality) as they can use the thunk.
6476     if (OldDecl->isUsed())
6477       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6478         JustWarn = false;
6479 
6480     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6481                                : diag::err_attribute_dll_redeclaration;
6482     S.Diag(NewDecl->getLocation(), DiagID)
6483         << NewDecl
6484         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6485     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6486     if (!JustWarn) {
6487       NewDecl->setInvalidDecl();
6488       return;
6489     }
6490   }
6491 
6492   // A redeclaration is not allowed to drop a dllimport attribute, the only
6493   // exceptions being inline function definitions (except for function
6494   // templates), local extern declarations, qualified friend declarations or
6495   // special MSVC extension: in the last case, the declaration is treated as if
6496   // it were marked dllexport.
6497   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6498   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6499   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6500     // Ignore static data because out-of-line definitions are diagnosed
6501     // separately.
6502     IsStaticDataMember = VD->isStaticDataMember();
6503     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6504                    VarDecl::DeclarationOnly;
6505   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6506     IsInline = FD->isInlined();
6507     IsQualifiedFriend = FD->getQualifier() &&
6508                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6509   }
6510 
6511   if (OldImportAttr && !HasNewAttr &&
6512       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6513       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6514     if (IsMicrosoft && IsDefinition) {
6515       S.Diag(NewDecl->getLocation(),
6516              diag::warn_redeclaration_without_import_attribute)
6517           << NewDecl;
6518       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6519       NewDecl->dropAttr<DLLImportAttr>();
6520       NewDecl->addAttr(
6521           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6522     } else {
6523       S.Diag(NewDecl->getLocation(),
6524              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6525           << NewDecl << OldImportAttr;
6526       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6527       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6528       OldDecl->dropAttr<DLLImportAttr>();
6529       NewDecl->dropAttr<DLLImportAttr>();
6530     }
6531   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6532     // In MinGW, seeing a function declared inline drops the dllimport
6533     // attribute.
6534     OldDecl->dropAttr<DLLImportAttr>();
6535     NewDecl->dropAttr<DLLImportAttr>();
6536     S.Diag(NewDecl->getLocation(),
6537            diag::warn_dllimport_dropped_from_inline_function)
6538         << NewDecl << OldImportAttr;
6539   }
6540 
6541   // A specialization of a class template member function is processed here
6542   // since it's a redeclaration. If the parent class is dllexport, the
6543   // specialization inherits that attribute. This doesn't happen automatically
6544   // since the parent class isn't instantiated until later.
6545   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6546     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6547         !NewImportAttr && !NewExportAttr) {
6548       if (const DLLExportAttr *ParentExportAttr =
6549               MD->getParent()->getAttr<DLLExportAttr>()) {
6550         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6551         NewAttr->setInherited(true);
6552         NewDecl->addAttr(NewAttr);
6553       }
6554     }
6555   }
6556 }
6557 
6558 /// Given that we are within the definition of the given function,
6559 /// will that definition behave like C99's 'inline', where the
6560 /// definition is discarded except for optimization purposes?
6561 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6562   // Try to avoid calling GetGVALinkageForFunction.
6563 
6564   // All cases of this require the 'inline' keyword.
6565   if (!FD->isInlined()) return false;
6566 
6567   // This is only possible in C++ with the gnu_inline attribute.
6568   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6569     return false;
6570 
6571   // Okay, go ahead and call the relatively-more-expensive function.
6572   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6573 }
6574 
6575 /// Determine whether a variable is extern "C" prior to attaching
6576 /// an initializer. We can't just call isExternC() here, because that
6577 /// will also compute and cache whether the declaration is externally
6578 /// visible, which might change when we attach the initializer.
6579 ///
6580 /// This can only be used if the declaration is known to not be a
6581 /// redeclaration of an internal linkage declaration.
6582 ///
6583 /// For instance:
6584 ///
6585 ///   auto x = []{};
6586 ///
6587 /// Attaching the initializer here makes this declaration not externally
6588 /// visible, because its type has internal linkage.
6589 ///
6590 /// FIXME: This is a hack.
6591 template<typename T>
6592 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6593   if (S.getLangOpts().CPlusPlus) {
6594     // In C++, the overloadable attribute negates the effects of extern "C".
6595     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6596       return false;
6597 
6598     // So do CUDA's host/device attributes.
6599     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6600                                  D->template hasAttr<CUDAHostAttr>()))
6601       return false;
6602   }
6603   return D->isExternC();
6604 }
6605 
6606 static bool shouldConsiderLinkage(const VarDecl *VD) {
6607   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6608   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6609       isa<OMPDeclareMapperDecl>(DC))
6610     return VD->hasExternalStorage();
6611   if (DC->isFileContext())
6612     return true;
6613   if (DC->isRecord())
6614     return false;
6615   if (isa<RequiresExprBodyDecl>(DC))
6616     return false;
6617   llvm_unreachable("Unexpected context");
6618 }
6619 
6620 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6621   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6622   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6623       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6624     return true;
6625   if (DC->isRecord())
6626     return false;
6627   llvm_unreachable("Unexpected context");
6628 }
6629 
6630 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6631                           ParsedAttr::Kind Kind) {
6632   // Check decl attributes on the DeclSpec.
6633   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6634     return true;
6635 
6636   // Walk the declarator structure, checking decl attributes that were in a type
6637   // position to the decl itself.
6638   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6639     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6640       return true;
6641   }
6642 
6643   // Finally, check attributes on the decl itself.
6644   return PD.getAttributes().hasAttribute(Kind);
6645 }
6646 
6647 /// Adjust the \c DeclContext for a function or variable that might be a
6648 /// function-local external declaration.
6649 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6650   if (!DC->isFunctionOrMethod())
6651     return false;
6652 
6653   // If this is a local extern function or variable declared within a function
6654   // template, don't add it into the enclosing namespace scope until it is
6655   // instantiated; it might have a dependent type right now.
6656   if (DC->isDependentContext())
6657     return true;
6658 
6659   // C++11 [basic.link]p7:
6660   //   When a block scope declaration of an entity with linkage is not found to
6661   //   refer to some other declaration, then that entity is a member of the
6662   //   innermost enclosing namespace.
6663   //
6664   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6665   // semantically-enclosing namespace, not a lexically-enclosing one.
6666   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6667     DC = DC->getParent();
6668   return true;
6669 }
6670 
6671 /// Returns true if given declaration has external C language linkage.
6672 static bool isDeclExternC(const Decl *D) {
6673   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6674     return FD->isExternC();
6675   if (const auto *VD = dyn_cast<VarDecl>(D))
6676     return VD->isExternC();
6677 
6678   llvm_unreachable("Unknown type of decl!");
6679 }
6680 /// Returns true if there hasn't been any invalid type diagnosed.
6681 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6682                                 DeclContext *DC, QualType R) {
6683   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6684   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6685   // argument.
6686   if (R->isImageType() || R->isPipeType()) {
6687     Se.Diag(D.getIdentifierLoc(),
6688             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6689         << R;
6690     D.setInvalidType();
6691     return false;
6692   }
6693 
6694   // OpenCL v1.2 s6.9.r:
6695   // The event type cannot be used to declare a program scope variable.
6696   // OpenCL v2.0 s6.9.q:
6697   // The clk_event_t and reserve_id_t types cannot be declared in program
6698   // scope.
6699   if (NULL == S->getParent()) {
6700     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6701       Se.Diag(D.getIdentifierLoc(),
6702               diag::err_invalid_type_for_program_scope_var)
6703           << R;
6704       D.setInvalidType();
6705       return false;
6706     }
6707   }
6708 
6709   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6710   QualType NR = R;
6711   while (NR->isPointerType()) {
6712     if (NR->isFunctionPointerType()) {
6713       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6714       D.setInvalidType();
6715       return false;
6716     }
6717     NR = NR->getPointeeType();
6718   }
6719 
6720   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6721     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6722     // half array type (unless the cl_khr_fp16 extension is enabled).
6723     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6724       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6725       D.setInvalidType();
6726       return false;
6727     }
6728   }
6729 
6730   // OpenCL v1.2 s6.9.r:
6731   // The event type cannot be used with the __local, __constant and __global
6732   // address space qualifiers.
6733   if (R->isEventT()) {
6734     if (R.getAddressSpace() != LangAS::opencl_private) {
6735       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6736       D.setInvalidType();
6737       return false;
6738     }
6739   }
6740 
6741   // C++ for OpenCL does not allow the thread_local storage qualifier.
6742   // OpenCL C does not support thread_local either, and
6743   // also reject all other thread storage class specifiers.
6744   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6745   if (TSC != TSCS_unspecified) {
6746     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6747     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6748             diag::err_opencl_unknown_type_specifier)
6749         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6750         << DeclSpec::getSpecifierName(TSC) << 1;
6751     D.setInvalidType();
6752     return false;
6753   }
6754 
6755   if (R->isSamplerT()) {
6756     // OpenCL v1.2 s6.9.b p4:
6757     // The sampler type cannot be used with the __local and __global address
6758     // space qualifiers.
6759     if (R.getAddressSpace() == LangAS::opencl_local ||
6760         R.getAddressSpace() == LangAS::opencl_global) {
6761       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6762       D.setInvalidType();
6763     }
6764 
6765     // OpenCL v1.2 s6.12.14.1:
6766     // A global sampler must be declared with either the constant address
6767     // space qualifier or with the const qualifier.
6768     if (DC->isTranslationUnit() &&
6769         !(R.getAddressSpace() == LangAS::opencl_constant ||
6770           R.isConstQualified())) {
6771       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6772       D.setInvalidType();
6773     }
6774     if (D.isInvalidType())
6775       return false;
6776   }
6777   return true;
6778 }
6779 
6780 NamedDecl *Sema::ActOnVariableDeclarator(
6781     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6782     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6783     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6784   QualType R = TInfo->getType();
6785   DeclarationName Name = GetNameForDeclarator(D).getName();
6786 
6787   IdentifierInfo *II = Name.getAsIdentifierInfo();
6788 
6789   if (D.isDecompositionDeclarator()) {
6790     // Take the name of the first declarator as our name for diagnostic
6791     // purposes.
6792     auto &Decomp = D.getDecompositionDeclarator();
6793     if (!Decomp.bindings().empty()) {
6794       II = Decomp.bindings()[0].Name;
6795       Name = II;
6796     }
6797   } else if (!II) {
6798     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6799     return nullptr;
6800   }
6801 
6802 
6803   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6804   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6805 
6806   // dllimport globals without explicit storage class are treated as extern. We
6807   // have to change the storage class this early to get the right DeclContext.
6808   if (SC == SC_None && !DC->isRecord() &&
6809       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6810       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6811     SC = SC_Extern;
6812 
6813   DeclContext *OriginalDC = DC;
6814   bool IsLocalExternDecl = SC == SC_Extern &&
6815                            adjustContextForLocalExternDecl(DC);
6816 
6817   if (SCSpec == DeclSpec::SCS_mutable) {
6818     // mutable can only appear on non-static class members, so it's always
6819     // an error here
6820     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6821     D.setInvalidType();
6822     SC = SC_None;
6823   }
6824 
6825   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6826       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6827                               D.getDeclSpec().getStorageClassSpecLoc())) {
6828     // In C++11, the 'register' storage class specifier is deprecated.
6829     // Suppress the warning in system macros, it's used in macros in some
6830     // popular C system headers, such as in glibc's htonl() macro.
6831     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6832          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6833                                    : diag::warn_deprecated_register)
6834       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6835   }
6836 
6837   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6838 
6839   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6840     // C99 6.9p2: The storage-class specifiers auto and register shall not
6841     // appear in the declaration specifiers in an external declaration.
6842     // Global Register+Asm is a GNU extension we support.
6843     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6844       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6845       D.setInvalidType();
6846     }
6847   }
6848 
6849   bool IsMemberSpecialization = false;
6850   bool IsVariableTemplateSpecialization = false;
6851   bool IsPartialSpecialization = false;
6852   bool IsVariableTemplate = false;
6853   VarDecl *NewVD = nullptr;
6854   VarTemplateDecl *NewTemplate = nullptr;
6855   TemplateParameterList *TemplateParams = nullptr;
6856   if (!getLangOpts().CPlusPlus) {
6857     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6858                             II, R, TInfo, SC);
6859 
6860     if (R->getContainedDeducedType())
6861       ParsingInitForAutoVars.insert(NewVD);
6862 
6863     if (D.isInvalidType())
6864       NewVD->setInvalidDecl();
6865 
6866     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6867         NewVD->hasLocalStorage())
6868       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6869                             NTCUC_AutoVar, NTCUK_Destruct);
6870   } else {
6871     bool Invalid = false;
6872 
6873     if (DC->isRecord() && !CurContext->isRecord()) {
6874       // This is an out-of-line definition of a static data member.
6875       switch (SC) {
6876       case SC_None:
6877         break;
6878       case SC_Static:
6879         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6880              diag::err_static_out_of_line)
6881           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6882         break;
6883       case SC_Auto:
6884       case SC_Register:
6885       case SC_Extern:
6886         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6887         // to names of variables declared in a block or to function parameters.
6888         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6889         // of class members
6890 
6891         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6892              diag::err_storage_class_for_static_member)
6893           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6894         break;
6895       case SC_PrivateExtern:
6896         llvm_unreachable("C storage class in c++!");
6897       }
6898     }
6899 
6900     if (SC == SC_Static && CurContext->isRecord()) {
6901       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6902         // Walk up the enclosing DeclContexts to check for any that are
6903         // incompatible with static data members.
6904         const DeclContext *FunctionOrMethod = nullptr;
6905         const CXXRecordDecl *AnonStruct = nullptr;
6906         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6907           if (Ctxt->isFunctionOrMethod()) {
6908             FunctionOrMethod = Ctxt;
6909             break;
6910           }
6911           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6912           if (ParentDecl && !ParentDecl->getDeclName()) {
6913             AnonStruct = ParentDecl;
6914             break;
6915           }
6916         }
6917         if (FunctionOrMethod) {
6918           // C++ [class.static.data]p5: A local class shall not have static data
6919           // members.
6920           Diag(D.getIdentifierLoc(),
6921                diag::err_static_data_member_not_allowed_in_local_class)
6922             << Name << RD->getDeclName() << RD->getTagKind();
6923         } else if (AnonStruct) {
6924           // C++ [class.static.data]p4: Unnamed classes and classes contained
6925           // directly or indirectly within unnamed classes shall not contain
6926           // static data members.
6927           Diag(D.getIdentifierLoc(),
6928                diag::err_static_data_member_not_allowed_in_anon_struct)
6929             << Name << AnonStruct->getTagKind();
6930           Invalid = true;
6931         } else if (RD->isUnion()) {
6932           // C++98 [class.union]p1: If a union contains a static data member,
6933           // the program is ill-formed. C++11 drops this restriction.
6934           Diag(D.getIdentifierLoc(),
6935                getLangOpts().CPlusPlus11
6936                  ? diag::warn_cxx98_compat_static_data_member_in_union
6937                  : diag::ext_static_data_member_in_union) << Name;
6938         }
6939       }
6940     }
6941 
6942     // Match up the template parameter lists with the scope specifier, then
6943     // determine whether we have a template or a template specialization.
6944     bool InvalidScope = false;
6945     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6946         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6947         D.getCXXScopeSpec(),
6948         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6949             ? D.getName().TemplateId
6950             : nullptr,
6951         TemplateParamLists,
6952         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6953     Invalid |= InvalidScope;
6954 
6955     if (TemplateParams) {
6956       if (!TemplateParams->size() &&
6957           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6958         // There is an extraneous 'template<>' for this variable. Complain
6959         // about it, but allow the declaration of the variable.
6960         Diag(TemplateParams->getTemplateLoc(),
6961              diag::err_template_variable_noparams)
6962           << II
6963           << SourceRange(TemplateParams->getTemplateLoc(),
6964                          TemplateParams->getRAngleLoc());
6965         TemplateParams = nullptr;
6966       } else {
6967         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6968           // This is an explicit specialization or a partial specialization.
6969           // FIXME: Check that we can declare a specialization here.
6970           IsVariableTemplateSpecialization = true;
6971           IsPartialSpecialization = TemplateParams->size() > 0;
6972         } else { // if (TemplateParams->size() > 0)
6973           // This is a template declaration.
6974           IsVariableTemplate = true;
6975 
6976           // Check that we can declare a template here.
6977           if (CheckTemplateDeclScope(S, TemplateParams))
6978             return nullptr;
6979 
6980           // Only C++1y supports variable templates (N3651).
6981           Diag(D.getIdentifierLoc(),
6982                getLangOpts().CPlusPlus14
6983                    ? diag::warn_cxx11_compat_variable_template
6984                    : diag::ext_variable_template);
6985         }
6986       }
6987     } else {
6988       assert((Invalid ||
6989               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6990              "should have a 'template<>' for this decl");
6991     }
6992 
6993     if (IsVariableTemplateSpecialization) {
6994       SourceLocation TemplateKWLoc =
6995           TemplateParamLists.size() > 0
6996               ? TemplateParamLists[0]->getTemplateLoc()
6997               : SourceLocation();
6998       DeclResult Res = ActOnVarTemplateSpecialization(
6999           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7000           IsPartialSpecialization);
7001       if (Res.isInvalid())
7002         return nullptr;
7003       NewVD = cast<VarDecl>(Res.get());
7004       AddToScope = false;
7005     } else if (D.isDecompositionDeclarator()) {
7006       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7007                                         D.getIdentifierLoc(), R, TInfo, SC,
7008                                         Bindings);
7009     } else
7010       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7011                               D.getIdentifierLoc(), II, R, TInfo, SC);
7012 
7013     // If this is supposed to be a variable template, create it as such.
7014     if (IsVariableTemplate) {
7015       NewTemplate =
7016           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7017                                   TemplateParams, NewVD);
7018       NewVD->setDescribedVarTemplate(NewTemplate);
7019     }
7020 
7021     // If this decl has an auto type in need of deduction, make a note of the
7022     // Decl so we can diagnose uses of it in its own initializer.
7023     if (R->getContainedDeducedType())
7024       ParsingInitForAutoVars.insert(NewVD);
7025 
7026     if (D.isInvalidType() || Invalid) {
7027       NewVD->setInvalidDecl();
7028       if (NewTemplate)
7029         NewTemplate->setInvalidDecl();
7030     }
7031 
7032     SetNestedNameSpecifier(*this, NewVD, D);
7033 
7034     // If we have any template parameter lists that don't directly belong to
7035     // the variable (matching the scope specifier), store them.
7036     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7037     if (TemplateParamLists.size() > VDTemplateParamLists)
7038       NewVD->setTemplateParameterListsInfo(
7039           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7040   }
7041 
7042   if (D.getDeclSpec().isInlineSpecified()) {
7043     if (!getLangOpts().CPlusPlus) {
7044       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7045           << 0;
7046     } else if (CurContext->isFunctionOrMethod()) {
7047       // 'inline' is not allowed on block scope variable declaration.
7048       Diag(D.getDeclSpec().getInlineSpecLoc(),
7049            diag::err_inline_declaration_block_scope) << Name
7050         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7051     } else {
7052       Diag(D.getDeclSpec().getInlineSpecLoc(),
7053            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7054                                      : diag::ext_inline_variable);
7055       NewVD->setInlineSpecified();
7056     }
7057   }
7058 
7059   // Set the lexical context. If the declarator has a C++ scope specifier, the
7060   // lexical context will be different from the semantic context.
7061   NewVD->setLexicalDeclContext(CurContext);
7062   if (NewTemplate)
7063     NewTemplate->setLexicalDeclContext(CurContext);
7064 
7065   if (IsLocalExternDecl) {
7066     if (D.isDecompositionDeclarator())
7067       for (auto *B : Bindings)
7068         B->setLocalExternDecl();
7069     else
7070       NewVD->setLocalExternDecl();
7071   }
7072 
7073   bool EmitTLSUnsupportedError = false;
7074   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7075     // C++11 [dcl.stc]p4:
7076     //   When thread_local is applied to a variable of block scope the
7077     //   storage-class-specifier static is implied if it does not appear
7078     //   explicitly.
7079     // Core issue: 'static' is not implied if the variable is declared
7080     //   'extern'.
7081     if (NewVD->hasLocalStorage() &&
7082         (SCSpec != DeclSpec::SCS_unspecified ||
7083          TSCS != DeclSpec::TSCS_thread_local ||
7084          !DC->isFunctionOrMethod()))
7085       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7086            diag::err_thread_non_global)
7087         << DeclSpec::getSpecifierName(TSCS);
7088     else if (!Context.getTargetInfo().isTLSSupported()) {
7089       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7090           getLangOpts().SYCLIsDevice) {
7091         // Postpone error emission until we've collected attributes required to
7092         // figure out whether it's a host or device variable and whether the
7093         // error should be ignored.
7094         EmitTLSUnsupportedError = true;
7095         // We still need to mark the variable as TLS so it shows up in AST with
7096         // proper storage class for other tools to use even if we're not going
7097         // to emit any code for it.
7098         NewVD->setTSCSpec(TSCS);
7099       } else
7100         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7101              diag::err_thread_unsupported);
7102     } else
7103       NewVD->setTSCSpec(TSCS);
7104   }
7105 
7106   switch (D.getDeclSpec().getConstexprSpecifier()) {
7107   case CSK_unspecified:
7108     break;
7109 
7110   case CSK_consteval:
7111     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7112         diag::err_constexpr_wrong_decl_kind)
7113       << D.getDeclSpec().getConstexprSpecifier();
7114     LLVM_FALLTHROUGH;
7115 
7116   case CSK_constexpr:
7117     NewVD->setConstexpr(true);
7118     MaybeAddCUDAConstantAttr(NewVD);
7119     // C++1z [dcl.spec.constexpr]p1:
7120     //   A static data member declared with the constexpr specifier is
7121     //   implicitly an inline variable.
7122     if (NewVD->isStaticDataMember() &&
7123         (getLangOpts().CPlusPlus17 ||
7124          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7125       NewVD->setImplicitlyInline();
7126     break;
7127 
7128   case CSK_constinit:
7129     if (!NewVD->hasGlobalStorage())
7130       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7131            diag::err_constinit_local_variable);
7132     else
7133       NewVD->addAttr(ConstInitAttr::Create(
7134           Context, D.getDeclSpec().getConstexprSpecLoc(),
7135           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7136     break;
7137   }
7138 
7139   // C99 6.7.4p3
7140   //   An inline definition of a function with external linkage shall
7141   //   not contain a definition of a modifiable object with static or
7142   //   thread storage duration...
7143   // We only apply this when the function is required to be defined
7144   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7145   // that a local variable with thread storage duration still has to
7146   // be marked 'static'.  Also note that it's possible to get these
7147   // semantics in C++ using __attribute__((gnu_inline)).
7148   if (SC == SC_Static && S->getFnParent() != nullptr &&
7149       !NewVD->getType().isConstQualified()) {
7150     FunctionDecl *CurFD = getCurFunctionDecl();
7151     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7152       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7153            diag::warn_static_local_in_extern_inline);
7154       MaybeSuggestAddingStaticToDecl(CurFD);
7155     }
7156   }
7157 
7158   if (D.getDeclSpec().isModulePrivateSpecified()) {
7159     if (IsVariableTemplateSpecialization)
7160       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7161           << (IsPartialSpecialization ? 1 : 0)
7162           << FixItHint::CreateRemoval(
7163                  D.getDeclSpec().getModulePrivateSpecLoc());
7164     else if (IsMemberSpecialization)
7165       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7166         << 2
7167         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7168     else if (NewVD->hasLocalStorage())
7169       Diag(NewVD->getLocation(), diag::err_module_private_local)
7170         << 0 << NewVD->getDeclName()
7171         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7172         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7173     else {
7174       NewVD->setModulePrivate();
7175       if (NewTemplate)
7176         NewTemplate->setModulePrivate();
7177       for (auto *B : Bindings)
7178         B->setModulePrivate();
7179     }
7180   }
7181 
7182   if (getLangOpts().OpenCL) {
7183 
7184     deduceOpenCLAddressSpace(NewVD);
7185 
7186     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7187   }
7188 
7189   // Handle attributes prior to checking for duplicates in MergeVarDecl
7190   ProcessDeclAttributes(S, NewVD, D);
7191 
7192   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7193       getLangOpts().SYCLIsDevice) {
7194     if (EmitTLSUnsupportedError &&
7195         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7196          (getLangOpts().OpenMPIsDevice &&
7197           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7198       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7199            diag::err_thread_unsupported);
7200 
7201     if (EmitTLSUnsupportedError &&
7202         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7203       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7204     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7205     // storage [duration]."
7206     if (SC == SC_None && S->getFnParent() != nullptr &&
7207         (NewVD->hasAttr<CUDASharedAttr>() ||
7208          NewVD->hasAttr<CUDAConstantAttr>())) {
7209       NewVD->setStorageClass(SC_Static);
7210     }
7211   }
7212 
7213   // Ensure that dllimport globals without explicit storage class are treated as
7214   // extern. The storage class is set above using parsed attributes. Now we can
7215   // check the VarDecl itself.
7216   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7217          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7218          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7219 
7220   // In auto-retain/release, infer strong retension for variables of
7221   // retainable type.
7222   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7223     NewVD->setInvalidDecl();
7224 
7225   // Handle GNU asm-label extension (encoded as an attribute).
7226   if (Expr *E = (Expr*)D.getAsmLabel()) {
7227     // The parser guarantees this is a string.
7228     StringLiteral *SE = cast<StringLiteral>(E);
7229     StringRef Label = SE->getString();
7230     if (S->getFnParent() != nullptr) {
7231       switch (SC) {
7232       case SC_None:
7233       case SC_Auto:
7234         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7235         break;
7236       case SC_Register:
7237         // Local Named register
7238         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7239             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7240           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7241         break;
7242       case SC_Static:
7243       case SC_Extern:
7244       case SC_PrivateExtern:
7245         break;
7246       }
7247     } else if (SC == SC_Register) {
7248       // Global Named register
7249       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7250         const auto &TI = Context.getTargetInfo();
7251         bool HasSizeMismatch;
7252 
7253         if (!TI.isValidGCCRegisterName(Label))
7254           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7255         else if (!TI.validateGlobalRegisterVariable(Label,
7256                                                     Context.getTypeSize(R),
7257                                                     HasSizeMismatch))
7258           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7259         else if (HasSizeMismatch)
7260           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7261       }
7262 
7263       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7264         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7265         NewVD->setInvalidDecl(true);
7266       }
7267     }
7268 
7269     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7270                                         /*IsLiteralLabel=*/true,
7271                                         SE->getStrTokenLoc(0)));
7272   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7273     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7274       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7275     if (I != ExtnameUndeclaredIdentifiers.end()) {
7276       if (isDeclExternC(NewVD)) {
7277         NewVD->addAttr(I->second);
7278         ExtnameUndeclaredIdentifiers.erase(I);
7279       } else
7280         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7281             << /*Variable*/1 << NewVD;
7282     }
7283   }
7284 
7285   // Find the shadowed declaration before filtering for scope.
7286   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7287                                 ? getShadowedDeclaration(NewVD, Previous)
7288                                 : nullptr;
7289 
7290   // Don't consider existing declarations that are in a different
7291   // scope and are out-of-semantic-context declarations (if the new
7292   // declaration has linkage).
7293   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7294                        D.getCXXScopeSpec().isNotEmpty() ||
7295                        IsMemberSpecialization ||
7296                        IsVariableTemplateSpecialization);
7297 
7298   // Check whether the previous declaration is in the same block scope. This
7299   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7300   if (getLangOpts().CPlusPlus &&
7301       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7302     NewVD->setPreviousDeclInSameBlockScope(
7303         Previous.isSingleResult() && !Previous.isShadowed() &&
7304         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7305 
7306   if (!getLangOpts().CPlusPlus) {
7307     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7308   } else {
7309     // If this is an explicit specialization of a static data member, check it.
7310     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7311         CheckMemberSpecialization(NewVD, Previous))
7312       NewVD->setInvalidDecl();
7313 
7314     // Merge the decl with the existing one if appropriate.
7315     if (!Previous.empty()) {
7316       if (Previous.isSingleResult() &&
7317           isa<FieldDecl>(Previous.getFoundDecl()) &&
7318           D.getCXXScopeSpec().isSet()) {
7319         // The user tried to define a non-static data member
7320         // out-of-line (C++ [dcl.meaning]p1).
7321         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7322           << D.getCXXScopeSpec().getRange();
7323         Previous.clear();
7324         NewVD->setInvalidDecl();
7325       }
7326     } else if (D.getCXXScopeSpec().isSet()) {
7327       // No previous declaration in the qualifying scope.
7328       Diag(D.getIdentifierLoc(), diag::err_no_member)
7329         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7330         << D.getCXXScopeSpec().getRange();
7331       NewVD->setInvalidDecl();
7332     }
7333 
7334     if (!IsVariableTemplateSpecialization)
7335       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7336 
7337     if (NewTemplate) {
7338       VarTemplateDecl *PrevVarTemplate =
7339           NewVD->getPreviousDecl()
7340               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7341               : nullptr;
7342 
7343       // Check the template parameter list of this declaration, possibly
7344       // merging in the template parameter list from the previous variable
7345       // template declaration.
7346       if (CheckTemplateParameterList(
7347               TemplateParams,
7348               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7349                               : nullptr,
7350               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7351                DC->isDependentContext())
7352                   ? TPC_ClassTemplateMember
7353                   : TPC_VarTemplate))
7354         NewVD->setInvalidDecl();
7355 
7356       // If we are providing an explicit specialization of a static variable
7357       // template, make a note of that.
7358       if (PrevVarTemplate &&
7359           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7360         PrevVarTemplate->setMemberSpecialization();
7361     }
7362   }
7363 
7364   // Diagnose shadowed variables iff this isn't a redeclaration.
7365   if (ShadowedDecl && !D.isRedeclaration())
7366     CheckShadow(NewVD, ShadowedDecl, Previous);
7367 
7368   ProcessPragmaWeak(S, NewVD);
7369 
7370   // If this is the first declaration of an extern C variable, update
7371   // the map of such variables.
7372   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7373       isIncompleteDeclExternC(*this, NewVD))
7374     RegisterLocallyScopedExternCDecl(NewVD, S);
7375 
7376   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7377     MangleNumberingContext *MCtx;
7378     Decl *ManglingContextDecl;
7379     std::tie(MCtx, ManglingContextDecl) =
7380         getCurrentMangleNumberContext(NewVD->getDeclContext());
7381     if (MCtx) {
7382       Context.setManglingNumber(
7383           NewVD, MCtx->getManglingNumber(
7384                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7385       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7386     }
7387   }
7388 
7389   // Special handling of variable named 'main'.
7390   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7391       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7392       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7393 
7394     // C++ [basic.start.main]p3
7395     // A program that declares a variable main at global scope is ill-formed.
7396     if (getLangOpts().CPlusPlus)
7397       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7398 
7399     // In C, and external-linkage variable named main results in undefined
7400     // behavior.
7401     else if (NewVD->hasExternalFormalLinkage())
7402       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7403   }
7404 
7405   if (D.isRedeclaration() && !Previous.empty()) {
7406     NamedDecl *Prev = Previous.getRepresentativeDecl();
7407     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7408                                    D.isFunctionDefinition());
7409   }
7410 
7411   if (NewTemplate) {
7412     if (NewVD->isInvalidDecl())
7413       NewTemplate->setInvalidDecl();
7414     ActOnDocumentableDecl(NewTemplate);
7415     return NewTemplate;
7416   }
7417 
7418   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7419     CompleteMemberSpecialization(NewVD, Previous);
7420 
7421   return NewVD;
7422 }
7423 
7424 /// Enum describing the %select options in diag::warn_decl_shadow.
7425 enum ShadowedDeclKind {
7426   SDK_Local,
7427   SDK_Global,
7428   SDK_StaticMember,
7429   SDK_Field,
7430   SDK_Typedef,
7431   SDK_Using
7432 };
7433 
7434 /// Determine what kind of declaration we're shadowing.
7435 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7436                                                 const DeclContext *OldDC) {
7437   if (isa<TypeAliasDecl>(ShadowedDecl))
7438     return SDK_Using;
7439   else if (isa<TypedefDecl>(ShadowedDecl))
7440     return SDK_Typedef;
7441   else if (isa<RecordDecl>(OldDC))
7442     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7443 
7444   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7445 }
7446 
7447 /// Return the location of the capture if the given lambda captures the given
7448 /// variable \p VD, or an invalid source location otherwise.
7449 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7450                                          const VarDecl *VD) {
7451   for (const Capture &Capture : LSI->Captures) {
7452     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7453       return Capture.getLocation();
7454   }
7455   return SourceLocation();
7456 }
7457 
7458 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7459                                      const LookupResult &R) {
7460   // Only diagnose if we're shadowing an unambiguous field or variable.
7461   if (R.getResultKind() != LookupResult::Found)
7462     return false;
7463 
7464   // Return false if warning is ignored.
7465   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7466 }
7467 
7468 /// Return the declaration shadowed by the given variable \p D, or null
7469 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7470 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7471                                         const LookupResult &R) {
7472   if (!shouldWarnIfShadowedDecl(Diags, R))
7473     return nullptr;
7474 
7475   // Don't diagnose declarations at file scope.
7476   if (D->hasGlobalStorage())
7477     return nullptr;
7478 
7479   NamedDecl *ShadowedDecl = R.getFoundDecl();
7480   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7481              ? ShadowedDecl
7482              : nullptr;
7483 }
7484 
7485 /// Return the declaration shadowed by the given typedef \p D, or null
7486 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7487 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7488                                         const LookupResult &R) {
7489   // Don't warn if typedef declaration is part of a class
7490   if (D->getDeclContext()->isRecord())
7491     return nullptr;
7492 
7493   if (!shouldWarnIfShadowedDecl(Diags, R))
7494     return nullptr;
7495 
7496   NamedDecl *ShadowedDecl = R.getFoundDecl();
7497   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7498 }
7499 
7500 /// Diagnose variable or built-in function shadowing.  Implements
7501 /// -Wshadow.
7502 ///
7503 /// This method is called whenever a VarDecl is added to a "useful"
7504 /// scope.
7505 ///
7506 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7507 /// \param R the lookup of the name
7508 ///
7509 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7510                        const LookupResult &R) {
7511   DeclContext *NewDC = D->getDeclContext();
7512 
7513   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7514     // Fields are not shadowed by variables in C++ static methods.
7515     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7516       if (MD->isStatic())
7517         return;
7518 
7519     // Fields shadowed by constructor parameters are a special case. Usually
7520     // the constructor initializes the field with the parameter.
7521     if (isa<CXXConstructorDecl>(NewDC))
7522       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7523         // Remember that this was shadowed so we can either warn about its
7524         // modification or its existence depending on warning settings.
7525         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7526         return;
7527       }
7528   }
7529 
7530   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7531     if (shadowedVar->isExternC()) {
7532       // For shadowing external vars, make sure that we point to the global
7533       // declaration, not a locally scoped extern declaration.
7534       for (auto I : shadowedVar->redecls())
7535         if (I->isFileVarDecl()) {
7536           ShadowedDecl = I;
7537           break;
7538         }
7539     }
7540 
7541   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7542 
7543   unsigned WarningDiag = diag::warn_decl_shadow;
7544   SourceLocation CaptureLoc;
7545   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7546       isa<CXXMethodDecl>(NewDC)) {
7547     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7548       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7549         if (RD->getLambdaCaptureDefault() == LCD_None) {
7550           // Try to avoid warnings for lambdas with an explicit capture list.
7551           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7552           // Warn only when the lambda captures the shadowed decl explicitly.
7553           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7554           if (CaptureLoc.isInvalid())
7555             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7556         } else {
7557           // Remember that this was shadowed so we can avoid the warning if the
7558           // shadowed decl isn't captured and the warning settings allow it.
7559           cast<LambdaScopeInfo>(getCurFunction())
7560               ->ShadowingDecls.push_back(
7561                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7562           return;
7563         }
7564       }
7565 
7566       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7567         // A variable can't shadow a local variable in an enclosing scope, if
7568         // they are separated by a non-capturing declaration context.
7569         for (DeclContext *ParentDC = NewDC;
7570              ParentDC && !ParentDC->Equals(OldDC);
7571              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7572           // Only block literals, captured statements, and lambda expressions
7573           // can capture; other scopes don't.
7574           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7575               !isLambdaCallOperator(ParentDC)) {
7576             return;
7577           }
7578         }
7579       }
7580     }
7581   }
7582 
7583   // Only warn about certain kinds of shadowing for class members.
7584   if (NewDC && NewDC->isRecord()) {
7585     // In particular, don't warn about shadowing non-class members.
7586     if (!OldDC->isRecord())
7587       return;
7588 
7589     // TODO: should we warn about static data members shadowing
7590     // static data members from base classes?
7591 
7592     // TODO: don't diagnose for inaccessible shadowed members.
7593     // This is hard to do perfectly because we might friend the
7594     // shadowing context, but that's just a false negative.
7595   }
7596 
7597 
7598   DeclarationName Name = R.getLookupName();
7599 
7600   // Emit warning and note.
7601   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7602     return;
7603   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7604   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7605   if (!CaptureLoc.isInvalid())
7606     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7607         << Name << /*explicitly*/ 1;
7608   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7609 }
7610 
7611 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7612 /// when these variables are captured by the lambda.
7613 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7614   for (const auto &Shadow : LSI->ShadowingDecls) {
7615     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7616     // Try to avoid the warning when the shadowed decl isn't captured.
7617     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7618     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7619     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7620                                        ? diag::warn_decl_shadow_uncaptured_local
7621                                        : diag::warn_decl_shadow)
7622         << Shadow.VD->getDeclName()
7623         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7624     if (!CaptureLoc.isInvalid())
7625       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7626           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7627     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7628   }
7629 }
7630 
7631 /// Check -Wshadow without the advantage of a previous lookup.
7632 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7633   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7634     return;
7635 
7636   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7637                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7638   LookupName(R, S);
7639   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7640     CheckShadow(D, ShadowedDecl, R);
7641 }
7642 
7643 /// Check if 'E', which is an expression that is about to be modified, refers
7644 /// to a constructor parameter that shadows a field.
7645 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7646   // Quickly ignore expressions that can't be shadowing ctor parameters.
7647   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7648     return;
7649   E = E->IgnoreParenImpCasts();
7650   auto *DRE = dyn_cast<DeclRefExpr>(E);
7651   if (!DRE)
7652     return;
7653   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7654   auto I = ShadowingDecls.find(D);
7655   if (I == ShadowingDecls.end())
7656     return;
7657   const NamedDecl *ShadowedDecl = I->second;
7658   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7659   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7660   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7661   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7662 
7663   // Avoid issuing multiple warnings about the same decl.
7664   ShadowingDecls.erase(I);
7665 }
7666 
7667 /// Check for conflict between this global or extern "C" declaration and
7668 /// previous global or extern "C" declarations. This is only used in C++.
7669 template<typename T>
7670 static bool checkGlobalOrExternCConflict(
7671     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7672   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7673   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7674 
7675   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7676     // The common case: this global doesn't conflict with any extern "C"
7677     // declaration.
7678     return false;
7679   }
7680 
7681   if (Prev) {
7682     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7683       // Both the old and new declarations have C language linkage. This is a
7684       // redeclaration.
7685       Previous.clear();
7686       Previous.addDecl(Prev);
7687       return true;
7688     }
7689 
7690     // This is a global, non-extern "C" declaration, and there is a previous
7691     // non-global extern "C" declaration. Diagnose if this is a variable
7692     // declaration.
7693     if (!isa<VarDecl>(ND))
7694       return false;
7695   } else {
7696     // The declaration is extern "C". Check for any declaration in the
7697     // translation unit which might conflict.
7698     if (IsGlobal) {
7699       // We have already performed the lookup into the translation unit.
7700       IsGlobal = false;
7701       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7702            I != E; ++I) {
7703         if (isa<VarDecl>(*I)) {
7704           Prev = *I;
7705           break;
7706         }
7707       }
7708     } else {
7709       DeclContext::lookup_result R =
7710           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7711       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7712            I != E; ++I) {
7713         if (isa<VarDecl>(*I)) {
7714           Prev = *I;
7715           break;
7716         }
7717         // FIXME: If we have any other entity with this name in global scope,
7718         // the declaration is ill-formed, but that is a defect: it breaks the
7719         // 'stat' hack, for instance. Only variables can have mangled name
7720         // clashes with extern "C" declarations, so only they deserve a
7721         // diagnostic.
7722       }
7723     }
7724 
7725     if (!Prev)
7726       return false;
7727   }
7728 
7729   // Use the first declaration's location to ensure we point at something which
7730   // is lexically inside an extern "C" linkage-spec.
7731   assert(Prev && "should have found a previous declaration to diagnose");
7732   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7733     Prev = FD->getFirstDecl();
7734   else
7735     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7736 
7737   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7738     << IsGlobal << ND;
7739   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7740     << IsGlobal;
7741   return false;
7742 }
7743 
7744 /// Apply special rules for handling extern "C" declarations. Returns \c true
7745 /// if we have found that this is a redeclaration of some prior entity.
7746 ///
7747 /// Per C++ [dcl.link]p6:
7748 ///   Two declarations [for a function or variable] with C language linkage
7749 ///   with the same name that appear in different scopes refer to the same
7750 ///   [entity]. An entity with C language linkage shall not be declared with
7751 ///   the same name as an entity in global scope.
7752 template<typename T>
7753 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7754                                                   LookupResult &Previous) {
7755   if (!S.getLangOpts().CPlusPlus) {
7756     // In C, when declaring a global variable, look for a corresponding 'extern'
7757     // variable declared in function scope. We don't need this in C++, because
7758     // we find local extern decls in the surrounding file-scope DeclContext.
7759     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7760       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7761         Previous.clear();
7762         Previous.addDecl(Prev);
7763         return true;
7764       }
7765     }
7766     return false;
7767   }
7768 
7769   // A declaration in the translation unit can conflict with an extern "C"
7770   // declaration.
7771   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7772     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7773 
7774   // An extern "C" declaration can conflict with a declaration in the
7775   // translation unit or can be a redeclaration of an extern "C" declaration
7776   // in another scope.
7777   if (isIncompleteDeclExternC(S,ND))
7778     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7779 
7780   // Neither global nor extern "C": nothing to do.
7781   return false;
7782 }
7783 
7784 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7785   // If the decl is already known invalid, don't check it.
7786   if (NewVD->isInvalidDecl())
7787     return;
7788 
7789   QualType T = NewVD->getType();
7790 
7791   // Defer checking an 'auto' type until its initializer is attached.
7792   if (T->isUndeducedType())
7793     return;
7794 
7795   if (NewVD->hasAttrs())
7796     CheckAlignasUnderalignment(NewVD);
7797 
7798   if (T->isObjCObjectType()) {
7799     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7800       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7801     T = Context.getObjCObjectPointerType(T);
7802     NewVD->setType(T);
7803   }
7804 
7805   // Emit an error if an address space was applied to decl with local storage.
7806   // This includes arrays of objects with address space qualifiers, but not
7807   // automatic variables that point to other address spaces.
7808   // ISO/IEC TR 18037 S5.1.2
7809   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7810       T.getAddressSpace() != LangAS::Default) {
7811     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7812     NewVD->setInvalidDecl();
7813     return;
7814   }
7815 
7816   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7817   // scope.
7818   if (getLangOpts().OpenCLVersion == 120 &&
7819       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7820       NewVD->isStaticLocal()) {
7821     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7822     NewVD->setInvalidDecl();
7823     return;
7824   }
7825 
7826   if (getLangOpts().OpenCL) {
7827     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7828     if (NewVD->hasAttr<BlocksAttr>()) {
7829       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7830       return;
7831     }
7832 
7833     if (T->isBlockPointerType()) {
7834       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7835       // can't use 'extern' storage class.
7836       if (!T.isConstQualified()) {
7837         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7838             << 0 /*const*/;
7839         NewVD->setInvalidDecl();
7840         return;
7841       }
7842       if (NewVD->hasExternalStorage()) {
7843         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7844         NewVD->setInvalidDecl();
7845         return;
7846       }
7847     }
7848     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7849     // __constant address space.
7850     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7851     // variables inside a function can also be declared in the global
7852     // address space.
7853     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7854     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7855     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7856         NewVD->hasExternalStorage()) {
7857       if (!T->isSamplerT() &&
7858           !T->isDependentType() &&
7859           !(T.getAddressSpace() == LangAS::opencl_constant ||
7860             (T.getAddressSpace() == LangAS::opencl_global &&
7861              (getLangOpts().OpenCLVersion == 200 ||
7862               getLangOpts().OpenCLCPlusPlus)))) {
7863         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7864         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7865           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7866               << Scope << "global or constant";
7867         else
7868           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7869               << Scope << "constant";
7870         NewVD->setInvalidDecl();
7871         return;
7872       }
7873     } else {
7874       if (T.getAddressSpace() == LangAS::opencl_global) {
7875         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7876             << 1 /*is any function*/ << "global";
7877         NewVD->setInvalidDecl();
7878         return;
7879       }
7880       if (T.getAddressSpace() == LangAS::opencl_constant ||
7881           T.getAddressSpace() == LangAS::opencl_local) {
7882         FunctionDecl *FD = getCurFunctionDecl();
7883         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7884         // in functions.
7885         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7886           if (T.getAddressSpace() == LangAS::opencl_constant)
7887             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7888                 << 0 /*non-kernel only*/ << "constant";
7889           else
7890             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7891                 << 0 /*non-kernel only*/ << "local";
7892           NewVD->setInvalidDecl();
7893           return;
7894         }
7895         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7896         // in the outermost scope of a kernel function.
7897         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7898           if (!getCurScope()->isFunctionScope()) {
7899             if (T.getAddressSpace() == LangAS::opencl_constant)
7900               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7901                   << "constant";
7902             else
7903               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7904                   << "local";
7905             NewVD->setInvalidDecl();
7906             return;
7907           }
7908         }
7909       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7910                  // If we are parsing a template we didn't deduce an addr
7911                  // space yet.
7912                  T.getAddressSpace() != LangAS::Default) {
7913         // Do not allow other address spaces on automatic variable.
7914         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7915         NewVD->setInvalidDecl();
7916         return;
7917       }
7918     }
7919   }
7920 
7921   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7922       && !NewVD->hasAttr<BlocksAttr>()) {
7923     if (getLangOpts().getGC() != LangOptions::NonGC)
7924       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7925     else {
7926       assert(!getLangOpts().ObjCAutoRefCount);
7927       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7928     }
7929   }
7930 
7931   bool isVM = T->isVariablyModifiedType();
7932   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7933       NewVD->hasAttr<BlocksAttr>())
7934     setFunctionHasBranchProtectedScope();
7935 
7936   if ((isVM && NewVD->hasLinkage()) ||
7937       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7938     bool SizeIsNegative;
7939     llvm::APSInt Oversized;
7940     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7941         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7942     QualType FixedT;
7943     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7944       FixedT = FixedTInfo->getType();
7945     else if (FixedTInfo) {
7946       // Type and type-as-written are canonically different. We need to fix up
7947       // both types separately.
7948       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7949                                                    Oversized);
7950     }
7951     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7952       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7953       // FIXME: This won't give the correct result for
7954       // int a[10][n];
7955       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7956 
7957       if (NewVD->isFileVarDecl())
7958         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7959         << SizeRange;
7960       else if (NewVD->isStaticLocal())
7961         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7962         << SizeRange;
7963       else
7964         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7965         << SizeRange;
7966       NewVD->setInvalidDecl();
7967       return;
7968     }
7969 
7970     if (!FixedTInfo) {
7971       if (NewVD->isFileVarDecl())
7972         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7973       else
7974         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7975       NewVD->setInvalidDecl();
7976       return;
7977     }
7978 
7979     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7980     NewVD->setType(FixedT);
7981     NewVD->setTypeSourceInfo(FixedTInfo);
7982   }
7983 
7984   if (T->isVoidType()) {
7985     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7986     //                    of objects and functions.
7987     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7988       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7989         << T;
7990       NewVD->setInvalidDecl();
7991       return;
7992     }
7993   }
7994 
7995   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7996     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7997     NewVD->setInvalidDecl();
7998     return;
7999   }
8000 
8001   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8002     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8003     NewVD->setInvalidDecl();
8004     return;
8005   }
8006 
8007   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8008     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8009     NewVD->setInvalidDecl();
8010     return;
8011   }
8012 
8013   if (NewVD->isConstexpr() && !T->isDependentType() &&
8014       RequireLiteralType(NewVD->getLocation(), T,
8015                          diag::err_constexpr_var_non_literal)) {
8016     NewVD->setInvalidDecl();
8017     return;
8018   }
8019 }
8020 
8021 /// Perform semantic checking on a newly-created variable
8022 /// declaration.
8023 ///
8024 /// This routine performs all of the type-checking required for a
8025 /// variable declaration once it has been built. It is used both to
8026 /// check variables after they have been parsed and their declarators
8027 /// have been translated into a declaration, and to check variables
8028 /// that have been instantiated from a template.
8029 ///
8030 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8031 ///
8032 /// Returns true if the variable declaration is a redeclaration.
8033 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8034   CheckVariableDeclarationType(NewVD);
8035 
8036   // If the decl is already known invalid, don't check it.
8037   if (NewVD->isInvalidDecl())
8038     return false;
8039 
8040   // If we did not find anything by this name, look for a non-visible
8041   // extern "C" declaration with the same name.
8042   if (Previous.empty() &&
8043       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8044     Previous.setShadowed();
8045 
8046   if (!Previous.empty()) {
8047     MergeVarDecl(NewVD, Previous);
8048     return true;
8049   }
8050   return false;
8051 }
8052 
8053 namespace {
8054 struct FindOverriddenMethod {
8055   Sema *S;
8056   CXXMethodDecl *Method;
8057 
8058   /// Member lookup function that determines whether a given C++
8059   /// method overrides a method in a base class, to be used with
8060   /// CXXRecordDecl::lookupInBases().
8061   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8062     RecordDecl *BaseRecord =
8063         Specifier->getType()->castAs<RecordType>()->getDecl();
8064 
8065     DeclarationName Name = Method->getDeclName();
8066 
8067     // FIXME: Do we care about other names here too?
8068     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8069       // We really want to find the base class destructor here.
8070       QualType T = S->Context.getTypeDeclType(BaseRecord);
8071       CanQualType CT = S->Context.getCanonicalType(T);
8072 
8073       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8074     }
8075 
8076     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8077          Path.Decls = Path.Decls.slice(1)) {
8078       NamedDecl *D = Path.Decls.front();
8079       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8080         if (MD->isVirtual() &&
8081             !S->IsOverload(
8082                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8083                 /*ConsiderCudaAttrs=*/true,
8084                 // C++2a [class.virtual]p2 does not consider requires clauses
8085                 // when overriding.
8086                 /*ConsiderRequiresClauses=*/false))
8087           return true;
8088       }
8089     }
8090 
8091     return false;
8092   }
8093 };
8094 } // end anonymous namespace
8095 
8096 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8097 /// and if so, check that it's a valid override and remember it.
8098 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8099   // Look for methods in base classes that this method might override.
8100   CXXBasePaths Paths;
8101   FindOverriddenMethod FOM;
8102   FOM.Method = MD;
8103   FOM.S = this;
8104   bool AddedAny = false;
8105   if (DC->lookupInBases(FOM, Paths)) {
8106     for (auto *I : Paths.found_decls()) {
8107       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8108         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8109         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8110             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8111             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8112             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8113           AddedAny = true;
8114         }
8115       }
8116     }
8117   }
8118 
8119   return AddedAny;
8120 }
8121 
8122 namespace {
8123   // Struct for holding all of the extra arguments needed by
8124   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8125   struct ActOnFDArgs {
8126     Scope *S;
8127     Declarator &D;
8128     MultiTemplateParamsArg TemplateParamLists;
8129     bool AddToScope;
8130   };
8131 } // end anonymous namespace
8132 
8133 namespace {
8134 
8135 // Callback to only accept typo corrections that have a non-zero edit distance.
8136 // Also only accept corrections that have the same parent decl.
8137 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8138  public:
8139   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8140                             CXXRecordDecl *Parent)
8141       : Context(Context), OriginalFD(TypoFD),
8142         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8143 
8144   bool ValidateCandidate(const TypoCorrection &candidate) override {
8145     if (candidate.getEditDistance() == 0)
8146       return false;
8147 
8148     SmallVector<unsigned, 1> MismatchedParams;
8149     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8150                                           CDeclEnd = candidate.end();
8151          CDecl != CDeclEnd; ++CDecl) {
8152       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8153 
8154       if (FD && !FD->hasBody() &&
8155           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8156         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8157           CXXRecordDecl *Parent = MD->getParent();
8158           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8159             return true;
8160         } else if (!ExpectedParent) {
8161           return true;
8162         }
8163       }
8164     }
8165 
8166     return false;
8167   }
8168 
8169   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8170     return std::make_unique<DifferentNameValidatorCCC>(*this);
8171   }
8172 
8173  private:
8174   ASTContext &Context;
8175   FunctionDecl *OriginalFD;
8176   CXXRecordDecl *ExpectedParent;
8177 };
8178 
8179 } // end anonymous namespace
8180 
8181 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8182   TypoCorrectedFunctionDefinitions.insert(F);
8183 }
8184 
8185 /// Generate diagnostics for an invalid function redeclaration.
8186 ///
8187 /// This routine handles generating the diagnostic messages for an invalid
8188 /// function redeclaration, including finding possible similar declarations
8189 /// or performing typo correction if there are no previous declarations with
8190 /// the same name.
8191 ///
8192 /// Returns a NamedDecl iff typo correction was performed and substituting in
8193 /// the new declaration name does not cause new errors.
8194 static NamedDecl *DiagnoseInvalidRedeclaration(
8195     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8196     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8197   DeclarationName Name = NewFD->getDeclName();
8198   DeclContext *NewDC = NewFD->getDeclContext();
8199   SmallVector<unsigned, 1> MismatchedParams;
8200   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8201   TypoCorrection Correction;
8202   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8203   unsigned DiagMsg =
8204     IsLocalFriend ? diag::err_no_matching_local_friend :
8205     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8206     diag::err_member_decl_does_not_match;
8207   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8208                     IsLocalFriend ? Sema::LookupLocalFriendName
8209                                   : Sema::LookupOrdinaryName,
8210                     Sema::ForVisibleRedeclaration);
8211 
8212   NewFD->setInvalidDecl();
8213   if (IsLocalFriend)
8214     SemaRef.LookupName(Prev, S);
8215   else
8216     SemaRef.LookupQualifiedName(Prev, NewDC);
8217   assert(!Prev.isAmbiguous() &&
8218          "Cannot have an ambiguity in previous-declaration lookup");
8219   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8220   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8221                                 MD ? MD->getParent() : nullptr);
8222   if (!Prev.empty()) {
8223     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8224          Func != FuncEnd; ++Func) {
8225       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8226       if (FD &&
8227           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8228         // Add 1 to the index so that 0 can mean the mismatch didn't
8229         // involve a parameter
8230         unsigned ParamNum =
8231             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8232         NearMatches.push_back(std::make_pair(FD, ParamNum));
8233       }
8234     }
8235   // If the qualified name lookup yielded nothing, try typo correction
8236   } else if ((Correction = SemaRef.CorrectTypo(
8237                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8238                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8239                   IsLocalFriend ? nullptr : NewDC))) {
8240     // Set up everything for the call to ActOnFunctionDeclarator
8241     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8242                               ExtraArgs.D.getIdentifierLoc());
8243     Previous.clear();
8244     Previous.setLookupName(Correction.getCorrection());
8245     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8246                                     CDeclEnd = Correction.end();
8247          CDecl != CDeclEnd; ++CDecl) {
8248       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8249       if (FD && !FD->hasBody() &&
8250           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8251         Previous.addDecl(FD);
8252       }
8253     }
8254     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8255 
8256     NamedDecl *Result;
8257     // Retry building the function declaration with the new previous
8258     // declarations, and with errors suppressed.
8259     {
8260       // Trap errors.
8261       Sema::SFINAETrap Trap(SemaRef);
8262 
8263       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8264       // pieces need to verify the typo-corrected C++ declaration and hopefully
8265       // eliminate the need for the parameter pack ExtraArgs.
8266       Result = SemaRef.ActOnFunctionDeclarator(
8267           ExtraArgs.S, ExtraArgs.D,
8268           Correction.getCorrectionDecl()->getDeclContext(),
8269           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8270           ExtraArgs.AddToScope);
8271 
8272       if (Trap.hasErrorOccurred())
8273         Result = nullptr;
8274     }
8275 
8276     if (Result) {
8277       // Determine which correction we picked.
8278       Decl *Canonical = Result->getCanonicalDecl();
8279       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8280            I != E; ++I)
8281         if ((*I)->getCanonicalDecl() == Canonical)
8282           Correction.setCorrectionDecl(*I);
8283 
8284       // Let Sema know about the correction.
8285       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8286       SemaRef.diagnoseTypo(
8287           Correction,
8288           SemaRef.PDiag(IsLocalFriend
8289                           ? diag::err_no_matching_local_friend_suggest
8290                           : diag::err_member_decl_does_not_match_suggest)
8291             << Name << NewDC << IsDefinition);
8292       return Result;
8293     }
8294 
8295     // Pretend the typo correction never occurred
8296     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8297                               ExtraArgs.D.getIdentifierLoc());
8298     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8299     Previous.clear();
8300     Previous.setLookupName(Name);
8301   }
8302 
8303   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8304       << Name << NewDC << IsDefinition << NewFD->getLocation();
8305 
8306   bool NewFDisConst = false;
8307   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8308     NewFDisConst = NewMD->isConst();
8309 
8310   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8311        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8312        NearMatch != NearMatchEnd; ++NearMatch) {
8313     FunctionDecl *FD = NearMatch->first;
8314     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8315     bool FDisConst = MD && MD->isConst();
8316     bool IsMember = MD || !IsLocalFriend;
8317 
8318     // FIXME: These notes are poorly worded for the local friend case.
8319     if (unsigned Idx = NearMatch->second) {
8320       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8321       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8322       if (Loc.isInvalid()) Loc = FD->getLocation();
8323       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8324                                  : diag::note_local_decl_close_param_match)
8325         << Idx << FDParam->getType()
8326         << NewFD->getParamDecl(Idx - 1)->getType();
8327     } else if (FDisConst != NewFDisConst) {
8328       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8329           << NewFDisConst << FD->getSourceRange().getEnd();
8330     } else
8331       SemaRef.Diag(FD->getLocation(),
8332                    IsMember ? diag::note_member_def_close_match
8333                             : diag::note_local_decl_close_match);
8334   }
8335   return nullptr;
8336 }
8337 
8338 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8339   switch (D.getDeclSpec().getStorageClassSpec()) {
8340   default: llvm_unreachable("Unknown storage class!");
8341   case DeclSpec::SCS_auto:
8342   case DeclSpec::SCS_register:
8343   case DeclSpec::SCS_mutable:
8344     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8345                  diag::err_typecheck_sclass_func);
8346     D.getMutableDeclSpec().ClearStorageClassSpecs();
8347     D.setInvalidType();
8348     break;
8349   case DeclSpec::SCS_unspecified: break;
8350   case DeclSpec::SCS_extern:
8351     if (D.getDeclSpec().isExternInLinkageSpec())
8352       return SC_None;
8353     return SC_Extern;
8354   case DeclSpec::SCS_static: {
8355     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8356       // C99 6.7.1p5:
8357       //   The declaration of an identifier for a function that has
8358       //   block scope shall have no explicit storage-class specifier
8359       //   other than extern
8360       // See also (C++ [dcl.stc]p4).
8361       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8362                    diag::err_static_block_func);
8363       break;
8364     } else
8365       return SC_Static;
8366   }
8367   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8368   }
8369 
8370   // No explicit storage class has already been returned
8371   return SC_None;
8372 }
8373 
8374 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8375                                            DeclContext *DC, QualType &R,
8376                                            TypeSourceInfo *TInfo,
8377                                            StorageClass SC,
8378                                            bool &IsVirtualOkay) {
8379   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8380   DeclarationName Name = NameInfo.getName();
8381 
8382   FunctionDecl *NewFD = nullptr;
8383   bool isInline = D.getDeclSpec().isInlineSpecified();
8384 
8385   if (!SemaRef.getLangOpts().CPlusPlus) {
8386     // Determine whether the function was written with a
8387     // prototype. This true when:
8388     //   - there is a prototype in the declarator, or
8389     //   - the type R of the function is some kind of typedef or other non-
8390     //     attributed reference to a type name (which eventually refers to a
8391     //     function type).
8392     bool HasPrototype =
8393       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8394       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8395 
8396     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8397                                  R, TInfo, SC, isInline, HasPrototype,
8398                                  CSK_unspecified,
8399                                  /*TrailingRequiresClause=*/nullptr);
8400     if (D.isInvalidType())
8401       NewFD->setInvalidDecl();
8402 
8403     return NewFD;
8404   }
8405 
8406   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8407 
8408   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8409   if (ConstexprKind == CSK_constinit) {
8410     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8411                  diag::err_constexpr_wrong_decl_kind)
8412         << ConstexprKind;
8413     ConstexprKind = CSK_unspecified;
8414     D.getMutableDeclSpec().ClearConstexprSpec();
8415   }
8416   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8417 
8418   // Check that the return type is not an abstract class type.
8419   // For record types, this is done by the AbstractClassUsageDiagnoser once
8420   // the class has been completely parsed.
8421   if (!DC->isRecord() &&
8422       SemaRef.RequireNonAbstractType(
8423           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8424           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8425     D.setInvalidType();
8426 
8427   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8428     // This is a C++ constructor declaration.
8429     assert(DC->isRecord() &&
8430            "Constructors can only be declared in a member context");
8431 
8432     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8433     return CXXConstructorDecl::Create(
8434         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8435         TInfo, ExplicitSpecifier, isInline,
8436         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8437         TrailingRequiresClause);
8438 
8439   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8440     // This is a C++ destructor declaration.
8441     if (DC->isRecord()) {
8442       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8443       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8444       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8445           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8446           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8447           TrailingRequiresClause);
8448 
8449       // If the destructor needs an implicit exception specification, set it
8450       // now. FIXME: It'd be nice to be able to create the right type to start
8451       // with, but the type needs to reference the destructor declaration.
8452       if (SemaRef.getLangOpts().CPlusPlus11)
8453         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8454 
8455       IsVirtualOkay = true;
8456       return NewDD;
8457 
8458     } else {
8459       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8460       D.setInvalidType();
8461 
8462       // Create a FunctionDecl to satisfy the function definition parsing
8463       // code path.
8464       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8465                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8466                                   isInline,
8467                                   /*hasPrototype=*/true, ConstexprKind,
8468                                   TrailingRequiresClause);
8469     }
8470 
8471   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8472     if (!DC->isRecord()) {
8473       SemaRef.Diag(D.getIdentifierLoc(),
8474            diag::err_conv_function_not_member);
8475       return nullptr;
8476     }
8477 
8478     SemaRef.CheckConversionDeclarator(D, R, SC);
8479     if (D.isInvalidType())
8480       return nullptr;
8481 
8482     IsVirtualOkay = true;
8483     return CXXConversionDecl::Create(
8484         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8485         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8486         TrailingRequiresClause);
8487 
8488   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8489     if (TrailingRequiresClause)
8490       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8491                    diag::err_trailing_requires_clause_on_deduction_guide)
8492           << TrailingRequiresClause->getSourceRange();
8493     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8494 
8495     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8496                                          ExplicitSpecifier, NameInfo, R, TInfo,
8497                                          D.getEndLoc());
8498   } else if (DC->isRecord()) {
8499     // If the name of the function is the same as the name of the record,
8500     // then this must be an invalid constructor that has a return type.
8501     // (The parser checks for a return type and makes the declarator a
8502     // constructor if it has no return type).
8503     if (Name.getAsIdentifierInfo() &&
8504         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8505       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8506         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8507         << SourceRange(D.getIdentifierLoc());
8508       return nullptr;
8509     }
8510 
8511     // This is a C++ method declaration.
8512     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8513         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8514         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8515         TrailingRequiresClause);
8516     IsVirtualOkay = !Ret->isStatic();
8517     return Ret;
8518   } else {
8519     bool isFriend =
8520         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8521     if (!isFriend && SemaRef.CurContext->isRecord())
8522       return nullptr;
8523 
8524     // Determine whether the function was written with a
8525     // prototype. This true when:
8526     //   - we're in C++ (where every function has a prototype),
8527     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8528                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8529                                 ConstexprKind, TrailingRequiresClause);
8530   }
8531 }
8532 
8533 enum OpenCLParamType {
8534   ValidKernelParam,
8535   PtrPtrKernelParam,
8536   PtrKernelParam,
8537   InvalidAddrSpacePtrKernelParam,
8538   InvalidKernelParam,
8539   RecordKernelParam
8540 };
8541 
8542 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8543   // Size dependent types are just typedefs to normal integer types
8544   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8545   // integers other than by their names.
8546   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8547 
8548   // Remove typedefs one by one until we reach a typedef
8549   // for a size dependent type.
8550   QualType DesugaredTy = Ty;
8551   do {
8552     ArrayRef<StringRef> Names(SizeTypeNames);
8553     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8554     if (Names.end() != Match)
8555       return true;
8556 
8557     Ty = DesugaredTy;
8558     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8559   } while (DesugaredTy != Ty);
8560 
8561   return false;
8562 }
8563 
8564 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8565   if (PT->isPointerType()) {
8566     QualType PointeeType = PT->getPointeeType();
8567     if (PointeeType->isPointerType())
8568       return PtrPtrKernelParam;
8569     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8570         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8571         PointeeType.getAddressSpace() == LangAS::Default)
8572       return InvalidAddrSpacePtrKernelParam;
8573     return PtrKernelParam;
8574   }
8575 
8576   // OpenCL v1.2 s6.9.k:
8577   // Arguments to kernel functions in a program cannot be declared with the
8578   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8579   // uintptr_t or a struct and/or union that contain fields declared to be one
8580   // of these built-in scalar types.
8581   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8582     return InvalidKernelParam;
8583 
8584   if (PT->isImageType())
8585     return PtrKernelParam;
8586 
8587   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8588     return InvalidKernelParam;
8589 
8590   // OpenCL extension spec v1.2 s9.5:
8591   // This extension adds support for half scalar and vector types as built-in
8592   // types that can be used for arithmetic operations, conversions etc.
8593   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8594     return InvalidKernelParam;
8595 
8596   if (PT->isRecordType())
8597     return RecordKernelParam;
8598 
8599   // Look into an array argument to check if it has a forbidden type.
8600   if (PT->isArrayType()) {
8601     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8602     // Call ourself to check an underlying type of an array. Since the
8603     // getPointeeOrArrayElementType returns an innermost type which is not an
8604     // array, this recursive call only happens once.
8605     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8606   }
8607 
8608   return ValidKernelParam;
8609 }
8610 
8611 static void checkIsValidOpenCLKernelParameter(
8612   Sema &S,
8613   Declarator &D,
8614   ParmVarDecl *Param,
8615   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8616   QualType PT = Param->getType();
8617 
8618   // Cache the valid types we encounter to avoid rechecking structs that are
8619   // used again
8620   if (ValidTypes.count(PT.getTypePtr()))
8621     return;
8622 
8623   switch (getOpenCLKernelParameterType(S, PT)) {
8624   case PtrPtrKernelParam:
8625     // OpenCL v1.2 s6.9.a:
8626     // A kernel function argument cannot be declared as a
8627     // pointer to a pointer type.
8628     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8629     D.setInvalidType();
8630     return;
8631 
8632   case InvalidAddrSpacePtrKernelParam:
8633     // OpenCL v1.0 s6.5:
8634     // __kernel function arguments declared to be a pointer of a type can point
8635     // to one of the following address spaces only : __global, __local or
8636     // __constant.
8637     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8638     D.setInvalidType();
8639     return;
8640 
8641     // OpenCL v1.2 s6.9.k:
8642     // Arguments to kernel functions in a program cannot be declared with the
8643     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8644     // uintptr_t or a struct and/or union that contain fields declared to be
8645     // one of these built-in scalar types.
8646 
8647   case InvalidKernelParam:
8648     // OpenCL v1.2 s6.8 n:
8649     // A kernel function argument cannot be declared
8650     // of event_t type.
8651     // Do not diagnose half type since it is diagnosed as invalid argument
8652     // type for any function elsewhere.
8653     if (!PT->isHalfType()) {
8654       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8655 
8656       // Explain what typedefs are involved.
8657       const TypedefType *Typedef = nullptr;
8658       while ((Typedef = PT->getAs<TypedefType>())) {
8659         SourceLocation Loc = Typedef->getDecl()->getLocation();
8660         // SourceLocation may be invalid for a built-in type.
8661         if (Loc.isValid())
8662           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8663         PT = Typedef->desugar();
8664       }
8665     }
8666 
8667     D.setInvalidType();
8668     return;
8669 
8670   case PtrKernelParam:
8671   case ValidKernelParam:
8672     ValidTypes.insert(PT.getTypePtr());
8673     return;
8674 
8675   case RecordKernelParam:
8676     break;
8677   }
8678 
8679   // Track nested structs we will inspect
8680   SmallVector<const Decl *, 4> VisitStack;
8681 
8682   // Track where we are in the nested structs. Items will migrate from
8683   // VisitStack to HistoryStack as we do the DFS for bad field.
8684   SmallVector<const FieldDecl *, 4> HistoryStack;
8685   HistoryStack.push_back(nullptr);
8686 
8687   // At this point we already handled everything except of a RecordType or
8688   // an ArrayType of a RecordType.
8689   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8690   const RecordType *RecTy =
8691       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8692   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8693 
8694   VisitStack.push_back(RecTy->getDecl());
8695   assert(VisitStack.back() && "First decl null?");
8696 
8697   do {
8698     const Decl *Next = VisitStack.pop_back_val();
8699     if (!Next) {
8700       assert(!HistoryStack.empty());
8701       // Found a marker, we have gone up a level
8702       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8703         ValidTypes.insert(Hist->getType().getTypePtr());
8704 
8705       continue;
8706     }
8707 
8708     // Adds everything except the original parameter declaration (which is not a
8709     // field itself) to the history stack.
8710     const RecordDecl *RD;
8711     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8712       HistoryStack.push_back(Field);
8713 
8714       QualType FieldTy = Field->getType();
8715       // Other field types (known to be valid or invalid) are handled while we
8716       // walk around RecordDecl::fields().
8717       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8718              "Unexpected type.");
8719       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8720 
8721       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8722     } else {
8723       RD = cast<RecordDecl>(Next);
8724     }
8725 
8726     // Add a null marker so we know when we've gone back up a level
8727     VisitStack.push_back(nullptr);
8728 
8729     for (const auto *FD : RD->fields()) {
8730       QualType QT = FD->getType();
8731 
8732       if (ValidTypes.count(QT.getTypePtr()))
8733         continue;
8734 
8735       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8736       if (ParamType == ValidKernelParam)
8737         continue;
8738 
8739       if (ParamType == RecordKernelParam) {
8740         VisitStack.push_back(FD);
8741         continue;
8742       }
8743 
8744       // OpenCL v1.2 s6.9.p:
8745       // Arguments to kernel functions that are declared to be a struct or union
8746       // do not allow OpenCL objects to be passed as elements of the struct or
8747       // union.
8748       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8749           ParamType == InvalidAddrSpacePtrKernelParam) {
8750         S.Diag(Param->getLocation(),
8751                diag::err_record_with_pointers_kernel_param)
8752           << PT->isUnionType()
8753           << PT;
8754       } else {
8755         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8756       }
8757 
8758       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8759           << OrigRecDecl->getDeclName();
8760 
8761       // We have an error, now let's go back up through history and show where
8762       // the offending field came from
8763       for (ArrayRef<const FieldDecl *>::const_iterator
8764                I = HistoryStack.begin() + 1,
8765                E = HistoryStack.end();
8766            I != E; ++I) {
8767         const FieldDecl *OuterField = *I;
8768         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8769           << OuterField->getType();
8770       }
8771 
8772       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8773         << QT->isPointerType()
8774         << QT;
8775       D.setInvalidType();
8776       return;
8777     }
8778   } while (!VisitStack.empty());
8779 }
8780 
8781 /// Find the DeclContext in which a tag is implicitly declared if we see an
8782 /// elaborated type specifier in the specified context, and lookup finds
8783 /// nothing.
8784 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8785   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8786     DC = DC->getParent();
8787   return DC;
8788 }
8789 
8790 /// Find the Scope in which a tag is implicitly declared if we see an
8791 /// elaborated type specifier in the specified context, and lookup finds
8792 /// nothing.
8793 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8794   while (S->isClassScope() ||
8795          (LangOpts.CPlusPlus &&
8796           S->isFunctionPrototypeScope()) ||
8797          ((S->getFlags() & Scope::DeclScope) == 0) ||
8798          (S->getEntity() && S->getEntity()->isTransparentContext()))
8799     S = S->getParent();
8800   return S;
8801 }
8802 
8803 NamedDecl*
8804 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8805                               TypeSourceInfo *TInfo, LookupResult &Previous,
8806                               MultiTemplateParamsArg TemplateParamListsRef,
8807                               bool &AddToScope) {
8808   QualType R = TInfo->getType();
8809 
8810   assert(R->isFunctionType());
8811   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8812     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8813 
8814   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8815   for (TemplateParameterList *TPL : TemplateParamListsRef)
8816     TemplateParamLists.push_back(TPL);
8817   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8818     if (!TemplateParamLists.empty() &&
8819         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8820       TemplateParamLists.back() = Invented;
8821     else
8822       TemplateParamLists.push_back(Invented);
8823   }
8824 
8825   // TODO: consider using NameInfo for diagnostic.
8826   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8827   DeclarationName Name = NameInfo.getName();
8828   StorageClass SC = getFunctionStorageClass(*this, D);
8829 
8830   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8831     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8832          diag::err_invalid_thread)
8833       << DeclSpec::getSpecifierName(TSCS);
8834 
8835   if (D.isFirstDeclarationOfMember())
8836     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8837                            D.getIdentifierLoc());
8838 
8839   bool isFriend = false;
8840   FunctionTemplateDecl *FunctionTemplate = nullptr;
8841   bool isMemberSpecialization = false;
8842   bool isFunctionTemplateSpecialization = false;
8843 
8844   bool isDependentClassScopeExplicitSpecialization = false;
8845   bool HasExplicitTemplateArgs = false;
8846   TemplateArgumentListInfo TemplateArgs;
8847 
8848   bool isVirtualOkay = false;
8849 
8850   DeclContext *OriginalDC = DC;
8851   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8852 
8853   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8854                                               isVirtualOkay);
8855   if (!NewFD) return nullptr;
8856 
8857   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8858     NewFD->setTopLevelDeclInObjCContainer();
8859 
8860   // Set the lexical context. If this is a function-scope declaration, or has a
8861   // C++ scope specifier, or is the object of a friend declaration, the lexical
8862   // context will be different from the semantic context.
8863   NewFD->setLexicalDeclContext(CurContext);
8864 
8865   if (IsLocalExternDecl)
8866     NewFD->setLocalExternDecl();
8867 
8868   if (getLangOpts().CPlusPlus) {
8869     bool isInline = D.getDeclSpec().isInlineSpecified();
8870     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8871     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8872     isFriend = D.getDeclSpec().isFriendSpecified();
8873     if (isFriend && !isInline && D.isFunctionDefinition()) {
8874       // C++ [class.friend]p5
8875       //   A function can be defined in a friend declaration of a
8876       //   class . . . . Such a function is implicitly inline.
8877       NewFD->setImplicitlyInline();
8878     }
8879 
8880     // If this is a method defined in an __interface, and is not a constructor
8881     // or an overloaded operator, then set the pure flag (isVirtual will already
8882     // return true).
8883     if (const CXXRecordDecl *Parent =
8884           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8885       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8886         NewFD->setPure(true);
8887 
8888       // C++ [class.union]p2
8889       //   A union can have member functions, but not virtual functions.
8890       if (isVirtual && Parent->isUnion())
8891         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8892     }
8893 
8894     SetNestedNameSpecifier(*this, NewFD, D);
8895     isMemberSpecialization = false;
8896     isFunctionTemplateSpecialization = false;
8897     if (D.isInvalidType())
8898       NewFD->setInvalidDecl();
8899 
8900     // Match up the template parameter lists with the scope specifier, then
8901     // determine whether we have a template or a template specialization.
8902     bool Invalid = false;
8903     TemplateParameterList *TemplateParams =
8904         MatchTemplateParametersToScopeSpecifier(
8905             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8906             D.getCXXScopeSpec(),
8907             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8908                 ? D.getName().TemplateId
8909                 : nullptr,
8910             TemplateParamLists, isFriend, isMemberSpecialization,
8911             Invalid);
8912     if (TemplateParams) {
8913       if (TemplateParams->size() > 0) {
8914         // This is a function template
8915 
8916         // Check that we can declare a template here.
8917         if (CheckTemplateDeclScope(S, TemplateParams))
8918           NewFD->setInvalidDecl();
8919 
8920         // A destructor cannot be a template.
8921         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8922           Diag(NewFD->getLocation(), diag::err_destructor_template);
8923           NewFD->setInvalidDecl();
8924         }
8925 
8926         // If we're adding a template to a dependent context, we may need to
8927         // rebuilding some of the types used within the template parameter list,
8928         // now that we know what the current instantiation is.
8929         if (DC->isDependentContext()) {
8930           ContextRAII SavedContext(*this, DC);
8931           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8932             Invalid = true;
8933         }
8934 
8935         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8936                                                         NewFD->getLocation(),
8937                                                         Name, TemplateParams,
8938                                                         NewFD);
8939         FunctionTemplate->setLexicalDeclContext(CurContext);
8940         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8941 
8942         // For source fidelity, store the other template param lists.
8943         if (TemplateParamLists.size() > 1) {
8944           NewFD->setTemplateParameterListsInfo(Context,
8945               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8946                   .drop_back(1));
8947         }
8948       } else {
8949         // This is a function template specialization.
8950         isFunctionTemplateSpecialization = true;
8951         // For source fidelity, store all the template param lists.
8952         if (TemplateParamLists.size() > 0)
8953           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8954 
8955         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8956         if (isFriend) {
8957           // We want to remove the "template<>", found here.
8958           SourceRange RemoveRange = TemplateParams->getSourceRange();
8959 
8960           // If we remove the template<> and the name is not a
8961           // template-id, we're actually silently creating a problem:
8962           // the friend declaration will refer to an untemplated decl,
8963           // and clearly the user wants a template specialization.  So
8964           // we need to insert '<>' after the name.
8965           SourceLocation InsertLoc;
8966           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8967             InsertLoc = D.getName().getSourceRange().getEnd();
8968             InsertLoc = getLocForEndOfToken(InsertLoc);
8969           }
8970 
8971           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8972             << Name << RemoveRange
8973             << FixItHint::CreateRemoval(RemoveRange)
8974             << FixItHint::CreateInsertion(InsertLoc, "<>");
8975         }
8976       }
8977     } else {
8978       // All template param lists were matched against the scope specifier:
8979       // this is NOT (an explicit specialization of) a template.
8980       if (TemplateParamLists.size() > 0)
8981         // For source fidelity, store all the template param lists.
8982         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8983     }
8984 
8985     if (Invalid) {
8986       NewFD->setInvalidDecl();
8987       if (FunctionTemplate)
8988         FunctionTemplate->setInvalidDecl();
8989     }
8990 
8991     // C++ [dcl.fct.spec]p5:
8992     //   The virtual specifier shall only be used in declarations of
8993     //   nonstatic class member functions that appear within a
8994     //   member-specification of a class declaration; see 10.3.
8995     //
8996     if (isVirtual && !NewFD->isInvalidDecl()) {
8997       if (!isVirtualOkay) {
8998         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8999              diag::err_virtual_non_function);
9000       } else if (!CurContext->isRecord()) {
9001         // 'virtual' was specified outside of the class.
9002         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9003              diag::err_virtual_out_of_class)
9004           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9005       } else if (NewFD->getDescribedFunctionTemplate()) {
9006         // C++ [temp.mem]p3:
9007         //  A member function template shall not be virtual.
9008         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9009              diag::err_virtual_member_function_template)
9010           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9011       } else {
9012         // Okay: Add virtual to the method.
9013         NewFD->setVirtualAsWritten(true);
9014       }
9015 
9016       if (getLangOpts().CPlusPlus14 &&
9017           NewFD->getReturnType()->isUndeducedType())
9018         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9019     }
9020 
9021     if (getLangOpts().CPlusPlus14 &&
9022         (NewFD->isDependentContext() ||
9023          (isFriend && CurContext->isDependentContext())) &&
9024         NewFD->getReturnType()->isUndeducedType()) {
9025       // If the function template is referenced directly (for instance, as a
9026       // member of the current instantiation), pretend it has a dependent type.
9027       // This is not really justified by the standard, but is the only sane
9028       // thing to do.
9029       // FIXME: For a friend function, we have not marked the function as being
9030       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9031       const FunctionProtoType *FPT =
9032           NewFD->getType()->castAs<FunctionProtoType>();
9033       QualType Result =
9034           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9035       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9036                                              FPT->getExtProtoInfo()));
9037     }
9038 
9039     // C++ [dcl.fct.spec]p3:
9040     //  The inline specifier shall not appear on a block scope function
9041     //  declaration.
9042     if (isInline && !NewFD->isInvalidDecl()) {
9043       if (CurContext->isFunctionOrMethod()) {
9044         // 'inline' is not allowed on block scope function declaration.
9045         Diag(D.getDeclSpec().getInlineSpecLoc(),
9046              diag::err_inline_declaration_block_scope) << Name
9047           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9048       }
9049     }
9050 
9051     // C++ [dcl.fct.spec]p6:
9052     //  The explicit specifier shall be used only in the declaration of a
9053     //  constructor or conversion function within its class definition;
9054     //  see 12.3.1 and 12.3.2.
9055     if (hasExplicit && !NewFD->isInvalidDecl() &&
9056         !isa<CXXDeductionGuideDecl>(NewFD)) {
9057       if (!CurContext->isRecord()) {
9058         // 'explicit' was specified outside of the class.
9059         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9060              diag::err_explicit_out_of_class)
9061             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9062       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9063                  !isa<CXXConversionDecl>(NewFD)) {
9064         // 'explicit' was specified on a function that wasn't a constructor
9065         // or conversion function.
9066         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9067              diag::err_explicit_non_ctor_or_conv_function)
9068             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9069       }
9070     }
9071 
9072     if (ConstexprSpecKind ConstexprKind =
9073             D.getDeclSpec().getConstexprSpecifier()) {
9074       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9075       // are implicitly inline.
9076       NewFD->setImplicitlyInline();
9077 
9078       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9079       // be either constructors or to return a literal type. Therefore,
9080       // destructors cannot be declared constexpr.
9081       if (isa<CXXDestructorDecl>(NewFD) &&
9082           (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9083         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9084             << ConstexprKind;
9085         NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9086       }
9087       // C++20 [dcl.constexpr]p2: An allocation function, or a
9088       // deallocation function shall not be declared with the consteval
9089       // specifier.
9090       if (ConstexprKind == CSK_consteval &&
9091           (NewFD->getOverloadedOperator() == OO_New ||
9092            NewFD->getOverloadedOperator() == OO_Array_New ||
9093            NewFD->getOverloadedOperator() == OO_Delete ||
9094            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9095         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9096              diag::err_invalid_consteval_decl_kind)
9097             << NewFD;
9098         NewFD->setConstexprKind(CSK_constexpr);
9099       }
9100     }
9101 
9102     // If __module_private__ was specified, mark the function accordingly.
9103     if (D.getDeclSpec().isModulePrivateSpecified()) {
9104       if (isFunctionTemplateSpecialization) {
9105         SourceLocation ModulePrivateLoc
9106           = D.getDeclSpec().getModulePrivateSpecLoc();
9107         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9108           << 0
9109           << FixItHint::CreateRemoval(ModulePrivateLoc);
9110       } else {
9111         NewFD->setModulePrivate();
9112         if (FunctionTemplate)
9113           FunctionTemplate->setModulePrivate();
9114       }
9115     }
9116 
9117     if (isFriend) {
9118       if (FunctionTemplate) {
9119         FunctionTemplate->setObjectOfFriendDecl();
9120         FunctionTemplate->setAccess(AS_public);
9121       }
9122       NewFD->setObjectOfFriendDecl();
9123       NewFD->setAccess(AS_public);
9124     }
9125 
9126     // If a function is defined as defaulted or deleted, mark it as such now.
9127     // We'll do the relevant checks on defaulted / deleted functions later.
9128     switch (D.getFunctionDefinitionKind()) {
9129       case FDK_Declaration:
9130       case FDK_Definition:
9131         break;
9132 
9133       case FDK_Defaulted:
9134         NewFD->setDefaulted();
9135         break;
9136 
9137       case FDK_Deleted:
9138         NewFD->setDeletedAsWritten();
9139         break;
9140     }
9141 
9142     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9143         D.isFunctionDefinition()) {
9144       // C++ [class.mfct]p2:
9145       //   A member function may be defined (8.4) in its class definition, in
9146       //   which case it is an inline member function (7.1.2)
9147       NewFD->setImplicitlyInline();
9148     }
9149 
9150     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9151         !CurContext->isRecord()) {
9152       // C++ [class.static]p1:
9153       //   A data or function member of a class may be declared static
9154       //   in a class definition, in which case it is a static member of
9155       //   the class.
9156 
9157       // Complain about the 'static' specifier if it's on an out-of-line
9158       // member function definition.
9159 
9160       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9161       // member function template declaration and class member template
9162       // declaration (MSVC versions before 2015), warn about this.
9163       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9164            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9165              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9166            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9167            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9168         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9169     }
9170 
9171     // C++11 [except.spec]p15:
9172     //   A deallocation function with no exception-specification is treated
9173     //   as if it were specified with noexcept(true).
9174     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9175     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9176          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9177         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9178       NewFD->setType(Context.getFunctionType(
9179           FPT->getReturnType(), FPT->getParamTypes(),
9180           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9181   }
9182 
9183   // Filter out previous declarations that don't match the scope.
9184   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9185                        D.getCXXScopeSpec().isNotEmpty() ||
9186                        isMemberSpecialization ||
9187                        isFunctionTemplateSpecialization);
9188 
9189   // Handle GNU asm-label extension (encoded as an attribute).
9190   if (Expr *E = (Expr*) D.getAsmLabel()) {
9191     // The parser guarantees this is a string.
9192     StringLiteral *SE = cast<StringLiteral>(E);
9193     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9194                                         /*IsLiteralLabel=*/true,
9195                                         SE->getStrTokenLoc(0)));
9196   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9197     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9198       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9199     if (I != ExtnameUndeclaredIdentifiers.end()) {
9200       if (isDeclExternC(NewFD)) {
9201         NewFD->addAttr(I->second);
9202         ExtnameUndeclaredIdentifiers.erase(I);
9203       } else
9204         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9205             << /*Variable*/0 << NewFD;
9206     }
9207   }
9208 
9209   // Copy the parameter declarations from the declarator D to the function
9210   // declaration NewFD, if they are available.  First scavenge them into Params.
9211   SmallVector<ParmVarDecl*, 16> Params;
9212   unsigned FTIIdx;
9213   if (D.isFunctionDeclarator(FTIIdx)) {
9214     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9215 
9216     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9217     // function that takes no arguments, not a function that takes a
9218     // single void argument.
9219     // We let through "const void" here because Sema::GetTypeForDeclarator
9220     // already checks for that case.
9221     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9222       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9223         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9224         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9225         Param->setDeclContext(NewFD);
9226         Params.push_back(Param);
9227 
9228         if (Param->isInvalidDecl())
9229           NewFD->setInvalidDecl();
9230       }
9231     }
9232 
9233     if (!getLangOpts().CPlusPlus) {
9234       // In C, find all the tag declarations from the prototype and move them
9235       // into the function DeclContext. Remove them from the surrounding tag
9236       // injection context of the function, which is typically but not always
9237       // the TU.
9238       DeclContext *PrototypeTagContext =
9239           getTagInjectionContext(NewFD->getLexicalDeclContext());
9240       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9241         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9242 
9243         // We don't want to reparent enumerators. Look at their parent enum
9244         // instead.
9245         if (!TD) {
9246           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9247             TD = cast<EnumDecl>(ECD->getDeclContext());
9248         }
9249         if (!TD)
9250           continue;
9251         DeclContext *TagDC = TD->getLexicalDeclContext();
9252         if (!TagDC->containsDecl(TD))
9253           continue;
9254         TagDC->removeDecl(TD);
9255         TD->setDeclContext(NewFD);
9256         NewFD->addDecl(TD);
9257 
9258         // Preserve the lexical DeclContext if it is not the surrounding tag
9259         // injection context of the FD. In this example, the semantic context of
9260         // E will be f and the lexical context will be S, while both the
9261         // semantic and lexical contexts of S will be f:
9262         //   void f(struct S { enum E { a } f; } s);
9263         if (TagDC != PrototypeTagContext)
9264           TD->setLexicalDeclContext(TagDC);
9265       }
9266     }
9267   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9268     // When we're declaring a function with a typedef, typeof, etc as in the
9269     // following example, we'll need to synthesize (unnamed)
9270     // parameters for use in the declaration.
9271     //
9272     // @code
9273     // typedef void fn(int);
9274     // fn f;
9275     // @endcode
9276 
9277     // Synthesize a parameter for each argument type.
9278     for (const auto &AI : FT->param_types()) {
9279       ParmVarDecl *Param =
9280           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9281       Param->setScopeInfo(0, Params.size());
9282       Params.push_back(Param);
9283     }
9284   } else {
9285     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9286            "Should not need args for typedef of non-prototype fn");
9287   }
9288 
9289   // Finally, we know we have the right number of parameters, install them.
9290   NewFD->setParams(Params);
9291 
9292   if (D.getDeclSpec().isNoreturnSpecified())
9293     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9294                                            D.getDeclSpec().getNoreturnSpecLoc(),
9295                                            AttributeCommonInfo::AS_Keyword));
9296 
9297   // Functions returning a variably modified type violate C99 6.7.5.2p2
9298   // because all functions have linkage.
9299   if (!NewFD->isInvalidDecl() &&
9300       NewFD->getReturnType()->isVariablyModifiedType()) {
9301     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9302     NewFD->setInvalidDecl();
9303   }
9304 
9305   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9306   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9307       !NewFD->hasAttr<SectionAttr>())
9308     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9309         Context, PragmaClangTextSection.SectionName,
9310         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9311 
9312   // Apply an implicit SectionAttr if #pragma code_seg is active.
9313   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9314       !NewFD->hasAttr<SectionAttr>()) {
9315     NewFD->addAttr(SectionAttr::CreateImplicit(
9316         Context, CodeSegStack.CurrentValue->getString(),
9317         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9318         SectionAttr::Declspec_allocate));
9319     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9320                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9321                          ASTContext::PSF_Read,
9322                      NewFD))
9323       NewFD->dropAttr<SectionAttr>();
9324   }
9325 
9326   // Apply an implicit CodeSegAttr from class declspec or
9327   // apply an implicit SectionAttr from #pragma code_seg if active.
9328   if (!NewFD->hasAttr<CodeSegAttr>()) {
9329     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9330                                                                  D.isFunctionDefinition())) {
9331       NewFD->addAttr(SAttr);
9332     }
9333   }
9334 
9335   // Handle attributes.
9336   ProcessDeclAttributes(S, NewFD, D);
9337 
9338   if (getLangOpts().OpenCL) {
9339     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9340     // type declaration will generate a compilation error.
9341     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9342     if (AddressSpace != LangAS::Default) {
9343       Diag(NewFD->getLocation(),
9344            diag::err_opencl_return_value_with_address_space);
9345       NewFD->setInvalidDecl();
9346     }
9347   }
9348 
9349   if (!getLangOpts().CPlusPlus) {
9350     // Perform semantic checking on the function declaration.
9351     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9352       CheckMain(NewFD, D.getDeclSpec());
9353 
9354     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9355       CheckMSVCRTEntryPoint(NewFD);
9356 
9357     if (!NewFD->isInvalidDecl())
9358       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9359                                                   isMemberSpecialization));
9360     else if (!Previous.empty())
9361       // Recover gracefully from an invalid redeclaration.
9362       D.setRedeclaration(true);
9363     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9364             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9365            "previous declaration set still overloaded");
9366 
9367     // Diagnose no-prototype function declarations with calling conventions that
9368     // don't support variadic calls. Only do this in C and do it after merging
9369     // possibly prototyped redeclarations.
9370     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9371     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9372       CallingConv CC = FT->getExtInfo().getCC();
9373       if (!supportsVariadicCall(CC)) {
9374         // Windows system headers sometimes accidentally use stdcall without
9375         // (void) parameters, so we relax this to a warning.
9376         int DiagID =
9377             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9378         Diag(NewFD->getLocation(), DiagID)
9379             << FunctionType::getNameForCallConv(CC);
9380       }
9381     }
9382 
9383    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9384        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9385      checkNonTrivialCUnion(NewFD->getReturnType(),
9386                            NewFD->getReturnTypeSourceRange().getBegin(),
9387                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9388   } else {
9389     // C++11 [replacement.functions]p3:
9390     //  The program's definitions shall not be specified as inline.
9391     //
9392     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9393     //
9394     // Suppress the diagnostic if the function is __attribute__((used)), since
9395     // that forces an external definition to be emitted.
9396     if (D.getDeclSpec().isInlineSpecified() &&
9397         NewFD->isReplaceableGlobalAllocationFunction() &&
9398         !NewFD->hasAttr<UsedAttr>())
9399       Diag(D.getDeclSpec().getInlineSpecLoc(),
9400            diag::ext_operator_new_delete_declared_inline)
9401         << NewFD->getDeclName();
9402 
9403     // If the declarator is a template-id, translate the parser's template
9404     // argument list into our AST format.
9405     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9406       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9407       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9408       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9409       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9410                                          TemplateId->NumArgs);
9411       translateTemplateArguments(TemplateArgsPtr,
9412                                  TemplateArgs);
9413 
9414       HasExplicitTemplateArgs = true;
9415 
9416       if (NewFD->isInvalidDecl()) {
9417         HasExplicitTemplateArgs = false;
9418       } else if (FunctionTemplate) {
9419         // Function template with explicit template arguments.
9420         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9421           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9422 
9423         HasExplicitTemplateArgs = false;
9424       } else {
9425         assert((isFunctionTemplateSpecialization ||
9426                 D.getDeclSpec().isFriendSpecified()) &&
9427                "should have a 'template<>' for this decl");
9428         // "friend void foo<>(int);" is an implicit specialization decl.
9429         isFunctionTemplateSpecialization = true;
9430       }
9431     } else if (isFriend && isFunctionTemplateSpecialization) {
9432       // This combination is only possible in a recovery case;  the user
9433       // wrote something like:
9434       //   template <> friend void foo(int);
9435       // which we're recovering from as if the user had written:
9436       //   friend void foo<>(int);
9437       // Go ahead and fake up a template id.
9438       HasExplicitTemplateArgs = true;
9439       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9440       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9441     }
9442 
9443     // We do not add HD attributes to specializations here because
9444     // they may have different constexpr-ness compared to their
9445     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9446     // may end up with different effective targets. Instead, a
9447     // specialization inherits its target attributes from its template
9448     // in the CheckFunctionTemplateSpecialization() call below.
9449     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9450       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9451 
9452     // If it's a friend (and only if it's a friend), it's possible
9453     // that either the specialized function type or the specialized
9454     // template is dependent, and therefore matching will fail.  In
9455     // this case, don't check the specialization yet.
9456     bool InstantiationDependent = false;
9457     if (isFunctionTemplateSpecialization && isFriend &&
9458         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9459          TemplateSpecializationType::anyDependentTemplateArguments(
9460             TemplateArgs,
9461             InstantiationDependent))) {
9462       assert(HasExplicitTemplateArgs &&
9463              "friend function specialization without template args");
9464       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9465                                                        Previous))
9466         NewFD->setInvalidDecl();
9467     } else if (isFunctionTemplateSpecialization) {
9468       if (CurContext->isDependentContext() && CurContext->isRecord()
9469           && !isFriend) {
9470         isDependentClassScopeExplicitSpecialization = true;
9471       } else if (!NewFD->isInvalidDecl() &&
9472                  CheckFunctionTemplateSpecialization(
9473                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9474                      Previous))
9475         NewFD->setInvalidDecl();
9476 
9477       // C++ [dcl.stc]p1:
9478       //   A storage-class-specifier shall not be specified in an explicit
9479       //   specialization (14.7.3)
9480       FunctionTemplateSpecializationInfo *Info =
9481           NewFD->getTemplateSpecializationInfo();
9482       if (Info && SC != SC_None) {
9483         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9484           Diag(NewFD->getLocation(),
9485                diag::err_explicit_specialization_inconsistent_storage_class)
9486             << SC
9487             << FixItHint::CreateRemoval(
9488                                       D.getDeclSpec().getStorageClassSpecLoc());
9489 
9490         else
9491           Diag(NewFD->getLocation(),
9492                diag::ext_explicit_specialization_storage_class)
9493             << FixItHint::CreateRemoval(
9494                                       D.getDeclSpec().getStorageClassSpecLoc());
9495       }
9496     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9497       if (CheckMemberSpecialization(NewFD, Previous))
9498           NewFD->setInvalidDecl();
9499     }
9500 
9501     // Perform semantic checking on the function declaration.
9502     if (!isDependentClassScopeExplicitSpecialization) {
9503       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9504         CheckMain(NewFD, D.getDeclSpec());
9505 
9506       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9507         CheckMSVCRTEntryPoint(NewFD);
9508 
9509       if (!NewFD->isInvalidDecl())
9510         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9511                                                     isMemberSpecialization));
9512       else if (!Previous.empty())
9513         // Recover gracefully from an invalid redeclaration.
9514         D.setRedeclaration(true);
9515     }
9516 
9517     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9518             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9519            "previous declaration set still overloaded");
9520 
9521     NamedDecl *PrincipalDecl = (FunctionTemplate
9522                                 ? cast<NamedDecl>(FunctionTemplate)
9523                                 : NewFD);
9524 
9525     if (isFriend && NewFD->getPreviousDecl()) {
9526       AccessSpecifier Access = AS_public;
9527       if (!NewFD->isInvalidDecl())
9528         Access = NewFD->getPreviousDecl()->getAccess();
9529 
9530       NewFD->setAccess(Access);
9531       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9532     }
9533 
9534     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9535         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9536       PrincipalDecl->setNonMemberOperator();
9537 
9538     // If we have a function template, check the template parameter
9539     // list. This will check and merge default template arguments.
9540     if (FunctionTemplate) {
9541       FunctionTemplateDecl *PrevTemplate =
9542                                      FunctionTemplate->getPreviousDecl();
9543       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9544                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9545                                     : nullptr,
9546                             D.getDeclSpec().isFriendSpecified()
9547                               ? (D.isFunctionDefinition()
9548                                    ? TPC_FriendFunctionTemplateDefinition
9549                                    : TPC_FriendFunctionTemplate)
9550                               : (D.getCXXScopeSpec().isSet() &&
9551                                  DC && DC->isRecord() &&
9552                                  DC->isDependentContext())
9553                                   ? TPC_ClassTemplateMember
9554                                   : TPC_FunctionTemplate);
9555     }
9556 
9557     if (NewFD->isInvalidDecl()) {
9558       // Ignore all the rest of this.
9559     } else if (!D.isRedeclaration()) {
9560       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9561                                        AddToScope };
9562       // Fake up an access specifier if it's supposed to be a class member.
9563       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9564         NewFD->setAccess(AS_public);
9565 
9566       // Qualified decls generally require a previous declaration.
9567       if (D.getCXXScopeSpec().isSet()) {
9568         // ...with the major exception of templated-scope or
9569         // dependent-scope friend declarations.
9570 
9571         // TODO: we currently also suppress this check in dependent
9572         // contexts because (1) the parameter depth will be off when
9573         // matching friend templates and (2) we might actually be
9574         // selecting a friend based on a dependent factor.  But there
9575         // are situations where these conditions don't apply and we
9576         // can actually do this check immediately.
9577         //
9578         // Unless the scope is dependent, it's always an error if qualified
9579         // redeclaration lookup found nothing at all. Diagnose that now;
9580         // nothing will diagnose that error later.
9581         if (isFriend &&
9582             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9583              (!Previous.empty() && CurContext->isDependentContext()))) {
9584           // ignore these
9585         } else {
9586           // The user tried to provide an out-of-line definition for a
9587           // function that is a member of a class or namespace, but there
9588           // was no such member function declared (C++ [class.mfct]p2,
9589           // C++ [namespace.memdef]p2). For example:
9590           //
9591           // class X {
9592           //   void f() const;
9593           // };
9594           //
9595           // void X::f() { } // ill-formed
9596           //
9597           // Complain about this problem, and attempt to suggest close
9598           // matches (e.g., those that differ only in cv-qualifiers and
9599           // whether the parameter types are references).
9600 
9601           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9602                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9603             AddToScope = ExtraArgs.AddToScope;
9604             return Result;
9605           }
9606         }
9607 
9608         // Unqualified local friend declarations are required to resolve
9609         // to something.
9610       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9611         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9612                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9613           AddToScope = ExtraArgs.AddToScope;
9614           return Result;
9615         }
9616       }
9617     } else if (!D.isFunctionDefinition() &&
9618                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9619                !isFriend && !isFunctionTemplateSpecialization &&
9620                !isMemberSpecialization) {
9621       // An out-of-line member function declaration must also be a
9622       // definition (C++ [class.mfct]p2).
9623       // Note that this is not the case for explicit specializations of
9624       // function templates or member functions of class templates, per
9625       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9626       // extension for compatibility with old SWIG code which likes to
9627       // generate them.
9628       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9629         << D.getCXXScopeSpec().getRange();
9630     }
9631   }
9632 
9633   // In C builtins get merged with implicitly lazily created declarations.
9634   // In C++ we need to check if it's a builtin and add the BuiltinAttr here.
9635   if (getLangOpts().CPlusPlus) {
9636     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9637       if (unsigned BuiltinID = II->getBuiltinID()) {
9638         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9639           // Declarations for builtins with custom typechecking by definition
9640           // don't make sense. Don't attempt typechecking and simply add the
9641           // attribute.
9642           if (Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
9643             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9644           } else {
9645             ASTContext::GetBuiltinTypeError Error;
9646             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9647 
9648             if (!Error && !BuiltinType.isNull() &&
9649                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9650                     NewFD->getType(), BuiltinType))
9651               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9652           }
9653         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9654                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9655           // FIXME: We should consider this a builtin only in the std namespace.
9656           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9657         }
9658       }
9659     }
9660   }
9661 
9662   ProcessPragmaWeak(S, NewFD);
9663   checkAttributesAfterMerging(*this, *NewFD);
9664 
9665   AddKnownFunctionAttributes(NewFD);
9666 
9667   if (NewFD->hasAttr<OverloadableAttr>() &&
9668       !NewFD->getType()->getAs<FunctionProtoType>()) {
9669     Diag(NewFD->getLocation(),
9670          diag::err_attribute_overloadable_no_prototype)
9671       << NewFD;
9672 
9673     // Turn this into a variadic function with no parameters.
9674     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9675     FunctionProtoType::ExtProtoInfo EPI(
9676         Context.getDefaultCallingConvention(true, false));
9677     EPI.Variadic = true;
9678     EPI.ExtInfo = FT->getExtInfo();
9679 
9680     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9681     NewFD->setType(R);
9682   }
9683 
9684   // If there's a #pragma GCC visibility in scope, and this isn't a class
9685   // member, set the visibility of this function.
9686   if (!DC->isRecord() && NewFD->isExternallyVisible())
9687     AddPushedVisibilityAttribute(NewFD);
9688 
9689   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9690   // marking the function.
9691   AddCFAuditedAttribute(NewFD);
9692 
9693   // If this is a function definition, check if we have to apply optnone due to
9694   // a pragma.
9695   if(D.isFunctionDefinition())
9696     AddRangeBasedOptnone(NewFD);
9697 
9698   // If this is the first declaration of an extern C variable, update
9699   // the map of such variables.
9700   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9701       isIncompleteDeclExternC(*this, NewFD))
9702     RegisterLocallyScopedExternCDecl(NewFD, S);
9703 
9704   // Set this FunctionDecl's range up to the right paren.
9705   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9706 
9707   if (D.isRedeclaration() && !Previous.empty()) {
9708     NamedDecl *Prev = Previous.getRepresentativeDecl();
9709     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9710                                    isMemberSpecialization ||
9711                                        isFunctionTemplateSpecialization,
9712                                    D.isFunctionDefinition());
9713   }
9714 
9715   if (getLangOpts().CUDA) {
9716     IdentifierInfo *II = NewFD->getIdentifier();
9717     if (II && II->isStr(getCudaConfigureFuncName()) &&
9718         !NewFD->isInvalidDecl() &&
9719         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9720       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9721         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9722             << getCudaConfigureFuncName();
9723       Context.setcudaConfigureCallDecl(NewFD);
9724     }
9725 
9726     // Variadic functions, other than a *declaration* of printf, are not allowed
9727     // in device-side CUDA code, unless someone passed
9728     // -fcuda-allow-variadic-functions.
9729     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9730         (NewFD->hasAttr<CUDADeviceAttr>() ||
9731          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9732         !(II && II->isStr("printf") && NewFD->isExternC() &&
9733           !D.isFunctionDefinition())) {
9734       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9735     }
9736   }
9737 
9738   MarkUnusedFileScopedDecl(NewFD);
9739 
9740 
9741 
9742   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9743     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9744     if ((getLangOpts().OpenCLVersion >= 120)
9745         && (SC == SC_Static)) {
9746       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9747       D.setInvalidType();
9748     }
9749 
9750     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9751     if (!NewFD->getReturnType()->isVoidType()) {
9752       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9753       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9754           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9755                                 : FixItHint());
9756       D.setInvalidType();
9757     }
9758 
9759     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9760     for (auto Param : NewFD->parameters())
9761       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9762 
9763     if (getLangOpts().OpenCLCPlusPlus) {
9764       if (DC->isRecord()) {
9765         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9766         D.setInvalidType();
9767       }
9768       if (FunctionTemplate) {
9769         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9770         D.setInvalidType();
9771       }
9772     }
9773   }
9774 
9775   if (getLangOpts().CPlusPlus) {
9776     if (FunctionTemplate) {
9777       if (NewFD->isInvalidDecl())
9778         FunctionTemplate->setInvalidDecl();
9779       return FunctionTemplate;
9780     }
9781 
9782     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9783       CompleteMemberSpecialization(NewFD, Previous);
9784   }
9785 
9786   for (const ParmVarDecl *Param : NewFD->parameters()) {
9787     QualType PT = Param->getType();
9788 
9789     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9790     // types.
9791     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9792       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9793         QualType ElemTy = PipeTy->getElementType();
9794           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9795             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9796             D.setInvalidType();
9797           }
9798       }
9799     }
9800   }
9801 
9802   // Here we have an function template explicit specialization at class scope.
9803   // The actual specialization will be postponed to template instatiation
9804   // time via the ClassScopeFunctionSpecializationDecl node.
9805   if (isDependentClassScopeExplicitSpecialization) {
9806     ClassScopeFunctionSpecializationDecl *NewSpec =
9807                          ClassScopeFunctionSpecializationDecl::Create(
9808                                 Context, CurContext, NewFD->getLocation(),
9809                                 cast<CXXMethodDecl>(NewFD),
9810                                 HasExplicitTemplateArgs, TemplateArgs);
9811     CurContext->addDecl(NewSpec);
9812     AddToScope = false;
9813   }
9814 
9815   // Diagnose availability attributes. Availability cannot be used on functions
9816   // that are run during load/unload.
9817   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9818     if (NewFD->hasAttr<ConstructorAttr>()) {
9819       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9820           << 1;
9821       NewFD->dropAttr<AvailabilityAttr>();
9822     }
9823     if (NewFD->hasAttr<DestructorAttr>()) {
9824       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9825           << 2;
9826       NewFD->dropAttr<AvailabilityAttr>();
9827     }
9828   }
9829 
9830   // Diagnose no_builtin attribute on function declaration that are not a
9831   // definition.
9832   // FIXME: We should really be doing this in
9833   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9834   // the FunctionDecl and at this point of the code
9835   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9836   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9837   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9838     switch (D.getFunctionDefinitionKind()) {
9839     case FDK_Defaulted:
9840     case FDK_Deleted:
9841       Diag(NBA->getLocation(),
9842            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9843           << NBA->getSpelling();
9844       break;
9845     case FDK_Declaration:
9846       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9847           << NBA->getSpelling();
9848       break;
9849     case FDK_Definition:
9850       break;
9851     }
9852 
9853   return NewFD;
9854 }
9855 
9856 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9857 /// when __declspec(code_seg) "is applied to a class, all member functions of
9858 /// the class and nested classes -- this includes compiler-generated special
9859 /// member functions -- are put in the specified segment."
9860 /// The actual behavior is a little more complicated. The Microsoft compiler
9861 /// won't check outer classes if there is an active value from #pragma code_seg.
9862 /// The CodeSeg is always applied from the direct parent but only from outer
9863 /// classes when the #pragma code_seg stack is empty. See:
9864 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9865 /// available since MS has removed the page.
9866 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9867   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9868   if (!Method)
9869     return nullptr;
9870   const CXXRecordDecl *Parent = Method->getParent();
9871   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9872     Attr *NewAttr = SAttr->clone(S.getASTContext());
9873     NewAttr->setImplicit(true);
9874     return NewAttr;
9875   }
9876 
9877   // The Microsoft compiler won't check outer classes for the CodeSeg
9878   // when the #pragma code_seg stack is active.
9879   if (S.CodeSegStack.CurrentValue)
9880    return nullptr;
9881 
9882   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9883     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9884       Attr *NewAttr = SAttr->clone(S.getASTContext());
9885       NewAttr->setImplicit(true);
9886       return NewAttr;
9887     }
9888   }
9889   return nullptr;
9890 }
9891 
9892 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9893 /// containing class. Otherwise it will return implicit SectionAttr if the
9894 /// function is a definition and there is an active value on CodeSegStack
9895 /// (from the current #pragma code-seg value).
9896 ///
9897 /// \param FD Function being declared.
9898 /// \param IsDefinition Whether it is a definition or just a declarartion.
9899 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9900 ///          nullptr if no attribute should be added.
9901 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9902                                                        bool IsDefinition) {
9903   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9904     return A;
9905   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9906       CodeSegStack.CurrentValue)
9907     return SectionAttr::CreateImplicit(
9908         getASTContext(), CodeSegStack.CurrentValue->getString(),
9909         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9910         SectionAttr::Declspec_allocate);
9911   return nullptr;
9912 }
9913 
9914 /// Determines if we can perform a correct type check for \p D as a
9915 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9916 /// best-effort check.
9917 ///
9918 /// \param NewD The new declaration.
9919 /// \param OldD The old declaration.
9920 /// \param NewT The portion of the type of the new declaration to check.
9921 /// \param OldT The portion of the type of the old declaration to check.
9922 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9923                                           QualType NewT, QualType OldT) {
9924   if (!NewD->getLexicalDeclContext()->isDependentContext())
9925     return true;
9926 
9927   // For dependently-typed local extern declarations and friends, we can't
9928   // perform a correct type check in general until instantiation:
9929   //
9930   //   int f();
9931   //   template<typename T> void g() { T f(); }
9932   //
9933   // (valid if g() is only instantiated with T = int).
9934   if (NewT->isDependentType() &&
9935       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9936     return false;
9937 
9938   // Similarly, if the previous declaration was a dependent local extern
9939   // declaration, we don't really know its type yet.
9940   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9941     return false;
9942 
9943   return true;
9944 }
9945 
9946 /// Checks if the new declaration declared in dependent context must be
9947 /// put in the same redeclaration chain as the specified declaration.
9948 ///
9949 /// \param D Declaration that is checked.
9950 /// \param PrevDecl Previous declaration found with proper lookup method for the
9951 ///                 same declaration name.
9952 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9953 ///          belongs to.
9954 ///
9955 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9956   if (!D->getLexicalDeclContext()->isDependentContext())
9957     return true;
9958 
9959   // Don't chain dependent friend function definitions until instantiation, to
9960   // permit cases like
9961   //
9962   //   void func();
9963   //   template<typename T> class C1 { friend void func() {} };
9964   //   template<typename T> class C2 { friend void func() {} };
9965   //
9966   // ... which is valid if only one of C1 and C2 is ever instantiated.
9967   //
9968   // FIXME: This need only apply to function definitions. For now, we proxy
9969   // this by checking for a file-scope function. We do not want this to apply
9970   // to friend declarations nominating member functions, because that gets in
9971   // the way of access checks.
9972   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9973     return false;
9974 
9975   auto *VD = dyn_cast<ValueDecl>(D);
9976   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9977   return !VD || !PrevVD ||
9978          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9979                                         PrevVD->getType());
9980 }
9981 
9982 /// Check the target attribute of the function for MultiVersion
9983 /// validity.
9984 ///
9985 /// Returns true if there was an error, false otherwise.
9986 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9987   const auto *TA = FD->getAttr<TargetAttr>();
9988   assert(TA && "MultiVersion Candidate requires a target attribute");
9989   ParsedTargetAttr ParseInfo = TA->parse();
9990   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9991   enum ErrType { Feature = 0, Architecture = 1 };
9992 
9993   if (!ParseInfo.Architecture.empty() &&
9994       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9995     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9996         << Architecture << ParseInfo.Architecture;
9997     return true;
9998   }
9999 
10000   for (const auto &Feat : ParseInfo.Features) {
10001     auto BareFeat = StringRef{Feat}.substr(1);
10002     if (Feat[0] == '-') {
10003       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10004           << Feature << ("no-" + BareFeat).str();
10005       return true;
10006     }
10007 
10008     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10009         !TargetInfo.isValidFeatureName(BareFeat)) {
10010       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10011           << Feature << BareFeat;
10012       return true;
10013     }
10014   }
10015   return false;
10016 }
10017 
10018 // Provide a white-list of attributes that are allowed to be combined with
10019 // multiversion functions.
10020 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10021                                            MultiVersionKind MVType) {
10022   switch (Kind) {
10023   default:
10024     return false;
10025   case attr::Used:
10026     return MVType == MultiVersionKind::Target;
10027   }
10028 }
10029 
10030 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
10031                                          MultiVersionKind MVType) {
10032   for (const Attr *A : FD->attrs()) {
10033     switch (A->getKind()) {
10034     case attr::CPUDispatch:
10035     case attr::CPUSpecific:
10036       if (MVType != MultiVersionKind::CPUDispatch &&
10037           MVType != MultiVersionKind::CPUSpecific)
10038         return true;
10039       break;
10040     case attr::Target:
10041       if (MVType != MultiVersionKind::Target)
10042         return true;
10043       break;
10044     default:
10045       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10046         return true;
10047       break;
10048     }
10049   }
10050   return false;
10051 }
10052 
10053 bool Sema::areMultiversionVariantFunctionsCompatible(
10054     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10055     const PartialDiagnostic &NoProtoDiagID,
10056     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10057     const PartialDiagnosticAt &NoSupportDiagIDAt,
10058     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10059     bool ConstexprSupported, bool CLinkageMayDiffer) {
10060   enum DoesntSupport {
10061     FuncTemplates = 0,
10062     VirtFuncs = 1,
10063     DeducedReturn = 2,
10064     Constructors = 3,
10065     Destructors = 4,
10066     DeletedFuncs = 5,
10067     DefaultedFuncs = 6,
10068     ConstexprFuncs = 7,
10069     ConstevalFuncs = 8,
10070   };
10071   enum Different {
10072     CallingConv = 0,
10073     ReturnType = 1,
10074     ConstexprSpec = 2,
10075     InlineSpec = 3,
10076     StorageClass = 4,
10077     Linkage = 5,
10078   };
10079 
10080   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10081       !OldFD->getType()->getAs<FunctionProtoType>()) {
10082     Diag(OldFD->getLocation(), NoProtoDiagID);
10083     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10084     return true;
10085   }
10086 
10087   if (NoProtoDiagID.getDiagID() != 0 &&
10088       !NewFD->getType()->getAs<FunctionProtoType>())
10089     return Diag(NewFD->getLocation(), NoProtoDiagID);
10090 
10091   if (!TemplatesSupported &&
10092       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10093     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10094            << FuncTemplates;
10095 
10096   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10097     if (NewCXXFD->isVirtual())
10098       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10099              << VirtFuncs;
10100 
10101     if (isa<CXXConstructorDecl>(NewCXXFD))
10102       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10103              << Constructors;
10104 
10105     if (isa<CXXDestructorDecl>(NewCXXFD))
10106       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10107              << Destructors;
10108   }
10109 
10110   if (NewFD->isDeleted())
10111     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10112            << DeletedFuncs;
10113 
10114   if (NewFD->isDefaulted())
10115     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10116            << DefaultedFuncs;
10117 
10118   if (!ConstexprSupported && NewFD->isConstexpr())
10119     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10120            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10121 
10122   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10123   const auto *NewType = cast<FunctionType>(NewQType);
10124   QualType NewReturnType = NewType->getReturnType();
10125 
10126   if (NewReturnType->isUndeducedType())
10127     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10128            << DeducedReturn;
10129 
10130   // Ensure the return type is identical.
10131   if (OldFD) {
10132     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10133     const auto *OldType = cast<FunctionType>(OldQType);
10134     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10135     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10136 
10137     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10138       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10139 
10140     QualType OldReturnType = OldType->getReturnType();
10141 
10142     if (OldReturnType != NewReturnType)
10143       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10144 
10145     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10146       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10147 
10148     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10149       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10150 
10151     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10152       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10153 
10154     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10155       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10156 
10157     if (CheckEquivalentExceptionSpec(
10158             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10159             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10160       return true;
10161   }
10162   return false;
10163 }
10164 
10165 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10166                                              const FunctionDecl *NewFD,
10167                                              bool CausesMV,
10168                                              MultiVersionKind MVType) {
10169   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10170     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10171     if (OldFD)
10172       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10173     return true;
10174   }
10175 
10176   bool IsCPUSpecificCPUDispatchMVType =
10177       MVType == MultiVersionKind::CPUDispatch ||
10178       MVType == MultiVersionKind::CPUSpecific;
10179 
10180   // For now, disallow all other attributes.  These should be opt-in, but
10181   // an analysis of all of them is a future FIXME.
10182   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
10183     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
10184         << IsCPUSpecificCPUDispatchMVType;
10185     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10186     return true;
10187   }
10188 
10189   if (HasNonMultiVersionAttributes(NewFD, MVType))
10190     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
10191            << IsCPUSpecificCPUDispatchMVType;
10192 
10193   // Only allow transition to MultiVersion if it hasn't been used.
10194   if (OldFD && CausesMV && OldFD->isUsed(false))
10195     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10196 
10197   return S.areMultiversionVariantFunctionsCompatible(
10198       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10199       PartialDiagnosticAt(NewFD->getLocation(),
10200                           S.PDiag(diag::note_multiversioning_caused_here)),
10201       PartialDiagnosticAt(NewFD->getLocation(),
10202                           S.PDiag(diag::err_multiversion_doesnt_support)
10203                               << IsCPUSpecificCPUDispatchMVType),
10204       PartialDiagnosticAt(NewFD->getLocation(),
10205                           S.PDiag(diag::err_multiversion_diff)),
10206       /*TemplatesSupported=*/false,
10207       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10208       /*CLinkageMayDiffer=*/false);
10209 }
10210 
10211 /// Check the validity of a multiversion function declaration that is the
10212 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10213 ///
10214 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10215 ///
10216 /// Returns true if there was an error, false otherwise.
10217 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10218                                            MultiVersionKind MVType,
10219                                            const TargetAttr *TA) {
10220   assert(MVType != MultiVersionKind::None &&
10221          "Function lacks multiversion attribute");
10222 
10223   // Target only causes MV if it is default, otherwise this is a normal
10224   // function.
10225   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10226     return false;
10227 
10228   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10229     FD->setInvalidDecl();
10230     return true;
10231   }
10232 
10233   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10234     FD->setInvalidDecl();
10235     return true;
10236   }
10237 
10238   FD->setIsMultiVersion();
10239   return false;
10240 }
10241 
10242 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10243   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10244     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10245       return true;
10246   }
10247 
10248   return false;
10249 }
10250 
10251 static bool CheckTargetCausesMultiVersioning(
10252     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10253     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10254     LookupResult &Previous) {
10255   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10256   ParsedTargetAttr NewParsed = NewTA->parse();
10257   // Sort order doesn't matter, it just needs to be consistent.
10258   llvm::sort(NewParsed.Features);
10259 
10260   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10261   // to change, this is a simple redeclaration.
10262   if (!NewTA->isDefaultVersion() &&
10263       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10264     return false;
10265 
10266   // Otherwise, this decl causes MultiVersioning.
10267   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10268     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10269     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10270     NewFD->setInvalidDecl();
10271     return true;
10272   }
10273 
10274   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10275                                        MultiVersionKind::Target)) {
10276     NewFD->setInvalidDecl();
10277     return true;
10278   }
10279 
10280   if (CheckMultiVersionValue(S, NewFD)) {
10281     NewFD->setInvalidDecl();
10282     return true;
10283   }
10284 
10285   // If this is 'default', permit the forward declaration.
10286   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10287     Redeclaration = true;
10288     OldDecl = OldFD;
10289     OldFD->setIsMultiVersion();
10290     NewFD->setIsMultiVersion();
10291     return false;
10292   }
10293 
10294   if (CheckMultiVersionValue(S, OldFD)) {
10295     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10296     NewFD->setInvalidDecl();
10297     return true;
10298   }
10299 
10300   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10301 
10302   if (OldParsed == NewParsed) {
10303     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10304     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10305     NewFD->setInvalidDecl();
10306     return true;
10307   }
10308 
10309   for (const auto *FD : OldFD->redecls()) {
10310     const auto *CurTA = FD->getAttr<TargetAttr>();
10311     // We allow forward declarations before ANY multiversioning attributes, but
10312     // nothing after the fact.
10313     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10314         (!CurTA || CurTA->isInherited())) {
10315       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10316           << 0;
10317       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10318       NewFD->setInvalidDecl();
10319       return true;
10320     }
10321   }
10322 
10323   OldFD->setIsMultiVersion();
10324   NewFD->setIsMultiVersion();
10325   Redeclaration = false;
10326   MergeTypeWithPrevious = false;
10327   OldDecl = nullptr;
10328   Previous.clear();
10329   return false;
10330 }
10331 
10332 /// Check the validity of a new function declaration being added to an existing
10333 /// multiversioned declaration collection.
10334 static bool CheckMultiVersionAdditionalDecl(
10335     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10336     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10337     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10338     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10339     LookupResult &Previous) {
10340 
10341   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10342   // Disallow mixing of multiversioning types.
10343   if ((OldMVType == MultiVersionKind::Target &&
10344        NewMVType != MultiVersionKind::Target) ||
10345       (NewMVType == MultiVersionKind::Target &&
10346        OldMVType != MultiVersionKind::Target)) {
10347     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10348     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10349     NewFD->setInvalidDecl();
10350     return true;
10351   }
10352 
10353   ParsedTargetAttr NewParsed;
10354   if (NewTA) {
10355     NewParsed = NewTA->parse();
10356     llvm::sort(NewParsed.Features);
10357   }
10358 
10359   bool UseMemberUsingDeclRules =
10360       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10361 
10362   // Next, check ALL non-overloads to see if this is a redeclaration of a
10363   // previous member of the MultiVersion set.
10364   for (NamedDecl *ND : Previous) {
10365     FunctionDecl *CurFD = ND->getAsFunction();
10366     if (!CurFD)
10367       continue;
10368     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10369       continue;
10370 
10371     if (NewMVType == MultiVersionKind::Target) {
10372       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10373       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10374         NewFD->setIsMultiVersion();
10375         Redeclaration = true;
10376         OldDecl = ND;
10377         return false;
10378       }
10379 
10380       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10381       if (CurParsed == NewParsed) {
10382         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10383         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10384         NewFD->setInvalidDecl();
10385         return true;
10386       }
10387     } else {
10388       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10389       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10390       // Handle CPUDispatch/CPUSpecific versions.
10391       // Only 1 CPUDispatch function is allowed, this will make it go through
10392       // the redeclaration errors.
10393       if (NewMVType == MultiVersionKind::CPUDispatch &&
10394           CurFD->hasAttr<CPUDispatchAttr>()) {
10395         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10396             std::equal(
10397                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10398                 NewCPUDisp->cpus_begin(),
10399                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10400                   return Cur->getName() == New->getName();
10401                 })) {
10402           NewFD->setIsMultiVersion();
10403           Redeclaration = true;
10404           OldDecl = ND;
10405           return false;
10406         }
10407 
10408         // If the declarations don't match, this is an error condition.
10409         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10410         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10411         NewFD->setInvalidDecl();
10412         return true;
10413       }
10414       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10415 
10416         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10417             std::equal(
10418                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10419                 NewCPUSpec->cpus_begin(),
10420                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10421                   return Cur->getName() == New->getName();
10422                 })) {
10423           NewFD->setIsMultiVersion();
10424           Redeclaration = true;
10425           OldDecl = ND;
10426           return false;
10427         }
10428 
10429         // Only 1 version of CPUSpecific is allowed for each CPU.
10430         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10431           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10432             if (CurII == NewII) {
10433               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10434                   << NewII;
10435               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10436               NewFD->setInvalidDecl();
10437               return true;
10438             }
10439           }
10440         }
10441       }
10442       // If the two decls aren't the same MVType, there is no possible error
10443       // condition.
10444     }
10445   }
10446 
10447   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10448   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10449   // handled in the attribute adding step.
10450   if (NewMVType == MultiVersionKind::Target &&
10451       CheckMultiVersionValue(S, NewFD)) {
10452     NewFD->setInvalidDecl();
10453     return true;
10454   }
10455 
10456   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10457                                        !OldFD->isMultiVersion(), NewMVType)) {
10458     NewFD->setInvalidDecl();
10459     return true;
10460   }
10461 
10462   // Permit forward declarations in the case where these two are compatible.
10463   if (!OldFD->isMultiVersion()) {
10464     OldFD->setIsMultiVersion();
10465     NewFD->setIsMultiVersion();
10466     Redeclaration = true;
10467     OldDecl = OldFD;
10468     return false;
10469   }
10470 
10471   NewFD->setIsMultiVersion();
10472   Redeclaration = false;
10473   MergeTypeWithPrevious = false;
10474   OldDecl = nullptr;
10475   Previous.clear();
10476   return false;
10477 }
10478 
10479 
10480 /// Check the validity of a mulitversion function declaration.
10481 /// Also sets the multiversion'ness' of the function itself.
10482 ///
10483 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10484 ///
10485 /// Returns true if there was an error, false otherwise.
10486 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10487                                       bool &Redeclaration, NamedDecl *&OldDecl,
10488                                       bool &MergeTypeWithPrevious,
10489                                       LookupResult &Previous) {
10490   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10491   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10492   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10493 
10494   // Mixing Multiversioning types is prohibited.
10495   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10496       (NewCPUDisp && NewCPUSpec)) {
10497     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10498     NewFD->setInvalidDecl();
10499     return true;
10500   }
10501 
10502   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10503 
10504   // Main isn't allowed to become a multiversion function, however it IS
10505   // permitted to have 'main' be marked with the 'target' optimization hint.
10506   if (NewFD->isMain()) {
10507     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10508         MVType == MultiVersionKind::CPUDispatch ||
10509         MVType == MultiVersionKind::CPUSpecific) {
10510       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10511       NewFD->setInvalidDecl();
10512       return true;
10513     }
10514     return false;
10515   }
10516 
10517   if (!OldDecl || !OldDecl->getAsFunction() ||
10518       OldDecl->getDeclContext()->getRedeclContext() !=
10519           NewFD->getDeclContext()->getRedeclContext()) {
10520     // If there's no previous declaration, AND this isn't attempting to cause
10521     // multiversioning, this isn't an error condition.
10522     if (MVType == MultiVersionKind::None)
10523       return false;
10524     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10525   }
10526 
10527   FunctionDecl *OldFD = OldDecl->getAsFunction();
10528 
10529   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10530     return false;
10531 
10532   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10533     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10534         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10535     NewFD->setInvalidDecl();
10536     return true;
10537   }
10538 
10539   // Handle the target potentially causes multiversioning case.
10540   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10541     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10542                                             Redeclaration, OldDecl,
10543                                             MergeTypeWithPrevious, Previous);
10544 
10545   // At this point, we have a multiversion function decl (in OldFD) AND an
10546   // appropriate attribute in the current function decl.  Resolve that these are
10547   // still compatible with previous declarations.
10548   return CheckMultiVersionAdditionalDecl(
10549       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10550       OldDecl, MergeTypeWithPrevious, Previous);
10551 }
10552 
10553 /// Perform semantic checking of a new function declaration.
10554 ///
10555 /// Performs semantic analysis of the new function declaration
10556 /// NewFD. This routine performs all semantic checking that does not
10557 /// require the actual declarator involved in the declaration, and is
10558 /// used both for the declaration of functions as they are parsed
10559 /// (called via ActOnDeclarator) and for the declaration of functions
10560 /// that have been instantiated via C++ template instantiation (called
10561 /// via InstantiateDecl).
10562 ///
10563 /// \param IsMemberSpecialization whether this new function declaration is
10564 /// a member specialization (that replaces any definition provided by the
10565 /// previous declaration).
10566 ///
10567 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10568 ///
10569 /// \returns true if the function declaration is a redeclaration.
10570 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10571                                     LookupResult &Previous,
10572                                     bool IsMemberSpecialization) {
10573   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10574          "Variably modified return types are not handled here");
10575 
10576   // Determine whether the type of this function should be merged with
10577   // a previous visible declaration. This never happens for functions in C++,
10578   // and always happens in C if the previous declaration was visible.
10579   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10580                                !Previous.isShadowed();
10581 
10582   bool Redeclaration = false;
10583   NamedDecl *OldDecl = nullptr;
10584   bool MayNeedOverloadableChecks = false;
10585 
10586   // Merge or overload the declaration with an existing declaration of
10587   // the same name, if appropriate.
10588   if (!Previous.empty()) {
10589     // Determine whether NewFD is an overload of PrevDecl or
10590     // a declaration that requires merging. If it's an overload,
10591     // there's no more work to do here; we'll just add the new
10592     // function to the scope.
10593     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10594       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10595       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10596         Redeclaration = true;
10597         OldDecl = Candidate;
10598       }
10599     } else {
10600       MayNeedOverloadableChecks = true;
10601       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10602                             /*NewIsUsingDecl*/ false)) {
10603       case Ovl_Match:
10604         Redeclaration = true;
10605         break;
10606 
10607       case Ovl_NonFunction:
10608         Redeclaration = true;
10609         break;
10610 
10611       case Ovl_Overload:
10612         Redeclaration = false;
10613         break;
10614       }
10615     }
10616   }
10617 
10618   // Check for a previous extern "C" declaration with this name.
10619   if (!Redeclaration &&
10620       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10621     if (!Previous.empty()) {
10622       // This is an extern "C" declaration with the same name as a previous
10623       // declaration, and thus redeclares that entity...
10624       Redeclaration = true;
10625       OldDecl = Previous.getFoundDecl();
10626       MergeTypeWithPrevious = false;
10627 
10628       // ... except in the presence of __attribute__((overloadable)).
10629       if (OldDecl->hasAttr<OverloadableAttr>() ||
10630           NewFD->hasAttr<OverloadableAttr>()) {
10631         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10632           MayNeedOverloadableChecks = true;
10633           Redeclaration = false;
10634           OldDecl = nullptr;
10635         }
10636       }
10637     }
10638   }
10639 
10640   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10641                                 MergeTypeWithPrevious, Previous))
10642     return Redeclaration;
10643 
10644   // C++11 [dcl.constexpr]p8:
10645   //   A constexpr specifier for a non-static member function that is not
10646   //   a constructor declares that member function to be const.
10647   //
10648   // This needs to be delayed until we know whether this is an out-of-line
10649   // definition of a static member function.
10650   //
10651   // This rule is not present in C++1y, so we produce a backwards
10652   // compatibility warning whenever it happens in C++11.
10653   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10654   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10655       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10656       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10657     CXXMethodDecl *OldMD = nullptr;
10658     if (OldDecl)
10659       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10660     if (!OldMD || !OldMD->isStatic()) {
10661       const FunctionProtoType *FPT =
10662         MD->getType()->castAs<FunctionProtoType>();
10663       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10664       EPI.TypeQuals.addConst();
10665       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10666                                           FPT->getParamTypes(), EPI));
10667 
10668       // Warn that we did this, if we're not performing template instantiation.
10669       // In that case, we'll have warned already when the template was defined.
10670       if (!inTemplateInstantiation()) {
10671         SourceLocation AddConstLoc;
10672         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10673                 .IgnoreParens().getAs<FunctionTypeLoc>())
10674           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10675 
10676         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10677           << FixItHint::CreateInsertion(AddConstLoc, " const");
10678       }
10679     }
10680   }
10681 
10682   if (Redeclaration) {
10683     // NewFD and OldDecl represent declarations that need to be
10684     // merged.
10685     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10686       NewFD->setInvalidDecl();
10687       return Redeclaration;
10688     }
10689 
10690     Previous.clear();
10691     Previous.addDecl(OldDecl);
10692 
10693     if (FunctionTemplateDecl *OldTemplateDecl =
10694             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10695       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10696       FunctionTemplateDecl *NewTemplateDecl
10697         = NewFD->getDescribedFunctionTemplate();
10698       assert(NewTemplateDecl && "Template/non-template mismatch");
10699 
10700       // The call to MergeFunctionDecl above may have created some state in
10701       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10702       // can add it as a redeclaration.
10703       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10704 
10705       NewFD->setPreviousDeclaration(OldFD);
10706       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10707       if (NewFD->isCXXClassMember()) {
10708         NewFD->setAccess(OldTemplateDecl->getAccess());
10709         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10710       }
10711 
10712       // If this is an explicit specialization of a member that is a function
10713       // template, mark it as a member specialization.
10714       if (IsMemberSpecialization &&
10715           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10716         NewTemplateDecl->setMemberSpecialization();
10717         assert(OldTemplateDecl->isMemberSpecialization());
10718         // Explicit specializations of a member template do not inherit deleted
10719         // status from the parent member template that they are specializing.
10720         if (OldFD->isDeleted()) {
10721           // FIXME: This assert will not hold in the presence of modules.
10722           assert(OldFD->getCanonicalDecl() == OldFD);
10723           // FIXME: We need an update record for this AST mutation.
10724           OldFD->setDeletedAsWritten(false);
10725         }
10726       }
10727 
10728     } else {
10729       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10730         auto *OldFD = cast<FunctionDecl>(OldDecl);
10731         // This needs to happen first so that 'inline' propagates.
10732         NewFD->setPreviousDeclaration(OldFD);
10733         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10734         if (NewFD->isCXXClassMember())
10735           NewFD->setAccess(OldFD->getAccess());
10736       }
10737     }
10738   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10739              !NewFD->getAttr<OverloadableAttr>()) {
10740     assert((Previous.empty() ||
10741             llvm::any_of(Previous,
10742                          [](const NamedDecl *ND) {
10743                            return ND->hasAttr<OverloadableAttr>();
10744                          })) &&
10745            "Non-redecls shouldn't happen without overloadable present");
10746 
10747     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10748       const auto *FD = dyn_cast<FunctionDecl>(ND);
10749       return FD && !FD->hasAttr<OverloadableAttr>();
10750     });
10751 
10752     if (OtherUnmarkedIter != Previous.end()) {
10753       Diag(NewFD->getLocation(),
10754            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10755       Diag((*OtherUnmarkedIter)->getLocation(),
10756            diag::note_attribute_overloadable_prev_overload)
10757           << false;
10758 
10759       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10760     }
10761   }
10762 
10763   // Semantic checking for this function declaration (in isolation).
10764 
10765   if (getLangOpts().CPlusPlus) {
10766     // C++-specific checks.
10767     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10768       CheckConstructor(Constructor);
10769     } else if (CXXDestructorDecl *Destructor =
10770                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10771       CXXRecordDecl *Record = Destructor->getParent();
10772       QualType ClassType = Context.getTypeDeclType(Record);
10773 
10774       // FIXME: Shouldn't we be able to perform this check even when the class
10775       // type is dependent? Both gcc and edg can handle that.
10776       if (!ClassType->isDependentType()) {
10777         DeclarationName Name
10778           = Context.DeclarationNames.getCXXDestructorName(
10779                                         Context.getCanonicalType(ClassType));
10780         if (NewFD->getDeclName() != Name) {
10781           Diag(NewFD->getLocation(), diag::err_destructor_name);
10782           NewFD->setInvalidDecl();
10783           return Redeclaration;
10784         }
10785       }
10786     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10787       if (auto *TD = Guide->getDescribedFunctionTemplate())
10788         CheckDeductionGuideTemplate(TD);
10789 
10790       // A deduction guide is not on the list of entities that can be
10791       // explicitly specialized.
10792       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10793         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10794             << /*explicit specialization*/ 1;
10795     }
10796 
10797     // Find any virtual functions that this function overrides.
10798     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10799       if (!Method->isFunctionTemplateSpecialization() &&
10800           !Method->getDescribedFunctionTemplate() &&
10801           Method->isCanonicalDecl()) {
10802         AddOverriddenMethods(Method->getParent(), Method);
10803       }
10804       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10805         // C++2a [class.virtual]p6
10806         // A virtual method shall not have a requires-clause.
10807         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10808              diag::err_constrained_virtual_method);
10809 
10810       if (Method->isStatic())
10811         checkThisInStaticMemberFunctionType(Method);
10812     }
10813 
10814     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10815       ActOnConversionDeclarator(Conversion);
10816 
10817     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10818     if (NewFD->isOverloadedOperator() &&
10819         CheckOverloadedOperatorDeclaration(NewFD)) {
10820       NewFD->setInvalidDecl();
10821       return Redeclaration;
10822     }
10823 
10824     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10825     if (NewFD->getLiteralIdentifier() &&
10826         CheckLiteralOperatorDeclaration(NewFD)) {
10827       NewFD->setInvalidDecl();
10828       return Redeclaration;
10829     }
10830 
10831     // In C++, check default arguments now that we have merged decls. Unless
10832     // the lexical context is the class, because in this case this is done
10833     // during delayed parsing anyway.
10834     if (!CurContext->isRecord())
10835       CheckCXXDefaultArguments(NewFD);
10836 
10837     // If this function declares a builtin function, check the type of this
10838     // declaration against the expected type for the builtin.
10839     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10840       ASTContext::GetBuiltinTypeError Error;
10841       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10842       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10843       // If the type of the builtin differs only in its exception
10844       // specification, that's OK.
10845       // FIXME: If the types do differ in this way, it would be better to
10846       // retain the 'noexcept' form of the type.
10847       if (!T.isNull() &&
10848           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10849                                                             NewFD->getType()))
10850         // The type of this function differs from the type of the builtin,
10851         // so forget about the builtin entirely.
10852         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10853     }
10854 
10855     // If this function is declared as being extern "C", then check to see if
10856     // the function returns a UDT (class, struct, or union type) that is not C
10857     // compatible, and if it does, warn the user.
10858     // But, issue any diagnostic on the first declaration only.
10859     if (Previous.empty() && NewFD->isExternC()) {
10860       QualType R = NewFD->getReturnType();
10861       if (R->isIncompleteType() && !R->isVoidType())
10862         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10863             << NewFD << R;
10864       else if (!R.isPODType(Context) && !R->isVoidType() &&
10865                !R->isObjCObjectPointerType())
10866         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10867     }
10868 
10869     // C++1z [dcl.fct]p6:
10870     //   [...] whether the function has a non-throwing exception-specification
10871     //   [is] part of the function type
10872     //
10873     // This results in an ABI break between C++14 and C++17 for functions whose
10874     // declared type includes an exception-specification in a parameter or
10875     // return type. (Exception specifications on the function itself are OK in
10876     // most cases, and exception specifications are not permitted in most other
10877     // contexts where they could make it into a mangling.)
10878     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10879       auto HasNoexcept = [&](QualType T) -> bool {
10880         // Strip off declarator chunks that could be between us and a function
10881         // type. We don't need to look far, exception specifications are very
10882         // restricted prior to C++17.
10883         if (auto *RT = T->getAs<ReferenceType>())
10884           T = RT->getPointeeType();
10885         else if (T->isAnyPointerType())
10886           T = T->getPointeeType();
10887         else if (auto *MPT = T->getAs<MemberPointerType>())
10888           T = MPT->getPointeeType();
10889         if (auto *FPT = T->getAs<FunctionProtoType>())
10890           if (FPT->isNothrow())
10891             return true;
10892         return false;
10893       };
10894 
10895       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10896       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10897       for (QualType T : FPT->param_types())
10898         AnyNoexcept |= HasNoexcept(T);
10899       if (AnyNoexcept)
10900         Diag(NewFD->getLocation(),
10901              diag::warn_cxx17_compat_exception_spec_in_signature)
10902             << NewFD;
10903     }
10904 
10905     if (!Redeclaration && LangOpts.CUDA)
10906       checkCUDATargetOverload(NewFD, Previous);
10907   }
10908   return Redeclaration;
10909 }
10910 
10911 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10912   // C++11 [basic.start.main]p3:
10913   //   A program that [...] declares main to be inline, static or
10914   //   constexpr is ill-formed.
10915   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10916   //   appear in a declaration of main.
10917   // static main is not an error under C99, but we should warn about it.
10918   // We accept _Noreturn main as an extension.
10919   if (FD->getStorageClass() == SC_Static)
10920     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10921          ? diag::err_static_main : diag::warn_static_main)
10922       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10923   if (FD->isInlineSpecified())
10924     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10925       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10926   if (DS.isNoreturnSpecified()) {
10927     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10928     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10929     Diag(NoreturnLoc, diag::ext_noreturn_main);
10930     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10931       << FixItHint::CreateRemoval(NoreturnRange);
10932   }
10933   if (FD->isConstexpr()) {
10934     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10935         << FD->isConsteval()
10936         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10937     FD->setConstexprKind(CSK_unspecified);
10938   }
10939 
10940   if (getLangOpts().OpenCL) {
10941     Diag(FD->getLocation(), diag::err_opencl_no_main)
10942         << FD->hasAttr<OpenCLKernelAttr>();
10943     FD->setInvalidDecl();
10944     return;
10945   }
10946 
10947   QualType T = FD->getType();
10948   assert(T->isFunctionType() && "function decl is not of function type");
10949   const FunctionType* FT = T->castAs<FunctionType>();
10950 
10951   // Set default calling convention for main()
10952   if (FT->getCallConv() != CC_C) {
10953     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10954     FD->setType(QualType(FT, 0));
10955     T = Context.getCanonicalType(FD->getType());
10956   }
10957 
10958   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10959     // In C with GNU extensions we allow main() to have non-integer return
10960     // type, but we should warn about the extension, and we disable the
10961     // implicit-return-zero rule.
10962 
10963     // GCC in C mode accepts qualified 'int'.
10964     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10965       FD->setHasImplicitReturnZero(true);
10966     else {
10967       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10968       SourceRange RTRange = FD->getReturnTypeSourceRange();
10969       if (RTRange.isValid())
10970         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10971             << FixItHint::CreateReplacement(RTRange, "int");
10972     }
10973   } else {
10974     // In C and C++, main magically returns 0 if you fall off the end;
10975     // set the flag which tells us that.
10976     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10977 
10978     // All the standards say that main() should return 'int'.
10979     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10980       FD->setHasImplicitReturnZero(true);
10981     else {
10982       // Otherwise, this is just a flat-out error.
10983       SourceRange RTRange = FD->getReturnTypeSourceRange();
10984       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10985           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10986                                 : FixItHint());
10987       FD->setInvalidDecl(true);
10988     }
10989   }
10990 
10991   // Treat protoless main() as nullary.
10992   if (isa<FunctionNoProtoType>(FT)) return;
10993 
10994   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10995   unsigned nparams = FTP->getNumParams();
10996   assert(FD->getNumParams() == nparams);
10997 
10998   bool HasExtraParameters = (nparams > 3);
10999 
11000   if (FTP->isVariadic()) {
11001     Diag(FD->getLocation(), diag::ext_variadic_main);
11002     // FIXME: if we had information about the location of the ellipsis, we
11003     // could add a FixIt hint to remove it as a parameter.
11004   }
11005 
11006   // Darwin passes an undocumented fourth argument of type char**.  If
11007   // other platforms start sprouting these, the logic below will start
11008   // getting shifty.
11009   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11010     HasExtraParameters = false;
11011 
11012   if (HasExtraParameters) {
11013     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11014     FD->setInvalidDecl(true);
11015     nparams = 3;
11016   }
11017 
11018   // FIXME: a lot of the following diagnostics would be improved
11019   // if we had some location information about types.
11020 
11021   QualType CharPP =
11022     Context.getPointerType(Context.getPointerType(Context.CharTy));
11023   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11024 
11025   for (unsigned i = 0; i < nparams; ++i) {
11026     QualType AT = FTP->getParamType(i);
11027 
11028     bool mismatch = true;
11029 
11030     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11031       mismatch = false;
11032     else if (Expected[i] == CharPP) {
11033       // As an extension, the following forms are okay:
11034       //   char const **
11035       //   char const * const *
11036       //   char * const *
11037 
11038       QualifierCollector qs;
11039       const PointerType* PT;
11040       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11041           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11042           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11043                               Context.CharTy)) {
11044         qs.removeConst();
11045         mismatch = !qs.empty();
11046       }
11047     }
11048 
11049     if (mismatch) {
11050       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11051       // TODO: suggest replacing given type with expected type
11052       FD->setInvalidDecl(true);
11053     }
11054   }
11055 
11056   if (nparams == 1 && !FD->isInvalidDecl()) {
11057     Diag(FD->getLocation(), diag::warn_main_one_arg);
11058   }
11059 
11060   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11061     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11062     FD->setInvalidDecl();
11063   }
11064 }
11065 
11066 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11067   QualType T = FD->getType();
11068   assert(T->isFunctionType() && "function decl is not of function type");
11069   const FunctionType *FT = T->castAs<FunctionType>();
11070 
11071   // Set an implicit return of 'zero' if the function can return some integral,
11072   // enumeration, pointer or nullptr type.
11073   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11074       FT->getReturnType()->isAnyPointerType() ||
11075       FT->getReturnType()->isNullPtrType())
11076     // DllMain is exempt because a return value of zero means it failed.
11077     if (FD->getName() != "DllMain")
11078       FD->setHasImplicitReturnZero(true);
11079 
11080   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11081     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11082     FD->setInvalidDecl();
11083   }
11084 }
11085 
11086 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11087   // FIXME: Need strict checking.  In C89, we need to check for
11088   // any assignment, increment, decrement, function-calls, or
11089   // commas outside of a sizeof.  In C99, it's the same list,
11090   // except that the aforementioned are allowed in unevaluated
11091   // expressions.  Everything else falls under the
11092   // "may accept other forms of constant expressions" exception.
11093   // (We never end up here for C++, so the constant expression
11094   // rules there don't matter.)
11095   const Expr *Culprit;
11096   if (Init->isConstantInitializer(Context, false, &Culprit))
11097     return false;
11098   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11099     << Culprit->getSourceRange();
11100   return true;
11101 }
11102 
11103 namespace {
11104   // Visits an initialization expression to see if OrigDecl is evaluated in
11105   // its own initialization and throws a warning if it does.
11106   class SelfReferenceChecker
11107       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11108     Sema &S;
11109     Decl *OrigDecl;
11110     bool isRecordType;
11111     bool isPODType;
11112     bool isReferenceType;
11113 
11114     bool isInitList;
11115     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11116 
11117   public:
11118     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11119 
11120     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11121                                                     S(S), OrigDecl(OrigDecl) {
11122       isPODType = false;
11123       isRecordType = false;
11124       isReferenceType = false;
11125       isInitList = false;
11126       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11127         isPODType = VD->getType().isPODType(S.Context);
11128         isRecordType = VD->getType()->isRecordType();
11129         isReferenceType = VD->getType()->isReferenceType();
11130       }
11131     }
11132 
11133     // For most expressions, just call the visitor.  For initializer lists,
11134     // track the index of the field being initialized since fields are
11135     // initialized in order allowing use of previously initialized fields.
11136     void CheckExpr(Expr *E) {
11137       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11138       if (!InitList) {
11139         Visit(E);
11140         return;
11141       }
11142 
11143       // Track and increment the index here.
11144       isInitList = true;
11145       InitFieldIndex.push_back(0);
11146       for (auto Child : InitList->children()) {
11147         CheckExpr(cast<Expr>(Child));
11148         ++InitFieldIndex.back();
11149       }
11150       InitFieldIndex.pop_back();
11151     }
11152 
11153     // Returns true if MemberExpr is checked and no further checking is needed.
11154     // Returns false if additional checking is required.
11155     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11156       llvm::SmallVector<FieldDecl*, 4> Fields;
11157       Expr *Base = E;
11158       bool ReferenceField = false;
11159 
11160       // Get the field members used.
11161       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11162         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11163         if (!FD)
11164           return false;
11165         Fields.push_back(FD);
11166         if (FD->getType()->isReferenceType())
11167           ReferenceField = true;
11168         Base = ME->getBase()->IgnoreParenImpCasts();
11169       }
11170 
11171       // Keep checking only if the base Decl is the same.
11172       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11173       if (!DRE || DRE->getDecl() != OrigDecl)
11174         return false;
11175 
11176       // A reference field can be bound to an unininitialized field.
11177       if (CheckReference && !ReferenceField)
11178         return true;
11179 
11180       // Convert FieldDecls to their index number.
11181       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11182       for (const FieldDecl *I : llvm::reverse(Fields))
11183         UsedFieldIndex.push_back(I->getFieldIndex());
11184 
11185       // See if a warning is needed by checking the first difference in index
11186       // numbers.  If field being used has index less than the field being
11187       // initialized, then the use is safe.
11188       for (auto UsedIter = UsedFieldIndex.begin(),
11189                 UsedEnd = UsedFieldIndex.end(),
11190                 OrigIter = InitFieldIndex.begin(),
11191                 OrigEnd = InitFieldIndex.end();
11192            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11193         if (*UsedIter < *OrigIter)
11194           return true;
11195         if (*UsedIter > *OrigIter)
11196           break;
11197       }
11198 
11199       // TODO: Add a different warning which will print the field names.
11200       HandleDeclRefExpr(DRE);
11201       return true;
11202     }
11203 
11204     // For most expressions, the cast is directly above the DeclRefExpr.
11205     // For conditional operators, the cast can be outside the conditional
11206     // operator if both expressions are DeclRefExpr's.
11207     void HandleValue(Expr *E) {
11208       E = E->IgnoreParens();
11209       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11210         HandleDeclRefExpr(DRE);
11211         return;
11212       }
11213 
11214       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11215         Visit(CO->getCond());
11216         HandleValue(CO->getTrueExpr());
11217         HandleValue(CO->getFalseExpr());
11218         return;
11219       }
11220 
11221       if (BinaryConditionalOperator *BCO =
11222               dyn_cast<BinaryConditionalOperator>(E)) {
11223         Visit(BCO->getCond());
11224         HandleValue(BCO->getFalseExpr());
11225         return;
11226       }
11227 
11228       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11229         HandleValue(OVE->getSourceExpr());
11230         return;
11231       }
11232 
11233       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11234         if (BO->getOpcode() == BO_Comma) {
11235           Visit(BO->getLHS());
11236           HandleValue(BO->getRHS());
11237           return;
11238         }
11239       }
11240 
11241       if (isa<MemberExpr>(E)) {
11242         if (isInitList) {
11243           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11244                                       false /*CheckReference*/))
11245             return;
11246         }
11247 
11248         Expr *Base = E->IgnoreParenImpCasts();
11249         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11250           // Check for static member variables and don't warn on them.
11251           if (!isa<FieldDecl>(ME->getMemberDecl()))
11252             return;
11253           Base = ME->getBase()->IgnoreParenImpCasts();
11254         }
11255         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11256           HandleDeclRefExpr(DRE);
11257         return;
11258       }
11259 
11260       Visit(E);
11261     }
11262 
11263     // Reference types not handled in HandleValue are handled here since all
11264     // uses of references are bad, not just r-value uses.
11265     void VisitDeclRefExpr(DeclRefExpr *E) {
11266       if (isReferenceType)
11267         HandleDeclRefExpr(E);
11268     }
11269 
11270     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11271       if (E->getCastKind() == CK_LValueToRValue) {
11272         HandleValue(E->getSubExpr());
11273         return;
11274       }
11275 
11276       Inherited::VisitImplicitCastExpr(E);
11277     }
11278 
11279     void VisitMemberExpr(MemberExpr *E) {
11280       if (isInitList) {
11281         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11282           return;
11283       }
11284 
11285       // Don't warn on arrays since they can be treated as pointers.
11286       if (E->getType()->canDecayToPointerType()) return;
11287 
11288       // Warn when a non-static method call is followed by non-static member
11289       // field accesses, which is followed by a DeclRefExpr.
11290       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11291       bool Warn = (MD && !MD->isStatic());
11292       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11293       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11294         if (!isa<FieldDecl>(ME->getMemberDecl()))
11295           Warn = false;
11296         Base = ME->getBase()->IgnoreParenImpCasts();
11297       }
11298 
11299       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11300         if (Warn)
11301           HandleDeclRefExpr(DRE);
11302         return;
11303       }
11304 
11305       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11306       // Visit that expression.
11307       Visit(Base);
11308     }
11309 
11310     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11311       Expr *Callee = E->getCallee();
11312 
11313       if (isa<UnresolvedLookupExpr>(Callee))
11314         return Inherited::VisitCXXOperatorCallExpr(E);
11315 
11316       Visit(Callee);
11317       for (auto Arg: E->arguments())
11318         HandleValue(Arg->IgnoreParenImpCasts());
11319     }
11320 
11321     void VisitUnaryOperator(UnaryOperator *E) {
11322       // For POD record types, addresses of its own members are well-defined.
11323       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11324           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11325         if (!isPODType)
11326           HandleValue(E->getSubExpr());
11327         return;
11328       }
11329 
11330       if (E->isIncrementDecrementOp()) {
11331         HandleValue(E->getSubExpr());
11332         return;
11333       }
11334 
11335       Inherited::VisitUnaryOperator(E);
11336     }
11337 
11338     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11339 
11340     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11341       if (E->getConstructor()->isCopyConstructor()) {
11342         Expr *ArgExpr = E->getArg(0);
11343         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11344           if (ILE->getNumInits() == 1)
11345             ArgExpr = ILE->getInit(0);
11346         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11347           if (ICE->getCastKind() == CK_NoOp)
11348             ArgExpr = ICE->getSubExpr();
11349         HandleValue(ArgExpr);
11350         return;
11351       }
11352       Inherited::VisitCXXConstructExpr(E);
11353     }
11354 
11355     void VisitCallExpr(CallExpr *E) {
11356       // Treat std::move as a use.
11357       if (E->isCallToStdMove()) {
11358         HandleValue(E->getArg(0));
11359         return;
11360       }
11361 
11362       Inherited::VisitCallExpr(E);
11363     }
11364 
11365     void VisitBinaryOperator(BinaryOperator *E) {
11366       if (E->isCompoundAssignmentOp()) {
11367         HandleValue(E->getLHS());
11368         Visit(E->getRHS());
11369         return;
11370       }
11371 
11372       Inherited::VisitBinaryOperator(E);
11373     }
11374 
11375     // A custom visitor for BinaryConditionalOperator is needed because the
11376     // regular visitor would check the condition and true expression separately
11377     // but both point to the same place giving duplicate diagnostics.
11378     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11379       Visit(E->getCond());
11380       Visit(E->getFalseExpr());
11381     }
11382 
11383     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11384       Decl* ReferenceDecl = DRE->getDecl();
11385       if (OrigDecl != ReferenceDecl) return;
11386       unsigned diag;
11387       if (isReferenceType) {
11388         diag = diag::warn_uninit_self_reference_in_reference_init;
11389       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11390         diag = diag::warn_static_self_reference_in_init;
11391       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11392                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11393                  DRE->getDecl()->getType()->isRecordType()) {
11394         diag = diag::warn_uninit_self_reference_in_init;
11395       } else {
11396         // Local variables will be handled by the CFG analysis.
11397         return;
11398       }
11399 
11400       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11401                             S.PDiag(diag)
11402                                 << DRE->getDecl() << OrigDecl->getLocation()
11403                                 << DRE->getSourceRange());
11404     }
11405   };
11406 
11407   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11408   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11409                                  bool DirectInit) {
11410     // Parameters arguments are occassionially constructed with itself,
11411     // for instance, in recursive functions.  Skip them.
11412     if (isa<ParmVarDecl>(OrigDecl))
11413       return;
11414 
11415     E = E->IgnoreParens();
11416 
11417     // Skip checking T a = a where T is not a record or reference type.
11418     // Doing so is a way to silence uninitialized warnings.
11419     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11420       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11421         if (ICE->getCastKind() == CK_LValueToRValue)
11422           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11423             if (DRE->getDecl() == OrigDecl)
11424               return;
11425 
11426     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11427   }
11428 } // end anonymous namespace
11429 
11430 namespace {
11431   // Simple wrapper to add the name of a variable or (if no variable is
11432   // available) a DeclarationName into a diagnostic.
11433   struct VarDeclOrName {
11434     VarDecl *VDecl;
11435     DeclarationName Name;
11436 
11437     friend const Sema::SemaDiagnosticBuilder &
11438     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11439       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11440     }
11441   };
11442 } // end anonymous namespace
11443 
11444 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11445                                             DeclarationName Name, QualType Type,
11446                                             TypeSourceInfo *TSI,
11447                                             SourceRange Range, bool DirectInit,
11448                                             Expr *Init) {
11449   bool IsInitCapture = !VDecl;
11450   assert((!VDecl || !VDecl->isInitCapture()) &&
11451          "init captures are expected to be deduced prior to initialization");
11452 
11453   VarDeclOrName VN{VDecl, Name};
11454 
11455   DeducedType *Deduced = Type->getContainedDeducedType();
11456   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11457 
11458   // C++11 [dcl.spec.auto]p3
11459   if (!Init) {
11460     assert(VDecl && "no init for init capture deduction?");
11461 
11462     // Except for class argument deduction, and then for an initializing
11463     // declaration only, i.e. no static at class scope or extern.
11464     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11465         VDecl->hasExternalStorage() ||
11466         VDecl->isStaticDataMember()) {
11467       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11468         << VDecl->getDeclName() << Type;
11469       return QualType();
11470     }
11471   }
11472 
11473   ArrayRef<Expr*> DeduceInits;
11474   if (Init)
11475     DeduceInits = Init;
11476 
11477   if (DirectInit) {
11478     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11479       DeduceInits = PL->exprs();
11480   }
11481 
11482   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11483     assert(VDecl && "non-auto type for init capture deduction?");
11484     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11485     InitializationKind Kind = InitializationKind::CreateForInit(
11486         VDecl->getLocation(), DirectInit, Init);
11487     // FIXME: Initialization should not be taking a mutable list of inits.
11488     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11489     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11490                                                        InitsCopy);
11491   }
11492 
11493   if (DirectInit) {
11494     if (auto *IL = dyn_cast<InitListExpr>(Init))
11495       DeduceInits = IL->inits();
11496   }
11497 
11498   // Deduction only works if we have exactly one source expression.
11499   if (DeduceInits.empty()) {
11500     // It isn't possible to write this directly, but it is possible to
11501     // end up in this situation with "auto x(some_pack...);"
11502     Diag(Init->getBeginLoc(), IsInitCapture
11503                                   ? diag::err_init_capture_no_expression
11504                                   : diag::err_auto_var_init_no_expression)
11505         << VN << Type << Range;
11506     return QualType();
11507   }
11508 
11509   if (DeduceInits.size() > 1) {
11510     Diag(DeduceInits[1]->getBeginLoc(),
11511          IsInitCapture ? diag::err_init_capture_multiple_expressions
11512                        : diag::err_auto_var_init_multiple_expressions)
11513         << VN << Type << Range;
11514     return QualType();
11515   }
11516 
11517   Expr *DeduceInit = DeduceInits[0];
11518   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11519     Diag(Init->getBeginLoc(), IsInitCapture
11520                                   ? diag::err_init_capture_paren_braces
11521                                   : diag::err_auto_var_init_paren_braces)
11522         << isa<InitListExpr>(Init) << VN << Type << Range;
11523     return QualType();
11524   }
11525 
11526   // Expressions default to 'id' when we're in a debugger.
11527   bool DefaultedAnyToId = false;
11528   if (getLangOpts().DebuggerCastResultToId &&
11529       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11530     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11531     if (Result.isInvalid()) {
11532       return QualType();
11533     }
11534     Init = Result.get();
11535     DefaultedAnyToId = true;
11536   }
11537 
11538   // C++ [dcl.decomp]p1:
11539   //   If the assignment-expression [...] has array type A and no ref-qualifier
11540   //   is present, e has type cv A
11541   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11542       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11543       DeduceInit->getType()->isConstantArrayType())
11544     return Context.getQualifiedType(DeduceInit->getType(),
11545                                     Type.getQualifiers());
11546 
11547   QualType DeducedType;
11548   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11549     if (!IsInitCapture)
11550       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11551     else if (isa<InitListExpr>(Init))
11552       Diag(Range.getBegin(),
11553            diag::err_init_capture_deduction_failure_from_init_list)
11554           << VN
11555           << (DeduceInit->getType().isNull() ? TSI->getType()
11556                                              : DeduceInit->getType())
11557           << DeduceInit->getSourceRange();
11558     else
11559       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11560           << VN << TSI->getType()
11561           << (DeduceInit->getType().isNull() ? TSI->getType()
11562                                              : DeduceInit->getType())
11563           << DeduceInit->getSourceRange();
11564   }
11565 
11566   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11567   // 'id' instead of a specific object type prevents most of our usual
11568   // checks.
11569   // We only want to warn outside of template instantiations, though:
11570   // inside a template, the 'id' could have come from a parameter.
11571   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11572       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11573     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11574     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11575   }
11576 
11577   return DeducedType;
11578 }
11579 
11580 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11581                                          Expr *Init) {
11582   assert(!Init || !Init->containsErrors());
11583   QualType DeducedType = deduceVarTypeFromInitializer(
11584       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11585       VDecl->getSourceRange(), DirectInit, Init);
11586   if (DeducedType.isNull()) {
11587     VDecl->setInvalidDecl();
11588     return true;
11589   }
11590 
11591   VDecl->setType(DeducedType);
11592   assert(VDecl->isLinkageValid());
11593 
11594   // In ARC, infer lifetime.
11595   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11596     VDecl->setInvalidDecl();
11597 
11598   if (getLangOpts().OpenCL)
11599     deduceOpenCLAddressSpace(VDecl);
11600 
11601   // If this is a redeclaration, check that the type we just deduced matches
11602   // the previously declared type.
11603   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11604     // We never need to merge the type, because we cannot form an incomplete
11605     // array of auto, nor deduce such a type.
11606     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11607   }
11608 
11609   // Check the deduced type is valid for a variable declaration.
11610   CheckVariableDeclarationType(VDecl);
11611   return VDecl->isInvalidDecl();
11612 }
11613 
11614 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11615                                               SourceLocation Loc) {
11616   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11617     Init = EWC->getSubExpr();
11618 
11619   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11620     Init = CE->getSubExpr();
11621 
11622   QualType InitType = Init->getType();
11623   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11624           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11625          "shouldn't be called if type doesn't have a non-trivial C struct");
11626   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11627     for (auto I : ILE->inits()) {
11628       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11629           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11630         continue;
11631       SourceLocation SL = I->getExprLoc();
11632       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11633     }
11634     return;
11635   }
11636 
11637   if (isa<ImplicitValueInitExpr>(Init)) {
11638     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11639       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11640                             NTCUK_Init);
11641   } else {
11642     // Assume all other explicit initializers involving copying some existing
11643     // object.
11644     // TODO: ignore any explicit initializers where we can guarantee
11645     // copy-elision.
11646     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11647       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11648   }
11649 }
11650 
11651 namespace {
11652 
11653 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11654   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11655   // in the source code or implicitly by the compiler if it is in a union
11656   // defined in a system header and has non-trivial ObjC ownership
11657   // qualifications. We don't want those fields to participate in determining
11658   // whether the containing union is non-trivial.
11659   return FD->hasAttr<UnavailableAttr>();
11660 }
11661 
11662 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11663     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11664                                     void> {
11665   using Super =
11666       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11667                                     void>;
11668 
11669   DiagNonTrivalCUnionDefaultInitializeVisitor(
11670       QualType OrigTy, SourceLocation OrigLoc,
11671       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11672       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11673 
11674   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11675                      const FieldDecl *FD, bool InNonTrivialUnion) {
11676     if (const auto *AT = S.Context.getAsArrayType(QT))
11677       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11678                                      InNonTrivialUnion);
11679     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11680   }
11681 
11682   void visitARCStrong(QualType QT, const FieldDecl *FD,
11683                       bool InNonTrivialUnion) {
11684     if (InNonTrivialUnion)
11685       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11686           << 1 << 0 << QT << FD->getName();
11687   }
11688 
11689   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11690     if (InNonTrivialUnion)
11691       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11692           << 1 << 0 << QT << FD->getName();
11693   }
11694 
11695   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11696     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11697     if (RD->isUnion()) {
11698       if (OrigLoc.isValid()) {
11699         bool IsUnion = false;
11700         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11701           IsUnion = OrigRD->isUnion();
11702         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11703             << 0 << OrigTy << IsUnion << UseContext;
11704         // Reset OrigLoc so that this diagnostic is emitted only once.
11705         OrigLoc = SourceLocation();
11706       }
11707       InNonTrivialUnion = true;
11708     }
11709 
11710     if (InNonTrivialUnion)
11711       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11712           << 0 << 0 << QT.getUnqualifiedType() << "";
11713 
11714     for (const FieldDecl *FD : RD->fields())
11715       if (!shouldIgnoreForRecordTriviality(FD))
11716         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11717   }
11718 
11719   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11720 
11721   // The non-trivial C union type or the struct/union type that contains a
11722   // non-trivial C union.
11723   QualType OrigTy;
11724   SourceLocation OrigLoc;
11725   Sema::NonTrivialCUnionContext UseContext;
11726   Sema &S;
11727 };
11728 
11729 struct DiagNonTrivalCUnionDestructedTypeVisitor
11730     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11731   using Super =
11732       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11733 
11734   DiagNonTrivalCUnionDestructedTypeVisitor(
11735       QualType OrigTy, SourceLocation OrigLoc,
11736       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11737       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11738 
11739   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11740                      const FieldDecl *FD, bool InNonTrivialUnion) {
11741     if (const auto *AT = S.Context.getAsArrayType(QT))
11742       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11743                                      InNonTrivialUnion);
11744     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11745   }
11746 
11747   void visitARCStrong(QualType QT, const FieldDecl *FD,
11748                       bool InNonTrivialUnion) {
11749     if (InNonTrivialUnion)
11750       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11751           << 1 << 1 << QT << FD->getName();
11752   }
11753 
11754   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11755     if (InNonTrivialUnion)
11756       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11757           << 1 << 1 << QT << FD->getName();
11758   }
11759 
11760   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11761     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11762     if (RD->isUnion()) {
11763       if (OrigLoc.isValid()) {
11764         bool IsUnion = false;
11765         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11766           IsUnion = OrigRD->isUnion();
11767         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11768             << 1 << OrigTy << IsUnion << UseContext;
11769         // Reset OrigLoc so that this diagnostic is emitted only once.
11770         OrigLoc = SourceLocation();
11771       }
11772       InNonTrivialUnion = true;
11773     }
11774 
11775     if (InNonTrivialUnion)
11776       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11777           << 0 << 1 << QT.getUnqualifiedType() << "";
11778 
11779     for (const FieldDecl *FD : RD->fields())
11780       if (!shouldIgnoreForRecordTriviality(FD))
11781         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11782   }
11783 
11784   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11785   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11786                           bool InNonTrivialUnion) {}
11787 
11788   // The non-trivial C union type or the struct/union type that contains a
11789   // non-trivial C union.
11790   QualType OrigTy;
11791   SourceLocation OrigLoc;
11792   Sema::NonTrivialCUnionContext UseContext;
11793   Sema &S;
11794 };
11795 
11796 struct DiagNonTrivalCUnionCopyVisitor
11797     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11798   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11799 
11800   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11801                                  Sema::NonTrivialCUnionContext UseContext,
11802                                  Sema &S)
11803       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11804 
11805   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11806                      const FieldDecl *FD, bool InNonTrivialUnion) {
11807     if (const auto *AT = S.Context.getAsArrayType(QT))
11808       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11809                                      InNonTrivialUnion);
11810     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11811   }
11812 
11813   void visitARCStrong(QualType QT, const FieldDecl *FD,
11814                       bool InNonTrivialUnion) {
11815     if (InNonTrivialUnion)
11816       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11817           << 1 << 2 << QT << FD->getName();
11818   }
11819 
11820   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11821     if (InNonTrivialUnion)
11822       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11823           << 1 << 2 << QT << FD->getName();
11824   }
11825 
11826   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11827     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11828     if (RD->isUnion()) {
11829       if (OrigLoc.isValid()) {
11830         bool IsUnion = false;
11831         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11832           IsUnion = OrigRD->isUnion();
11833         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11834             << 2 << OrigTy << IsUnion << UseContext;
11835         // Reset OrigLoc so that this diagnostic is emitted only once.
11836         OrigLoc = SourceLocation();
11837       }
11838       InNonTrivialUnion = true;
11839     }
11840 
11841     if (InNonTrivialUnion)
11842       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11843           << 0 << 2 << QT.getUnqualifiedType() << "";
11844 
11845     for (const FieldDecl *FD : RD->fields())
11846       if (!shouldIgnoreForRecordTriviality(FD))
11847         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11848   }
11849 
11850   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11851                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11852   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11853   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11854                             bool InNonTrivialUnion) {}
11855 
11856   // The non-trivial C union type or the struct/union type that contains a
11857   // non-trivial C union.
11858   QualType OrigTy;
11859   SourceLocation OrigLoc;
11860   Sema::NonTrivialCUnionContext UseContext;
11861   Sema &S;
11862 };
11863 
11864 } // namespace
11865 
11866 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11867                                  NonTrivialCUnionContext UseContext,
11868                                  unsigned NonTrivialKind) {
11869   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11870           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11871           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11872          "shouldn't be called if type doesn't have a non-trivial C union");
11873 
11874   if ((NonTrivialKind & NTCUK_Init) &&
11875       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11876     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11877         .visit(QT, nullptr, false);
11878   if ((NonTrivialKind & NTCUK_Destruct) &&
11879       QT.hasNonTrivialToPrimitiveDestructCUnion())
11880     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11881         .visit(QT, nullptr, false);
11882   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11883     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11884         .visit(QT, nullptr, false);
11885 }
11886 
11887 /// AddInitializerToDecl - Adds the initializer Init to the
11888 /// declaration dcl. If DirectInit is true, this is C++ direct
11889 /// initialization rather than copy initialization.
11890 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11891   // If there is no declaration, there was an error parsing it.  Just ignore
11892   // the initializer.
11893   if (!RealDecl || RealDecl->isInvalidDecl()) {
11894     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11895     return;
11896   }
11897 
11898   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11899     // Pure-specifiers are handled in ActOnPureSpecifier.
11900     Diag(Method->getLocation(), diag::err_member_function_initialization)
11901       << Method->getDeclName() << Init->getSourceRange();
11902     Method->setInvalidDecl();
11903     return;
11904   }
11905 
11906   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11907   if (!VDecl) {
11908     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11909     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11910     RealDecl->setInvalidDecl();
11911     return;
11912   }
11913 
11914   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11915   if (VDecl->getType()->isUndeducedType()) {
11916     // Attempt typo correction early so that the type of the init expression can
11917     // be deduced based on the chosen correction if the original init contains a
11918     // TypoExpr.
11919     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11920     if (!Res.isUsable()) {
11921       // There are unresolved typos in Init, just drop them.
11922       // FIXME: improve the recovery strategy to preserve the Init.
11923       RealDecl->setInvalidDecl();
11924       return;
11925     }
11926     if (Res.get()->containsErrors()) {
11927       // Invalidate the decl as we don't know the type for recovery-expr yet.
11928       RealDecl->setInvalidDecl();
11929       VDecl->setInit(Res.get());
11930       return;
11931     }
11932     Init = Res.get();
11933 
11934     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11935       return;
11936   }
11937 
11938   // dllimport cannot be used on variable definitions.
11939   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11940     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11941     VDecl->setInvalidDecl();
11942     return;
11943   }
11944 
11945   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11946     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11947     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11948     VDecl->setInvalidDecl();
11949     return;
11950   }
11951 
11952   if (!VDecl->getType()->isDependentType()) {
11953     // A definition must end up with a complete type, which means it must be
11954     // complete with the restriction that an array type might be completed by
11955     // the initializer; note that later code assumes this restriction.
11956     QualType BaseDeclType = VDecl->getType();
11957     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11958       BaseDeclType = Array->getElementType();
11959     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11960                             diag::err_typecheck_decl_incomplete_type)) {
11961       RealDecl->setInvalidDecl();
11962       return;
11963     }
11964 
11965     // The variable can not have an abstract class type.
11966     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11967                                diag::err_abstract_type_in_decl,
11968                                AbstractVariableType))
11969       VDecl->setInvalidDecl();
11970   }
11971 
11972   // If adding the initializer will turn this declaration into a definition,
11973   // and we already have a definition for this variable, diagnose or otherwise
11974   // handle the situation.
11975   VarDecl *Def;
11976   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11977       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11978       !VDecl->isThisDeclarationADemotedDefinition() &&
11979       checkVarDeclRedefinition(Def, VDecl))
11980     return;
11981 
11982   if (getLangOpts().CPlusPlus) {
11983     // C++ [class.static.data]p4
11984     //   If a static data member is of const integral or const
11985     //   enumeration type, its declaration in the class definition can
11986     //   specify a constant-initializer which shall be an integral
11987     //   constant expression (5.19). In that case, the member can appear
11988     //   in integral constant expressions. The member shall still be
11989     //   defined in a namespace scope if it is used in the program and the
11990     //   namespace scope definition shall not contain an initializer.
11991     //
11992     // We already performed a redefinition check above, but for static
11993     // data members we also need to check whether there was an in-class
11994     // declaration with an initializer.
11995     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11996       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11997           << VDecl->getDeclName();
11998       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11999            diag::note_previous_initializer)
12000           << 0;
12001       return;
12002     }
12003 
12004     if (VDecl->hasLocalStorage())
12005       setFunctionHasBranchProtectedScope();
12006 
12007     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12008       VDecl->setInvalidDecl();
12009       return;
12010     }
12011   }
12012 
12013   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12014   // a kernel function cannot be initialized."
12015   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12016     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12017     VDecl->setInvalidDecl();
12018     return;
12019   }
12020 
12021   // The LoaderUninitialized attribute acts as a definition (of undef).
12022   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12023     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12024     VDecl->setInvalidDecl();
12025     return;
12026   }
12027 
12028   // Get the decls type and save a reference for later, since
12029   // CheckInitializerTypes may change it.
12030   QualType DclT = VDecl->getType(), SavT = DclT;
12031 
12032   // Expressions default to 'id' when we're in a debugger
12033   // and we are assigning it to a variable of Objective-C pointer type.
12034   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12035       Init->getType() == Context.UnknownAnyTy) {
12036     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12037     if (Result.isInvalid()) {
12038       VDecl->setInvalidDecl();
12039       return;
12040     }
12041     Init = Result.get();
12042   }
12043 
12044   // Perform the initialization.
12045   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12046   if (!VDecl->isInvalidDecl()) {
12047     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12048     InitializationKind Kind = InitializationKind::CreateForInit(
12049         VDecl->getLocation(), DirectInit, Init);
12050 
12051     MultiExprArg Args = Init;
12052     if (CXXDirectInit)
12053       Args = MultiExprArg(CXXDirectInit->getExprs(),
12054                           CXXDirectInit->getNumExprs());
12055 
12056     // Try to correct any TypoExprs in the initialization arguments.
12057     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12058       ExprResult Res = CorrectDelayedTyposInExpr(
12059           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/false,
12060           [this, Entity, Kind](Expr *E) {
12061             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12062             return Init.Failed() ? ExprError() : E;
12063           });
12064       if (Res.isInvalid()) {
12065         VDecl->setInvalidDecl();
12066       } else if (Res.get() != Args[Idx]) {
12067         Args[Idx] = Res.get();
12068       }
12069     }
12070     if (VDecl->isInvalidDecl())
12071       return;
12072 
12073     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12074                                    /*TopLevelOfInitList=*/false,
12075                                    /*TreatUnavailableAsInvalid=*/false);
12076     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12077     if (Result.isInvalid()) {
12078       // If the provied initializer fails to initialize the var decl,
12079       // we attach a recovery expr for better recovery.
12080       auto RecoveryExpr =
12081           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12082       if (RecoveryExpr.get())
12083         VDecl->setInit(RecoveryExpr.get());
12084       return;
12085     }
12086 
12087     Init = Result.getAs<Expr>();
12088   }
12089 
12090   // Check for self-references within variable initializers.
12091   // Variables declared within a function/method body (except for references)
12092   // are handled by a dataflow analysis.
12093   // This is undefined behavior in C++, but valid in C.
12094   if (getLangOpts().CPlusPlus) {
12095     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12096         VDecl->getType()->isReferenceType()) {
12097       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12098     }
12099   }
12100 
12101   // If the type changed, it means we had an incomplete type that was
12102   // completed by the initializer. For example:
12103   //   int ary[] = { 1, 3, 5 };
12104   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12105   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12106     VDecl->setType(DclT);
12107 
12108   if (!VDecl->isInvalidDecl()) {
12109     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12110 
12111     if (VDecl->hasAttr<BlocksAttr>())
12112       checkRetainCycles(VDecl, Init);
12113 
12114     // It is safe to assign a weak reference into a strong variable.
12115     // Although this code can still have problems:
12116     //   id x = self.weakProp;
12117     //   id y = self.weakProp;
12118     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12119     // paths through the function. This should be revisited if
12120     // -Wrepeated-use-of-weak is made flow-sensitive.
12121     if (FunctionScopeInfo *FSI = getCurFunction())
12122       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12123            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12124           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12125                            Init->getBeginLoc()))
12126         FSI->markSafeWeakUse(Init);
12127   }
12128 
12129   // The initialization is usually a full-expression.
12130   //
12131   // FIXME: If this is a braced initialization of an aggregate, it is not
12132   // an expression, and each individual field initializer is a separate
12133   // full-expression. For instance, in:
12134   //
12135   //   struct Temp { ~Temp(); };
12136   //   struct S { S(Temp); };
12137   //   struct T { S a, b; } t = { Temp(), Temp() }
12138   //
12139   // we should destroy the first Temp before constructing the second.
12140   ExprResult Result =
12141       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12142                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12143   if (Result.isInvalid()) {
12144     VDecl->setInvalidDecl();
12145     return;
12146   }
12147   Init = Result.get();
12148 
12149   // Attach the initializer to the decl.
12150   VDecl->setInit(Init);
12151 
12152   if (VDecl->isLocalVarDecl()) {
12153     // Don't check the initializer if the declaration is malformed.
12154     if (VDecl->isInvalidDecl()) {
12155       // do nothing
12156 
12157     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12158     // This is true even in C++ for OpenCL.
12159     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12160       CheckForConstantInitializer(Init, DclT);
12161 
12162     // Otherwise, C++ does not restrict the initializer.
12163     } else if (getLangOpts().CPlusPlus) {
12164       // do nothing
12165 
12166     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12167     // static storage duration shall be constant expressions or string literals.
12168     } else if (VDecl->getStorageClass() == SC_Static) {
12169       CheckForConstantInitializer(Init, DclT);
12170 
12171     // C89 is stricter than C99 for aggregate initializers.
12172     // C89 6.5.7p3: All the expressions [...] in an initializer list
12173     // for an object that has aggregate or union type shall be
12174     // constant expressions.
12175     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12176                isa<InitListExpr>(Init)) {
12177       const Expr *Culprit;
12178       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12179         Diag(Culprit->getExprLoc(),
12180              diag::ext_aggregate_init_not_constant)
12181           << Culprit->getSourceRange();
12182       }
12183     }
12184 
12185     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12186       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12187         if (VDecl->hasLocalStorage())
12188           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12189   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12190              VDecl->getLexicalDeclContext()->isRecord()) {
12191     // This is an in-class initialization for a static data member, e.g.,
12192     //
12193     // struct S {
12194     //   static const int value = 17;
12195     // };
12196 
12197     // C++ [class.mem]p4:
12198     //   A member-declarator can contain a constant-initializer only
12199     //   if it declares a static member (9.4) of const integral or
12200     //   const enumeration type, see 9.4.2.
12201     //
12202     // C++11 [class.static.data]p3:
12203     //   If a non-volatile non-inline const static data member is of integral
12204     //   or enumeration type, its declaration in the class definition can
12205     //   specify a brace-or-equal-initializer in which every initializer-clause
12206     //   that is an assignment-expression is a constant expression. A static
12207     //   data member of literal type can be declared in the class definition
12208     //   with the constexpr specifier; if so, its declaration shall specify a
12209     //   brace-or-equal-initializer in which every initializer-clause that is
12210     //   an assignment-expression is a constant expression.
12211 
12212     // Do nothing on dependent types.
12213     if (DclT->isDependentType()) {
12214 
12215     // Allow any 'static constexpr' members, whether or not they are of literal
12216     // type. We separately check that every constexpr variable is of literal
12217     // type.
12218     } else if (VDecl->isConstexpr()) {
12219 
12220     // Require constness.
12221     } else if (!DclT.isConstQualified()) {
12222       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12223         << Init->getSourceRange();
12224       VDecl->setInvalidDecl();
12225 
12226     // We allow integer constant expressions in all cases.
12227     } else if (DclT->isIntegralOrEnumerationType()) {
12228       // Check whether the expression is a constant expression.
12229       SourceLocation Loc;
12230       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12231         // In C++11, a non-constexpr const static data member with an
12232         // in-class initializer cannot be volatile.
12233         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12234       else if (Init->isValueDependent())
12235         ; // Nothing to check.
12236       else if (Init->isIntegerConstantExpr(Context, &Loc))
12237         ; // Ok, it's an ICE!
12238       else if (Init->getType()->isScopedEnumeralType() &&
12239                Init->isCXX11ConstantExpr(Context))
12240         ; // Ok, it is a scoped-enum constant expression.
12241       else if (Init->isEvaluatable(Context)) {
12242         // If we can constant fold the initializer through heroics, accept it,
12243         // but report this as a use of an extension for -pedantic.
12244         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12245           << Init->getSourceRange();
12246       } else {
12247         // Otherwise, this is some crazy unknown case.  Report the issue at the
12248         // location provided by the isIntegerConstantExpr failed check.
12249         Diag(Loc, diag::err_in_class_initializer_non_constant)
12250           << Init->getSourceRange();
12251         VDecl->setInvalidDecl();
12252       }
12253 
12254     // We allow foldable floating-point constants as an extension.
12255     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12256       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12257       // it anyway and provide a fixit to add the 'constexpr'.
12258       if (getLangOpts().CPlusPlus11) {
12259         Diag(VDecl->getLocation(),
12260              diag::ext_in_class_initializer_float_type_cxx11)
12261             << DclT << Init->getSourceRange();
12262         Diag(VDecl->getBeginLoc(),
12263              diag::note_in_class_initializer_float_type_cxx11)
12264             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12265       } else {
12266         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12267           << DclT << Init->getSourceRange();
12268 
12269         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12270           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12271             << Init->getSourceRange();
12272           VDecl->setInvalidDecl();
12273         }
12274       }
12275 
12276     // Suggest adding 'constexpr' in C++11 for literal types.
12277     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12278       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12279           << DclT << Init->getSourceRange()
12280           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12281       VDecl->setConstexpr(true);
12282 
12283     } else {
12284       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12285         << DclT << Init->getSourceRange();
12286       VDecl->setInvalidDecl();
12287     }
12288   } else if (VDecl->isFileVarDecl()) {
12289     // In C, extern is typically used to avoid tentative definitions when
12290     // declaring variables in headers, but adding an intializer makes it a
12291     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12292     // In C++, extern is often used to give implictly static const variables
12293     // external linkage, so don't warn in that case. If selectany is present,
12294     // this might be header code intended for C and C++ inclusion, so apply the
12295     // C++ rules.
12296     if (VDecl->getStorageClass() == SC_Extern &&
12297         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12298          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12299         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12300         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12301       Diag(VDecl->getLocation(), diag::warn_extern_init);
12302 
12303     // In Microsoft C++ mode, a const variable defined in namespace scope has
12304     // external linkage by default if the variable is declared with
12305     // __declspec(dllexport).
12306     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12307         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12308         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12309       VDecl->setStorageClass(SC_Extern);
12310 
12311     // C99 6.7.8p4. All file scoped initializers need to be constant.
12312     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12313       CheckForConstantInitializer(Init, DclT);
12314   }
12315 
12316   QualType InitType = Init->getType();
12317   if (!InitType.isNull() &&
12318       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12319        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12320     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12321 
12322   // We will represent direct-initialization similarly to copy-initialization:
12323   //    int x(1);  -as-> int x = 1;
12324   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12325   //
12326   // Clients that want to distinguish between the two forms, can check for
12327   // direct initializer using VarDecl::getInitStyle().
12328   // A major benefit is that clients that don't particularly care about which
12329   // exactly form was it (like the CodeGen) can handle both cases without
12330   // special case code.
12331 
12332   // C++ 8.5p11:
12333   // The form of initialization (using parentheses or '=') is generally
12334   // insignificant, but does matter when the entity being initialized has a
12335   // class type.
12336   if (CXXDirectInit) {
12337     assert(DirectInit && "Call-style initializer must be direct init.");
12338     VDecl->setInitStyle(VarDecl::CallInit);
12339   } else if (DirectInit) {
12340     // This must be list-initialization. No other way is direct-initialization.
12341     VDecl->setInitStyle(VarDecl::ListInit);
12342   }
12343 
12344   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12345     DeclsToCheckForDeferredDiags.push_back(VDecl);
12346   CheckCompleteVariableDeclaration(VDecl);
12347 }
12348 
12349 /// ActOnInitializerError - Given that there was an error parsing an
12350 /// initializer for the given declaration, try to return to some form
12351 /// of sanity.
12352 void Sema::ActOnInitializerError(Decl *D) {
12353   // Our main concern here is re-establishing invariants like "a
12354   // variable's type is either dependent or complete".
12355   if (!D || D->isInvalidDecl()) return;
12356 
12357   VarDecl *VD = dyn_cast<VarDecl>(D);
12358   if (!VD) return;
12359 
12360   // Bindings are not usable if we can't make sense of the initializer.
12361   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12362     for (auto *BD : DD->bindings())
12363       BD->setInvalidDecl();
12364 
12365   // Auto types are meaningless if we can't make sense of the initializer.
12366   if (VD->getType()->isUndeducedType()) {
12367     D->setInvalidDecl();
12368     return;
12369   }
12370 
12371   QualType Ty = VD->getType();
12372   if (Ty->isDependentType()) return;
12373 
12374   // Require a complete type.
12375   if (RequireCompleteType(VD->getLocation(),
12376                           Context.getBaseElementType(Ty),
12377                           diag::err_typecheck_decl_incomplete_type)) {
12378     VD->setInvalidDecl();
12379     return;
12380   }
12381 
12382   // Require a non-abstract type.
12383   if (RequireNonAbstractType(VD->getLocation(), Ty,
12384                              diag::err_abstract_type_in_decl,
12385                              AbstractVariableType)) {
12386     VD->setInvalidDecl();
12387     return;
12388   }
12389 
12390   // Don't bother complaining about constructors or destructors,
12391   // though.
12392 }
12393 
12394 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12395   // If there is no declaration, there was an error parsing it. Just ignore it.
12396   if (!RealDecl)
12397     return;
12398 
12399   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12400     QualType Type = Var->getType();
12401 
12402     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12403     if (isa<DecompositionDecl>(RealDecl)) {
12404       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12405       Var->setInvalidDecl();
12406       return;
12407     }
12408 
12409     if (Type->isUndeducedType() &&
12410         DeduceVariableDeclarationType(Var, false, nullptr))
12411       return;
12412 
12413     // C++11 [class.static.data]p3: A static data member can be declared with
12414     // the constexpr specifier; if so, its declaration shall specify
12415     // a brace-or-equal-initializer.
12416     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12417     // the definition of a variable [...] or the declaration of a static data
12418     // member.
12419     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12420         !Var->isThisDeclarationADemotedDefinition()) {
12421       if (Var->isStaticDataMember()) {
12422         // C++1z removes the relevant rule; the in-class declaration is always
12423         // a definition there.
12424         if (!getLangOpts().CPlusPlus17 &&
12425             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12426           Diag(Var->getLocation(),
12427                diag::err_constexpr_static_mem_var_requires_init)
12428             << Var->getDeclName();
12429           Var->setInvalidDecl();
12430           return;
12431         }
12432       } else {
12433         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12434         Var->setInvalidDecl();
12435         return;
12436       }
12437     }
12438 
12439     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12440     // be initialized.
12441     if (!Var->isInvalidDecl() &&
12442         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12443         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12444       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12445       Var->setInvalidDecl();
12446       return;
12447     }
12448 
12449     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12450       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12451         if (!RD->hasTrivialDefaultConstructor()) {
12452           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12453           Var->setInvalidDecl();
12454           return;
12455         }
12456       }
12457       if (Var->getStorageClass() == SC_Extern) {
12458         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12459             << Var;
12460         Var->setInvalidDecl();
12461         return;
12462       }
12463     }
12464 
12465     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12466     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12467         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12468       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12469                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12470 
12471 
12472     switch (DefKind) {
12473     case VarDecl::Definition:
12474       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12475         break;
12476 
12477       // We have an out-of-line definition of a static data member
12478       // that has an in-class initializer, so we type-check this like
12479       // a declaration.
12480       //
12481       LLVM_FALLTHROUGH;
12482 
12483     case VarDecl::DeclarationOnly:
12484       // It's only a declaration.
12485 
12486       // Block scope. C99 6.7p7: If an identifier for an object is
12487       // declared with no linkage (C99 6.2.2p6), the type for the
12488       // object shall be complete.
12489       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12490           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12491           RequireCompleteType(Var->getLocation(), Type,
12492                               diag::err_typecheck_decl_incomplete_type))
12493         Var->setInvalidDecl();
12494 
12495       // Make sure that the type is not abstract.
12496       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12497           RequireNonAbstractType(Var->getLocation(), Type,
12498                                  diag::err_abstract_type_in_decl,
12499                                  AbstractVariableType))
12500         Var->setInvalidDecl();
12501       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12502           Var->getStorageClass() == SC_PrivateExtern) {
12503         Diag(Var->getLocation(), diag::warn_private_extern);
12504         Diag(Var->getLocation(), diag::note_private_extern);
12505       }
12506 
12507       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12508           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12509         ExternalDeclarations.push_back(Var);
12510 
12511       return;
12512 
12513     case VarDecl::TentativeDefinition:
12514       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12515       // object that has file scope without an initializer, and without a
12516       // storage-class specifier or with the storage-class specifier "static",
12517       // constitutes a tentative definition. Note: A tentative definition with
12518       // external linkage is valid (C99 6.2.2p5).
12519       if (!Var->isInvalidDecl()) {
12520         if (const IncompleteArrayType *ArrayT
12521                                     = Context.getAsIncompleteArrayType(Type)) {
12522           if (RequireCompleteSizedType(
12523                   Var->getLocation(), ArrayT->getElementType(),
12524                   diag::err_array_incomplete_or_sizeless_type))
12525             Var->setInvalidDecl();
12526         } else if (Var->getStorageClass() == SC_Static) {
12527           // C99 6.9.2p3: If the declaration of an identifier for an object is
12528           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12529           // declared type shall not be an incomplete type.
12530           // NOTE: code such as the following
12531           //     static struct s;
12532           //     struct s { int a; };
12533           // is accepted by gcc. Hence here we issue a warning instead of
12534           // an error and we do not invalidate the static declaration.
12535           // NOTE: to avoid multiple warnings, only check the first declaration.
12536           if (Var->isFirstDecl())
12537             RequireCompleteType(Var->getLocation(), Type,
12538                                 diag::ext_typecheck_decl_incomplete_type);
12539         }
12540       }
12541 
12542       // Record the tentative definition; we're done.
12543       if (!Var->isInvalidDecl())
12544         TentativeDefinitions.push_back(Var);
12545       return;
12546     }
12547 
12548     // Provide a specific diagnostic for uninitialized variable
12549     // definitions with incomplete array type.
12550     if (Type->isIncompleteArrayType()) {
12551       Diag(Var->getLocation(),
12552            diag::err_typecheck_incomplete_array_needs_initializer);
12553       Var->setInvalidDecl();
12554       return;
12555     }
12556 
12557     // Provide a specific diagnostic for uninitialized variable
12558     // definitions with reference type.
12559     if (Type->isReferenceType()) {
12560       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12561         << Var->getDeclName()
12562         << SourceRange(Var->getLocation(), Var->getLocation());
12563       Var->setInvalidDecl();
12564       return;
12565     }
12566 
12567     // Do not attempt to type-check the default initializer for a
12568     // variable with dependent type.
12569     if (Type->isDependentType())
12570       return;
12571 
12572     if (Var->isInvalidDecl())
12573       return;
12574 
12575     if (!Var->hasAttr<AliasAttr>()) {
12576       if (RequireCompleteType(Var->getLocation(),
12577                               Context.getBaseElementType(Type),
12578                               diag::err_typecheck_decl_incomplete_type)) {
12579         Var->setInvalidDecl();
12580         return;
12581       }
12582     } else {
12583       return;
12584     }
12585 
12586     // The variable can not have an abstract class type.
12587     if (RequireNonAbstractType(Var->getLocation(), Type,
12588                                diag::err_abstract_type_in_decl,
12589                                AbstractVariableType)) {
12590       Var->setInvalidDecl();
12591       return;
12592     }
12593 
12594     // Check for jumps past the implicit initializer.  C++0x
12595     // clarifies that this applies to a "variable with automatic
12596     // storage duration", not a "local variable".
12597     // C++11 [stmt.dcl]p3
12598     //   A program that jumps from a point where a variable with automatic
12599     //   storage duration is not in scope to a point where it is in scope is
12600     //   ill-formed unless the variable has scalar type, class type with a
12601     //   trivial default constructor and a trivial destructor, a cv-qualified
12602     //   version of one of these types, or an array of one of the preceding
12603     //   types and is declared without an initializer.
12604     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12605       if (const RecordType *Record
12606             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12607         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12608         // Mark the function (if we're in one) for further checking even if the
12609         // looser rules of C++11 do not require such checks, so that we can
12610         // diagnose incompatibilities with C++98.
12611         if (!CXXRecord->isPOD())
12612           setFunctionHasBranchProtectedScope();
12613       }
12614     }
12615     // In OpenCL, we can't initialize objects in the __local address space,
12616     // even implicitly, so don't synthesize an implicit initializer.
12617     if (getLangOpts().OpenCL &&
12618         Var->getType().getAddressSpace() == LangAS::opencl_local)
12619       return;
12620     // C++03 [dcl.init]p9:
12621     //   If no initializer is specified for an object, and the
12622     //   object is of (possibly cv-qualified) non-POD class type (or
12623     //   array thereof), the object shall be default-initialized; if
12624     //   the object is of const-qualified type, the underlying class
12625     //   type shall have a user-declared default
12626     //   constructor. Otherwise, if no initializer is specified for
12627     //   a non- static object, the object and its subobjects, if
12628     //   any, have an indeterminate initial value); if the object
12629     //   or any of its subobjects are of const-qualified type, the
12630     //   program is ill-formed.
12631     // C++0x [dcl.init]p11:
12632     //   If no initializer is specified for an object, the object is
12633     //   default-initialized; [...].
12634     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12635     InitializationKind Kind
12636       = InitializationKind::CreateDefault(Var->getLocation());
12637 
12638     InitializationSequence InitSeq(*this, Entity, Kind, None);
12639     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12640 
12641     if (Init.get()) {
12642       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12643       // This is important for template substitution.
12644       Var->setInitStyle(VarDecl::CallInit);
12645     } else if (Init.isInvalid()) {
12646       // If default-init fails, attach a recovery-expr initializer to track
12647       // that initialization was attempted and failed.
12648       auto RecoveryExpr =
12649           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12650       if (RecoveryExpr.get())
12651         Var->setInit(RecoveryExpr.get());
12652     }
12653 
12654     CheckCompleteVariableDeclaration(Var);
12655   }
12656 }
12657 
12658 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12659   // If there is no declaration, there was an error parsing it. Ignore it.
12660   if (!D)
12661     return;
12662 
12663   VarDecl *VD = dyn_cast<VarDecl>(D);
12664   if (!VD) {
12665     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12666     D->setInvalidDecl();
12667     return;
12668   }
12669 
12670   VD->setCXXForRangeDecl(true);
12671 
12672   // for-range-declaration cannot be given a storage class specifier.
12673   int Error = -1;
12674   switch (VD->getStorageClass()) {
12675   case SC_None:
12676     break;
12677   case SC_Extern:
12678     Error = 0;
12679     break;
12680   case SC_Static:
12681     Error = 1;
12682     break;
12683   case SC_PrivateExtern:
12684     Error = 2;
12685     break;
12686   case SC_Auto:
12687     Error = 3;
12688     break;
12689   case SC_Register:
12690     Error = 4;
12691     break;
12692   }
12693   if (Error != -1) {
12694     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12695       << VD->getDeclName() << Error;
12696     D->setInvalidDecl();
12697   }
12698 }
12699 
12700 StmtResult
12701 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12702                                  IdentifierInfo *Ident,
12703                                  ParsedAttributes &Attrs,
12704                                  SourceLocation AttrEnd) {
12705   // C++1y [stmt.iter]p1:
12706   //   A range-based for statement of the form
12707   //      for ( for-range-identifier : for-range-initializer ) statement
12708   //   is equivalent to
12709   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12710   DeclSpec DS(Attrs.getPool().getFactory());
12711 
12712   const char *PrevSpec;
12713   unsigned DiagID;
12714   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12715                      getPrintingPolicy());
12716 
12717   Declarator D(DS, DeclaratorContext::ForContext);
12718   D.SetIdentifier(Ident, IdentLoc);
12719   D.takeAttributes(Attrs, AttrEnd);
12720 
12721   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12722                 IdentLoc);
12723   Decl *Var = ActOnDeclarator(S, D);
12724   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12725   FinalizeDeclaration(Var);
12726   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12727                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12728 }
12729 
12730 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12731   if (var->isInvalidDecl()) return;
12732 
12733   if (getLangOpts().OpenCL) {
12734     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12735     // initialiser
12736     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12737         !var->hasInit()) {
12738       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12739           << 1 /*Init*/;
12740       var->setInvalidDecl();
12741       return;
12742     }
12743   }
12744 
12745   // In Objective-C, don't allow jumps past the implicit initialization of a
12746   // local retaining variable.
12747   if (getLangOpts().ObjC &&
12748       var->hasLocalStorage()) {
12749     switch (var->getType().getObjCLifetime()) {
12750     case Qualifiers::OCL_None:
12751     case Qualifiers::OCL_ExplicitNone:
12752     case Qualifiers::OCL_Autoreleasing:
12753       break;
12754 
12755     case Qualifiers::OCL_Weak:
12756     case Qualifiers::OCL_Strong:
12757       setFunctionHasBranchProtectedScope();
12758       break;
12759     }
12760   }
12761 
12762   if (var->hasLocalStorage() &&
12763       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12764     setFunctionHasBranchProtectedScope();
12765 
12766   // Warn about externally-visible variables being defined without a
12767   // prior declaration.  We only want to do this for global
12768   // declarations, but we also specifically need to avoid doing it for
12769   // class members because the linkage of an anonymous class can
12770   // change if it's later given a typedef name.
12771   if (var->isThisDeclarationADefinition() &&
12772       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12773       var->isExternallyVisible() && var->hasLinkage() &&
12774       !var->isInline() && !var->getDescribedVarTemplate() &&
12775       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12776       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12777       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12778                                   var->getLocation())) {
12779     // Find a previous declaration that's not a definition.
12780     VarDecl *prev = var->getPreviousDecl();
12781     while (prev && prev->isThisDeclarationADefinition())
12782       prev = prev->getPreviousDecl();
12783 
12784     if (!prev) {
12785       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12786       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12787           << /* variable */ 0;
12788     }
12789   }
12790 
12791   // Cache the result of checking for constant initialization.
12792   Optional<bool> CacheHasConstInit;
12793   const Expr *CacheCulprit = nullptr;
12794   auto checkConstInit = [&]() mutable {
12795     if (!CacheHasConstInit)
12796       CacheHasConstInit = var->getInit()->isConstantInitializer(
12797             Context, var->getType()->isReferenceType(), &CacheCulprit);
12798     return *CacheHasConstInit;
12799   };
12800 
12801   if (var->getTLSKind() == VarDecl::TLS_Static) {
12802     if (var->getType().isDestructedType()) {
12803       // GNU C++98 edits for __thread, [basic.start.term]p3:
12804       //   The type of an object with thread storage duration shall not
12805       //   have a non-trivial destructor.
12806       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12807       if (getLangOpts().CPlusPlus11)
12808         Diag(var->getLocation(), diag::note_use_thread_local);
12809     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12810       if (!checkConstInit()) {
12811         // GNU C++98 edits for __thread, [basic.start.init]p4:
12812         //   An object of thread storage duration shall not require dynamic
12813         //   initialization.
12814         // FIXME: Need strict checking here.
12815         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12816           << CacheCulprit->getSourceRange();
12817         if (getLangOpts().CPlusPlus11)
12818           Diag(var->getLocation(), diag::note_use_thread_local);
12819       }
12820     }
12821   }
12822 
12823   // Apply section attributes and pragmas to global variables.
12824   bool GlobalStorage = var->hasGlobalStorage();
12825   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12826       !inTemplateInstantiation()) {
12827     PragmaStack<StringLiteral *> *Stack = nullptr;
12828     int SectionFlags = ASTContext::PSF_Read;
12829     if (var->getType().isConstQualified())
12830       Stack = &ConstSegStack;
12831     else if (!var->getInit()) {
12832       Stack = &BSSSegStack;
12833       SectionFlags |= ASTContext::PSF_Write;
12834     } else {
12835       Stack = &DataSegStack;
12836       SectionFlags |= ASTContext::PSF_Write;
12837     }
12838     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12839       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12840         SectionFlags |= ASTContext::PSF_Implicit;
12841       UnifySection(SA->getName(), SectionFlags, var);
12842     } else if (Stack->CurrentValue) {
12843       SectionFlags |= ASTContext::PSF_Implicit;
12844       auto SectionName = Stack->CurrentValue->getString();
12845       var->addAttr(SectionAttr::CreateImplicit(
12846           Context, SectionName, Stack->CurrentPragmaLocation,
12847           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12848       if (UnifySection(SectionName, SectionFlags, var))
12849         var->dropAttr<SectionAttr>();
12850     }
12851 
12852     // Apply the init_seg attribute if this has an initializer.  If the
12853     // initializer turns out to not be dynamic, we'll end up ignoring this
12854     // attribute.
12855     if (CurInitSeg && var->getInit())
12856       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12857                                                CurInitSegLoc,
12858                                                AttributeCommonInfo::AS_Pragma));
12859   }
12860 
12861   // All the following checks are C++ only.
12862   if (!getLangOpts().CPlusPlus) {
12863       // If this variable must be emitted, add it as an initializer for the
12864       // current module.
12865      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12866        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12867      return;
12868   }
12869 
12870   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12871     CheckCompleteDecompositionDeclaration(DD);
12872 
12873   QualType type = var->getType();
12874   if (type->isDependentType()) return;
12875 
12876   if (var->hasAttr<BlocksAttr>())
12877     getCurFunction()->addByrefBlockVar(var);
12878 
12879   Expr *Init = var->getInit();
12880   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12881   QualType baseType = Context.getBaseElementType(type);
12882 
12883   if (Init && !Init->isValueDependent()) {
12884     if (var->isConstexpr()) {
12885       SmallVector<PartialDiagnosticAt, 8> Notes;
12886       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12887         SourceLocation DiagLoc = var->getLocation();
12888         // If the note doesn't add any useful information other than a source
12889         // location, fold it into the primary diagnostic.
12890         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12891               diag::note_invalid_subexpr_in_const_expr) {
12892           DiagLoc = Notes[0].first;
12893           Notes.clear();
12894         }
12895         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12896           << var << Init->getSourceRange();
12897         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12898           Diag(Notes[I].first, Notes[I].second);
12899       }
12900     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12901       // Check whether the initializer of a const variable of integral or
12902       // enumeration type is an ICE now, since we can't tell whether it was
12903       // initialized by a constant expression if we check later.
12904       var->checkInitIsICE();
12905     }
12906 
12907     // Don't emit further diagnostics about constexpr globals since they
12908     // were just diagnosed.
12909     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12910       // FIXME: Need strict checking in C++03 here.
12911       bool DiagErr = getLangOpts().CPlusPlus11
12912           ? !var->checkInitIsICE() : !checkConstInit();
12913       if (DiagErr) {
12914         auto *Attr = var->getAttr<ConstInitAttr>();
12915         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12916           << Init->getSourceRange();
12917         Diag(Attr->getLocation(),
12918              diag::note_declared_required_constant_init_here)
12919             << Attr->getRange() << Attr->isConstinit();
12920         if (getLangOpts().CPlusPlus11) {
12921           APValue Value;
12922           SmallVector<PartialDiagnosticAt, 8> Notes;
12923           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12924           for (auto &it : Notes)
12925             Diag(it.first, it.second);
12926         } else {
12927           Diag(CacheCulprit->getExprLoc(),
12928                diag::note_invalid_subexpr_in_const_expr)
12929               << CacheCulprit->getSourceRange();
12930         }
12931       }
12932     }
12933     else if (!var->isConstexpr() && IsGlobal &&
12934              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12935                                     var->getLocation())) {
12936       // Warn about globals which don't have a constant initializer.  Don't
12937       // warn about globals with a non-trivial destructor because we already
12938       // warned about them.
12939       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12940       if (!(RD && !RD->hasTrivialDestructor())) {
12941         if (!checkConstInit())
12942           Diag(var->getLocation(), diag::warn_global_constructor)
12943             << Init->getSourceRange();
12944       }
12945     }
12946   }
12947 
12948   // Require the destructor.
12949   if (const RecordType *recordType = baseType->getAs<RecordType>())
12950     FinalizeVarWithDestructor(var, recordType);
12951 
12952   // If this variable must be emitted, add it as an initializer for the current
12953   // module.
12954   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12955     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12956 }
12957 
12958 /// Determines if a variable's alignment is dependent.
12959 static bool hasDependentAlignment(VarDecl *VD) {
12960   if (VD->getType()->isDependentType())
12961     return true;
12962   for (auto *I : VD->specific_attrs<AlignedAttr>())
12963     if (I->isAlignmentDependent())
12964       return true;
12965   return false;
12966 }
12967 
12968 /// Check if VD needs to be dllexport/dllimport due to being in a
12969 /// dllexport/import function.
12970 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12971   assert(VD->isStaticLocal());
12972 
12973   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12974 
12975   // Find outermost function when VD is in lambda function.
12976   while (FD && !getDLLAttr(FD) &&
12977          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12978          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12979     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12980   }
12981 
12982   if (!FD)
12983     return;
12984 
12985   // Static locals inherit dll attributes from their function.
12986   if (Attr *A = getDLLAttr(FD)) {
12987     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12988     NewAttr->setInherited(true);
12989     VD->addAttr(NewAttr);
12990   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12991     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12992     NewAttr->setInherited(true);
12993     VD->addAttr(NewAttr);
12994 
12995     // Export this function to enforce exporting this static variable even
12996     // if it is not used in this compilation unit.
12997     if (!FD->hasAttr<DLLExportAttr>())
12998       FD->addAttr(NewAttr);
12999 
13000   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13001     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13002     NewAttr->setInherited(true);
13003     VD->addAttr(NewAttr);
13004   }
13005 }
13006 
13007 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13008 /// any semantic actions necessary after any initializer has been attached.
13009 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13010   // Note that we are no longer parsing the initializer for this declaration.
13011   ParsingInitForAutoVars.erase(ThisDecl);
13012 
13013   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13014   if (!VD)
13015     return;
13016 
13017   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13018   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13019       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13020     if (PragmaClangBSSSection.Valid)
13021       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13022           Context, PragmaClangBSSSection.SectionName,
13023           PragmaClangBSSSection.PragmaLocation,
13024           AttributeCommonInfo::AS_Pragma));
13025     if (PragmaClangDataSection.Valid)
13026       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13027           Context, PragmaClangDataSection.SectionName,
13028           PragmaClangDataSection.PragmaLocation,
13029           AttributeCommonInfo::AS_Pragma));
13030     if (PragmaClangRodataSection.Valid)
13031       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13032           Context, PragmaClangRodataSection.SectionName,
13033           PragmaClangRodataSection.PragmaLocation,
13034           AttributeCommonInfo::AS_Pragma));
13035     if (PragmaClangRelroSection.Valid)
13036       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13037           Context, PragmaClangRelroSection.SectionName,
13038           PragmaClangRelroSection.PragmaLocation,
13039           AttributeCommonInfo::AS_Pragma));
13040   }
13041 
13042   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13043     for (auto *BD : DD->bindings()) {
13044       FinalizeDeclaration(BD);
13045     }
13046   }
13047 
13048   checkAttributesAfterMerging(*this, *VD);
13049 
13050   // Perform TLS alignment check here after attributes attached to the variable
13051   // which may affect the alignment have been processed. Only perform the check
13052   // if the target has a maximum TLS alignment (zero means no constraints).
13053   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13054     // Protect the check so that it's not performed on dependent types and
13055     // dependent alignments (we can't determine the alignment in that case).
13056     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13057         !VD->isInvalidDecl()) {
13058       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13059       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13060         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13061           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13062           << (unsigned)MaxAlignChars.getQuantity();
13063       }
13064     }
13065   }
13066 
13067   if (VD->isStaticLocal()) {
13068     CheckStaticLocalForDllExport(VD);
13069 
13070     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13071       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13072       // function, only __shared__ variables or variables without any device
13073       // memory qualifiers may be declared with static storage class.
13074       // Note: It is unclear how a function-scope non-const static variable
13075       // without device memory qualifier is implemented, therefore only static
13076       // const variable without device memory qualifier is allowed.
13077       [&]() {
13078         if (!getLangOpts().CUDA)
13079           return;
13080         if (VD->hasAttr<CUDASharedAttr>())
13081           return;
13082         if (VD->getType().isConstQualified() &&
13083             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13084           return;
13085         if (CUDADiagIfDeviceCode(VD->getLocation(),
13086                                  diag::err_device_static_local_var)
13087             << CurrentCUDATarget())
13088           VD->setInvalidDecl();
13089       }();
13090     }
13091   }
13092 
13093   // Perform check for initializers of device-side global variables.
13094   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13095   // 7.5). We must also apply the same checks to all __shared__
13096   // variables whether they are local or not. CUDA also allows
13097   // constant initializers for __constant__ and __device__ variables.
13098   if (getLangOpts().CUDA)
13099     checkAllowedCUDAInitializer(VD);
13100 
13101   // Grab the dllimport or dllexport attribute off of the VarDecl.
13102   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13103 
13104   // Imported static data members cannot be defined out-of-line.
13105   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13106     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13107         VD->isThisDeclarationADefinition()) {
13108       // We allow definitions of dllimport class template static data members
13109       // with a warning.
13110       CXXRecordDecl *Context =
13111         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13112       bool IsClassTemplateMember =
13113           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13114           Context->getDescribedClassTemplate();
13115 
13116       Diag(VD->getLocation(),
13117            IsClassTemplateMember
13118                ? diag::warn_attribute_dllimport_static_field_definition
13119                : diag::err_attribute_dllimport_static_field_definition);
13120       Diag(IA->getLocation(), diag::note_attribute);
13121       if (!IsClassTemplateMember)
13122         VD->setInvalidDecl();
13123     }
13124   }
13125 
13126   // dllimport/dllexport variables cannot be thread local, their TLS index
13127   // isn't exported with the variable.
13128   if (DLLAttr && VD->getTLSKind()) {
13129     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13130     if (F && getDLLAttr(F)) {
13131       assert(VD->isStaticLocal());
13132       // But if this is a static local in a dlimport/dllexport function, the
13133       // function will never be inlined, which means the var would never be
13134       // imported, so having it marked import/export is safe.
13135     } else {
13136       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13137                                                                     << DLLAttr;
13138       VD->setInvalidDecl();
13139     }
13140   }
13141 
13142   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13143     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13144       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13145       VD->dropAttr<UsedAttr>();
13146     }
13147   }
13148 
13149   const DeclContext *DC = VD->getDeclContext();
13150   // If there's a #pragma GCC visibility in scope, and this isn't a class
13151   // member, set the visibility of this variable.
13152   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13153     AddPushedVisibilityAttribute(VD);
13154 
13155   // FIXME: Warn on unused var template partial specializations.
13156   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13157     MarkUnusedFileScopedDecl(VD);
13158 
13159   // Now we have parsed the initializer and can update the table of magic
13160   // tag values.
13161   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13162       !VD->getType()->isIntegralOrEnumerationType())
13163     return;
13164 
13165   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13166     const Expr *MagicValueExpr = VD->getInit();
13167     if (!MagicValueExpr) {
13168       continue;
13169     }
13170     llvm::APSInt MagicValueInt;
13171     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
13172       Diag(I->getRange().getBegin(),
13173            diag::err_type_tag_for_datatype_not_ice)
13174         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13175       continue;
13176     }
13177     if (MagicValueInt.getActiveBits() > 64) {
13178       Diag(I->getRange().getBegin(),
13179            diag::err_type_tag_for_datatype_too_large)
13180         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13181       continue;
13182     }
13183     uint64_t MagicValue = MagicValueInt.getZExtValue();
13184     RegisterTypeTagForDatatype(I->getArgumentKind(),
13185                                MagicValue,
13186                                I->getMatchingCType(),
13187                                I->getLayoutCompatible(),
13188                                I->getMustBeNull());
13189   }
13190 }
13191 
13192 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13193   auto *VD = dyn_cast<VarDecl>(DD);
13194   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13195 }
13196 
13197 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13198                                                    ArrayRef<Decl *> Group) {
13199   SmallVector<Decl*, 8> Decls;
13200 
13201   if (DS.isTypeSpecOwned())
13202     Decls.push_back(DS.getRepAsDecl());
13203 
13204   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13205   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13206   bool DiagnosedMultipleDecomps = false;
13207   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13208   bool DiagnosedNonDeducedAuto = false;
13209 
13210   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13211     if (Decl *D = Group[i]) {
13212       // For declarators, there are some additional syntactic-ish checks we need
13213       // to perform.
13214       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13215         if (!FirstDeclaratorInGroup)
13216           FirstDeclaratorInGroup = DD;
13217         if (!FirstDecompDeclaratorInGroup)
13218           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13219         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13220             !hasDeducedAuto(DD))
13221           FirstNonDeducedAutoInGroup = DD;
13222 
13223         if (FirstDeclaratorInGroup != DD) {
13224           // A decomposition declaration cannot be combined with any other
13225           // declaration in the same group.
13226           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13227             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13228                  diag::err_decomp_decl_not_alone)
13229                 << FirstDeclaratorInGroup->getSourceRange()
13230                 << DD->getSourceRange();
13231             DiagnosedMultipleDecomps = true;
13232           }
13233 
13234           // A declarator that uses 'auto' in any way other than to declare a
13235           // variable with a deduced type cannot be combined with any other
13236           // declarator in the same group.
13237           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13238             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13239                  diag::err_auto_non_deduced_not_alone)
13240                 << FirstNonDeducedAutoInGroup->getType()
13241                        ->hasAutoForTrailingReturnType()
13242                 << FirstDeclaratorInGroup->getSourceRange()
13243                 << DD->getSourceRange();
13244             DiagnosedNonDeducedAuto = true;
13245           }
13246         }
13247       }
13248 
13249       Decls.push_back(D);
13250     }
13251   }
13252 
13253   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13254     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13255       handleTagNumbering(Tag, S);
13256       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13257           getLangOpts().CPlusPlus)
13258         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13259     }
13260   }
13261 
13262   return BuildDeclaratorGroup(Decls);
13263 }
13264 
13265 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13266 /// group, performing any necessary semantic checking.
13267 Sema::DeclGroupPtrTy
13268 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13269   // C++14 [dcl.spec.auto]p7: (DR1347)
13270   //   If the type that replaces the placeholder type is not the same in each
13271   //   deduction, the program is ill-formed.
13272   if (Group.size() > 1) {
13273     QualType Deduced;
13274     VarDecl *DeducedDecl = nullptr;
13275     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13276       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13277       if (!D || D->isInvalidDecl())
13278         break;
13279       DeducedType *DT = D->getType()->getContainedDeducedType();
13280       if (!DT || DT->getDeducedType().isNull())
13281         continue;
13282       if (Deduced.isNull()) {
13283         Deduced = DT->getDeducedType();
13284         DeducedDecl = D;
13285       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13286         auto *AT = dyn_cast<AutoType>(DT);
13287         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13288                         diag::err_auto_different_deductions)
13289                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13290                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13291                    << D->getDeclName();
13292         if (DeducedDecl->hasInit())
13293           Dia << DeducedDecl->getInit()->getSourceRange();
13294         if (D->getInit())
13295           Dia << D->getInit()->getSourceRange();
13296         D->setInvalidDecl();
13297         break;
13298       }
13299     }
13300   }
13301 
13302   ActOnDocumentableDecls(Group);
13303 
13304   return DeclGroupPtrTy::make(
13305       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13306 }
13307 
13308 void Sema::ActOnDocumentableDecl(Decl *D) {
13309   ActOnDocumentableDecls(D);
13310 }
13311 
13312 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13313   // Don't parse the comment if Doxygen diagnostics are ignored.
13314   if (Group.empty() || !Group[0])
13315     return;
13316 
13317   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13318                       Group[0]->getLocation()) &&
13319       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13320                       Group[0]->getLocation()))
13321     return;
13322 
13323   if (Group.size() >= 2) {
13324     // This is a decl group.  Normally it will contain only declarations
13325     // produced from declarator list.  But in case we have any definitions or
13326     // additional declaration references:
13327     //   'typedef struct S {} S;'
13328     //   'typedef struct S *S;'
13329     //   'struct S *pS;'
13330     // FinalizeDeclaratorGroup adds these as separate declarations.
13331     Decl *MaybeTagDecl = Group[0];
13332     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13333       Group = Group.slice(1);
13334     }
13335   }
13336 
13337   // FIMXE: We assume every Decl in the group is in the same file.
13338   // This is false when preprocessor constructs the group from decls in
13339   // different files (e. g. macros or #include).
13340   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13341 }
13342 
13343 /// Common checks for a parameter-declaration that should apply to both function
13344 /// parameters and non-type template parameters.
13345 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13346   // Check that there are no default arguments inside the type of this
13347   // parameter.
13348   if (getLangOpts().CPlusPlus)
13349     CheckExtraCXXDefaultArguments(D);
13350 
13351   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13352   if (D.getCXXScopeSpec().isSet()) {
13353     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13354       << D.getCXXScopeSpec().getRange();
13355   }
13356 
13357   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13358   // simple identifier except [...irrelevant cases...].
13359   switch (D.getName().getKind()) {
13360   case UnqualifiedIdKind::IK_Identifier:
13361     break;
13362 
13363   case UnqualifiedIdKind::IK_OperatorFunctionId:
13364   case UnqualifiedIdKind::IK_ConversionFunctionId:
13365   case UnqualifiedIdKind::IK_LiteralOperatorId:
13366   case UnqualifiedIdKind::IK_ConstructorName:
13367   case UnqualifiedIdKind::IK_DestructorName:
13368   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13369   case UnqualifiedIdKind::IK_DeductionGuideName:
13370     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13371       << GetNameForDeclarator(D).getName();
13372     break;
13373 
13374   case UnqualifiedIdKind::IK_TemplateId:
13375   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13376     // GetNameForDeclarator would not produce a useful name in this case.
13377     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13378     break;
13379   }
13380 }
13381 
13382 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13383 /// to introduce parameters into function prototype scope.
13384 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13385   const DeclSpec &DS = D.getDeclSpec();
13386 
13387   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13388 
13389   // C++03 [dcl.stc]p2 also permits 'auto'.
13390   StorageClass SC = SC_None;
13391   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13392     SC = SC_Register;
13393     // In C++11, the 'register' storage class specifier is deprecated.
13394     // In C++17, it is not allowed, but we tolerate it as an extension.
13395     if (getLangOpts().CPlusPlus11) {
13396       Diag(DS.getStorageClassSpecLoc(),
13397            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13398                                      : diag::warn_deprecated_register)
13399         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13400     }
13401   } else if (getLangOpts().CPlusPlus &&
13402              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13403     SC = SC_Auto;
13404   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13405     Diag(DS.getStorageClassSpecLoc(),
13406          diag::err_invalid_storage_class_in_func_decl);
13407     D.getMutableDeclSpec().ClearStorageClassSpecs();
13408   }
13409 
13410   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13411     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13412       << DeclSpec::getSpecifierName(TSCS);
13413   if (DS.isInlineSpecified())
13414     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13415         << getLangOpts().CPlusPlus17;
13416   if (DS.hasConstexprSpecifier())
13417     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13418         << 0 << D.getDeclSpec().getConstexprSpecifier();
13419 
13420   DiagnoseFunctionSpecifiers(DS);
13421 
13422   CheckFunctionOrTemplateParamDeclarator(S, D);
13423 
13424   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13425   QualType parmDeclType = TInfo->getType();
13426 
13427   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13428   IdentifierInfo *II = D.getIdentifier();
13429   if (II) {
13430     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13431                    ForVisibleRedeclaration);
13432     LookupName(R, S);
13433     if (R.isSingleResult()) {
13434       NamedDecl *PrevDecl = R.getFoundDecl();
13435       if (PrevDecl->isTemplateParameter()) {
13436         // Maybe we will complain about the shadowed template parameter.
13437         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13438         // Just pretend that we didn't see the previous declaration.
13439         PrevDecl = nullptr;
13440       } else if (S->isDeclScope(PrevDecl)) {
13441         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13442         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13443 
13444         // Recover by removing the name
13445         II = nullptr;
13446         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13447         D.setInvalidType(true);
13448       }
13449     }
13450   }
13451 
13452   // Temporarily put parameter variables in the translation unit, not
13453   // the enclosing context.  This prevents them from accidentally
13454   // looking like class members in C++.
13455   ParmVarDecl *New =
13456       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13457                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13458 
13459   if (D.isInvalidType())
13460     New->setInvalidDecl();
13461 
13462   assert(S->isFunctionPrototypeScope());
13463   assert(S->getFunctionPrototypeDepth() >= 1);
13464   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13465                     S->getNextFunctionPrototypeIndex());
13466 
13467   // Add the parameter declaration into this scope.
13468   S->AddDecl(New);
13469   if (II)
13470     IdResolver.AddDecl(New);
13471 
13472   ProcessDeclAttributes(S, New, D);
13473 
13474   if (D.getDeclSpec().isModulePrivateSpecified())
13475     Diag(New->getLocation(), diag::err_module_private_local)
13476       << 1 << New->getDeclName()
13477       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13478       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13479 
13480   if (New->hasAttr<BlocksAttr>()) {
13481     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13482   }
13483 
13484   if (getLangOpts().OpenCL)
13485     deduceOpenCLAddressSpace(New);
13486 
13487   return New;
13488 }
13489 
13490 /// Synthesizes a variable for a parameter arising from a
13491 /// typedef.
13492 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13493                                               SourceLocation Loc,
13494                                               QualType T) {
13495   /* FIXME: setting StartLoc == Loc.
13496      Would it be worth to modify callers so as to provide proper source
13497      location for the unnamed parameters, embedding the parameter's type? */
13498   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13499                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13500                                            SC_None, nullptr);
13501   Param->setImplicit();
13502   return Param;
13503 }
13504 
13505 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13506   // Don't diagnose unused-parameter errors in template instantiations; we
13507   // will already have done so in the template itself.
13508   if (inTemplateInstantiation())
13509     return;
13510 
13511   for (const ParmVarDecl *Parameter : Parameters) {
13512     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13513         !Parameter->hasAttr<UnusedAttr>()) {
13514       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13515         << Parameter->getDeclName();
13516     }
13517   }
13518 }
13519 
13520 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13521     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13522   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13523     return;
13524 
13525   // Warn if the return value is pass-by-value and larger than the specified
13526   // threshold.
13527   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13528     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13529     if (Size > LangOpts.NumLargeByValueCopy)
13530       Diag(D->getLocation(), diag::warn_return_value_size)
13531           << D->getDeclName() << Size;
13532   }
13533 
13534   // Warn if any parameter is pass-by-value and larger than the specified
13535   // threshold.
13536   for (const ParmVarDecl *Parameter : Parameters) {
13537     QualType T = Parameter->getType();
13538     if (T->isDependentType() || !T.isPODType(Context))
13539       continue;
13540     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13541     if (Size > LangOpts.NumLargeByValueCopy)
13542       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13543           << Parameter->getDeclName() << Size;
13544   }
13545 }
13546 
13547 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13548                                   SourceLocation NameLoc, IdentifierInfo *Name,
13549                                   QualType T, TypeSourceInfo *TSInfo,
13550                                   StorageClass SC) {
13551   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13552   if (getLangOpts().ObjCAutoRefCount &&
13553       T.getObjCLifetime() == Qualifiers::OCL_None &&
13554       T->isObjCLifetimeType()) {
13555 
13556     Qualifiers::ObjCLifetime lifetime;
13557 
13558     // Special cases for arrays:
13559     //   - if it's const, use __unsafe_unretained
13560     //   - otherwise, it's an error
13561     if (T->isArrayType()) {
13562       if (!T.isConstQualified()) {
13563         if (DelayedDiagnostics.shouldDelayDiagnostics())
13564           DelayedDiagnostics.add(
13565               sema::DelayedDiagnostic::makeForbiddenType(
13566               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13567         else
13568           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13569               << TSInfo->getTypeLoc().getSourceRange();
13570       }
13571       lifetime = Qualifiers::OCL_ExplicitNone;
13572     } else {
13573       lifetime = T->getObjCARCImplicitLifetime();
13574     }
13575     T = Context.getLifetimeQualifiedType(T, lifetime);
13576   }
13577 
13578   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13579                                          Context.getAdjustedParameterType(T),
13580                                          TSInfo, SC, nullptr);
13581 
13582   // Make a note if we created a new pack in the scope of a lambda, so that
13583   // we know that references to that pack must also be expanded within the
13584   // lambda scope.
13585   if (New->isParameterPack())
13586     if (auto *LSI = getEnclosingLambda())
13587       LSI->LocalPacks.push_back(New);
13588 
13589   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13590       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13591     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13592                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13593 
13594   // Parameters can not be abstract class types.
13595   // For record types, this is done by the AbstractClassUsageDiagnoser once
13596   // the class has been completely parsed.
13597   if (!CurContext->isRecord() &&
13598       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13599                              AbstractParamType))
13600     New->setInvalidDecl();
13601 
13602   // Parameter declarators cannot be interface types. All ObjC objects are
13603   // passed by reference.
13604   if (T->isObjCObjectType()) {
13605     SourceLocation TypeEndLoc =
13606         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13607     Diag(NameLoc,
13608          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13609       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13610     T = Context.getObjCObjectPointerType(T);
13611     New->setType(T);
13612   }
13613 
13614   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13615   // duration shall not be qualified by an address-space qualifier."
13616   // Since all parameters have automatic store duration, they can not have
13617   // an address space.
13618   if (T.getAddressSpace() != LangAS::Default &&
13619       // OpenCL allows function arguments declared to be an array of a type
13620       // to be qualified with an address space.
13621       !(getLangOpts().OpenCL &&
13622         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13623     Diag(NameLoc, diag::err_arg_with_address_space);
13624     New->setInvalidDecl();
13625   }
13626 
13627   return New;
13628 }
13629 
13630 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13631                                            SourceLocation LocAfterDecls) {
13632   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13633 
13634   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13635   // for a K&R function.
13636   if (!FTI.hasPrototype) {
13637     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13638       --i;
13639       if (FTI.Params[i].Param == nullptr) {
13640         SmallString<256> Code;
13641         llvm::raw_svector_ostream(Code)
13642             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13643         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13644             << FTI.Params[i].Ident
13645             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13646 
13647         // Implicitly declare the argument as type 'int' for lack of a better
13648         // type.
13649         AttributeFactory attrs;
13650         DeclSpec DS(attrs);
13651         const char* PrevSpec; // unused
13652         unsigned DiagID; // unused
13653         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13654                            DiagID, Context.getPrintingPolicy());
13655         // Use the identifier location for the type source range.
13656         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13657         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13658         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13659         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13660         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13661       }
13662     }
13663   }
13664 }
13665 
13666 Decl *
13667 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13668                               MultiTemplateParamsArg TemplateParameterLists,
13669                               SkipBodyInfo *SkipBody) {
13670   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13671   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13672   Scope *ParentScope = FnBodyScope->getParent();
13673 
13674   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13675   // we define a non-templated function definition, we will create a declaration
13676   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13677   // The base function declaration will have the equivalent of an `omp declare
13678   // variant` annotation which specifies the mangled definition as a
13679   // specialization function under the OpenMP context defined as part of the
13680   // `omp begin declare variant`.
13681   FunctionDecl *BaseFD = nullptr;
13682   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() &&
13683       TemplateParameterLists.empty())
13684     BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13685         ParentScope, D);
13686 
13687   D.setFunctionDefinitionKind(FDK_Definition);
13688   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13689   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13690 
13691   if (BaseFD)
13692     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
13693         cast<FunctionDecl>(Dcl), BaseFD);
13694 
13695   return Dcl;
13696 }
13697 
13698 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13699   Consumer.HandleInlineFunctionDefinition(D);
13700 }
13701 
13702 static bool
13703 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13704                                 const FunctionDecl *&PossiblePrototype) {
13705   // Don't warn about invalid declarations.
13706   if (FD->isInvalidDecl())
13707     return false;
13708 
13709   // Or declarations that aren't global.
13710   if (!FD->isGlobal())
13711     return false;
13712 
13713   // Don't warn about C++ member functions.
13714   if (isa<CXXMethodDecl>(FD))
13715     return false;
13716 
13717   // Don't warn about 'main'.
13718   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13719     if (IdentifierInfo *II = FD->getIdentifier())
13720       if (II->isStr("main"))
13721         return false;
13722 
13723   // Don't warn about inline functions.
13724   if (FD->isInlined())
13725     return false;
13726 
13727   // Don't warn about function templates.
13728   if (FD->getDescribedFunctionTemplate())
13729     return false;
13730 
13731   // Don't warn about function template specializations.
13732   if (FD->isFunctionTemplateSpecialization())
13733     return false;
13734 
13735   // Don't warn for OpenCL kernels.
13736   if (FD->hasAttr<OpenCLKernelAttr>())
13737     return false;
13738 
13739   // Don't warn on explicitly deleted functions.
13740   if (FD->isDeleted())
13741     return false;
13742 
13743   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13744        Prev; Prev = Prev->getPreviousDecl()) {
13745     // Ignore any declarations that occur in function or method
13746     // scope, because they aren't visible from the header.
13747     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13748       continue;
13749 
13750     PossiblePrototype = Prev;
13751     return Prev->getType()->isFunctionNoProtoType();
13752   }
13753 
13754   return true;
13755 }
13756 
13757 void
13758 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13759                                    const FunctionDecl *EffectiveDefinition,
13760                                    SkipBodyInfo *SkipBody) {
13761   const FunctionDecl *Definition = EffectiveDefinition;
13762   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13763     // If this is a friend function defined in a class template, it does not
13764     // have a body until it is used, nevertheless it is a definition, see
13765     // [temp.inst]p2:
13766     //
13767     // ... for the purpose of determining whether an instantiated redeclaration
13768     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13769     // corresponds to a definition in the template is considered to be a
13770     // definition.
13771     //
13772     // The following code must produce redefinition error:
13773     //
13774     //     template<typename T> struct C20 { friend void func_20() {} };
13775     //     C20<int> c20i;
13776     //     void func_20() {}
13777     //
13778     for (auto I : FD->redecls()) {
13779       if (I != FD && !I->isInvalidDecl() &&
13780           I->getFriendObjectKind() != Decl::FOK_None) {
13781         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13782           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13783             // A merged copy of the same function, instantiated as a member of
13784             // the same class, is OK.
13785             if (declaresSameEntity(OrigFD, Original) &&
13786                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13787                                    cast<Decl>(FD->getLexicalDeclContext())))
13788               continue;
13789           }
13790 
13791           if (Original->isThisDeclarationADefinition()) {
13792             Definition = I;
13793             break;
13794           }
13795         }
13796       }
13797     }
13798   }
13799 
13800   if (!Definition)
13801     // Similar to friend functions a friend function template may be a
13802     // definition and do not have a body if it is instantiated in a class
13803     // template.
13804     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13805       for (auto I : FTD->redecls()) {
13806         auto D = cast<FunctionTemplateDecl>(I);
13807         if (D != FTD) {
13808           assert(!D->isThisDeclarationADefinition() &&
13809                  "More than one definition in redeclaration chain");
13810           if (D->getFriendObjectKind() != Decl::FOK_None)
13811             if (FunctionTemplateDecl *FT =
13812                                        D->getInstantiatedFromMemberTemplate()) {
13813               if (FT->isThisDeclarationADefinition()) {
13814                 Definition = D->getTemplatedDecl();
13815                 break;
13816               }
13817             }
13818         }
13819       }
13820     }
13821 
13822   if (!Definition)
13823     return;
13824 
13825   if (canRedefineFunction(Definition, getLangOpts()))
13826     return;
13827 
13828   // Don't emit an error when this is redefinition of a typo-corrected
13829   // definition.
13830   if (TypoCorrectedFunctionDefinitions.count(Definition))
13831     return;
13832 
13833   // If we don't have a visible definition of the function, and it's inline or
13834   // a template, skip the new definition.
13835   if (SkipBody && !hasVisibleDefinition(Definition) &&
13836       (Definition->getFormalLinkage() == InternalLinkage ||
13837        Definition->isInlined() ||
13838        Definition->getDescribedFunctionTemplate() ||
13839        Definition->getNumTemplateParameterLists())) {
13840     SkipBody->ShouldSkip = true;
13841     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13842     if (auto *TD = Definition->getDescribedFunctionTemplate())
13843       makeMergedDefinitionVisible(TD);
13844     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13845     return;
13846   }
13847 
13848   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13849       Definition->getStorageClass() == SC_Extern)
13850     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13851         << FD->getDeclName() << getLangOpts().CPlusPlus;
13852   else
13853     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13854 
13855   Diag(Definition->getLocation(), diag::note_previous_definition);
13856   FD->setInvalidDecl();
13857 }
13858 
13859 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13860                                    Sema &S) {
13861   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13862 
13863   LambdaScopeInfo *LSI = S.PushLambdaScope();
13864   LSI->CallOperator = CallOperator;
13865   LSI->Lambda = LambdaClass;
13866   LSI->ReturnType = CallOperator->getReturnType();
13867   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13868 
13869   if (LCD == LCD_None)
13870     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13871   else if (LCD == LCD_ByCopy)
13872     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13873   else if (LCD == LCD_ByRef)
13874     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13875   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13876 
13877   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13878   LSI->Mutable = !CallOperator->isConst();
13879 
13880   // Add the captures to the LSI so they can be noted as already
13881   // captured within tryCaptureVar.
13882   auto I = LambdaClass->field_begin();
13883   for (const auto &C : LambdaClass->captures()) {
13884     if (C.capturesVariable()) {
13885       VarDecl *VD = C.getCapturedVar();
13886       if (VD->isInitCapture())
13887         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13888       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13889       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13890           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13891           /*EllipsisLoc*/C.isPackExpansion()
13892                          ? C.getEllipsisLoc() : SourceLocation(),
13893           I->getType(), /*Invalid*/false);
13894 
13895     } else if (C.capturesThis()) {
13896       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13897                           C.getCaptureKind() == LCK_StarThis);
13898     } else {
13899       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13900                              I->getType());
13901     }
13902     ++I;
13903   }
13904 }
13905 
13906 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13907                                     SkipBodyInfo *SkipBody) {
13908   if (!D) {
13909     // Parsing the function declaration failed in some way. Push on a fake scope
13910     // anyway so we can try to parse the function body.
13911     PushFunctionScope();
13912     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13913     return D;
13914   }
13915 
13916   FunctionDecl *FD = nullptr;
13917 
13918   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13919     FD = FunTmpl->getTemplatedDecl();
13920   else
13921     FD = cast<FunctionDecl>(D);
13922 
13923   // Do not push if it is a lambda because one is already pushed when building
13924   // the lambda in ActOnStartOfLambdaDefinition().
13925   if (!isLambdaCallOperator(FD))
13926     PushExpressionEvaluationContext(
13927         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
13928                           : ExprEvalContexts.back().Context);
13929 
13930   // Check for defining attributes before the check for redefinition.
13931   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13932     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13933     FD->dropAttr<AliasAttr>();
13934     FD->setInvalidDecl();
13935   }
13936   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13937     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13938     FD->dropAttr<IFuncAttr>();
13939     FD->setInvalidDecl();
13940   }
13941 
13942   // See if this is a redefinition. If 'will have body' is already set, then
13943   // these checks were already performed when it was set.
13944   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13945     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13946 
13947     // If we're skipping the body, we're done. Don't enter the scope.
13948     if (SkipBody && SkipBody->ShouldSkip)
13949       return D;
13950   }
13951 
13952   // Mark this function as "will have a body eventually".  This lets users to
13953   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13954   // this function.
13955   FD->setWillHaveBody();
13956 
13957   // If we are instantiating a generic lambda call operator, push
13958   // a LambdaScopeInfo onto the function stack.  But use the information
13959   // that's already been calculated (ActOnLambdaExpr) to prime the current
13960   // LambdaScopeInfo.
13961   // When the template operator is being specialized, the LambdaScopeInfo,
13962   // has to be properly restored so that tryCaptureVariable doesn't try
13963   // and capture any new variables. In addition when calculating potential
13964   // captures during transformation of nested lambdas, it is necessary to
13965   // have the LSI properly restored.
13966   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13967     assert(inTemplateInstantiation() &&
13968            "There should be an active template instantiation on the stack "
13969            "when instantiating a generic lambda!");
13970     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13971   } else {
13972     // Enter a new function scope
13973     PushFunctionScope();
13974   }
13975 
13976   // Builtin functions cannot be defined.
13977   if (unsigned BuiltinID = FD->getBuiltinID()) {
13978     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13979         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13980       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13981       FD->setInvalidDecl();
13982     }
13983   }
13984 
13985   // The return type of a function definition must be complete
13986   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13987   QualType ResultType = FD->getReturnType();
13988   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13989       !FD->isInvalidDecl() &&
13990       RequireCompleteType(FD->getLocation(), ResultType,
13991                           diag::err_func_def_incomplete_result))
13992     FD->setInvalidDecl();
13993 
13994   if (FnBodyScope)
13995     PushDeclContext(FnBodyScope, FD);
13996 
13997   // Check the validity of our function parameters
13998   CheckParmsForFunctionDef(FD->parameters(),
13999                            /*CheckParameterNames=*/true);
14000 
14001   // Add non-parameter declarations already in the function to the current
14002   // scope.
14003   if (FnBodyScope) {
14004     for (Decl *NPD : FD->decls()) {
14005       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14006       if (!NonParmDecl)
14007         continue;
14008       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14009              "parameters should not be in newly created FD yet");
14010 
14011       // If the decl has a name, make it accessible in the current scope.
14012       if (NonParmDecl->getDeclName())
14013         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14014 
14015       // Similarly, dive into enums and fish their constants out, making them
14016       // accessible in this scope.
14017       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14018         for (auto *EI : ED->enumerators())
14019           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14020       }
14021     }
14022   }
14023 
14024   // Introduce our parameters into the function scope
14025   for (auto Param : FD->parameters()) {
14026     Param->setOwningFunction(FD);
14027 
14028     // If this has an identifier, add it to the scope stack.
14029     if (Param->getIdentifier() && FnBodyScope) {
14030       CheckShadow(FnBodyScope, Param);
14031 
14032       PushOnScopeChains(Param, FnBodyScope);
14033     }
14034   }
14035 
14036   // Ensure that the function's exception specification is instantiated.
14037   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14038     ResolveExceptionSpec(D->getLocation(), FPT);
14039 
14040   // dllimport cannot be applied to non-inline function definitions.
14041   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14042       !FD->isTemplateInstantiation()) {
14043     assert(!FD->hasAttr<DLLExportAttr>());
14044     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14045     FD->setInvalidDecl();
14046     return D;
14047   }
14048   // We want to attach documentation to original Decl (which might be
14049   // a function template).
14050   ActOnDocumentableDecl(D);
14051   if (getCurLexicalContext()->isObjCContainer() &&
14052       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14053       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14054     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14055 
14056   return D;
14057 }
14058 
14059 /// Given the set of return statements within a function body,
14060 /// compute the variables that are subject to the named return value
14061 /// optimization.
14062 ///
14063 /// Each of the variables that is subject to the named return value
14064 /// optimization will be marked as NRVO variables in the AST, and any
14065 /// return statement that has a marked NRVO variable as its NRVO candidate can
14066 /// use the named return value optimization.
14067 ///
14068 /// This function applies a very simplistic algorithm for NRVO: if every return
14069 /// statement in the scope of a variable has the same NRVO candidate, that
14070 /// candidate is an NRVO variable.
14071 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14072   ReturnStmt **Returns = Scope->Returns.data();
14073 
14074   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14075     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14076       if (!NRVOCandidate->isNRVOVariable())
14077         Returns[I]->setNRVOCandidate(nullptr);
14078     }
14079   }
14080 }
14081 
14082 bool Sema::canDelayFunctionBody(const Declarator &D) {
14083   // We can't delay parsing the body of a constexpr function template (yet).
14084   if (D.getDeclSpec().hasConstexprSpecifier())
14085     return false;
14086 
14087   // We can't delay parsing the body of a function template with a deduced
14088   // return type (yet).
14089   if (D.getDeclSpec().hasAutoTypeSpec()) {
14090     // If the placeholder introduces a non-deduced trailing return type,
14091     // we can still delay parsing it.
14092     if (D.getNumTypeObjects()) {
14093       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14094       if (Outer.Kind == DeclaratorChunk::Function &&
14095           Outer.Fun.hasTrailingReturnType()) {
14096         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14097         return Ty.isNull() || !Ty->isUndeducedType();
14098       }
14099     }
14100     return false;
14101   }
14102 
14103   return true;
14104 }
14105 
14106 bool Sema::canSkipFunctionBody(Decl *D) {
14107   // We cannot skip the body of a function (or function template) which is
14108   // constexpr, since we may need to evaluate its body in order to parse the
14109   // rest of the file.
14110   // We cannot skip the body of a function with an undeduced return type,
14111   // because any callers of that function need to know the type.
14112   if (const FunctionDecl *FD = D->getAsFunction()) {
14113     if (FD->isConstexpr())
14114       return false;
14115     // We can't simply call Type::isUndeducedType here, because inside template
14116     // auto can be deduced to a dependent type, which is not considered
14117     // "undeduced".
14118     if (FD->getReturnType()->getContainedDeducedType())
14119       return false;
14120   }
14121   return Consumer.shouldSkipFunctionBody(D);
14122 }
14123 
14124 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14125   if (!Decl)
14126     return nullptr;
14127   if (FunctionDecl *FD = Decl->getAsFunction())
14128     FD->setHasSkippedBody();
14129   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14130     MD->setHasSkippedBody();
14131   return Decl;
14132 }
14133 
14134 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14135   return ActOnFinishFunctionBody(D, BodyArg, false);
14136 }
14137 
14138 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14139 /// body.
14140 class ExitFunctionBodyRAII {
14141 public:
14142   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14143   ~ExitFunctionBodyRAII() {
14144     if (!IsLambda)
14145       S.PopExpressionEvaluationContext();
14146   }
14147 
14148 private:
14149   Sema &S;
14150   bool IsLambda = false;
14151 };
14152 
14153 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14154   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14155 
14156   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14157     if (EscapeInfo.count(BD))
14158       return EscapeInfo[BD];
14159 
14160     bool R = false;
14161     const BlockDecl *CurBD = BD;
14162 
14163     do {
14164       R = !CurBD->doesNotEscape();
14165       if (R)
14166         break;
14167       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14168     } while (CurBD);
14169 
14170     return EscapeInfo[BD] = R;
14171   };
14172 
14173   // If the location where 'self' is implicitly retained is inside a escaping
14174   // block, emit a diagnostic.
14175   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14176        S.ImplicitlyRetainedSelfLocs)
14177     if (IsOrNestedInEscapingBlock(P.second))
14178       S.Diag(P.first, diag::warn_implicitly_retains_self)
14179           << FixItHint::CreateInsertion(P.first, "self->");
14180 }
14181 
14182 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14183                                     bool IsInstantiation) {
14184   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14185 
14186   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14187   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14188 
14189   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14190     CheckCompletedCoroutineBody(FD, Body);
14191 
14192   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14193   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14194   // meant to pop the context added in ActOnStartOfFunctionDef().
14195   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14196 
14197   if (FD) {
14198     FD->setBody(Body);
14199     FD->setWillHaveBody(false);
14200 
14201     if (getLangOpts().CPlusPlus14) {
14202       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14203           FD->getReturnType()->isUndeducedType()) {
14204         // If the function has a deduced result type but contains no 'return'
14205         // statements, the result type as written must be exactly 'auto', and
14206         // the deduced result type is 'void'.
14207         if (!FD->getReturnType()->getAs<AutoType>()) {
14208           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14209               << FD->getReturnType();
14210           FD->setInvalidDecl();
14211         } else {
14212           // Substitute 'void' for the 'auto' in the type.
14213           TypeLoc ResultType = getReturnTypeLoc(FD);
14214           Context.adjustDeducedFunctionResultType(
14215               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14216         }
14217       }
14218     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14219       // In C++11, we don't use 'auto' deduction rules for lambda call
14220       // operators because we don't support return type deduction.
14221       auto *LSI = getCurLambda();
14222       if (LSI->HasImplicitReturnType) {
14223         deduceClosureReturnType(*LSI);
14224 
14225         // C++11 [expr.prim.lambda]p4:
14226         //   [...] if there are no return statements in the compound-statement
14227         //   [the deduced type is] the type void
14228         QualType RetType =
14229             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14230 
14231         // Update the return type to the deduced type.
14232         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14233         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14234                                             Proto->getExtProtoInfo()));
14235       }
14236     }
14237 
14238     // If the function implicitly returns zero (like 'main') or is naked,
14239     // don't complain about missing return statements.
14240     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14241       WP.disableCheckFallThrough();
14242 
14243     // MSVC permits the use of pure specifier (=0) on function definition,
14244     // defined at class scope, warn about this non-standard construct.
14245     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14246       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14247 
14248     if (!FD->isInvalidDecl()) {
14249       // Don't diagnose unused parameters of defaulted or deleted functions.
14250       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14251         DiagnoseUnusedParameters(FD->parameters());
14252       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14253                                              FD->getReturnType(), FD);
14254 
14255       // If this is a structor, we need a vtable.
14256       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14257         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14258       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14259         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14260 
14261       // Try to apply the named return value optimization. We have to check
14262       // if we can do this here because lambdas keep return statements around
14263       // to deduce an implicit return type.
14264       if (FD->getReturnType()->isRecordType() &&
14265           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14266         computeNRVO(Body, getCurFunction());
14267     }
14268 
14269     // GNU warning -Wmissing-prototypes:
14270     //   Warn if a global function is defined without a previous
14271     //   prototype declaration. This warning is issued even if the
14272     //   definition itself provides a prototype. The aim is to detect
14273     //   global functions that fail to be declared in header files.
14274     const FunctionDecl *PossiblePrototype = nullptr;
14275     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14276       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14277 
14278       if (PossiblePrototype) {
14279         // We found a declaration that is not a prototype,
14280         // but that could be a zero-parameter prototype
14281         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14282           TypeLoc TL = TI->getTypeLoc();
14283           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14284             Diag(PossiblePrototype->getLocation(),
14285                  diag::note_declaration_not_a_prototype)
14286                 << (FD->getNumParams() != 0)
14287                 << (FD->getNumParams() == 0
14288                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14289                         : FixItHint{});
14290         }
14291       } else {
14292         // Returns true if the token beginning at this Loc is `const`.
14293         auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14294                                 const LangOptions &LangOpts) {
14295           std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14296           if (LocInfo.first.isInvalid())
14297             return false;
14298 
14299           bool Invalid = false;
14300           StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14301           if (Invalid)
14302             return false;
14303 
14304           if (LocInfo.second > Buffer.size())
14305             return false;
14306 
14307           const char *LexStart = Buffer.data() + LocInfo.second;
14308           StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14309 
14310           return StartTok.consume_front("const") &&
14311                  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14312                   StartTok.startswith("/*") || StartTok.startswith("//"));
14313         };
14314 
14315         auto findBeginLoc = [&]() {
14316           // If the return type has `const` qualifier, we want to insert
14317           // `static` before `const` (and not before the typename).
14318           if ((FD->getReturnType()->isAnyPointerType() &&
14319                FD->getReturnType()->getPointeeType().isConstQualified()) ||
14320               FD->getReturnType().isConstQualified()) {
14321             // But only do this if we can determine where the `const` is.
14322 
14323             if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14324                              getLangOpts()))
14325 
14326               return FD->getBeginLoc();
14327           }
14328           return FD->getTypeSpecStartLoc();
14329         };
14330         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14331             << /* function */ 1
14332             << (FD->getStorageClass() == SC_None
14333                     ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14334                     : FixItHint{});
14335       }
14336 
14337       // GNU warning -Wstrict-prototypes
14338       //   Warn if K&R function is defined without a previous declaration.
14339       //   This warning is issued only if the definition itself does not provide
14340       //   a prototype. Only K&R definitions do not provide a prototype.
14341       if (!FD->hasWrittenPrototype()) {
14342         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14343         TypeLoc TL = TI->getTypeLoc();
14344         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14345         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14346       }
14347     }
14348 
14349     // Warn on CPUDispatch with an actual body.
14350     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14351       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14352         if (!CmpndBody->body_empty())
14353           Diag(CmpndBody->body_front()->getBeginLoc(),
14354                diag::warn_dispatch_body_ignored);
14355 
14356     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14357       const CXXMethodDecl *KeyFunction;
14358       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14359           MD->isVirtual() &&
14360           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14361           MD == KeyFunction->getCanonicalDecl()) {
14362         // Update the key-function state if necessary for this ABI.
14363         if (FD->isInlined() &&
14364             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14365           Context.setNonKeyFunction(MD);
14366 
14367           // If the newly-chosen key function is already defined, then we
14368           // need to mark the vtable as used retroactively.
14369           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14370           const FunctionDecl *Definition;
14371           if (KeyFunction && KeyFunction->isDefined(Definition))
14372             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14373         } else {
14374           // We just defined they key function; mark the vtable as used.
14375           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14376         }
14377       }
14378     }
14379 
14380     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14381            "Function parsing confused");
14382   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14383     assert(MD == getCurMethodDecl() && "Method parsing confused");
14384     MD->setBody(Body);
14385     if (!MD->isInvalidDecl()) {
14386       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14387                                              MD->getReturnType(), MD);
14388 
14389       if (Body)
14390         computeNRVO(Body, getCurFunction());
14391     }
14392     if (getCurFunction()->ObjCShouldCallSuper) {
14393       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14394           << MD->getSelector().getAsString();
14395       getCurFunction()->ObjCShouldCallSuper = false;
14396     }
14397     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14398       const ObjCMethodDecl *InitMethod = nullptr;
14399       bool isDesignated =
14400           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14401       assert(isDesignated && InitMethod);
14402       (void)isDesignated;
14403 
14404       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14405         auto IFace = MD->getClassInterface();
14406         if (!IFace)
14407           return false;
14408         auto SuperD = IFace->getSuperClass();
14409         if (!SuperD)
14410           return false;
14411         return SuperD->getIdentifier() ==
14412             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14413       };
14414       // Don't issue this warning for unavailable inits or direct subclasses
14415       // of NSObject.
14416       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14417         Diag(MD->getLocation(),
14418              diag::warn_objc_designated_init_missing_super_call);
14419         Diag(InitMethod->getLocation(),
14420              diag::note_objc_designated_init_marked_here);
14421       }
14422       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14423     }
14424     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14425       // Don't issue this warning for unavaialable inits.
14426       if (!MD->isUnavailable())
14427         Diag(MD->getLocation(),
14428              diag::warn_objc_secondary_init_missing_init_call);
14429       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14430     }
14431 
14432     diagnoseImplicitlyRetainedSelf(*this);
14433   } else {
14434     // Parsing the function declaration failed in some way. Pop the fake scope
14435     // we pushed on.
14436     PopFunctionScopeInfo(ActivePolicy, dcl);
14437     return nullptr;
14438   }
14439 
14440   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14441     DiagnoseUnguardedAvailabilityViolations(dcl);
14442 
14443   assert(!getCurFunction()->ObjCShouldCallSuper &&
14444          "This should only be set for ObjC methods, which should have been "
14445          "handled in the block above.");
14446 
14447   // Verify and clean out per-function state.
14448   if (Body && (!FD || !FD->isDefaulted())) {
14449     // C++ constructors that have function-try-blocks can't have return
14450     // statements in the handlers of that block. (C++ [except.handle]p14)
14451     // Verify this.
14452     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14453       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14454 
14455     // Verify that gotos and switch cases don't jump into scopes illegally.
14456     if (getCurFunction()->NeedsScopeChecking() &&
14457         !PP.isCodeCompletionEnabled())
14458       DiagnoseInvalidJumps(Body);
14459 
14460     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14461       if (!Destructor->getParent()->isDependentType())
14462         CheckDestructor(Destructor);
14463 
14464       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14465                                              Destructor->getParent());
14466     }
14467 
14468     // If any errors have occurred, clear out any temporaries that may have
14469     // been leftover. This ensures that these temporaries won't be picked up for
14470     // deletion in some later function.
14471     if (getDiagnostics().hasUncompilableErrorOccurred() ||
14472         getDiagnostics().getSuppressAllDiagnostics()) {
14473       DiscardCleanupsInEvaluationContext();
14474     }
14475     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14476         !isa<FunctionTemplateDecl>(dcl)) {
14477       // Since the body is valid, issue any analysis-based warnings that are
14478       // enabled.
14479       ActivePolicy = &WP;
14480     }
14481 
14482     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14483         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14484       FD->setInvalidDecl();
14485 
14486     if (FD && FD->hasAttr<NakedAttr>()) {
14487       for (const Stmt *S : Body->children()) {
14488         // Allow local register variables without initializer as they don't
14489         // require prologue.
14490         bool RegisterVariables = false;
14491         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14492           for (const auto *Decl : DS->decls()) {
14493             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14494               RegisterVariables =
14495                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14496               if (!RegisterVariables)
14497                 break;
14498             }
14499           }
14500         }
14501         if (RegisterVariables)
14502           continue;
14503         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14504           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14505           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14506           FD->setInvalidDecl();
14507           break;
14508         }
14509       }
14510     }
14511 
14512     assert(ExprCleanupObjects.size() ==
14513                ExprEvalContexts.back().NumCleanupObjects &&
14514            "Leftover temporaries in function");
14515     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14516     assert(MaybeODRUseExprs.empty() &&
14517            "Leftover expressions for odr-use checking");
14518   }
14519 
14520   if (!IsInstantiation)
14521     PopDeclContext();
14522 
14523   PopFunctionScopeInfo(ActivePolicy, dcl);
14524   // If any errors have occurred, clear out any temporaries that may have
14525   // been leftover. This ensures that these temporaries won't be picked up for
14526   // deletion in some later function.
14527   if (getDiagnostics().hasUncompilableErrorOccurred()) {
14528     DiscardCleanupsInEvaluationContext();
14529   }
14530 
14531   if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14532     auto ES = getEmissionStatus(FD);
14533     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14534         ES == Sema::FunctionEmissionStatus::Unknown)
14535       DeclsToCheckForDeferredDiags.push_back(FD);
14536   }
14537 
14538   return dcl;
14539 }
14540 
14541 /// When we finish delayed parsing of an attribute, we must attach it to the
14542 /// relevant Decl.
14543 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14544                                        ParsedAttributes &Attrs) {
14545   // Always attach attributes to the underlying decl.
14546   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14547     D = TD->getTemplatedDecl();
14548   ProcessDeclAttributeList(S, D, Attrs);
14549 
14550   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14551     if (Method->isStatic())
14552       checkThisInStaticMemberFunctionAttributes(Method);
14553 }
14554 
14555 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14556 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14557 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14558                                           IdentifierInfo &II, Scope *S) {
14559   // Find the scope in which the identifier is injected and the corresponding
14560   // DeclContext.
14561   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14562   // In that case, we inject the declaration into the translation unit scope
14563   // instead.
14564   Scope *BlockScope = S;
14565   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14566     BlockScope = BlockScope->getParent();
14567 
14568   Scope *ContextScope = BlockScope;
14569   while (!ContextScope->getEntity())
14570     ContextScope = ContextScope->getParent();
14571   ContextRAII SavedContext(*this, ContextScope->getEntity());
14572 
14573   // Before we produce a declaration for an implicitly defined
14574   // function, see whether there was a locally-scoped declaration of
14575   // this name as a function or variable. If so, use that
14576   // (non-visible) declaration, and complain about it.
14577   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14578   if (ExternCPrev) {
14579     // We still need to inject the function into the enclosing block scope so
14580     // that later (non-call) uses can see it.
14581     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14582 
14583     // C89 footnote 38:
14584     //   If in fact it is not defined as having type "function returning int",
14585     //   the behavior is undefined.
14586     if (!isa<FunctionDecl>(ExternCPrev) ||
14587         !Context.typesAreCompatible(
14588             cast<FunctionDecl>(ExternCPrev)->getType(),
14589             Context.getFunctionNoProtoType(Context.IntTy))) {
14590       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14591           << ExternCPrev << !getLangOpts().C99;
14592       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14593       return ExternCPrev;
14594     }
14595   }
14596 
14597   // Extension in C99.  Legal in C90, but warn about it.
14598   unsigned diag_id;
14599   if (II.getName().startswith("__builtin_"))
14600     diag_id = diag::warn_builtin_unknown;
14601   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14602   else if (getLangOpts().OpenCL)
14603     diag_id = diag::err_opencl_implicit_function_decl;
14604   else if (getLangOpts().C99)
14605     diag_id = diag::ext_implicit_function_decl;
14606   else
14607     diag_id = diag::warn_implicit_function_decl;
14608   Diag(Loc, diag_id) << &II;
14609 
14610   // If we found a prior declaration of this function, don't bother building
14611   // another one. We've already pushed that one into scope, so there's nothing
14612   // more to do.
14613   if (ExternCPrev)
14614     return ExternCPrev;
14615 
14616   // Because typo correction is expensive, only do it if the implicit
14617   // function declaration is going to be treated as an error.
14618   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14619     TypoCorrection Corrected;
14620     DeclFilterCCC<FunctionDecl> CCC{};
14621     if (S && (Corrected =
14622                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14623                               S, nullptr, CCC, CTK_NonError)))
14624       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14625                    /*ErrorRecovery*/false);
14626   }
14627 
14628   // Set a Declarator for the implicit definition: int foo();
14629   const char *Dummy;
14630   AttributeFactory attrFactory;
14631   DeclSpec DS(attrFactory);
14632   unsigned DiagID;
14633   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14634                                   Context.getPrintingPolicy());
14635   (void)Error; // Silence warning.
14636   assert(!Error && "Error setting up implicit decl!");
14637   SourceLocation NoLoc;
14638   Declarator D(DS, DeclaratorContext::BlockContext);
14639   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14640                                              /*IsAmbiguous=*/false,
14641                                              /*LParenLoc=*/NoLoc,
14642                                              /*Params=*/nullptr,
14643                                              /*NumParams=*/0,
14644                                              /*EllipsisLoc=*/NoLoc,
14645                                              /*RParenLoc=*/NoLoc,
14646                                              /*RefQualifierIsLvalueRef=*/true,
14647                                              /*RefQualifierLoc=*/NoLoc,
14648                                              /*MutableLoc=*/NoLoc, EST_None,
14649                                              /*ESpecRange=*/SourceRange(),
14650                                              /*Exceptions=*/nullptr,
14651                                              /*ExceptionRanges=*/nullptr,
14652                                              /*NumExceptions=*/0,
14653                                              /*NoexceptExpr=*/nullptr,
14654                                              /*ExceptionSpecTokens=*/nullptr,
14655                                              /*DeclsInPrototype=*/None, Loc,
14656                                              Loc, D),
14657                 std::move(DS.getAttributes()), SourceLocation());
14658   D.SetIdentifier(&II, Loc);
14659 
14660   // Insert this function into the enclosing block scope.
14661   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14662   FD->setImplicit();
14663 
14664   AddKnownFunctionAttributes(FD);
14665 
14666   return FD;
14667 }
14668 
14669 /// If this function is a C++ replaceable global allocation function
14670 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14671 /// adds any function attributes that we know a priori based on the standard.
14672 ///
14673 /// We need to check for duplicate attributes both here and where user-written
14674 /// attributes are applied to declarations.
14675 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14676     FunctionDecl *FD) {
14677   if (FD->isInvalidDecl())
14678     return;
14679 
14680   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14681       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14682     return;
14683 
14684   Optional<unsigned> AlignmentParam;
14685   bool IsNothrow = false;
14686   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14687     return;
14688 
14689   // C++2a [basic.stc.dynamic.allocation]p4:
14690   //   An allocation function that has a non-throwing exception specification
14691   //   indicates failure by returning a null pointer value. Any other allocation
14692   //   function never returns a null pointer value and indicates failure only by
14693   //   throwing an exception [...]
14694   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14695     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14696 
14697   // C++2a [basic.stc.dynamic.allocation]p2:
14698   //   An allocation function attempts to allocate the requested amount of
14699   //   storage. [...] If the request succeeds, the value returned by a
14700   //   replaceable allocation function is a [...] pointer value p0 different
14701   //   from any previously returned value p1 [...]
14702   //
14703   // However, this particular information is being added in codegen,
14704   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14705 
14706   // C++2a [basic.stc.dynamic.allocation]p2:
14707   //   An allocation function attempts to allocate the requested amount of
14708   //   storage. If it is successful, it returns the address of the start of a
14709   //   block of storage whose length in bytes is at least as large as the
14710   //   requested size.
14711   if (!FD->hasAttr<AllocSizeAttr>()) {
14712     FD->addAttr(AllocSizeAttr::CreateImplicit(
14713         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14714         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14715   }
14716 
14717   // C++2a [basic.stc.dynamic.allocation]p3:
14718   //   For an allocation function [...], the pointer returned on a successful
14719   //   call shall represent the address of storage that is aligned as follows:
14720   //   (3.1) If the allocation function takes an argument of type
14721   //         std​::​align_­val_­t, the storage will have the alignment
14722   //         specified by the value of this argument.
14723   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14724     FD->addAttr(AllocAlignAttr::CreateImplicit(
14725         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14726   }
14727 
14728   // FIXME:
14729   // C++2a [basic.stc.dynamic.allocation]p3:
14730   //   For an allocation function [...], the pointer returned on a successful
14731   //   call shall represent the address of storage that is aligned as follows:
14732   //   (3.2) Otherwise, if the allocation function is named operator new[],
14733   //         the storage is aligned for any object that does not have
14734   //         new-extended alignment ([basic.align]) and is no larger than the
14735   //         requested size.
14736   //   (3.3) Otherwise, the storage is aligned for any object that does not
14737   //         have new-extended alignment and is of the requested size.
14738 }
14739 
14740 /// Adds any function attributes that we know a priori based on
14741 /// the declaration of this function.
14742 ///
14743 /// These attributes can apply both to implicitly-declared builtins
14744 /// (like __builtin___printf_chk) or to library-declared functions
14745 /// like NSLog or printf.
14746 ///
14747 /// We need to check for duplicate attributes both here and where user-written
14748 /// attributes are applied to declarations.
14749 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14750   if (FD->isInvalidDecl())
14751     return;
14752 
14753   // If this is a built-in function, map its builtin attributes to
14754   // actual attributes.
14755   if (unsigned BuiltinID = FD->getBuiltinID()) {
14756     // Handle printf-formatting attributes.
14757     unsigned FormatIdx;
14758     bool HasVAListArg;
14759     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14760       if (!FD->hasAttr<FormatAttr>()) {
14761         const char *fmt = "printf";
14762         unsigned int NumParams = FD->getNumParams();
14763         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14764             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14765           fmt = "NSString";
14766         FD->addAttr(FormatAttr::CreateImplicit(Context,
14767                                                &Context.Idents.get(fmt),
14768                                                FormatIdx+1,
14769                                                HasVAListArg ? 0 : FormatIdx+2,
14770                                                FD->getLocation()));
14771       }
14772     }
14773     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14774                                              HasVAListArg)) {
14775      if (!FD->hasAttr<FormatAttr>())
14776        FD->addAttr(FormatAttr::CreateImplicit(Context,
14777                                               &Context.Idents.get("scanf"),
14778                                               FormatIdx+1,
14779                                               HasVAListArg ? 0 : FormatIdx+2,
14780                                               FD->getLocation()));
14781     }
14782 
14783     // Handle automatically recognized callbacks.
14784     SmallVector<int, 4> Encoding;
14785     if (!FD->hasAttr<CallbackAttr>() &&
14786         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14787       FD->addAttr(CallbackAttr::CreateImplicit(
14788           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14789 
14790     // Mark const if we don't care about errno and that is the only thing
14791     // preventing the function from being const. This allows IRgen to use LLVM
14792     // intrinsics for such functions.
14793     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14794         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14795       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14796 
14797     // We make "fma" on some platforms const because we know it does not set
14798     // errno in those environments even though it could set errno based on the
14799     // C standard.
14800     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14801     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14802         !FD->hasAttr<ConstAttr>()) {
14803       switch (BuiltinID) {
14804       case Builtin::BI__builtin_fma:
14805       case Builtin::BI__builtin_fmaf:
14806       case Builtin::BI__builtin_fmal:
14807       case Builtin::BIfma:
14808       case Builtin::BIfmaf:
14809       case Builtin::BIfmal:
14810         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14811         break;
14812       default:
14813         break;
14814       }
14815     }
14816 
14817     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14818         !FD->hasAttr<ReturnsTwiceAttr>())
14819       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14820                                          FD->getLocation()));
14821     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14822       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14823     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14824       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14825     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14826       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14827     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14828         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14829       // Add the appropriate attribute, depending on the CUDA compilation mode
14830       // and which target the builtin belongs to. For example, during host
14831       // compilation, aux builtins are __device__, while the rest are __host__.
14832       if (getLangOpts().CUDAIsDevice !=
14833           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14834         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14835       else
14836         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14837     }
14838   }
14839 
14840   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14841 
14842   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14843   // throw, add an implicit nothrow attribute to any extern "C" function we come
14844   // across.
14845   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14846       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14847     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14848     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14849       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14850   }
14851 
14852   IdentifierInfo *Name = FD->getIdentifier();
14853   if (!Name)
14854     return;
14855   if ((!getLangOpts().CPlusPlus &&
14856        FD->getDeclContext()->isTranslationUnit()) ||
14857       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14858        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14859        LinkageSpecDecl::lang_c)) {
14860     // Okay: this could be a libc/libm/Objective-C function we know
14861     // about.
14862   } else
14863     return;
14864 
14865   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14866     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14867     // target-specific builtins, perhaps?
14868     if (!FD->hasAttr<FormatAttr>())
14869       FD->addAttr(FormatAttr::CreateImplicit(Context,
14870                                              &Context.Idents.get("printf"), 2,
14871                                              Name->isStr("vasprintf") ? 0 : 3,
14872                                              FD->getLocation()));
14873   }
14874 
14875   if (Name->isStr("__CFStringMakeConstantString")) {
14876     // We already have a __builtin___CFStringMakeConstantString,
14877     // but builds that use -fno-constant-cfstrings don't go through that.
14878     if (!FD->hasAttr<FormatArgAttr>())
14879       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14880                                                 FD->getLocation()));
14881   }
14882 }
14883 
14884 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14885                                     TypeSourceInfo *TInfo) {
14886   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14887   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14888 
14889   if (!TInfo) {
14890     assert(D.isInvalidType() && "no declarator info for valid type");
14891     TInfo = Context.getTrivialTypeSourceInfo(T);
14892   }
14893 
14894   // Scope manipulation handled by caller.
14895   TypedefDecl *NewTD =
14896       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14897                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14898 
14899   // Bail out immediately if we have an invalid declaration.
14900   if (D.isInvalidType()) {
14901     NewTD->setInvalidDecl();
14902     return NewTD;
14903   }
14904 
14905   if (D.getDeclSpec().isModulePrivateSpecified()) {
14906     if (CurContext->isFunctionOrMethod())
14907       Diag(NewTD->getLocation(), diag::err_module_private_local)
14908         << 2 << NewTD->getDeclName()
14909         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14910         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14911     else
14912       NewTD->setModulePrivate();
14913   }
14914 
14915   // C++ [dcl.typedef]p8:
14916   //   If the typedef declaration defines an unnamed class (or
14917   //   enum), the first typedef-name declared by the declaration
14918   //   to be that class type (or enum type) is used to denote the
14919   //   class type (or enum type) for linkage purposes only.
14920   // We need to check whether the type was declared in the declaration.
14921   switch (D.getDeclSpec().getTypeSpecType()) {
14922   case TST_enum:
14923   case TST_struct:
14924   case TST_interface:
14925   case TST_union:
14926   case TST_class: {
14927     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14928     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14929     break;
14930   }
14931 
14932   default:
14933     break;
14934   }
14935 
14936   return NewTD;
14937 }
14938 
14939 /// Check that this is a valid underlying type for an enum declaration.
14940 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14941   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14942   QualType T = TI->getType();
14943 
14944   if (T->isDependentType())
14945     return false;
14946 
14947   // This doesn't use 'isIntegralType' despite the error message mentioning
14948   // integral type because isIntegralType would also allow enum types in C.
14949   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14950     if (BT->isInteger())
14951       return false;
14952 
14953   if (T->isExtIntType())
14954     return false;
14955 
14956   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14957 }
14958 
14959 /// Check whether this is a valid redeclaration of a previous enumeration.
14960 /// \return true if the redeclaration was invalid.
14961 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14962                                   QualType EnumUnderlyingTy, bool IsFixed,
14963                                   const EnumDecl *Prev) {
14964   if (IsScoped != Prev->isScoped()) {
14965     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14966       << Prev->isScoped();
14967     Diag(Prev->getLocation(), diag::note_previous_declaration);
14968     return true;
14969   }
14970 
14971   if (IsFixed && Prev->isFixed()) {
14972     if (!EnumUnderlyingTy->isDependentType() &&
14973         !Prev->getIntegerType()->isDependentType() &&
14974         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14975                                         Prev->getIntegerType())) {
14976       // TODO: Highlight the underlying type of the redeclaration.
14977       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14978         << EnumUnderlyingTy << Prev->getIntegerType();
14979       Diag(Prev->getLocation(), diag::note_previous_declaration)
14980           << Prev->getIntegerTypeRange();
14981       return true;
14982     }
14983   } else if (IsFixed != Prev->isFixed()) {
14984     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14985       << Prev->isFixed();
14986     Diag(Prev->getLocation(), diag::note_previous_declaration);
14987     return true;
14988   }
14989 
14990   return false;
14991 }
14992 
14993 /// Get diagnostic %select index for tag kind for
14994 /// redeclaration diagnostic message.
14995 /// WARNING: Indexes apply to particular diagnostics only!
14996 ///
14997 /// \returns diagnostic %select index.
14998 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14999   switch (Tag) {
15000   case TTK_Struct: return 0;
15001   case TTK_Interface: return 1;
15002   case TTK_Class:  return 2;
15003   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15004   }
15005 }
15006 
15007 /// Determine if tag kind is a class-key compatible with
15008 /// class for redeclaration (class, struct, or __interface).
15009 ///
15010 /// \returns true iff the tag kind is compatible.
15011 static bool isClassCompatTagKind(TagTypeKind Tag)
15012 {
15013   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15014 }
15015 
15016 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15017                                              TagTypeKind TTK) {
15018   if (isa<TypedefDecl>(PrevDecl))
15019     return NTK_Typedef;
15020   else if (isa<TypeAliasDecl>(PrevDecl))
15021     return NTK_TypeAlias;
15022   else if (isa<ClassTemplateDecl>(PrevDecl))
15023     return NTK_Template;
15024   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15025     return NTK_TypeAliasTemplate;
15026   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15027     return NTK_TemplateTemplateArgument;
15028   switch (TTK) {
15029   case TTK_Struct:
15030   case TTK_Interface:
15031   case TTK_Class:
15032     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15033   case TTK_Union:
15034     return NTK_NonUnion;
15035   case TTK_Enum:
15036     return NTK_NonEnum;
15037   }
15038   llvm_unreachable("invalid TTK");
15039 }
15040 
15041 /// Determine whether a tag with a given kind is acceptable
15042 /// as a redeclaration of the given tag declaration.
15043 ///
15044 /// \returns true if the new tag kind is acceptable, false otherwise.
15045 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15046                                         TagTypeKind NewTag, bool isDefinition,
15047                                         SourceLocation NewTagLoc,
15048                                         const IdentifierInfo *Name) {
15049   // C++ [dcl.type.elab]p3:
15050   //   The class-key or enum keyword present in the
15051   //   elaborated-type-specifier shall agree in kind with the
15052   //   declaration to which the name in the elaborated-type-specifier
15053   //   refers. This rule also applies to the form of
15054   //   elaborated-type-specifier that declares a class-name or
15055   //   friend class since it can be construed as referring to the
15056   //   definition of the class. Thus, in any
15057   //   elaborated-type-specifier, the enum keyword shall be used to
15058   //   refer to an enumeration (7.2), the union class-key shall be
15059   //   used to refer to a union (clause 9), and either the class or
15060   //   struct class-key shall be used to refer to a class (clause 9)
15061   //   declared using the class or struct class-key.
15062   TagTypeKind OldTag = Previous->getTagKind();
15063   if (OldTag != NewTag &&
15064       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15065     return false;
15066 
15067   // Tags are compatible, but we might still want to warn on mismatched tags.
15068   // Non-class tags can't be mismatched at this point.
15069   if (!isClassCompatTagKind(NewTag))
15070     return true;
15071 
15072   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15073   // by our warning analysis. We don't want to warn about mismatches with (eg)
15074   // declarations in system headers that are designed to be specialized, but if
15075   // a user asks us to warn, we should warn if their code contains mismatched
15076   // declarations.
15077   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15078     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15079                                       Loc);
15080   };
15081   if (IsIgnoredLoc(NewTagLoc))
15082     return true;
15083 
15084   auto IsIgnored = [&](const TagDecl *Tag) {
15085     return IsIgnoredLoc(Tag->getLocation());
15086   };
15087   while (IsIgnored(Previous)) {
15088     Previous = Previous->getPreviousDecl();
15089     if (!Previous)
15090       return true;
15091     OldTag = Previous->getTagKind();
15092   }
15093 
15094   bool isTemplate = false;
15095   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15096     isTemplate = Record->getDescribedClassTemplate();
15097 
15098   if (inTemplateInstantiation()) {
15099     if (OldTag != NewTag) {
15100       // In a template instantiation, do not offer fix-its for tag mismatches
15101       // since they usually mess up the template instead of fixing the problem.
15102       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15103         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15104         << getRedeclDiagFromTagKind(OldTag);
15105       // FIXME: Note previous location?
15106     }
15107     return true;
15108   }
15109 
15110   if (isDefinition) {
15111     // On definitions, check all previous tags and issue a fix-it for each
15112     // one that doesn't match the current tag.
15113     if (Previous->getDefinition()) {
15114       // Don't suggest fix-its for redefinitions.
15115       return true;
15116     }
15117 
15118     bool previousMismatch = false;
15119     for (const TagDecl *I : Previous->redecls()) {
15120       if (I->getTagKind() != NewTag) {
15121         // Ignore previous declarations for which the warning was disabled.
15122         if (IsIgnored(I))
15123           continue;
15124 
15125         if (!previousMismatch) {
15126           previousMismatch = true;
15127           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15128             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15129             << getRedeclDiagFromTagKind(I->getTagKind());
15130         }
15131         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15132           << getRedeclDiagFromTagKind(NewTag)
15133           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15134                TypeWithKeyword::getTagTypeKindName(NewTag));
15135       }
15136     }
15137     return true;
15138   }
15139 
15140   // Identify the prevailing tag kind: this is the kind of the definition (if
15141   // there is a non-ignored definition), or otherwise the kind of the prior
15142   // (non-ignored) declaration.
15143   const TagDecl *PrevDef = Previous->getDefinition();
15144   if (PrevDef && IsIgnored(PrevDef))
15145     PrevDef = nullptr;
15146   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15147   if (Redecl->getTagKind() != NewTag) {
15148     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15149       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15150       << getRedeclDiagFromTagKind(OldTag);
15151     Diag(Redecl->getLocation(), diag::note_previous_use);
15152 
15153     // If there is a previous definition, suggest a fix-it.
15154     if (PrevDef) {
15155       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15156         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15157         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15158              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15159     }
15160   }
15161 
15162   return true;
15163 }
15164 
15165 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15166 /// from an outer enclosing namespace or file scope inside a friend declaration.
15167 /// This should provide the commented out code in the following snippet:
15168 ///   namespace N {
15169 ///     struct X;
15170 ///     namespace M {
15171 ///       struct Y { friend struct /*N::*/ X; };
15172 ///     }
15173 ///   }
15174 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15175                                          SourceLocation NameLoc) {
15176   // While the decl is in a namespace, do repeated lookup of that name and see
15177   // if we get the same namespace back.  If we do not, continue until
15178   // translation unit scope, at which point we have a fully qualified NNS.
15179   SmallVector<IdentifierInfo *, 4> Namespaces;
15180   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15181   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15182     // This tag should be declared in a namespace, which can only be enclosed by
15183     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15184     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15185     if (!Namespace || Namespace->isAnonymousNamespace())
15186       return FixItHint();
15187     IdentifierInfo *II = Namespace->getIdentifier();
15188     Namespaces.push_back(II);
15189     NamedDecl *Lookup = SemaRef.LookupSingleName(
15190         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15191     if (Lookup == Namespace)
15192       break;
15193   }
15194 
15195   // Once we have all the namespaces, reverse them to go outermost first, and
15196   // build an NNS.
15197   SmallString<64> Insertion;
15198   llvm::raw_svector_ostream OS(Insertion);
15199   if (DC->isTranslationUnit())
15200     OS << "::";
15201   std::reverse(Namespaces.begin(), Namespaces.end());
15202   for (auto *II : Namespaces)
15203     OS << II->getName() << "::";
15204   return FixItHint::CreateInsertion(NameLoc, Insertion);
15205 }
15206 
15207 /// Determine whether a tag originally declared in context \p OldDC can
15208 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15209 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15210 /// using-declaration).
15211 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15212                                          DeclContext *NewDC) {
15213   OldDC = OldDC->getRedeclContext();
15214   NewDC = NewDC->getRedeclContext();
15215 
15216   if (OldDC->Equals(NewDC))
15217     return true;
15218 
15219   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15220   // encloses the other).
15221   if (S.getLangOpts().MSVCCompat &&
15222       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15223     return true;
15224 
15225   return false;
15226 }
15227 
15228 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15229 /// former case, Name will be non-null.  In the later case, Name will be null.
15230 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15231 /// reference/declaration/definition of a tag.
15232 ///
15233 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15234 /// trailing-type-specifier) other than one in an alias-declaration.
15235 ///
15236 /// \param SkipBody If non-null, will be set to indicate if the caller should
15237 /// skip the definition of this tag and treat it as if it were a declaration.
15238 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15239                      SourceLocation KWLoc, CXXScopeSpec &SS,
15240                      IdentifierInfo *Name, SourceLocation NameLoc,
15241                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15242                      SourceLocation ModulePrivateLoc,
15243                      MultiTemplateParamsArg TemplateParameterLists,
15244                      bool &OwnedDecl, bool &IsDependent,
15245                      SourceLocation ScopedEnumKWLoc,
15246                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15247                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15248                      SkipBodyInfo *SkipBody) {
15249   // If this is not a definition, it must have a name.
15250   IdentifierInfo *OrigName = Name;
15251   assert((Name != nullptr || TUK == TUK_Definition) &&
15252          "Nameless record must be a definition!");
15253   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15254 
15255   OwnedDecl = false;
15256   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15257   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15258 
15259   // FIXME: Check member specializations more carefully.
15260   bool isMemberSpecialization = false;
15261   bool Invalid = false;
15262 
15263   // We only need to do this matching if we have template parameters
15264   // or a scope specifier, which also conveniently avoids this work
15265   // for non-C++ cases.
15266   if (TemplateParameterLists.size() > 0 ||
15267       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15268     if (TemplateParameterList *TemplateParams =
15269             MatchTemplateParametersToScopeSpecifier(
15270                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15271                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15272       if (Kind == TTK_Enum) {
15273         Diag(KWLoc, diag::err_enum_template);
15274         return nullptr;
15275       }
15276 
15277       if (TemplateParams->size() > 0) {
15278         // This is a declaration or definition of a class template (which may
15279         // be a member of another template).
15280 
15281         if (Invalid)
15282           return nullptr;
15283 
15284         OwnedDecl = false;
15285         DeclResult Result = CheckClassTemplate(
15286             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15287             AS, ModulePrivateLoc,
15288             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15289             TemplateParameterLists.data(), SkipBody);
15290         return Result.get();
15291       } else {
15292         // The "template<>" header is extraneous.
15293         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15294           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15295         isMemberSpecialization = true;
15296       }
15297     }
15298   }
15299 
15300   // Figure out the underlying type if this a enum declaration. We need to do
15301   // this early, because it's needed to detect if this is an incompatible
15302   // redeclaration.
15303   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15304   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15305 
15306   if (Kind == TTK_Enum) {
15307     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15308       // No underlying type explicitly specified, or we failed to parse the
15309       // type, default to int.
15310       EnumUnderlying = Context.IntTy.getTypePtr();
15311     } else if (UnderlyingType.get()) {
15312       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15313       // integral type; any cv-qualification is ignored.
15314       TypeSourceInfo *TI = nullptr;
15315       GetTypeFromParser(UnderlyingType.get(), &TI);
15316       EnumUnderlying = TI;
15317 
15318       if (CheckEnumUnderlyingType(TI))
15319         // Recover by falling back to int.
15320         EnumUnderlying = Context.IntTy.getTypePtr();
15321 
15322       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15323                                           UPPC_FixedUnderlyingType))
15324         EnumUnderlying = Context.IntTy.getTypePtr();
15325 
15326     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15327       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15328       // of 'int'. However, if this is an unfixed forward declaration, don't set
15329       // the underlying type unless the user enables -fms-compatibility. This
15330       // makes unfixed forward declared enums incomplete and is more conforming.
15331       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15332         EnumUnderlying = Context.IntTy.getTypePtr();
15333     }
15334   }
15335 
15336   DeclContext *SearchDC = CurContext;
15337   DeclContext *DC = CurContext;
15338   bool isStdBadAlloc = false;
15339   bool isStdAlignValT = false;
15340 
15341   RedeclarationKind Redecl = forRedeclarationInCurContext();
15342   if (TUK == TUK_Friend || TUK == TUK_Reference)
15343     Redecl = NotForRedeclaration;
15344 
15345   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15346   /// implemented asks for structural equivalence checking, the returned decl
15347   /// here is passed back to the parser, allowing the tag body to be parsed.
15348   auto createTagFromNewDecl = [&]() -> TagDecl * {
15349     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15350     // If there is an identifier, use the location of the identifier as the
15351     // location of the decl, otherwise use the location of the struct/union
15352     // keyword.
15353     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15354     TagDecl *New = nullptr;
15355 
15356     if (Kind == TTK_Enum) {
15357       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15358                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15359       // If this is an undefined enum, bail.
15360       if (TUK != TUK_Definition && !Invalid)
15361         return nullptr;
15362       if (EnumUnderlying) {
15363         EnumDecl *ED = cast<EnumDecl>(New);
15364         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15365           ED->setIntegerTypeSourceInfo(TI);
15366         else
15367           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15368         ED->setPromotionType(ED->getIntegerType());
15369       }
15370     } else { // struct/union
15371       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15372                                nullptr);
15373     }
15374 
15375     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15376       // Add alignment attributes if necessary; these attributes are checked
15377       // when the ASTContext lays out the structure.
15378       //
15379       // It is important for implementing the correct semantics that this
15380       // happen here (in ActOnTag). The #pragma pack stack is
15381       // maintained as a result of parser callbacks which can occur at
15382       // many points during the parsing of a struct declaration (because
15383       // the #pragma tokens are effectively skipped over during the
15384       // parsing of the struct).
15385       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15386         AddAlignmentAttributesForRecord(RD);
15387         AddMsStructLayoutForRecord(RD);
15388       }
15389     }
15390     New->setLexicalDeclContext(CurContext);
15391     return New;
15392   };
15393 
15394   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15395   if (Name && SS.isNotEmpty()) {
15396     // We have a nested-name tag ('struct foo::bar').
15397 
15398     // Check for invalid 'foo::'.
15399     if (SS.isInvalid()) {
15400       Name = nullptr;
15401       goto CreateNewDecl;
15402     }
15403 
15404     // If this is a friend or a reference to a class in a dependent
15405     // context, don't try to make a decl for it.
15406     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15407       DC = computeDeclContext(SS, false);
15408       if (!DC) {
15409         IsDependent = true;
15410         return nullptr;
15411       }
15412     } else {
15413       DC = computeDeclContext(SS, true);
15414       if (!DC) {
15415         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15416           << SS.getRange();
15417         return nullptr;
15418       }
15419     }
15420 
15421     if (RequireCompleteDeclContext(SS, DC))
15422       return nullptr;
15423 
15424     SearchDC = DC;
15425     // Look-up name inside 'foo::'.
15426     LookupQualifiedName(Previous, DC);
15427 
15428     if (Previous.isAmbiguous())
15429       return nullptr;
15430 
15431     if (Previous.empty()) {
15432       // Name lookup did not find anything. However, if the
15433       // nested-name-specifier refers to the current instantiation,
15434       // and that current instantiation has any dependent base
15435       // classes, we might find something at instantiation time: treat
15436       // this as a dependent elaborated-type-specifier.
15437       // But this only makes any sense for reference-like lookups.
15438       if (Previous.wasNotFoundInCurrentInstantiation() &&
15439           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15440         IsDependent = true;
15441         return nullptr;
15442       }
15443 
15444       // A tag 'foo::bar' must already exist.
15445       Diag(NameLoc, diag::err_not_tag_in_scope)
15446         << Kind << Name << DC << SS.getRange();
15447       Name = nullptr;
15448       Invalid = true;
15449       goto CreateNewDecl;
15450     }
15451   } else if (Name) {
15452     // C++14 [class.mem]p14:
15453     //   If T is the name of a class, then each of the following shall have a
15454     //   name different from T:
15455     //    -- every member of class T that is itself a type
15456     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15457         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15458       return nullptr;
15459 
15460     // If this is a named struct, check to see if there was a previous forward
15461     // declaration or definition.
15462     // FIXME: We're looking into outer scopes here, even when we
15463     // shouldn't be. Doing so can result in ambiguities that we
15464     // shouldn't be diagnosing.
15465     LookupName(Previous, S);
15466 
15467     // When declaring or defining a tag, ignore ambiguities introduced
15468     // by types using'ed into this scope.
15469     if (Previous.isAmbiguous() &&
15470         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15471       LookupResult::Filter F = Previous.makeFilter();
15472       while (F.hasNext()) {
15473         NamedDecl *ND = F.next();
15474         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15475                 SearchDC->getRedeclContext()))
15476           F.erase();
15477       }
15478       F.done();
15479     }
15480 
15481     // C++11 [namespace.memdef]p3:
15482     //   If the name in a friend declaration is neither qualified nor
15483     //   a template-id and the declaration is a function or an
15484     //   elaborated-type-specifier, the lookup to determine whether
15485     //   the entity has been previously declared shall not consider
15486     //   any scopes outside the innermost enclosing namespace.
15487     //
15488     // MSVC doesn't implement the above rule for types, so a friend tag
15489     // declaration may be a redeclaration of a type declared in an enclosing
15490     // scope.  They do implement this rule for friend functions.
15491     //
15492     // Does it matter that this should be by scope instead of by
15493     // semantic context?
15494     if (!Previous.empty() && TUK == TUK_Friend) {
15495       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15496       LookupResult::Filter F = Previous.makeFilter();
15497       bool FriendSawTagOutsideEnclosingNamespace = false;
15498       while (F.hasNext()) {
15499         NamedDecl *ND = F.next();
15500         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15501         if (DC->isFileContext() &&
15502             !EnclosingNS->Encloses(ND->getDeclContext())) {
15503           if (getLangOpts().MSVCCompat)
15504             FriendSawTagOutsideEnclosingNamespace = true;
15505           else
15506             F.erase();
15507         }
15508       }
15509       F.done();
15510 
15511       // Diagnose this MSVC extension in the easy case where lookup would have
15512       // unambiguously found something outside the enclosing namespace.
15513       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15514         NamedDecl *ND = Previous.getFoundDecl();
15515         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15516             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15517       }
15518     }
15519 
15520     // Note:  there used to be some attempt at recovery here.
15521     if (Previous.isAmbiguous())
15522       return nullptr;
15523 
15524     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15525       // FIXME: This makes sure that we ignore the contexts associated
15526       // with C structs, unions, and enums when looking for a matching
15527       // tag declaration or definition. See the similar lookup tweak
15528       // in Sema::LookupName; is there a better way to deal with this?
15529       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15530         SearchDC = SearchDC->getParent();
15531     }
15532   }
15533 
15534   if (Previous.isSingleResult() &&
15535       Previous.getFoundDecl()->isTemplateParameter()) {
15536     // Maybe we will complain about the shadowed template parameter.
15537     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15538     // Just pretend that we didn't see the previous declaration.
15539     Previous.clear();
15540   }
15541 
15542   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15543       DC->Equals(getStdNamespace())) {
15544     if (Name->isStr("bad_alloc")) {
15545       // This is a declaration of or a reference to "std::bad_alloc".
15546       isStdBadAlloc = true;
15547 
15548       // If std::bad_alloc has been implicitly declared (but made invisible to
15549       // name lookup), fill in this implicit declaration as the previous
15550       // declaration, so that the declarations get chained appropriately.
15551       if (Previous.empty() && StdBadAlloc)
15552         Previous.addDecl(getStdBadAlloc());
15553     } else if (Name->isStr("align_val_t")) {
15554       isStdAlignValT = true;
15555       if (Previous.empty() && StdAlignValT)
15556         Previous.addDecl(getStdAlignValT());
15557     }
15558   }
15559 
15560   // If we didn't find a previous declaration, and this is a reference
15561   // (or friend reference), move to the correct scope.  In C++, we
15562   // also need to do a redeclaration lookup there, just in case
15563   // there's a shadow friend decl.
15564   if (Name && Previous.empty() &&
15565       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15566     if (Invalid) goto CreateNewDecl;
15567     assert(SS.isEmpty());
15568 
15569     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15570       // C++ [basic.scope.pdecl]p5:
15571       //   -- for an elaborated-type-specifier of the form
15572       //
15573       //          class-key identifier
15574       //
15575       //      if the elaborated-type-specifier is used in the
15576       //      decl-specifier-seq or parameter-declaration-clause of a
15577       //      function defined in namespace scope, the identifier is
15578       //      declared as a class-name in the namespace that contains
15579       //      the declaration; otherwise, except as a friend
15580       //      declaration, the identifier is declared in the smallest
15581       //      non-class, non-function-prototype scope that contains the
15582       //      declaration.
15583       //
15584       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15585       // C structs and unions.
15586       //
15587       // It is an error in C++ to declare (rather than define) an enum
15588       // type, including via an elaborated type specifier.  We'll
15589       // diagnose that later; for now, declare the enum in the same
15590       // scope as we would have picked for any other tag type.
15591       //
15592       // GNU C also supports this behavior as part of its incomplete
15593       // enum types extension, while GNU C++ does not.
15594       //
15595       // Find the context where we'll be declaring the tag.
15596       // FIXME: We would like to maintain the current DeclContext as the
15597       // lexical context,
15598       SearchDC = getTagInjectionContext(SearchDC);
15599 
15600       // Find the scope where we'll be declaring the tag.
15601       S = getTagInjectionScope(S, getLangOpts());
15602     } else {
15603       assert(TUK == TUK_Friend);
15604       // C++ [namespace.memdef]p3:
15605       //   If a friend declaration in a non-local class first declares a
15606       //   class or function, the friend class or function is a member of
15607       //   the innermost enclosing namespace.
15608       SearchDC = SearchDC->getEnclosingNamespaceContext();
15609     }
15610 
15611     // In C++, we need to do a redeclaration lookup to properly
15612     // diagnose some problems.
15613     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15614     // hidden declaration so that we don't get ambiguity errors when using a
15615     // type declared by an elaborated-type-specifier.  In C that is not correct
15616     // and we should instead merge compatible types found by lookup.
15617     if (getLangOpts().CPlusPlus) {
15618       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15619       LookupQualifiedName(Previous, SearchDC);
15620     } else {
15621       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15622       LookupName(Previous, S);
15623     }
15624   }
15625 
15626   // If we have a known previous declaration to use, then use it.
15627   if (Previous.empty() && SkipBody && SkipBody->Previous)
15628     Previous.addDecl(SkipBody->Previous);
15629 
15630   if (!Previous.empty()) {
15631     NamedDecl *PrevDecl = Previous.getFoundDecl();
15632     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15633 
15634     // It's okay to have a tag decl in the same scope as a typedef
15635     // which hides a tag decl in the same scope.  Finding this
15636     // insanity with a redeclaration lookup can only actually happen
15637     // in C++.
15638     //
15639     // This is also okay for elaborated-type-specifiers, which is
15640     // technically forbidden by the current standard but which is
15641     // okay according to the likely resolution of an open issue;
15642     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15643     if (getLangOpts().CPlusPlus) {
15644       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15645         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15646           TagDecl *Tag = TT->getDecl();
15647           if (Tag->getDeclName() == Name &&
15648               Tag->getDeclContext()->getRedeclContext()
15649                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15650             PrevDecl = Tag;
15651             Previous.clear();
15652             Previous.addDecl(Tag);
15653             Previous.resolveKind();
15654           }
15655         }
15656       }
15657     }
15658 
15659     // If this is a redeclaration of a using shadow declaration, it must
15660     // declare a tag in the same context. In MSVC mode, we allow a
15661     // redefinition if either context is within the other.
15662     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15663       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15664       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15665           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15666           !(OldTag && isAcceptableTagRedeclContext(
15667                           *this, OldTag->getDeclContext(), SearchDC))) {
15668         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15669         Diag(Shadow->getTargetDecl()->getLocation(),
15670              diag::note_using_decl_target);
15671         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15672             << 0;
15673         // Recover by ignoring the old declaration.
15674         Previous.clear();
15675         goto CreateNewDecl;
15676       }
15677     }
15678 
15679     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15680       // If this is a use of a previous tag, or if the tag is already declared
15681       // in the same scope (so that the definition/declaration completes or
15682       // rementions the tag), reuse the decl.
15683       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15684           isDeclInScope(DirectPrevDecl, SearchDC, S,
15685                         SS.isNotEmpty() || isMemberSpecialization)) {
15686         // Make sure that this wasn't declared as an enum and now used as a
15687         // struct or something similar.
15688         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15689                                           TUK == TUK_Definition, KWLoc,
15690                                           Name)) {
15691           bool SafeToContinue
15692             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15693                Kind != TTK_Enum);
15694           if (SafeToContinue)
15695             Diag(KWLoc, diag::err_use_with_wrong_tag)
15696               << Name
15697               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15698                                               PrevTagDecl->getKindName());
15699           else
15700             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15701           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15702 
15703           if (SafeToContinue)
15704             Kind = PrevTagDecl->getTagKind();
15705           else {
15706             // Recover by making this an anonymous redefinition.
15707             Name = nullptr;
15708             Previous.clear();
15709             Invalid = true;
15710           }
15711         }
15712 
15713         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15714           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15715           if (TUK == TUK_Reference || TUK == TUK_Friend)
15716             return PrevTagDecl;
15717 
15718           QualType EnumUnderlyingTy;
15719           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15720             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15721           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15722             EnumUnderlyingTy = QualType(T, 0);
15723 
15724           // All conflicts with previous declarations are recovered by
15725           // returning the previous declaration, unless this is a definition,
15726           // in which case we want the caller to bail out.
15727           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15728                                      ScopedEnum, EnumUnderlyingTy,
15729                                      IsFixed, PrevEnum))
15730             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15731         }
15732 
15733         // C++11 [class.mem]p1:
15734         //   A member shall not be declared twice in the member-specification,
15735         //   except that a nested class or member class template can be declared
15736         //   and then later defined.
15737         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15738             S->isDeclScope(PrevDecl)) {
15739           Diag(NameLoc, diag::ext_member_redeclared);
15740           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15741         }
15742 
15743         if (!Invalid) {
15744           // If this is a use, just return the declaration we found, unless
15745           // we have attributes.
15746           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15747             if (!Attrs.empty()) {
15748               // FIXME: Diagnose these attributes. For now, we create a new
15749               // declaration to hold them.
15750             } else if (TUK == TUK_Reference &&
15751                        (PrevTagDecl->getFriendObjectKind() ==
15752                             Decl::FOK_Undeclared ||
15753                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15754                        SS.isEmpty()) {
15755               // This declaration is a reference to an existing entity, but
15756               // has different visibility from that entity: it either makes
15757               // a friend visible or it makes a type visible in a new module.
15758               // In either case, create a new declaration. We only do this if
15759               // the declaration would have meant the same thing if no prior
15760               // declaration were found, that is, if it was found in the same
15761               // scope where we would have injected a declaration.
15762               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15763                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15764                 return PrevTagDecl;
15765               // This is in the injected scope, create a new declaration in
15766               // that scope.
15767               S = getTagInjectionScope(S, getLangOpts());
15768             } else {
15769               return PrevTagDecl;
15770             }
15771           }
15772 
15773           // Diagnose attempts to redefine a tag.
15774           if (TUK == TUK_Definition) {
15775             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15776               // If we're defining a specialization and the previous definition
15777               // is from an implicit instantiation, don't emit an error
15778               // here; we'll catch this in the general case below.
15779               bool IsExplicitSpecializationAfterInstantiation = false;
15780               if (isMemberSpecialization) {
15781                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15782                   IsExplicitSpecializationAfterInstantiation =
15783                     RD->getTemplateSpecializationKind() !=
15784                     TSK_ExplicitSpecialization;
15785                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15786                   IsExplicitSpecializationAfterInstantiation =
15787                     ED->getTemplateSpecializationKind() !=
15788                     TSK_ExplicitSpecialization;
15789               }
15790 
15791               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15792               // not keep more that one definition around (merge them). However,
15793               // ensure the decl passes the structural compatibility check in
15794               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15795               NamedDecl *Hidden = nullptr;
15796               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15797                 // There is a definition of this tag, but it is not visible. We
15798                 // explicitly make use of C++'s one definition rule here, and
15799                 // assume that this definition is identical to the hidden one
15800                 // we already have. Make the existing definition visible and
15801                 // use it in place of this one.
15802                 if (!getLangOpts().CPlusPlus) {
15803                   // Postpone making the old definition visible until after we
15804                   // complete parsing the new one and do the structural
15805                   // comparison.
15806                   SkipBody->CheckSameAsPrevious = true;
15807                   SkipBody->New = createTagFromNewDecl();
15808                   SkipBody->Previous = Def;
15809                   return Def;
15810                 } else {
15811                   SkipBody->ShouldSkip = true;
15812                   SkipBody->Previous = Def;
15813                   makeMergedDefinitionVisible(Hidden);
15814                   // Carry on and handle it like a normal definition. We'll
15815                   // skip starting the definitiion later.
15816                 }
15817               } else if (!IsExplicitSpecializationAfterInstantiation) {
15818                 // A redeclaration in function prototype scope in C isn't
15819                 // visible elsewhere, so merely issue a warning.
15820                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15821                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15822                 else
15823                   Diag(NameLoc, diag::err_redefinition) << Name;
15824                 notePreviousDefinition(Def,
15825                                        NameLoc.isValid() ? NameLoc : KWLoc);
15826                 // If this is a redefinition, recover by making this
15827                 // struct be anonymous, which will make any later
15828                 // references get the previous definition.
15829                 Name = nullptr;
15830                 Previous.clear();
15831                 Invalid = true;
15832               }
15833             } else {
15834               // If the type is currently being defined, complain
15835               // about a nested redefinition.
15836               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15837               if (TD->isBeingDefined()) {
15838                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15839                 Diag(PrevTagDecl->getLocation(),
15840                      diag::note_previous_definition);
15841                 Name = nullptr;
15842                 Previous.clear();
15843                 Invalid = true;
15844               }
15845             }
15846 
15847             // Okay, this is definition of a previously declared or referenced
15848             // tag. We're going to create a new Decl for it.
15849           }
15850 
15851           // Okay, we're going to make a redeclaration.  If this is some kind
15852           // of reference, make sure we build the redeclaration in the same DC
15853           // as the original, and ignore the current access specifier.
15854           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15855             SearchDC = PrevTagDecl->getDeclContext();
15856             AS = AS_none;
15857           }
15858         }
15859         // If we get here we have (another) forward declaration or we
15860         // have a definition.  Just create a new decl.
15861 
15862       } else {
15863         // If we get here, this is a definition of a new tag type in a nested
15864         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15865         // new decl/type.  We set PrevDecl to NULL so that the entities
15866         // have distinct types.
15867         Previous.clear();
15868       }
15869       // If we get here, we're going to create a new Decl. If PrevDecl
15870       // is non-NULL, it's a definition of the tag declared by
15871       // PrevDecl. If it's NULL, we have a new definition.
15872 
15873     // Otherwise, PrevDecl is not a tag, but was found with tag
15874     // lookup.  This is only actually possible in C++, where a few
15875     // things like templates still live in the tag namespace.
15876     } else {
15877       // Use a better diagnostic if an elaborated-type-specifier
15878       // found the wrong kind of type on the first
15879       // (non-redeclaration) lookup.
15880       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15881           !Previous.isForRedeclaration()) {
15882         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15883         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15884                                                        << Kind;
15885         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15886         Invalid = true;
15887 
15888       // Otherwise, only diagnose if the declaration is in scope.
15889       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15890                                 SS.isNotEmpty() || isMemberSpecialization)) {
15891         // do nothing
15892 
15893       // Diagnose implicit declarations introduced by elaborated types.
15894       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15895         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15896         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15897         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15898         Invalid = true;
15899 
15900       // Otherwise it's a declaration.  Call out a particularly common
15901       // case here.
15902       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15903         unsigned Kind = 0;
15904         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15905         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15906           << Name << Kind << TND->getUnderlyingType();
15907         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15908         Invalid = true;
15909 
15910       // Otherwise, diagnose.
15911       } else {
15912         // The tag name clashes with something else in the target scope,
15913         // issue an error and recover by making this tag be anonymous.
15914         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15915         notePreviousDefinition(PrevDecl, NameLoc);
15916         Name = nullptr;
15917         Invalid = true;
15918       }
15919 
15920       // The existing declaration isn't relevant to us; we're in a
15921       // new scope, so clear out the previous declaration.
15922       Previous.clear();
15923     }
15924   }
15925 
15926 CreateNewDecl:
15927 
15928   TagDecl *PrevDecl = nullptr;
15929   if (Previous.isSingleResult())
15930     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15931 
15932   // If there is an identifier, use the location of the identifier as the
15933   // location of the decl, otherwise use the location of the struct/union
15934   // keyword.
15935   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15936 
15937   // Otherwise, create a new declaration. If there is a previous
15938   // declaration of the same entity, the two will be linked via
15939   // PrevDecl.
15940   TagDecl *New;
15941 
15942   if (Kind == TTK_Enum) {
15943     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15944     // enum X { A, B, C } D;    D should chain to X.
15945     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15946                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15947                            ScopedEnumUsesClassTag, IsFixed);
15948 
15949     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15950       StdAlignValT = cast<EnumDecl>(New);
15951 
15952     // If this is an undefined enum, warn.
15953     if (TUK != TUK_Definition && !Invalid) {
15954       TagDecl *Def;
15955       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15956         // C++0x: 7.2p2: opaque-enum-declaration.
15957         // Conflicts are diagnosed above. Do nothing.
15958       }
15959       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15960         Diag(Loc, diag::ext_forward_ref_enum_def)
15961           << New;
15962         Diag(Def->getLocation(), diag::note_previous_definition);
15963       } else {
15964         unsigned DiagID = diag::ext_forward_ref_enum;
15965         if (getLangOpts().MSVCCompat)
15966           DiagID = diag::ext_ms_forward_ref_enum;
15967         else if (getLangOpts().CPlusPlus)
15968           DiagID = diag::err_forward_ref_enum;
15969         Diag(Loc, DiagID);
15970       }
15971     }
15972 
15973     if (EnumUnderlying) {
15974       EnumDecl *ED = cast<EnumDecl>(New);
15975       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15976         ED->setIntegerTypeSourceInfo(TI);
15977       else
15978         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15979       ED->setPromotionType(ED->getIntegerType());
15980       assert(ED->isComplete() && "enum with type should be complete");
15981     }
15982   } else {
15983     // struct/union/class
15984 
15985     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15986     // struct X { int A; } D;    D should chain to X.
15987     if (getLangOpts().CPlusPlus) {
15988       // FIXME: Look for a way to use RecordDecl for simple structs.
15989       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15990                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15991 
15992       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15993         StdBadAlloc = cast<CXXRecordDecl>(New);
15994     } else
15995       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15996                                cast_or_null<RecordDecl>(PrevDecl));
15997   }
15998 
15999   // C++11 [dcl.type]p3:
16000   //   A type-specifier-seq shall not define a class or enumeration [...].
16001   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16002       TUK == TUK_Definition) {
16003     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16004       << Context.getTagDeclType(New);
16005     Invalid = true;
16006   }
16007 
16008   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16009       DC->getDeclKind() == Decl::Enum) {
16010     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16011       << Context.getTagDeclType(New);
16012     Invalid = true;
16013   }
16014 
16015   // Maybe add qualifier info.
16016   if (SS.isNotEmpty()) {
16017     if (SS.isSet()) {
16018       // If this is either a declaration or a definition, check the
16019       // nested-name-specifier against the current context.
16020       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16021           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16022                                        isMemberSpecialization))
16023         Invalid = true;
16024 
16025       New->setQualifierInfo(SS.getWithLocInContext(Context));
16026       if (TemplateParameterLists.size() > 0) {
16027         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16028       }
16029     }
16030     else
16031       Invalid = true;
16032   }
16033 
16034   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16035     // Add alignment attributes if necessary; these attributes are checked when
16036     // the ASTContext lays out the structure.
16037     //
16038     // It is important for implementing the correct semantics that this
16039     // happen here (in ActOnTag). The #pragma pack stack is
16040     // maintained as a result of parser callbacks which can occur at
16041     // many points during the parsing of a struct declaration (because
16042     // the #pragma tokens are effectively skipped over during the
16043     // parsing of the struct).
16044     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16045       AddAlignmentAttributesForRecord(RD);
16046       AddMsStructLayoutForRecord(RD);
16047     }
16048   }
16049 
16050   if (ModulePrivateLoc.isValid()) {
16051     if (isMemberSpecialization)
16052       Diag(New->getLocation(), diag::err_module_private_specialization)
16053         << 2
16054         << FixItHint::CreateRemoval(ModulePrivateLoc);
16055     // __module_private__ does not apply to local classes. However, we only
16056     // diagnose this as an error when the declaration specifiers are
16057     // freestanding. Here, we just ignore the __module_private__.
16058     else if (!SearchDC->isFunctionOrMethod())
16059       New->setModulePrivate();
16060   }
16061 
16062   // If this is a specialization of a member class (of a class template),
16063   // check the specialization.
16064   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16065     Invalid = true;
16066 
16067   // If we're declaring or defining a tag in function prototype scope in C,
16068   // note that this type can only be used within the function and add it to
16069   // the list of decls to inject into the function definition scope.
16070   if ((Name || Kind == TTK_Enum) &&
16071       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16072     if (getLangOpts().CPlusPlus) {
16073       // C++ [dcl.fct]p6:
16074       //   Types shall not be defined in return or parameter types.
16075       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16076         Diag(Loc, diag::err_type_defined_in_param_type)
16077             << Name;
16078         Invalid = true;
16079       }
16080     } else if (!PrevDecl) {
16081       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16082     }
16083   }
16084 
16085   if (Invalid)
16086     New->setInvalidDecl();
16087 
16088   // Set the lexical context. If the tag has a C++ scope specifier, the
16089   // lexical context will be different from the semantic context.
16090   New->setLexicalDeclContext(CurContext);
16091 
16092   // Mark this as a friend decl if applicable.
16093   // In Microsoft mode, a friend declaration also acts as a forward
16094   // declaration so we always pass true to setObjectOfFriendDecl to make
16095   // the tag name visible.
16096   if (TUK == TUK_Friend)
16097     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16098 
16099   // Set the access specifier.
16100   if (!Invalid && SearchDC->isRecord())
16101     SetMemberAccessSpecifier(New, PrevDecl, AS);
16102 
16103   if (PrevDecl)
16104     CheckRedeclarationModuleOwnership(New, PrevDecl);
16105 
16106   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16107     New->startDefinition();
16108 
16109   ProcessDeclAttributeList(S, New, Attrs);
16110   AddPragmaAttributes(S, New);
16111 
16112   // If this has an identifier, add it to the scope stack.
16113   if (TUK == TUK_Friend) {
16114     // We might be replacing an existing declaration in the lookup tables;
16115     // if so, borrow its access specifier.
16116     if (PrevDecl)
16117       New->setAccess(PrevDecl->getAccess());
16118 
16119     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16120     DC->makeDeclVisibleInContext(New);
16121     if (Name) // can be null along some error paths
16122       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16123         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16124   } else if (Name) {
16125     S = getNonFieldDeclScope(S);
16126     PushOnScopeChains(New, S, true);
16127   } else {
16128     CurContext->addDecl(New);
16129   }
16130 
16131   // If this is the C FILE type, notify the AST context.
16132   if (IdentifierInfo *II = New->getIdentifier())
16133     if (!New->isInvalidDecl() &&
16134         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16135         II->isStr("FILE"))
16136       Context.setFILEDecl(New);
16137 
16138   if (PrevDecl)
16139     mergeDeclAttributes(New, PrevDecl);
16140 
16141   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16142     inferGslOwnerPointerAttribute(CXXRD);
16143 
16144   // If there's a #pragma GCC visibility in scope, set the visibility of this
16145   // record.
16146   AddPushedVisibilityAttribute(New);
16147 
16148   if (isMemberSpecialization && !New->isInvalidDecl())
16149     CompleteMemberSpecialization(New, Previous);
16150 
16151   OwnedDecl = true;
16152   // In C++, don't return an invalid declaration. We can't recover well from
16153   // the cases where we make the type anonymous.
16154   if (Invalid && getLangOpts().CPlusPlus) {
16155     if (New->isBeingDefined())
16156       if (auto RD = dyn_cast<RecordDecl>(New))
16157         RD->completeDefinition();
16158     return nullptr;
16159   } else if (SkipBody && SkipBody->ShouldSkip) {
16160     return SkipBody->Previous;
16161   } else {
16162     return New;
16163   }
16164 }
16165 
16166 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16167   AdjustDeclIfTemplate(TagD);
16168   TagDecl *Tag = cast<TagDecl>(TagD);
16169 
16170   // Enter the tag context.
16171   PushDeclContext(S, Tag);
16172 
16173   ActOnDocumentableDecl(TagD);
16174 
16175   // If there's a #pragma GCC visibility in scope, set the visibility of this
16176   // record.
16177   AddPushedVisibilityAttribute(Tag);
16178 }
16179 
16180 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16181                                     SkipBodyInfo &SkipBody) {
16182   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16183     return false;
16184 
16185   // Make the previous decl visible.
16186   makeMergedDefinitionVisible(SkipBody.Previous);
16187   return true;
16188 }
16189 
16190 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16191   assert(isa<ObjCContainerDecl>(IDecl) &&
16192          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16193   DeclContext *OCD = cast<DeclContext>(IDecl);
16194   assert(OCD->getLexicalParent() == CurContext &&
16195       "The next DeclContext should be lexically contained in the current one.");
16196   CurContext = OCD;
16197   return IDecl;
16198 }
16199 
16200 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16201                                            SourceLocation FinalLoc,
16202                                            bool IsFinalSpelledSealed,
16203                                            SourceLocation LBraceLoc) {
16204   AdjustDeclIfTemplate(TagD);
16205   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16206 
16207   FieldCollector->StartClass();
16208 
16209   if (!Record->getIdentifier())
16210     return;
16211 
16212   if (FinalLoc.isValid())
16213     Record->addAttr(FinalAttr::Create(
16214         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16215         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16216 
16217   // C++ [class]p2:
16218   //   [...] The class-name is also inserted into the scope of the
16219   //   class itself; this is known as the injected-class-name. For
16220   //   purposes of access checking, the injected-class-name is treated
16221   //   as if it were a public member name.
16222   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16223       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16224       Record->getLocation(), Record->getIdentifier(),
16225       /*PrevDecl=*/nullptr,
16226       /*DelayTypeCreation=*/true);
16227   Context.getTypeDeclType(InjectedClassName, Record);
16228   InjectedClassName->setImplicit();
16229   InjectedClassName->setAccess(AS_public);
16230   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16231       InjectedClassName->setDescribedClassTemplate(Template);
16232   PushOnScopeChains(InjectedClassName, S);
16233   assert(InjectedClassName->isInjectedClassName() &&
16234          "Broken injected-class-name");
16235 }
16236 
16237 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16238                                     SourceRange BraceRange) {
16239   AdjustDeclIfTemplate(TagD);
16240   TagDecl *Tag = cast<TagDecl>(TagD);
16241   Tag->setBraceRange(BraceRange);
16242 
16243   // Make sure we "complete" the definition even it is invalid.
16244   if (Tag->isBeingDefined()) {
16245     assert(Tag->isInvalidDecl() && "We should already have completed it");
16246     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16247       RD->completeDefinition();
16248   }
16249 
16250   if (isa<CXXRecordDecl>(Tag)) {
16251     FieldCollector->FinishClass();
16252   }
16253 
16254   // Exit this scope of this tag's definition.
16255   PopDeclContext();
16256 
16257   if (getCurLexicalContext()->isObjCContainer() &&
16258       Tag->getDeclContext()->isFileContext())
16259     Tag->setTopLevelDeclInObjCContainer();
16260 
16261   // Notify the consumer that we've defined a tag.
16262   if (!Tag->isInvalidDecl())
16263     Consumer.HandleTagDeclDefinition(Tag);
16264 }
16265 
16266 void Sema::ActOnObjCContainerFinishDefinition() {
16267   // Exit this scope of this interface definition.
16268   PopDeclContext();
16269 }
16270 
16271 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16272   assert(DC == CurContext && "Mismatch of container contexts");
16273   OriginalLexicalContext = DC;
16274   ActOnObjCContainerFinishDefinition();
16275 }
16276 
16277 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16278   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16279   OriginalLexicalContext = nullptr;
16280 }
16281 
16282 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16283   AdjustDeclIfTemplate(TagD);
16284   TagDecl *Tag = cast<TagDecl>(TagD);
16285   Tag->setInvalidDecl();
16286 
16287   // Make sure we "complete" the definition even it is invalid.
16288   if (Tag->isBeingDefined()) {
16289     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16290       RD->completeDefinition();
16291   }
16292 
16293   // We're undoing ActOnTagStartDefinition here, not
16294   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16295   // the FieldCollector.
16296 
16297   PopDeclContext();
16298 }
16299 
16300 // Note that FieldName may be null for anonymous bitfields.
16301 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16302                                 IdentifierInfo *FieldName,
16303                                 QualType FieldTy, bool IsMsStruct,
16304                                 Expr *BitWidth, bool *ZeroWidth) {
16305   assert(BitWidth);
16306   if (BitWidth->containsErrors())
16307     return ExprError();
16308 
16309   // Default to true; that shouldn't confuse checks for emptiness
16310   if (ZeroWidth)
16311     *ZeroWidth = true;
16312 
16313   // C99 6.7.2.1p4 - verify the field type.
16314   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16315   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16316     // Handle incomplete and sizeless types with a specific error.
16317     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16318                                  diag::err_field_incomplete_or_sizeless))
16319       return ExprError();
16320     if (FieldName)
16321       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16322         << FieldName << FieldTy << BitWidth->getSourceRange();
16323     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16324       << FieldTy << BitWidth->getSourceRange();
16325   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16326                                              UPPC_BitFieldWidth))
16327     return ExprError();
16328 
16329   // If the bit-width is type- or value-dependent, don't try to check
16330   // it now.
16331   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16332     return BitWidth;
16333 
16334   llvm::APSInt Value;
16335   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16336   if (ICE.isInvalid())
16337     return ICE;
16338   BitWidth = ICE.get();
16339 
16340   if (Value != 0 && ZeroWidth)
16341     *ZeroWidth = false;
16342 
16343   // Zero-width bitfield is ok for anonymous field.
16344   if (Value == 0 && FieldName)
16345     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16346 
16347   if (Value.isSigned() && Value.isNegative()) {
16348     if (FieldName)
16349       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16350                << FieldName << Value.toString(10);
16351     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16352       << Value.toString(10);
16353   }
16354 
16355   if (!FieldTy->isDependentType()) {
16356     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16357     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16358     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16359 
16360     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16361     // ABI.
16362     bool CStdConstraintViolation =
16363         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16364     bool MSBitfieldViolation =
16365         Value.ugt(TypeStorageSize) &&
16366         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16367     if (CStdConstraintViolation || MSBitfieldViolation) {
16368       unsigned DiagWidth =
16369           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16370       if (FieldName)
16371         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16372                << FieldName << (unsigned)Value.getZExtValue()
16373                << !CStdConstraintViolation << DiagWidth;
16374 
16375       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16376              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16377              << DiagWidth;
16378     }
16379 
16380     // Warn on types where the user might conceivably expect to get all
16381     // specified bits as value bits: that's all integral types other than
16382     // 'bool'.
16383     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16384       if (FieldName)
16385         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16386             << FieldName << (unsigned)Value.getZExtValue()
16387             << (unsigned)TypeWidth;
16388       else
16389         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16390             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16391     }
16392   }
16393 
16394   return BitWidth;
16395 }
16396 
16397 /// ActOnField - Each field of a C struct/union is passed into this in order
16398 /// to create a FieldDecl object for it.
16399 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16400                        Declarator &D, Expr *BitfieldWidth) {
16401   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16402                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16403                                /*InitStyle=*/ICIS_NoInit, AS_public);
16404   return Res;
16405 }
16406 
16407 /// HandleField - Analyze a field of a C struct or a C++ data member.
16408 ///
16409 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16410                              SourceLocation DeclStart,
16411                              Declarator &D, Expr *BitWidth,
16412                              InClassInitStyle InitStyle,
16413                              AccessSpecifier AS) {
16414   if (D.isDecompositionDeclarator()) {
16415     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16416     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16417       << Decomp.getSourceRange();
16418     return nullptr;
16419   }
16420 
16421   IdentifierInfo *II = D.getIdentifier();
16422   SourceLocation Loc = DeclStart;
16423   if (II) Loc = D.getIdentifierLoc();
16424 
16425   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16426   QualType T = TInfo->getType();
16427   if (getLangOpts().CPlusPlus) {
16428     CheckExtraCXXDefaultArguments(D);
16429 
16430     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16431                                         UPPC_DataMemberType)) {
16432       D.setInvalidType();
16433       T = Context.IntTy;
16434       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16435     }
16436   }
16437 
16438   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16439 
16440   if (D.getDeclSpec().isInlineSpecified())
16441     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16442         << getLangOpts().CPlusPlus17;
16443   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16444     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16445          diag::err_invalid_thread)
16446       << DeclSpec::getSpecifierName(TSCS);
16447 
16448   // Check to see if this name was declared as a member previously
16449   NamedDecl *PrevDecl = nullptr;
16450   LookupResult Previous(*this, II, Loc, LookupMemberName,
16451                         ForVisibleRedeclaration);
16452   LookupName(Previous, S);
16453   switch (Previous.getResultKind()) {
16454     case LookupResult::Found:
16455     case LookupResult::FoundUnresolvedValue:
16456       PrevDecl = Previous.getAsSingle<NamedDecl>();
16457       break;
16458 
16459     case LookupResult::FoundOverloaded:
16460       PrevDecl = Previous.getRepresentativeDecl();
16461       break;
16462 
16463     case LookupResult::NotFound:
16464     case LookupResult::NotFoundInCurrentInstantiation:
16465     case LookupResult::Ambiguous:
16466       break;
16467   }
16468   Previous.suppressDiagnostics();
16469 
16470   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16471     // Maybe we will complain about the shadowed template parameter.
16472     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16473     // Just pretend that we didn't see the previous declaration.
16474     PrevDecl = nullptr;
16475   }
16476 
16477   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16478     PrevDecl = nullptr;
16479 
16480   bool Mutable
16481     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16482   SourceLocation TSSL = D.getBeginLoc();
16483   FieldDecl *NewFD
16484     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16485                      TSSL, AS, PrevDecl, &D);
16486 
16487   if (NewFD->isInvalidDecl())
16488     Record->setInvalidDecl();
16489 
16490   if (D.getDeclSpec().isModulePrivateSpecified())
16491     NewFD->setModulePrivate();
16492 
16493   if (NewFD->isInvalidDecl() && PrevDecl) {
16494     // Don't introduce NewFD into scope; there's already something
16495     // with the same name in the same scope.
16496   } else if (II) {
16497     PushOnScopeChains(NewFD, S);
16498   } else
16499     Record->addDecl(NewFD);
16500 
16501   return NewFD;
16502 }
16503 
16504 /// Build a new FieldDecl and check its well-formedness.
16505 ///
16506 /// This routine builds a new FieldDecl given the fields name, type,
16507 /// record, etc. \p PrevDecl should refer to any previous declaration
16508 /// with the same name and in the same scope as the field to be
16509 /// created.
16510 ///
16511 /// \returns a new FieldDecl.
16512 ///
16513 /// \todo The Declarator argument is a hack. It will be removed once
16514 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16515                                 TypeSourceInfo *TInfo,
16516                                 RecordDecl *Record, SourceLocation Loc,
16517                                 bool Mutable, Expr *BitWidth,
16518                                 InClassInitStyle InitStyle,
16519                                 SourceLocation TSSL,
16520                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16521                                 Declarator *D) {
16522   IdentifierInfo *II = Name.getAsIdentifierInfo();
16523   bool InvalidDecl = false;
16524   if (D) InvalidDecl = D->isInvalidType();
16525 
16526   // If we receive a broken type, recover by assuming 'int' and
16527   // marking this declaration as invalid.
16528   if (T.isNull() || T->containsErrors()) {
16529     InvalidDecl = true;
16530     T = Context.IntTy;
16531   }
16532 
16533   QualType EltTy = Context.getBaseElementType(T);
16534   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16535     if (RequireCompleteSizedType(Loc, EltTy,
16536                                  diag::err_field_incomplete_or_sizeless)) {
16537       // Fields of incomplete type force their record to be invalid.
16538       Record->setInvalidDecl();
16539       InvalidDecl = true;
16540     } else {
16541       NamedDecl *Def;
16542       EltTy->isIncompleteType(&Def);
16543       if (Def && Def->isInvalidDecl()) {
16544         Record->setInvalidDecl();
16545         InvalidDecl = true;
16546       }
16547     }
16548   }
16549 
16550   // TR 18037 does not allow fields to be declared with address space
16551   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16552       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16553     Diag(Loc, diag::err_field_with_address_space);
16554     Record->setInvalidDecl();
16555     InvalidDecl = true;
16556   }
16557 
16558   if (LangOpts.OpenCL) {
16559     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16560     // used as structure or union field: image, sampler, event or block types.
16561     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16562         T->isBlockPointerType()) {
16563       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16564       Record->setInvalidDecl();
16565       InvalidDecl = true;
16566     }
16567     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16568     if (BitWidth) {
16569       Diag(Loc, diag::err_opencl_bitfields);
16570       InvalidDecl = true;
16571     }
16572   }
16573 
16574   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16575   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16576       T.hasQualifiers()) {
16577     InvalidDecl = true;
16578     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16579   }
16580 
16581   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16582   // than a variably modified type.
16583   if (!InvalidDecl && T->isVariablyModifiedType()) {
16584     bool SizeIsNegative;
16585     llvm::APSInt Oversized;
16586 
16587     TypeSourceInfo *FixedTInfo =
16588       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16589                                                     SizeIsNegative,
16590                                                     Oversized);
16591     if (FixedTInfo) {
16592       Diag(Loc, diag::warn_illegal_constant_array_size);
16593       TInfo = FixedTInfo;
16594       T = FixedTInfo->getType();
16595     } else {
16596       if (SizeIsNegative)
16597         Diag(Loc, diag::err_typecheck_negative_array_size);
16598       else if (Oversized.getBoolValue())
16599         Diag(Loc, diag::err_array_too_large)
16600           << Oversized.toString(10);
16601       else
16602         Diag(Loc, diag::err_typecheck_field_variable_size);
16603       InvalidDecl = true;
16604     }
16605   }
16606 
16607   // Fields can not have abstract class types
16608   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16609                                              diag::err_abstract_type_in_decl,
16610                                              AbstractFieldType))
16611     InvalidDecl = true;
16612 
16613   bool ZeroWidth = false;
16614   if (InvalidDecl)
16615     BitWidth = nullptr;
16616   // If this is declared as a bit-field, check the bit-field.
16617   if (BitWidth) {
16618     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16619                               &ZeroWidth).get();
16620     if (!BitWidth) {
16621       InvalidDecl = true;
16622       BitWidth = nullptr;
16623       ZeroWidth = false;
16624     }
16625 
16626     // Only data members can have in-class initializers.
16627     if (BitWidth && !II && InitStyle) {
16628       Diag(Loc, diag::err_anon_bitfield_init);
16629       InvalidDecl = true;
16630       BitWidth = nullptr;
16631       ZeroWidth = false;
16632     }
16633   }
16634 
16635   // Check that 'mutable' is consistent with the type of the declaration.
16636   if (!InvalidDecl && Mutable) {
16637     unsigned DiagID = 0;
16638     if (T->isReferenceType())
16639       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16640                                         : diag::err_mutable_reference;
16641     else if (T.isConstQualified())
16642       DiagID = diag::err_mutable_const;
16643 
16644     if (DiagID) {
16645       SourceLocation ErrLoc = Loc;
16646       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16647         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16648       Diag(ErrLoc, DiagID);
16649       if (DiagID != diag::ext_mutable_reference) {
16650         Mutable = false;
16651         InvalidDecl = true;
16652       }
16653     }
16654   }
16655 
16656   // C++11 [class.union]p8 (DR1460):
16657   //   At most one variant member of a union may have a
16658   //   brace-or-equal-initializer.
16659   if (InitStyle != ICIS_NoInit)
16660     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16661 
16662   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16663                                        BitWidth, Mutable, InitStyle);
16664   if (InvalidDecl)
16665     NewFD->setInvalidDecl();
16666 
16667   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16668     Diag(Loc, diag::err_duplicate_member) << II;
16669     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16670     NewFD->setInvalidDecl();
16671   }
16672 
16673   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16674     if (Record->isUnion()) {
16675       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16676         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16677         if (RDecl->getDefinition()) {
16678           // C++ [class.union]p1: An object of a class with a non-trivial
16679           // constructor, a non-trivial copy constructor, a non-trivial
16680           // destructor, or a non-trivial copy assignment operator
16681           // cannot be a member of a union, nor can an array of such
16682           // objects.
16683           if (CheckNontrivialField(NewFD))
16684             NewFD->setInvalidDecl();
16685         }
16686       }
16687 
16688       // C++ [class.union]p1: If a union contains a member of reference type,
16689       // the program is ill-formed, except when compiling with MSVC extensions
16690       // enabled.
16691       if (EltTy->isReferenceType()) {
16692         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16693                                     diag::ext_union_member_of_reference_type :
16694                                     diag::err_union_member_of_reference_type)
16695           << NewFD->getDeclName() << EltTy;
16696         if (!getLangOpts().MicrosoftExt)
16697           NewFD->setInvalidDecl();
16698       }
16699     }
16700   }
16701 
16702   // FIXME: We need to pass in the attributes given an AST
16703   // representation, not a parser representation.
16704   if (D) {
16705     // FIXME: The current scope is almost... but not entirely... correct here.
16706     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16707 
16708     if (NewFD->hasAttrs())
16709       CheckAlignasUnderalignment(NewFD);
16710   }
16711 
16712   // In auto-retain/release, infer strong retension for fields of
16713   // retainable type.
16714   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16715     NewFD->setInvalidDecl();
16716 
16717   if (T.isObjCGCWeak())
16718     Diag(Loc, diag::warn_attribute_weak_on_field);
16719 
16720   NewFD->setAccess(AS);
16721   return NewFD;
16722 }
16723 
16724 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16725   assert(FD);
16726   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16727 
16728   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16729     return false;
16730 
16731   QualType EltTy = Context.getBaseElementType(FD->getType());
16732   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16733     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16734     if (RDecl->getDefinition()) {
16735       // We check for copy constructors before constructors
16736       // because otherwise we'll never get complaints about
16737       // copy constructors.
16738 
16739       CXXSpecialMember member = CXXInvalid;
16740       // We're required to check for any non-trivial constructors. Since the
16741       // implicit default constructor is suppressed if there are any
16742       // user-declared constructors, we just need to check that there is a
16743       // trivial default constructor and a trivial copy constructor. (We don't
16744       // worry about move constructors here, since this is a C++98 check.)
16745       if (RDecl->hasNonTrivialCopyConstructor())
16746         member = CXXCopyConstructor;
16747       else if (!RDecl->hasTrivialDefaultConstructor())
16748         member = CXXDefaultConstructor;
16749       else if (RDecl->hasNonTrivialCopyAssignment())
16750         member = CXXCopyAssignment;
16751       else if (RDecl->hasNonTrivialDestructor())
16752         member = CXXDestructor;
16753 
16754       if (member != CXXInvalid) {
16755         if (!getLangOpts().CPlusPlus11 &&
16756             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16757           // Objective-C++ ARC: it is an error to have a non-trivial field of
16758           // a union. However, system headers in Objective-C programs
16759           // occasionally have Objective-C lifetime objects within unions,
16760           // and rather than cause the program to fail, we make those
16761           // members unavailable.
16762           SourceLocation Loc = FD->getLocation();
16763           if (getSourceManager().isInSystemHeader(Loc)) {
16764             if (!FD->hasAttr<UnavailableAttr>())
16765               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16766                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16767             return false;
16768           }
16769         }
16770 
16771         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16772                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16773                diag::err_illegal_union_or_anon_struct_member)
16774           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16775         DiagnoseNontrivial(RDecl, member);
16776         return !getLangOpts().CPlusPlus11;
16777       }
16778     }
16779   }
16780 
16781   return false;
16782 }
16783 
16784 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16785 ///  AST enum value.
16786 static ObjCIvarDecl::AccessControl
16787 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16788   switch (ivarVisibility) {
16789   default: llvm_unreachable("Unknown visitibility kind");
16790   case tok::objc_private: return ObjCIvarDecl::Private;
16791   case tok::objc_public: return ObjCIvarDecl::Public;
16792   case tok::objc_protected: return ObjCIvarDecl::Protected;
16793   case tok::objc_package: return ObjCIvarDecl::Package;
16794   }
16795 }
16796 
16797 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16798 /// in order to create an IvarDecl object for it.
16799 Decl *Sema::ActOnIvar(Scope *S,
16800                                 SourceLocation DeclStart,
16801                                 Declarator &D, Expr *BitfieldWidth,
16802                                 tok::ObjCKeywordKind Visibility) {
16803 
16804   IdentifierInfo *II = D.getIdentifier();
16805   Expr *BitWidth = (Expr*)BitfieldWidth;
16806   SourceLocation Loc = DeclStart;
16807   if (II) Loc = D.getIdentifierLoc();
16808 
16809   // FIXME: Unnamed fields can be handled in various different ways, for
16810   // example, unnamed unions inject all members into the struct namespace!
16811 
16812   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16813   QualType T = TInfo->getType();
16814 
16815   if (BitWidth) {
16816     // 6.7.2.1p3, 6.7.2.1p4
16817     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16818     if (!BitWidth)
16819       D.setInvalidType();
16820   } else {
16821     // Not a bitfield.
16822 
16823     // validate II.
16824 
16825   }
16826   if (T->isReferenceType()) {
16827     Diag(Loc, diag::err_ivar_reference_type);
16828     D.setInvalidType();
16829   }
16830   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16831   // than a variably modified type.
16832   else if (T->isVariablyModifiedType()) {
16833     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16834     D.setInvalidType();
16835   }
16836 
16837   // Get the visibility (access control) for this ivar.
16838   ObjCIvarDecl::AccessControl ac =
16839     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16840                                         : ObjCIvarDecl::None;
16841   // Must set ivar's DeclContext to its enclosing interface.
16842   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16843   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16844     return nullptr;
16845   ObjCContainerDecl *EnclosingContext;
16846   if (ObjCImplementationDecl *IMPDecl =
16847       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16848     if (LangOpts.ObjCRuntime.isFragile()) {
16849     // Case of ivar declared in an implementation. Context is that of its class.
16850       EnclosingContext = IMPDecl->getClassInterface();
16851       assert(EnclosingContext && "Implementation has no class interface!");
16852     }
16853     else
16854       EnclosingContext = EnclosingDecl;
16855   } else {
16856     if (ObjCCategoryDecl *CDecl =
16857         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16858       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16859         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16860         return nullptr;
16861       }
16862     }
16863     EnclosingContext = EnclosingDecl;
16864   }
16865 
16866   // Construct the decl.
16867   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16868                                              DeclStart, Loc, II, T,
16869                                              TInfo, ac, (Expr *)BitfieldWidth);
16870 
16871   if (II) {
16872     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16873                                            ForVisibleRedeclaration);
16874     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16875         && !isa<TagDecl>(PrevDecl)) {
16876       Diag(Loc, diag::err_duplicate_member) << II;
16877       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16878       NewID->setInvalidDecl();
16879     }
16880   }
16881 
16882   // Process attributes attached to the ivar.
16883   ProcessDeclAttributes(S, NewID, D);
16884 
16885   if (D.isInvalidType())
16886     NewID->setInvalidDecl();
16887 
16888   // In ARC, infer 'retaining' for ivars of retainable type.
16889   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16890     NewID->setInvalidDecl();
16891 
16892   if (D.getDeclSpec().isModulePrivateSpecified())
16893     NewID->setModulePrivate();
16894 
16895   if (II) {
16896     // FIXME: When interfaces are DeclContexts, we'll need to add
16897     // these to the interface.
16898     S->AddDecl(NewID);
16899     IdResolver.AddDecl(NewID);
16900   }
16901 
16902   if (LangOpts.ObjCRuntime.isNonFragile() &&
16903       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16904     Diag(Loc, diag::warn_ivars_in_interface);
16905 
16906   return NewID;
16907 }
16908 
16909 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16910 /// class and class extensions. For every class \@interface and class
16911 /// extension \@interface, if the last ivar is a bitfield of any type,
16912 /// then add an implicit `char :0` ivar to the end of that interface.
16913 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16914                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16915   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16916     return;
16917 
16918   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16919   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16920 
16921   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16922     return;
16923   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16924   if (!ID) {
16925     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16926       if (!CD->IsClassExtension())
16927         return;
16928     }
16929     // No need to add this to end of @implementation.
16930     else
16931       return;
16932   }
16933   // All conditions are met. Add a new bitfield to the tail end of ivars.
16934   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16935   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16936 
16937   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16938                               DeclLoc, DeclLoc, nullptr,
16939                               Context.CharTy,
16940                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16941                                                                DeclLoc),
16942                               ObjCIvarDecl::Private, BW,
16943                               true);
16944   AllIvarDecls.push_back(Ivar);
16945 }
16946 
16947 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16948                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16949                        SourceLocation RBrac,
16950                        const ParsedAttributesView &Attrs) {
16951   assert(EnclosingDecl && "missing record or interface decl");
16952 
16953   // If this is an Objective-C @implementation or category and we have
16954   // new fields here we should reset the layout of the interface since
16955   // it will now change.
16956   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16957     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16958     switch (DC->getKind()) {
16959     default: break;
16960     case Decl::ObjCCategory:
16961       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16962       break;
16963     case Decl::ObjCImplementation:
16964       Context.
16965         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16966       break;
16967     }
16968   }
16969 
16970   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16971   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16972 
16973   // Start counting up the number of named members; make sure to include
16974   // members of anonymous structs and unions in the total.
16975   unsigned NumNamedMembers = 0;
16976   if (Record) {
16977     for (const auto *I : Record->decls()) {
16978       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16979         if (IFD->getDeclName())
16980           ++NumNamedMembers;
16981     }
16982   }
16983 
16984   // Verify that all the fields are okay.
16985   SmallVector<FieldDecl*, 32> RecFields;
16986 
16987   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16988        i != end; ++i) {
16989     FieldDecl *FD = cast<FieldDecl>(*i);
16990 
16991     // Get the type for the field.
16992     const Type *FDTy = FD->getType().getTypePtr();
16993 
16994     if (!FD->isAnonymousStructOrUnion()) {
16995       // Remember all fields written by the user.
16996       RecFields.push_back(FD);
16997     }
16998 
16999     // If the field is already invalid for some reason, don't emit more
17000     // diagnostics about it.
17001     if (FD->isInvalidDecl()) {
17002       EnclosingDecl->setInvalidDecl();
17003       continue;
17004     }
17005 
17006     // C99 6.7.2.1p2:
17007     //   A structure or union shall not contain a member with
17008     //   incomplete or function type (hence, a structure shall not
17009     //   contain an instance of itself, but may contain a pointer to
17010     //   an instance of itself), except that the last member of a
17011     //   structure with more than one named member may have incomplete
17012     //   array type; such a structure (and any union containing,
17013     //   possibly recursively, a member that is such a structure)
17014     //   shall not be a member of a structure or an element of an
17015     //   array.
17016     bool IsLastField = (i + 1 == Fields.end());
17017     if (FDTy->isFunctionType()) {
17018       // Field declared as a function.
17019       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17020         << FD->getDeclName();
17021       FD->setInvalidDecl();
17022       EnclosingDecl->setInvalidDecl();
17023       continue;
17024     } else if (FDTy->isIncompleteArrayType() &&
17025                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17026       if (Record) {
17027         // Flexible array member.
17028         // Microsoft and g++ is more permissive regarding flexible array.
17029         // It will accept flexible array in union and also
17030         // as the sole element of a struct/class.
17031         unsigned DiagID = 0;
17032         if (!Record->isUnion() && !IsLastField) {
17033           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17034             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17035           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17036           FD->setInvalidDecl();
17037           EnclosingDecl->setInvalidDecl();
17038           continue;
17039         } else if (Record->isUnion())
17040           DiagID = getLangOpts().MicrosoftExt
17041                        ? diag::ext_flexible_array_union_ms
17042                        : getLangOpts().CPlusPlus
17043                              ? diag::ext_flexible_array_union_gnu
17044                              : diag::err_flexible_array_union;
17045         else if (NumNamedMembers < 1)
17046           DiagID = getLangOpts().MicrosoftExt
17047                        ? diag::ext_flexible_array_empty_aggregate_ms
17048                        : getLangOpts().CPlusPlus
17049                              ? diag::ext_flexible_array_empty_aggregate_gnu
17050                              : diag::err_flexible_array_empty_aggregate;
17051 
17052         if (DiagID)
17053           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17054                                           << Record->getTagKind();
17055         // While the layout of types that contain virtual bases is not specified
17056         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17057         // virtual bases after the derived members.  This would make a flexible
17058         // array member declared at the end of an object not adjacent to the end
17059         // of the type.
17060         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17061           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17062               << FD->getDeclName() << Record->getTagKind();
17063         if (!getLangOpts().C99)
17064           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17065             << FD->getDeclName() << Record->getTagKind();
17066 
17067         // If the element type has a non-trivial destructor, we would not
17068         // implicitly destroy the elements, so disallow it for now.
17069         //
17070         // FIXME: GCC allows this. We should probably either implicitly delete
17071         // the destructor of the containing class, or just allow this.
17072         QualType BaseElem = Context.getBaseElementType(FD->getType());
17073         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17074           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17075             << FD->getDeclName() << FD->getType();
17076           FD->setInvalidDecl();
17077           EnclosingDecl->setInvalidDecl();
17078           continue;
17079         }
17080         // Okay, we have a legal flexible array member at the end of the struct.
17081         Record->setHasFlexibleArrayMember(true);
17082       } else {
17083         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17084         // unless they are followed by another ivar. That check is done
17085         // elsewhere, after synthesized ivars are known.
17086       }
17087     } else if (!FDTy->isDependentType() &&
17088                RequireCompleteSizedType(
17089                    FD->getLocation(), FD->getType(),
17090                    diag::err_field_incomplete_or_sizeless)) {
17091       // Incomplete type
17092       FD->setInvalidDecl();
17093       EnclosingDecl->setInvalidDecl();
17094       continue;
17095     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17096       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17097         // A type which contains a flexible array member is considered to be a
17098         // flexible array member.
17099         Record->setHasFlexibleArrayMember(true);
17100         if (!Record->isUnion()) {
17101           // If this is a struct/class and this is not the last element, reject
17102           // it.  Note that GCC supports variable sized arrays in the middle of
17103           // structures.
17104           if (!IsLastField)
17105             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17106               << FD->getDeclName() << FD->getType();
17107           else {
17108             // We support flexible arrays at the end of structs in
17109             // other structs as an extension.
17110             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17111               << FD->getDeclName();
17112           }
17113         }
17114       }
17115       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17116           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17117                                  diag::err_abstract_type_in_decl,
17118                                  AbstractIvarType)) {
17119         // Ivars can not have abstract class types
17120         FD->setInvalidDecl();
17121       }
17122       if (Record && FDTTy->getDecl()->hasObjectMember())
17123         Record->setHasObjectMember(true);
17124       if (Record && FDTTy->getDecl()->hasVolatileMember())
17125         Record->setHasVolatileMember(true);
17126     } else if (FDTy->isObjCObjectType()) {
17127       /// A field cannot be an Objective-c object
17128       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17129         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17130       QualType T = Context.getObjCObjectPointerType(FD->getType());
17131       FD->setType(T);
17132     } else if (Record && Record->isUnion() &&
17133                FD->getType().hasNonTrivialObjCLifetime() &&
17134                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17135                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17136                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17137                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17138       // For backward compatibility, fields of C unions declared in system
17139       // headers that have non-trivial ObjC ownership qualifications are marked
17140       // as unavailable unless the qualifier is explicit and __strong. This can
17141       // break ABI compatibility between programs compiled with ARC and MRR, but
17142       // is a better option than rejecting programs using those unions under
17143       // ARC.
17144       FD->addAttr(UnavailableAttr::CreateImplicit(
17145           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17146           FD->getLocation()));
17147     } else if (getLangOpts().ObjC &&
17148                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17149                !Record->hasObjectMember()) {
17150       if (FD->getType()->isObjCObjectPointerType() ||
17151           FD->getType().isObjCGCStrong())
17152         Record->setHasObjectMember(true);
17153       else if (Context.getAsArrayType(FD->getType())) {
17154         QualType BaseType = Context.getBaseElementType(FD->getType());
17155         if (BaseType->isRecordType() &&
17156             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17157           Record->setHasObjectMember(true);
17158         else if (BaseType->isObjCObjectPointerType() ||
17159                  BaseType.isObjCGCStrong())
17160                Record->setHasObjectMember(true);
17161       }
17162     }
17163 
17164     if (Record && !getLangOpts().CPlusPlus &&
17165         !shouldIgnoreForRecordTriviality(FD)) {
17166       QualType FT = FD->getType();
17167       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17168         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17169         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17170             Record->isUnion())
17171           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17172       }
17173       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17174       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17175         Record->setNonTrivialToPrimitiveCopy(true);
17176         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17177           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17178       }
17179       if (FT.isDestructedType()) {
17180         Record->setNonTrivialToPrimitiveDestroy(true);
17181         Record->setParamDestroyedInCallee(true);
17182         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17183           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17184       }
17185 
17186       if (const auto *RT = FT->getAs<RecordType>()) {
17187         if (RT->getDecl()->getArgPassingRestrictions() ==
17188             RecordDecl::APK_CanNeverPassInRegs)
17189           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17190       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17191         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17192     }
17193 
17194     if (Record && FD->getType().isVolatileQualified())
17195       Record->setHasVolatileMember(true);
17196     // Keep track of the number of named members.
17197     if (FD->getIdentifier())
17198       ++NumNamedMembers;
17199   }
17200 
17201   // Okay, we successfully defined 'Record'.
17202   if (Record) {
17203     bool Completed = false;
17204     if (CXXRecord) {
17205       if (!CXXRecord->isInvalidDecl()) {
17206         // Set access bits correctly on the directly-declared conversions.
17207         for (CXXRecordDecl::conversion_iterator
17208                I = CXXRecord->conversion_begin(),
17209                E = CXXRecord->conversion_end(); I != E; ++I)
17210           I.setAccess((*I)->getAccess());
17211       }
17212 
17213       // Add any implicitly-declared members to this class.
17214       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17215 
17216       if (!CXXRecord->isDependentType()) {
17217         if (!CXXRecord->isInvalidDecl()) {
17218           // If we have virtual base classes, we may end up finding multiple
17219           // final overriders for a given virtual function. Check for this
17220           // problem now.
17221           if (CXXRecord->getNumVBases()) {
17222             CXXFinalOverriderMap FinalOverriders;
17223             CXXRecord->getFinalOverriders(FinalOverriders);
17224 
17225             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17226                                              MEnd = FinalOverriders.end();
17227                  M != MEnd; ++M) {
17228               for (OverridingMethods::iterator SO = M->second.begin(),
17229                                             SOEnd = M->second.end();
17230                    SO != SOEnd; ++SO) {
17231                 assert(SO->second.size() > 0 &&
17232                        "Virtual function without overriding functions?");
17233                 if (SO->second.size() == 1)
17234                   continue;
17235 
17236                 // C++ [class.virtual]p2:
17237                 //   In a derived class, if a virtual member function of a base
17238                 //   class subobject has more than one final overrider the
17239                 //   program is ill-formed.
17240                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17241                   << (const NamedDecl *)M->first << Record;
17242                 Diag(M->first->getLocation(),
17243                      diag::note_overridden_virtual_function);
17244                 for (OverridingMethods::overriding_iterator
17245                           OM = SO->second.begin(),
17246                        OMEnd = SO->second.end();
17247                      OM != OMEnd; ++OM)
17248                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17249                     << (const NamedDecl *)M->first << OM->Method->getParent();
17250 
17251                 Record->setInvalidDecl();
17252               }
17253             }
17254             CXXRecord->completeDefinition(&FinalOverriders);
17255             Completed = true;
17256           }
17257         }
17258       }
17259     }
17260 
17261     if (!Completed)
17262       Record->completeDefinition();
17263 
17264     // Handle attributes before checking the layout.
17265     ProcessDeclAttributeList(S, Record, Attrs);
17266 
17267     // We may have deferred checking for a deleted destructor. Check now.
17268     if (CXXRecord) {
17269       auto *Dtor = CXXRecord->getDestructor();
17270       if (Dtor && Dtor->isImplicit() &&
17271           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17272         CXXRecord->setImplicitDestructorIsDeleted();
17273         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17274       }
17275     }
17276 
17277     if (Record->hasAttrs()) {
17278       CheckAlignasUnderalignment(Record);
17279 
17280       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17281         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17282                                            IA->getRange(), IA->getBestCase(),
17283                                            IA->getInheritanceModel());
17284     }
17285 
17286     // Check if the structure/union declaration is a type that can have zero
17287     // size in C. For C this is a language extension, for C++ it may cause
17288     // compatibility problems.
17289     bool CheckForZeroSize;
17290     if (!getLangOpts().CPlusPlus) {
17291       CheckForZeroSize = true;
17292     } else {
17293       // For C++ filter out types that cannot be referenced in C code.
17294       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17295       CheckForZeroSize =
17296           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17297           !CXXRecord->isDependentType() &&
17298           CXXRecord->isCLike();
17299     }
17300     if (CheckForZeroSize) {
17301       bool ZeroSize = true;
17302       bool IsEmpty = true;
17303       unsigned NonBitFields = 0;
17304       for (RecordDecl::field_iterator I = Record->field_begin(),
17305                                       E = Record->field_end();
17306            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17307         IsEmpty = false;
17308         if (I->isUnnamedBitfield()) {
17309           if (!I->isZeroLengthBitField(Context))
17310             ZeroSize = false;
17311         } else {
17312           ++NonBitFields;
17313           QualType FieldType = I->getType();
17314           if (FieldType->isIncompleteType() ||
17315               !Context.getTypeSizeInChars(FieldType).isZero())
17316             ZeroSize = false;
17317         }
17318       }
17319 
17320       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17321       // allowed in C++, but warn if its declaration is inside
17322       // extern "C" block.
17323       if (ZeroSize) {
17324         Diag(RecLoc, getLangOpts().CPlusPlus ?
17325                          diag::warn_zero_size_struct_union_in_extern_c :
17326                          diag::warn_zero_size_struct_union_compat)
17327           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17328       }
17329 
17330       // Structs without named members are extension in C (C99 6.7.2.1p7),
17331       // but are accepted by GCC.
17332       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17333         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17334                                diag::ext_no_named_members_in_struct_union)
17335           << Record->isUnion();
17336       }
17337     }
17338   } else {
17339     ObjCIvarDecl **ClsFields =
17340       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17341     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17342       ID->setEndOfDefinitionLoc(RBrac);
17343       // Add ivar's to class's DeclContext.
17344       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17345         ClsFields[i]->setLexicalDeclContext(ID);
17346         ID->addDecl(ClsFields[i]);
17347       }
17348       // Must enforce the rule that ivars in the base classes may not be
17349       // duplicates.
17350       if (ID->getSuperClass())
17351         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17352     } else if (ObjCImplementationDecl *IMPDecl =
17353                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17354       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17355       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17356         // Ivar declared in @implementation never belongs to the implementation.
17357         // Only it is in implementation's lexical context.
17358         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17359       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17360       IMPDecl->setIvarLBraceLoc(LBrac);
17361       IMPDecl->setIvarRBraceLoc(RBrac);
17362     } else if (ObjCCategoryDecl *CDecl =
17363                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17364       // case of ivars in class extension; all other cases have been
17365       // reported as errors elsewhere.
17366       // FIXME. Class extension does not have a LocEnd field.
17367       // CDecl->setLocEnd(RBrac);
17368       // Add ivar's to class extension's DeclContext.
17369       // Diagnose redeclaration of private ivars.
17370       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17371       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17372         if (IDecl) {
17373           if (const ObjCIvarDecl *ClsIvar =
17374               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17375             Diag(ClsFields[i]->getLocation(),
17376                  diag::err_duplicate_ivar_declaration);
17377             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17378             continue;
17379           }
17380           for (const auto *Ext : IDecl->known_extensions()) {
17381             if (const ObjCIvarDecl *ClsExtIvar
17382                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17383               Diag(ClsFields[i]->getLocation(),
17384                    diag::err_duplicate_ivar_declaration);
17385               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17386               continue;
17387             }
17388           }
17389         }
17390         ClsFields[i]->setLexicalDeclContext(CDecl);
17391         CDecl->addDecl(ClsFields[i]);
17392       }
17393       CDecl->setIvarLBraceLoc(LBrac);
17394       CDecl->setIvarRBraceLoc(RBrac);
17395     }
17396   }
17397 }
17398 
17399 /// Determine whether the given integral value is representable within
17400 /// the given type T.
17401 static bool isRepresentableIntegerValue(ASTContext &Context,
17402                                         llvm::APSInt &Value,
17403                                         QualType T) {
17404   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17405          "Integral type required!");
17406   unsigned BitWidth = Context.getIntWidth(T);
17407 
17408   if (Value.isUnsigned() || Value.isNonNegative()) {
17409     if (T->isSignedIntegerOrEnumerationType())
17410       --BitWidth;
17411     return Value.getActiveBits() <= BitWidth;
17412   }
17413   return Value.getMinSignedBits() <= BitWidth;
17414 }
17415 
17416 // Given an integral type, return the next larger integral type
17417 // (or a NULL type of no such type exists).
17418 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17419   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17420   // enum checking below.
17421   assert((T->isIntegralType(Context) ||
17422          T->isEnumeralType()) && "Integral type required!");
17423   const unsigned NumTypes = 4;
17424   QualType SignedIntegralTypes[NumTypes] = {
17425     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17426   };
17427   QualType UnsignedIntegralTypes[NumTypes] = {
17428     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17429     Context.UnsignedLongLongTy
17430   };
17431 
17432   unsigned BitWidth = Context.getTypeSize(T);
17433   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17434                                                         : UnsignedIntegralTypes;
17435   for (unsigned I = 0; I != NumTypes; ++I)
17436     if (Context.getTypeSize(Types[I]) > BitWidth)
17437       return Types[I];
17438 
17439   return QualType();
17440 }
17441 
17442 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17443                                           EnumConstantDecl *LastEnumConst,
17444                                           SourceLocation IdLoc,
17445                                           IdentifierInfo *Id,
17446                                           Expr *Val) {
17447   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17448   llvm::APSInt EnumVal(IntWidth);
17449   QualType EltTy;
17450 
17451   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17452     Val = nullptr;
17453 
17454   if (Val)
17455     Val = DefaultLvalueConversion(Val).get();
17456 
17457   if (Val) {
17458     if (Enum->isDependentType() || Val->isTypeDependent())
17459       EltTy = Context.DependentTy;
17460     else {
17461       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17462         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17463         // constant-expression in the enumerator-definition shall be a converted
17464         // constant expression of the underlying type.
17465         EltTy = Enum->getIntegerType();
17466         ExprResult Converted =
17467           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17468                                            CCEK_Enumerator);
17469         if (Converted.isInvalid())
17470           Val = nullptr;
17471         else
17472           Val = Converted.get();
17473       } else if (!Val->isValueDependent() &&
17474                  !(Val = VerifyIntegerConstantExpression(Val,
17475                                                          &EnumVal).get())) {
17476         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17477       } else {
17478         if (Enum->isComplete()) {
17479           EltTy = Enum->getIntegerType();
17480 
17481           // In Obj-C and Microsoft mode, require the enumeration value to be
17482           // representable in the underlying type of the enumeration. In C++11,
17483           // we perform a non-narrowing conversion as part of converted constant
17484           // expression checking.
17485           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17486             if (Context.getTargetInfo()
17487                     .getTriple()
17488                     .isWindowsMSVCEnvironment()) {
17489               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17490             } else {
17491               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17492             }
17493           }
17494 
17495           // Cast to the underlying type.
17496           Val = ImpCastExprToType(Val, EltTy,
17497                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17498                                                          : CK_IntegralCast)
17499                     .get();
17500         } else if (getLangOpts().CPlusPlus) {
17501           // C++11 [dcl.enum]p5:
17502           //   If the underlying type is not fixed, the type of each enumerator
17503           //   is the type of its initializing value:
17504           //     - If an initializer is specified for an enumerator, the
17505           //       initializing value has the same type as the expression.
17506           EltTy = Val->getType();
17507         } else {
17508           // C99 6.7.2.2p2:
17509           //   The expression that defines the value of an enumeration constant
17510           //   shall be an integer constant expression that has a value
17511           //   representable as an int.
17512 
17513           // Complain if the value is not representable in an int.
17514           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17515             Diag(IdLoc, diag::ext_enum_value_not_int)
17516               << EnumVal.toString(10) << Val->getSourceRange()
17517               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17518           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17519             // Force the type of the expression to 'int'.
17520             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17521           }
17522           EltTy = Val->getType();
17523         }
17524       }
17525     }
17526   }
17527 
17528   if (!Val) {
17529     if (Enum->isDependentType())
17530       EltTy = Context.DependentTy;
17531     else if (!LastEnumConst) {
17532       // C++0x [dcl.enum]p5:
17533       //   If the underlying type is not fixed, the type of each enumerator
17534       //   is the type of its initializing value:
17535       //     - If no initializer is specified for the first enumerator, the
17536       //       initializing value has an unspecified integral type.
17537       //
17538       // GCC uses 'int' for its unspecified integral type, as does
17539       // C99 6.7.2.2p3.
17540       if (Enum->isFixed()) {
17541         EltTy = Enum->getIntegerType();
17542       }
17543       else {
17544         EltTy = Context.IntTy;
17545       }
17546     } else {
17547       // Assign the last value + 1.
17548       EnumVal = LastEnumConst->getInitVal();
17549       ++EnumVal;
17550       EltTy = LastEnumConst->getType();
17551 
17552       // Check for overflow on increment.
17553       if (EnumVal < LastEnumConst->getInitVal()) {
17554         // C++0x [dcl.enum]p5:
17555         //   If the underlying type is not fixed, the type of each enumerator
17556         //   is the type of its initializing value:
17557         //
17558         //     - Otherwise the type of the initializing value is the same as
17559         //       the type of the initializing value of the preceding enumerator
17560         //       unless the incremented value is not representable in that type,
17561         //       in which case the type is an unspecified integral type
17562         //       sufficient to contain the incremented value. If no such type
17563         //       exists, the program is ill-formed.
17564         QualType T = getNextLargerIntegralType(Context, EltTy);
17565         if (T.isNull() || Enum->isFixed()) {
17566           // There is no integral type larger enough to represent this
17567           // value. Complain, then allow the value to wrap around.
17568           EnumVal = LastEnumConst->getInitVal();
17569           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17570           ++EnumVal;
17571           if (Enum->isFixed())
17572             // When the underlying type is fixed, this is ill-formed.
17573             Diag(IdLoc, diag::err_enumerator_wrapped)
17574               << EnumVal.toString(10)
17575               << EltTy;
17576           else
17577             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17578               << EnumVal.toString(10);
17579         } else {
17580           EltTy = T;
17581         }
17582 
17583         // Retrieve the last enumerator's value, extent that type to the
17584         // type that is supposed to be large enough to represent the incremented
17585         // value, then increment.
17586         EnumVal = LastEnumConst->getInitVal();
17587         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17588         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17589         ++EnumVal;
17590 
17591         // If we're not in C++, diagnose the overflow of enumerator values,
17592         // which in C99 means that the enumerator value is not representable in
17593         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17594         // permits enumerator values that are representable in some larger
17595         // integral type.
17596         if (!getLangOpts().CPlusPlus && !T.isNull())
17597           Diag(IdLoc, diag::warn_enum_value_overflow);
17598       } else if (!getLangOpts().CPlusPlus &&
17599                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17600         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17601         Diag(IdLoc, diag::ext_enum_value_not_int)
17602           << EnumVal.toString(10) << 1;
17603       }
17604     }
17605   }
17606 
17607   if (!EltTy->isDependentType()) {
17608     // Make the enumerator value match the signedness and size of the
17609     // enumerator's type.
17610     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17611     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17612   }
17613 
17614   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17615                                   Val, EnumVal);
17616 }
17617 
17618 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17619                                                 SourceLocation IILoc) {
17620   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17621       !getLangOpts().CPlusPlus)
17622     return SkipBodyInfo();
17623 
17624   // We have an anonymous enum definition. Look up the first enumerator to
17625   // determine if we should merge the definition with an existing one and
17626   // skip the body.
17627   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17628                                          forRedeclarationInCurContext());
17629   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17630   if (!PrevECD)
17631     return SkipBodyInfo();
17632 
17633   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17634   NamedDecl *Hidden;
17635   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17636     SkipBodyInfo Skip;
17637     Skip.Previous = Hidden;
17638     return Skip;
17639   }
17640 
17641   return SkipBodyInfo();
17642 }
17643 
17644 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17645                               SourceLocation IdLoc, IdentifierInfo *Id,
17646                               const ParsedAttributesView &Attrs,
17647                               SourceLocation EqualLoc, Expr *Val) {
17648   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17649   EnumConstantDecl *LastEnumConst =
17650     cast_or_null<EnumConstantDecl>(lastEnumConst);
17651 
17652   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17653   // we find one that is.
17654   S = getNonFieldDeclScope(S);
17655 
17656   // Verify that there isn't already something declared with this name in this
17657   // scope.
17658   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17659   LookupName(R, S);
17660   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17661 
17662   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17663     // Maybe we will complain about the shadowed template parameter.
17664     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17665     // Just pretend that we didn't see the previous declaration.
17666     PrevDecl = nullptr;
17667   }
17668 
17669   // C++ [class.mem]p15:
17670   // If T is the name of a class, then each of the following shall have a name
17671   // different from T:
17672   // - every enumerator of every member of class T that is an unscoped
17673   // enumerated type
17674   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17675     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17676                             DeclarationNameInfo(Id, IdLoc));
17677 
17678   EnumConstantDecl *New =
17679     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17680   if (!New)
17681     return nullptr;
17682 
17683   if (PrevDecl) {
17684     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17685       // Check for other kinds of shadowing not already handled.
17686       CheckShadow(New, PrevDecl, R);
17687     }
17688 
17689     // When in C++, we may get a TagDecl with the same name; in this case the
17690     // enum constant will 'hide' the tag.
17691     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17692            "Received TagDecl when not in C++!");
17693     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17694       if (isa<EnumConstantDecl>(PrevDecl))
17695         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17696       else
17697         Diag(IdLoc, diag::err_redefinition) << Id;
17698       notePreviousDefinition(PrevDecl, IdLoc);
17699       return nullptr;
17700     }
17701   }
17702 
17703   // Process attributes.
17704   ProcessDeclAttributeList(S, New, Attrs);
17705   AddPragmaAttributes(S, New);
17706 
17707   // Register this decl in the current scope stack.
17708   New->setAccess(TheEnumDecl->getAccess());
17709   PushOnScopeChains(New, S);
17710 
17711   ActOnDocumentableDecl(New);
17712 
17713   return New;
17714 }
17715 
17716 // Returns true when the enum initial expression does not trigger the
17717 // duplicate enum warning.  A few common cases are exempted as follows:
17718 // Element2 = Element1
17719 // Element2 = Element1 + 1
17720 // Element2 = Element1 - 1
17721 // Where Element2 and Element1 are from the same enum.
17722 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17723   Expr *InitExpr = ECD->getInitExpr();
17724   if (!InitExpr)
17725     return true;
17726   InitExpr = InitExpr->IgnoreImpCasts();
17727 
17728   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17729     if (!BO->isAdditiveOp())
17730       return true;
17731     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17732     if (!IL)
17733       return true;
17734     if (IL->getValue() != 1)
17735       return true;
17736 
17737     InitExpr = BO->getLHS();
17738   }
17739 
17740   // This checks if the elements are from the same enum.
17741   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17742   if (!DRE)
17743     return true;
17744 
17745   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17746   if (!EnumConstant)
17747     return true;
17748 
17749   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17750       Enum)
17751     return true;
17752 
17753   return false;
17754 }
17755 
17756 // Emits a warning when an element is implicitly set a value that
17757 // a previous element has already been set to.
17758 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17759                                         EnumDecl *Enum, QualType EnumType) {
17760   // Avoid anonymous enums
17761   if (!Enum->getIdentifier())
17762     return;
17763 
17764   // Only check for small enums.
17765   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17766     return;
17767 
17768   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17769     return;
17770 
17771   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17772   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17773 
17774   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17775 
17776   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17777   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17778 
17779   // Use int64_t as a key to avoid needing special handling for map keys.
17780   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17781     llvm::APSInt Val = D->getInitVal();
17782     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17783   };
17784 
17785   DuplicatesVector DupVector;
17786   ValueToVectorMap EnumMap;
17787 
17788   // Populate the EnumMap with all values represented by enum constants without
17789   // an initializer.
17790   for (auto *Element : Elements) {
17791     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17792 
17793     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17794     // this constant.  Skip this enum since it may be ill-formed.
17795     if (!ECD) {
17796       return;
17797     }
17798 
17799     // Constants with initalizers are handled in the next loop.
17800     if (ECD->getInitExpr())
17801       continue;
17802 
17803     // Duplicate values are handled in the next loop.
17804     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17805   }
17806 
17807   if (EnumMap.size() == 0)
17808     return;
17809 
17810   // Create vectors for any values that has duplicates.
17811   for (auto *Element : Elements) {
17812     // The last loop returned if any constant was null.
17813     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17814     if (!ValidDuplicateEnum(ECD, Enum))
17815       continue;
17816 
17817     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17818     if (Iter == EnumMap.end())
17819       continue;
17820 
17821     DeclOrVector& Entry = Iter->second;
17822     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17823       // Ensure constants are different.
17824       if (D == ECD)
17825         continue;
17826 
17827       // Create new vector and push values onto it.
17828       auto Vec = std::make_unique<ECDVector>();
17829       Vec->push_back(D);
17830       Vec->push_back(ECD);
17831 
17832       // Update entry to point to the duplicates vector.
17833       Entry = Vec.get();
17834 
17835       // Store the vector somewhere we can consult later for quick emission of
17836       // diagnostics.
17837       DupVector.emplace_back(std::move(Vec));
17838       continue;
17839     }
17840 
17841     ECDVector *Vec = Entry.get<ECDVector*>();
17842     // Make sure constants are not added more than once.
17843     if (*Vec->begin() == ECD)
17844       continue;
17845 
17846     Vec->push_back(ECD);
17847   }
17848 
17849   // Emit diagnostics.
17850   for (const auto &Vec : DupVector) {
17851     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17852 
17853     // Emit warning for one enum constant.
17854     auto *FirstECD = Vec->front();
17855     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17856       << FirstECD << FirstECD->getInitVal().toString(10)
17857       << FirstECD->getSourceRange();
17858 
17859     // Emit one note for each of the remaining enum constants with
17860     // the same value.
17861     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17862       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17863         << ECD << ECD->getInitVal().toString(10)
17864         << ECD->getSourceRange();
17865   }
17866 }
17867 
17868 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17869                              bool AllowMask) const {
17870   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17871   assert(ED->isCompleteDefinition() && "expected enum definition");
17872 
17873   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17874   llvm::APInt &FlagBits = R.first->second;
17875 
17876   if (R.second) {
17877     for (auto *E : ED->enumerators()) {
17878       const auto &EVal = E->getInitVal();
17879       // Only single-bit enumerators introduce new flag values.
17880       if (EVal.isPowerOf2())
17881         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17882     }
17883   }
17884 
17885   // A value is in a flag enum if either its bits are a subset of the enum's
17886   // flag bits (the first condition) or we are allowing masks and the same is
17887   // true of its complement (the second condition). When masks are allowed, we
17888   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17889   //
17890   // While it's true that any value could be used as a mask, the assumption is
17891   // that a mask will have all of the insignificant bits set. Anything else is
17892   // likely a logic error.
17893   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17894   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17895 }
17896 
17897 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17898                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17899                          const ParsedAttributesView &Attrs) {
17900   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17901   QualType EnumType = Context.getTypeDeclType(Enum);
17902 
17903   ProcessDeclAttributeList(S, Enum, Attrs);
17904 
17905   if (Enum->isDependentType()) {
17906     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17907       EnumConstantDecl *ECD =
17908         cast_or_null<EnumConstantDecl>(Elements[i]);
17909       if (!ECD) continue;
17910 
17911       ECD->setType(EnumType);
17912     }
17913 
17914     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17915     return;
17916   }
17917 
17918   // TODO: If the result value doesn't fit in an int, it must be a long or long
17919   // long value.  ISO C does not support this, but GCC does as an extension,
17920   // emit a warning.
17921   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17922   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17923   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17924 
17925   // Verify that all the values are okay, compute the size of the values, and
17926   // reverse the list.
17927   unsigned NumNegativeBits = 0;
17928   unsigned NumPositiveBits = 0;
17929 
17930   // Keep track of whether all elements have type int.
17931   bool AllElementsInt = true;
17932 
17933   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17934     EnumConstantDecl *ECD =
17935       cast_or_null<EnumConstantDecl>(Elements[i]);
17936     if (!ECD) continue;  // Already issued a diagnostic.
17937 
17938     const llvm::APSInt &InitVal = ECD->getInitVal();
17939 
17940     // Keep track of the size of positive and negative values.
17941     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17942       NumPositiveBits = std::max(NumPositiveBits,
17943                                  (unsigned)InitVal.getActiveBits());
17944     else
17945       NumNegativeBits = std::max(NumNegativeBits,
17946                                  (unsigned)InitVal.getMinSignedBits());
17947 
17948     // Keep track of whether every enum element has type int (very common).
17949     if (AllElementsInt)
17950       AllElementsInt = ECD->getType() == Context.IntTy;
17951   }
17952 
17953   // Figure out the type that should be used for this enum.
17954   QualType BestType;
17955   unsigned BestWidth;
17956 
17957   // C++0x N3000 [conv.prom]p3:
17958   //   An rvalue of an unscoped enumeration type whose underlying
17959   //   type is not fixed can be converted to an rvalue of the first
17960   //   of the following types that can represent all the values of
17961   //   the enumeration: int, unsigned int, long int, unsigned long
17962   //   int, long long int, or unsigned long long int.
17963   // C99 6.4.4.3p2:
17964   //   An identifier declared as an enumeration constant has type int.
17965   // The C99 rule is modified by a gcc extension
17966   QualType BestPromotionType;
17967 
17968   bool Packed = Enum->hasAttr<PackedAttr>();
17969   // -fshort-enums is the equivalent to specifying the packed attribute on all
17970   // enum definitions.
17971   if (LangOpts.ShortEnums)
17972     Packed = true;
17973 
17974   // If the enum already has a type because it is fixed or dictated by the
17975   // target, promote that type instead of analyzing the enumerators.
17976   if (Enum->isComplete()) {
17977     BestType = Enum->getIntegerType();
17978     if (BestType->isPromotableIntegerType())
17979       BestPromotionType = Context.getPromotedIntegerType(BestType);
17980     else
17981       BestPromotionType = BestType;
17982 
17983     BestWidth = Context.getIntWidth(BestType);
17984   }
17985   else if (NumNegativeBits) {
17986     // If there is a negative value, figure out the smallest integer type (of
17987     // int/long/longlong) that fits.
17988     // If it's packed, check also if it fits a char or a short.
17989     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17990       BestType = Context.SignedCharTy;
17991       BestWidth = CharWidth;
17992     } else if (Packed && NumNegativeBits <= ShortWidth &&
17993                NumPositiveBits < ShortWidth) {
17994       BestType = Context.ShortTy;
17995       BestWidth = ShortWidth;
17996     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17997       BestType = Context.IntTy;
17998       BestWidth = IntWidth;
17999     } else {
18000       BestWidth = Context.getTargetInfo().getLongWidth();
18001 
18002       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18003         BestType = Context.LongTy;
18004       } else {
18005         BestWidth = Context.getTargetInfo().getLongLongWidth();
18006 
18007         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18008           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18009         BestType = Context.LongLongTy;
18010       }
18011     }
18012     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18013   } else {
18014     // If there is no negative value, figure out the smallest type that fits
18015     // all of the enumerator values.
18016     // If it's packed, check also if it fits a char or a short.
18017     if (Packed && NumPositiveBits <= CharWidth) {
18018       BestType = Context.UnsignedCharTy;
18019       BestPromotionType = Context.IntTy;
18020       BestWidth = CharWidth;
18021     } else if (Packed && NumPositiveBits <= ShortWidth) {
18022       BestType = Context.UnsignedShortTy;
18023       BestPromotionType = Context.IntTy;
18024       BestWidth = ShortWidth;
18025     } else if (NumPositiveBits <= IntWidth) {
18026       BestType = Context.UnsignedIntTy;
18027       BestWidth = IntWidth;
18028       BestPromotionType
18029         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18030                            ? Context.UnsignedIntTy : Context.IntTy;
18031     } else if (NumPositiveBits <=
18032                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18033       BestType = Context.UnsignedLongTy;
18034       BestPromotionType
18035         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18036                            ? Context.UnsignedLongTy : Context.LongTy;
18037     } else {
18038       BestWidth = Context.getTargetInfo().getLongLongWidth();
18039       assert(NumPositiveBits <= BestWidth &&
18040              "How could an initializer get larger than ULL?");
18041       BestType = Context.UnsignedLongLongTy;
18042       BestPromotionType
18043         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18044                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18045     }
18046   }
18047 
18048   // Loop over all of the enumerator constants, changing their types to match
18049   // the type of the enum if needed.
18050   for (auto *D : Elements) {
18051     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18052     if (!ECD) continue;  // Already issued a diagnostic.
18053 
18054     // Standard C says the enumerators have int type, but we allow, as an
18055     // extension, the enumerators to be larger than int size.  If each
18056     // enumerator value fits in an int, type it as an int, otherwise type it the
18057     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18058     // that X has type 'int', not 'unsigned'.
18059 
18060     // Determine whether the value fits into an int.
18061     llvm::APSInt InitVal = ECD->getInitVal();
18062 
18063     // If it fits into an integer type, force it.  Otherwise force it to match
18064     // the enum decl type.
18065     QualType NewTy;
18066     unsigned NewWidth;
18067     bool NewSign;
18068     if (!getLangOpts().CPlusPlus &&
18069         !Enum->isFixed() &&
18070         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18071       NewTy = Context.IntTy;
18072       NewWidth = IntWidth;
18073       NewSign = true;
18074     } else if (ECD->getType() == BestType) {
18075       // Already the right type!
18076       if (getLangOpts().CPlusPlus)
18077         // C++ [dcl.enum]p4: Following the closing brace of an
18078         // enum-specifier, each enumerator has the type of its
18079         // enumeration.
18080         ECD->setType(EnumType);
18081       continue;
18082     } else {
18083       NewTy = BestType;
18084       NewWidth = BestWidth;
18085       NewSign = BestType->isSignedIntegerOrEnumerationType();
18086     }
18087 
18088     // Adjust the APSInt value.
18089     InitVal = InitVal.extOrTrunc(NewWidth);
18090     InitVal.setIsSigned(NewSign);
18091     ECD->setInitVal(InitVal);
18092 
18093     // Adjust the Expr initializer and type.
18094     if (ECD->getInitExpr() &&
18095         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18096       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
18097                                                 CK_IntegralCast,
18098                                                 ECD->getInitExpr(),
18099                                                 /*base paths*/ nullptr,
18100                                                 VK_RValue));
18101     if (getLangOpts().CPlusPlus)
18102       // C++ [dcl.enum]p4: Following the closing brace of an
18103       // enum-specifier, each enumerator has the type of its
18104       // enumeration.
18105       ECD->setType(EnumType);
18106     else
18107       ECD->setType(NewTy);
18108   }
18109 
18110   Enum->completeDefinition(BestType, BestPromotionType,
18111                            NumPositiveBits, NumNegativeBits);
18112 
18113   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18114 
18115   if (Enum->isClosedFlag()) {
18116     for (Decl *D : Elements) {
18117       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18118       if (!ECD) continue;  // Already issued a diagnostic.
18119 
18120       llvm::APSInt InitVal = ECD->getInitVal();
18121       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18122           !IsValueInFlagEnum(Enum, InitVal, true))
18123         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18124           << ECD << Enum;
18125     }
18126   }
18127 
18128   // Now that the enum type is defined, ensure it's not been underaligned.
18129   if (Enum->hasAttrs())
18130     CheckAlignasUnderalignment(Enum);
18131 }
18132 
18133 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18134                                   SourceLocation StartLoc,
18135                                   SourceLocation EndLoc) {
18136   StringLiteral *AsmString = cast<StringLiteral>(expr);
18137 
18138   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18139                                                    AsmString, StartLoc,
18140                                                    EndLoc);
18141   CurContext->addDecl(New);
18142   return New;
18143 }
18144 
18145 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18146                                       IdentifierInfo* AliasName,
18147                                       SourceLocation PragmaLoc,
18148                                       SourceLocation NameLoc,
18149                                       SourceLocation AliasNameLoc) {
18150   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18151                                          LookupOrdinaryName);
18152   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18153                            AttributeCommonInfo::AS_Pragma);
18154   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18155       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18156 
18157   // If a declaration that:
18158   // 1) declares a function or a variable
18159   // 2) has external linkage
18160   // already exists, add a label attribute to it.
18161   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18162     if (isDeclExternC(PrevDecl))
18163       PrevDecl->addAttr(Attr);
18164     else
18165       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18166           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18167   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18168   } else
18169     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18170 }
18171 
18172 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18173                              SourceLocation PragmaLoc,
18174                              SourceLocation NameLoc) {
18175   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18176 
18177   if (PrevDecl) {
18178     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18179   } else {
18180     (void)WeakUndeclaredIdentifiers.insert(
18181       std::pair<IdentifierInfo*,WeakInfo>
18182         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18183   }
18184 }
18185 
18186 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18187                                 IdentifierInfo* AliasName,
18188                                 SourceLocation PragmaLoc,
18189                                 SourceLocation NameLoc,
18190                                 SourceLocation AliasNameLoc) {
18191   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18192                                     LookupOrdinaryName);
18193   WeakInfo W = WeakInfo(Name, NameLoc);
18194 
18195   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18196     if (!PrevDecl->hasAttr<AliasAttr>())
18197       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18198         DeclApplyPragmaWeak(TUScope, ND, W);
18199   } else {
18200     (void)WeakUndeclaredIdentifiers.insert(
18201       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18202   }
18203 }
18204 
18205 Decl *Sema::getObjCDeclContext() const {
18206   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18207 }
18208 
18209 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18210                                                      bool Final) {
18211   // SYCL functions can be template, so we check if they have appropriate
18212   // attribute prior to checking if it is a template.
18213   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18214     return FunctionEmissionStatus::Emitted;
18215 
18216   // Templates are emitted when they're instantiated.
18217   if (FD->isDependentContext())
18218     return FunctionEmissionStatus::TemplateDiscarded;
18219 
18220   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18221   if (LangOpts.OpenMPIsDevice) {
18222     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18223         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18224     if (DevTy.hasValue()) {
18225       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18226         OMPES = FunctionEmissionStatus::OMPDiscarded;
18227       else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18228                *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18229         OMPES = FunctionEmissionStatus::Emitted;
18230       }
18231     }
18232   } else if (LangOpts.OpenMP) {
18233     // In OpenMP 4.5 all the functions are host functions.
18234     if (LangOpts.OpenMP <= 45) {
18235       OMPES = FunctionEmissionStatus::Emitted;
18236     } else {
18237       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18238           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18239       // In OpenMP 5.0 or above, DevTy may be changed later by
18240       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18241       // having no value does not imply host. The emission status will be
18242       // checked again at the end of compilation unit.
18243       if (DevTy.hasValue()) {
18244         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18245           OMPES = FunctionEmissionStatus::OMPDiscarded;
18246         } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18247                    *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18248           OMPES = FunctionEmissionStatus::Emitted;
18249       } else if (Final)
18250         OMPES = FunctionEmissionStatus::Emitted;
18251     }
18252   }
18253   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18254       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18255     return OMPES;
18256 
18257   if (LangOpts.CUDA) {
18258     // When compiling for device, host functions are never emitted.  Similarly,
18259     // when compiling for host, device and global functions are never emitted.
18260     // (Technically, we do emit a host-side stub for global functions, but this
18261     // doesn't count for our purposes here.)
18262     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18263     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18264       return FunctionEmissionStatus::CUDADiscarded;
18265     if (!LangOpts.CUDAIsDevice &&
18266         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18267       return FunctionEmissionStatus::CUDADiscarded;
18268 
18269     // Check whether this function is externally visible -- if so, it's
18270     // known-emitted.
18271     //
18272     // We have to check the GVA linkage of the function's *definition* -- if we
18273     // only have a declaration, we don't know whether or not the function will
18274     // be emitted, because (say) the definition could include "inline".
18275     FunctionDecl *Def = FD->getDefinition();
18276 
18277     if (Def &&
18278         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18279         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18280       return FunctionEmissionStatus::Emitted;
18281   }
18282 
18283   // Otherwise, the function is known-emitted if it's in our set of
18284   // known-emitted functions.
18285   return FunctionEmissionStatus::Unknown;
18286 }
18287 
18288 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18289   // Host-side references to a __global__ function refer to the stub, so the
18290   // function itself is never emitted and therefore should not be marked.
18291   // If we have host fn calls kernel fn calls host+device, the HD function
18292   // does not get instantiated on the host. We model this by omitting at the
18293   // call to the kernel from the callgraph. This ensures that, when compiling
18294   // for host, only HD functions actually called from the host get marked as
18295   // known-emitted.
18296   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18297          IdentifyCUDATarget(Callee) == CFT_Global;
18298 }
18299