xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDecl.cpp (revision dc318a4ffabcbfa23bb56a33403aad36e6de30af)
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         Context.BuiltinInfo.allowTypeMismatch(ID))
2112       return nullptr;
2113 
2114     // If we could not find a type for setjmp it is because the jmp_buf type was
2115     // not defined prior to the setjmp declaration.
2116     if (Error == ASTContext::GE_Missing_setjmp) {
2117       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2118           << Context.BuiltinInfo.getName(ID);
2119       return nullptr;
2120     }
2121 
2122     // Generally, we emit a warning that the declaration requires the
2123     // appropriate header.
2124     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2125         << getHeaderName(Context.BuiltinInfo, ID, Error)
2126         << Context.BuiltinInfo.getName(ID);
2127     return nullptr;
2128   }
2129 
2130   if (!ForRedeclaration &&
2131       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2132        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2133     Diag(Loc, diag::ext_implicit_lib_function_decl)
2134         << Context.BuiltinInfo.getName(ID) << R;
2135     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2136       Diag(Loc, diag::note_include_header_or_declare)
2137           << Header << Context.BuiltinInfo.getName(ID);
2138   }
2139 
2140   if (R.isNull())
2141     return nullptr;
2142 
2143   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2144   RegisterLocallyScopedExternCDecl(New, S);
2145 
2146   // TUScope is the translation-unit scope to insert this function into.
2147   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2148   // relate Scopes to DeclContexts, and probably eliminate CurContext
2149   // entirely, but we're not there yet.
2150   DeclContext *SavedContext = CurContext;
2151   CurContext = New->getDeclContext();
2152   PushOnScopeChains(New, TUScope);
2153   CurContext = SavedContext;
2154   return New;
2155 }
2156 
2157 /// Typedef declarations don't have linkage, but they still denote the same
2158 /// entity if their types are the same.
2159 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2160 /// isSameEntity.
2161 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2162                                                      TypedefNameDecl *Decl,
2163                                                      LookupResult &Previous) {
2164   // This is only interesting when modules are enabled.
2165   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2166     return;
2167 
2168   // Empty sets are uninteresting.
2169   if (Previous.empty())
2170     return;
2171 
2172   LookupResult::Filter Filter = Previous.makeFilter();
2173   while (Filter.hasNext()) {
2174     NamedDecl *Old = Filter.next();
2175 
2176     // Non-hidden declarations are never ignored.
2177     if (S.isVisible(Old))
2178       continue;
2179 
2180     // Declarations of the same entity are not ignored, even if they have
2181     // different linkages.
2182     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2183       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2184                                 Decl->getUnderlyingType()))
2185         continue;
2186 
2187       // If both declarations give a tag declaration a typedef name for linkage
2188       // purposes, then they declare the same entity.
2189       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2190           Decl->getAnonDeclWithTypedefName())
2191         continue;
2192     }
2193 
2194     Filter.erase();
2195   }
2196 
2197   Filter.done();
2198 }
2199 
2200 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2201   QualType OldType;
2202   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2203     OldType = OldTypedef->getUnderlyingType();
2204   else
2205     OldType = Context.getTypeDeclType(Old);
2206   QualType NewType = New->getUnderlyingType();
2207 
2208   if (NewType->isVariablyModifiedType()) {
2209     // Must not redefine a typedef with a variably-modified type.
2210     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2211     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2212       << Kind << NewType;
2213     if (Old->getLocation().isValid())
2214       notePreviousDefinition(Old, New->getLocation());
2215     New->setInvalidDecl();
2216     return true;
2217   }
2218 
2219   if (OldType != NewType &&
2220       !OldType->isDependentType() &&
2221       !NewType->isDependentType() &&
2222       !Context.hasSameType(OldType, NewType)) {
2223     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2224     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2225       << Kind << NewType << OldType;
2226     if (Old->getLocation().isValid())
2227       notePreviousDefinition(Old, New->getLocation());
2228     New->setInvalidDecl();
2229     return true;
2230   }
2231   return false;
2232 }
2233 
2234 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2235 /// same name and scope as a previous declaration 'Old'.  Figure out
2236 /// how to resolve this situation, merging decls or emitting
2237 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2238 ///
2239 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2240                                 LookupResult &OldDecls) {
2241   // If the new decl is known invalid already, don't bother doing any
2242   // merging checks.
2243   if (New->isInvalidDecl()) return;
2244 
2245   // Allow multiple definitions for ObjC built-in typedefs.
2246   // FIXME: Verify the underlying types are equivalent!
2247   if (getLangOpts().ObjC) {
2248     const IdentifierInfo *TypeID = New->getIdentifier();
2249     switch (TypeID->getLength()) {
2250     default: break;
2251     case 2:
2252       {
2253         if (!TypeID->isStr("id"))
2254           break;
2255         QualType T = New->getUnderlyingType();
2256         if (!T->isPointerType())
2257           break;
2258         if (!T->isVoidPointerType()) {
2259           QualType PT = T->castAs<PointerType>()->getPointeeType();
2260           if (!PT->isStructureType())
2261             break;
2262         }
2263         Context.setObjCIdRedefinitionType(T);
2264         // Install the built-in type for 'id', ignoring the current definition.
2265         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2266         return;
2267       }
2268     case 5:
2269       if (!TypeID->isStr("Class"))
2270         break;
2271       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2272       // Install the built-in type for 'Class', ignoring the current definition.
2273       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2274       return;
2275     case 3:
2276       if (!TypeID->isStr("SEL"))
2277         break;
2278       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2279       // Install the built-in type for 'SEL', ignoring the current definition.
2280       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2281       return;
2282     }
2283     // Fall through - the typedef name was not a builtin type.
2284   }
2285 
2286   // Verify the old decl was also a type.
2287   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2288   if (!Old) {
2289     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2290       << New->getDeclName();
2291 
2292     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2293     if (OldD->getLocation().isValid())
2294       notePreviousDefinition(OldD, New->getLocation());
2295 
2296     return New->setInvalidDecl();
2297   }
2298 
2299   // If the old declaration is invalid, just give up here.
2300   if (Old->isInvalidDecl())
2301     return New->setInvalidDecl();
2302 
2303   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2304     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2305     auto *NewTag = New->getAnonDeclWithTypedefName();
2306     NamedDecl *Hidden = nullptr;
2307     if (OldTag && NewTag &&
2308         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2309         !hasVisibleDefinition(OldTag, &Hidden)) {
2310       // There is a definition of this tag, but it is not visible. Use it
2311       // instead of our tag.
2312       New->setTypeForDecl(OldTD->getTypeForDecl());
2313       if (OldTD->isModed())
2314         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2315                                     OldTD->getUnderlyingType());
2316       else
2317         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2318 
2319       // Make the old tag definition visible.
2320       makeMergedDefinitionVisible(Hidden);
2321 
2322       // If this was an unscoped enumeration, yank all of its enumerators
2323       // out of the scope.
2324       if (isa<EnumDecl>(NewTag)) {
2325         Scope *EnumScope = getNonFieldDeclScope(S);
2326         for (auto *D : NewTag->decls()) {
2327           auto *ED = cast<EnumConstantDecl>(D);
2328           assert(EnumScope->isDeclScope(ED));
2329           EnumScope->RemoveDecl(ED);
2330           IdResolver.RemoveDecl(ED);
2331           ED->getLexicalDeclContext()->removeDecl(ED);
2332         }
2333       }
2334     }
2335   }
2336 
2337   // If the typedef types are not identical, reject them in all languages and
2338   // with any extensions enabled.
2339   if (isIncompatibleTypedef(Old, New))
2340     return;
2341 
2342   // The types match.  Link up the redeclaration chain and merge attributes if
2343   // the old declaration was a typedef.
2344   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2345     New->setPreviousDecl(Typedef);
2346     mergeDeclAttributes(New, Old);
2347   }
2348 
2349   if (getLangOpts().MicrosoftExt)
2350     return;
2351 
2352   if (getLangOpts().CPlusPlus) {
2353     // C++ [dcl.typedef]p2:
2354     //   In a given non-class scope, a typedef specifier can be used to
2355     //   redefine the name of any type declared in that scope to refer
2356     //   to the type to which it already refers.
2357     if (!isa<CXXRecordDecl>(CurContext))
2358       return;
2359 
2360     // C++0x [dcl.typedef]p4:
2361     //   In a given class scope, a typedef specifier can be used to redefine
2362     //   any class-name declared in that scope that is not also a typedef-name
2363     //   to refer to the type to which it already refers.
2364     //
2365     // This wording came in via DR424, which was a correction to the
2366     // wording in DR56, which accidentally banned code like:
2367     //
2368     //   struct S {
2369     //     typedef struct A { } A;
2370     //   };
2371     //
2372     // in the C++03 standard. We implement the C++0x semantics, which
2373     // allow the above but disallow
2374     //
2375     //   struct S {
2376     //     typedef int I;
2377     //     typedef int I;
2378     //   };
2379     //
2380     // since that was the intent of DR56.
2381     if (!isa<TypedefNameDecl>(Old))
2382       return;
2383 
2384     Diag(New->getLocation(), diag::err_redefinition)
2385       << New->getDeclName();
2386     notePreviousDefinition(Old, New->getLocation());
2387     return New->setInvalidDecl();
2388   }
2389 
2390   // Modules always permit redefinition of typedefs, as does C11.
2391   if (getLangOpts().Modules || getLangOpts().C11)
2392     return;
2393 
2394   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2395   // is normally mapped to an error, but can be controlled with
2396   // -Wtypedef-redefinition.  If either the original or the redefinition is
2397   // in a system header, don't emit this for compatibility with GCC.
2398   if (getDiagnostics().getSuppressSystemWarnings() &&
2399       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2400       (Old->isImplicit() ||
2401        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2402        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2403     return;
2404 
2405   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2406     << New->getDeclName();
2407   notePreviousDefinition(Old, New->getLocation());
2408 }
2409 
2410 /// DeclhasAttr - returns true if decl Declaration already has the target
2411 /// attribute.
2412 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2413   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2414   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2415   for (const auto *i : D->attrs())
2416     if (i->getKind() == A->getKind()) {
2417       if (Ann) {
2418         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2419           return true;
2420         continue;
2421       }
2422       // FIXME: Don't hardcode this check
2423       if (OA && isa<OwnershipAttr>(i))
2424         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2425       return true;
2426     }
2427 
2428   return false;
2429 }
2430 
2431 static bool isAttributeTargetADefinition(Decl *D) {
2432   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2433     return VD->isThisDeclarationADefinition();
2434   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2435     return TD->isCompleteDefinition() || TD->isBeingDefined();
2436   return true;
2437 }
2438 
2439 /// Merge alignment attributes from \p Old to \p New, taking into account the
2440 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2441 ///
2442 /// \return \c true if any attributes were added to \p New.
2443 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2444   // Look for alignas attributes on Old, and pick out whichever attribute
2445   // specifies the strictest alignment requirement.
2446   AlignedAttr *OldAlignasAttr = nullptr;
2447   AlignedAttr *OldStrictestAlignAttr = nullptr;
2448   unsigned OldAlign = 0;
2449   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2450     // FIXME: We have no way of representing inherited dependent alignments
2451     // in a case like:
2452     //   template<int A, int B> struct alignas(A) X;
2453     //   template<int A, int B> struct alignas(B) X {};
2454     // For now, we just ignore any alignas attributes which are not on the
2455     // definition in such a case.
2456     if (I->isAlignmentDependent())
2457       return false;
2458 
2459     if (I->isAlignas())
2460       OldAlignasAttr = I;
2461 
2462     unsigned Align = I->getAlignment(S.Context);
2463     if (Align > OldAlign) {
2464       OldAlign = Align;
2465       OldStrictestAlignAttr = I;
2466     }
2467   }
2468 
2469   // Look for alignas attributes on New.
2470   AlignedAttr *NewAlignasAttr = nullptr;
2471   unsigned NewAlign = 0;
2472   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2473     if (I->isAlignmentDependent())
2474       return false;
2475 
2476     if (I->isAlignas())
2477       NewAlignasAttr = I;
2478 
2479     unsigned Align = I->getAlignment(S.Context);
2480     if (Align > NewAlign)
2481       NewAlign = Align;
2482   }
2483 
2484   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2485     // Both declarations have 'alignas' attributes. We require them to match.
2486     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2487     // fall short. (If two declarations both have alignas, they must both match
2488     // every definition, and so must match each other if there is a definition.)
2489 
2490     // If either declaration only contains 'alignas(0)' specifiers, then it
2491     // specifies the natural alignment for the type.
2492     if (OldAlign == 0 || NewAlign == 0) {
2493       QualType Ty;
2494       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2495         Ty = VD->getType();
2496       else
2497         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2498 
2499       if (OldAlign == 0)
2500         OldAlign = S.Context.getTypeAlign(Ty);
2501       if (NewAlign == 0)
2502         NewAlign = S.Context.getTypeAlign(Ty);
2503     }
2504 
2505     if (OldAlign != NewAlign) {
2506       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2507         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2508         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2509       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2510     }
2511   }
2512 
2513   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2514     // C++11 [dcl.align]p6:
2515     //   if any declaration of an entity has an alignment-specifier,
2516     //   every defining declaration of that entity shall specify an
2517     //   equivalent alignment.
2518     // C11 6.7.5/7:
2519     //   If the definition of an object does not have an alignment
2520     //   specifier, any other declaration of that object shall also
2521     //   have no alignment specifier.
2522     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2523       << OldAlignasAttr;
2524     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2525       << OldAlignasAttr;
2526   }
2527 
2528   bool AnyAdded = false;
2529 
2530   // Ensure we have an attribute representing the strictest alignment.
2531   if (OldAlign > NewAlign) {
2532     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2533     Clone->setInherited(true);
2534     New->addAttr(Clone);
2535     AnyAdded = true;
2536   }
2537 
2538   // Ensure we have an alignas attribute if the old declaration had one.
2539   if (OldAlignasAttr && !NewAlignasAttr &&
2540       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2541     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2542     Clone->setInherited(true);
2543     New->addAttr(Clone);
2544     AnyAdded = true;
2545   }
2546 
2547   return AnyAdded;
2548 }
2549 
2550 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2551                                const InheritableAttr *Attr,
2552                                Sema::AvailabilityMergeKind AMK) {
2553   // This function copies an attribute Attr from a previous declaration to the
2554   // new declaration D if the new declaration doesn't itself have that attribute
2555   // yet or if that attribute allows duplicates.
2556   // If you're adding a new attribute that requires logic different from
2557   // "use explicit attribute on decl if present, else use attribute from
2558   // previous decl", for example if the attribute needs to be consistent
2559   // between redeclarations, you need to call a custom merge function here.
2560   InheritableAttr *NewAttr = nullptr;
2561   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2562     NewAttr = S.mergeAvailabilityAttr(
2563         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2564         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2565         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2566         AA->getPriority());
2567   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2568     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2569   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2570     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2571   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2572     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2573   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2574     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2575   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2576     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2577                                 FA->getFirstArg());
2578   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2579     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2580   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2581     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2582   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2583     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2584                                        IA->getInheritanceModel());
2585   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2586     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2587                                       &S.Context.Idents.get(AA->getSpelling()));
2588   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2589            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2590             isa<CUDAGlobalAttr>(Attr))) {
2591     // CUDA target attributes are part of function signature for
2592     // overloading purposes and must not be merged.
2593     return false;
2594   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2595     NewAttr = S.mergeMinSizeAttr(D, *MA);
2596   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2597     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2598   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2599     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2600   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2601     NewAttr = S.mergeCommonAttr(D, *CommonA);
2602   else if (isa<AlignedAttr>(Attr))
2603     // AlignedAttrs are handled separately, because we need to handle all
2604     // such attributes on a declaration at the same time.
2605     NewAttr = nullptr;
2606   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2607            (AMK == Sema::AMK_Override ||
2608             AMK == Sema::AMK_ProtocolImplementation))
2609     NewAttr = nullptr;
2610   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2611     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2612   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2613     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2614   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2615     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2616   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2617     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2618   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2619     NewAttr = S.mergeImportNameAttr(D, *INA);
2620   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2621     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2622 
2623   if (NewAttr) {
2624     NewAttr->setInherited(true);
2625     D->addAttr(NewAttr);
2626     if (isa<MSInheritanceAttr>(NewAttr))
2627       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2628     return true;
2629   }
2630 
2631   return false;
2632 }
2633 
2634 static const NamedDecl *getDefinition(const Decl *D) {
2635   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2636     return TD->getDefinition();
2637   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2638     const VarDecl *Def = VD->getDefinition();
2639     if (Def)
2640       return Def;
2641     return VD->getActingDefinition();
2642   }
2643   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2644     return FD->getDefinition();
2645   return nullptr;
2646 }
2647 
2648 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2649   for (const auto *Attribute : D->attrs())
2650     if (Attribute->getKind() == Kind)
2651       return true;
2652   return false;
2653 }
2654 
2655 /// checkNewAttributesAfterDef - If we already have a definition, check that
2656 /// there are no new attributes in this declaration.
2657 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2658   if (!New->hasAttrs())
2659     return;
2660 
2661   const NamedDecl *Def = getDefinition(Old);
2662   if (!Def || Def == New)
2663     return;
2664 
2665   AttrVec &NewAttributes = New->getAttrs();
2666   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2667     const Attr *NewAttribute = NewAttributes[I];
2668 
2669     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2670       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2671         Sema::SkipBodyInfo SkipBody;
2672         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2673 
2674         // If we're skipping this definition, drop the "alias" attribute.
2675         if (SkipBody.ShouldSkip) {
2676           NewAttributes.erase(NewAttributes.begin() + I);
2677           --E;
2678           continue;
2679         }
2680       } else {
2681         VarDecl *VD = cast<VarDecl>(New);
2682         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2683                                 VarDecl::TentativeDefinition
2684                             ? diag::err_alias_after_tentative
2685                             : diag::err_redefinition;
2686         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2687         if (Diag == diag::err_redefinition)
2688           S.notePreviousDefinition(Def, VD->getLocation());
2689         else
2690           S.Diag(Def->getLocation(), diag::note_previous_definition);
2691         VD->setInvalidDecl();
2692       }
2693       ++I;
2694       continue;
2695     }
2696 
2697     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2698       // Tentative definitions are only interesting for the alias check above.
2699       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2700         ++I;
2701         continue;
2702       }
2703     }
2704 
2705     if (hasAttribute(Def, NewAttribute->getKind())) {
2706       ++I;
2707       continue; // regular attr merging will take care of validating this.
2708     }
2709 
2710     if (isa<C11NoReturnAttr>(NewAttribute)) {
2711       // C's _Noreturn is allowed to be added to a function after it is defined.
2712       ++I;
2713       continue;
2714     } else if (isa<UuidAttr>(NewAttribute)) {
2715       // msvc will allow a subsequent definition to add an uuid to a class
2716       ++I;
2717       continue;
2718     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2719       if (AA->isAlignas()) {
2720         // C++11 [dcl.align]p6:
2721         //   if any declaration of an entity has an alignment-specifier,
2722         //   every defining declaration of that entity shall specify an
2723         //   equivalent alignment.
2724         // C11 6.7.5/7:
2725         //   If the definition of an object does not have an alignment
2726         //   specifier, any other declaration of that object shall also
2727         //   have no alignment specifier.
2728         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2729           << AA;
2730         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2731           << AA;
2732         NewAttributes.erase(NewAttributes.begin() + I);
2733         --E;
2734         continue;
2735       }
2736     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2737       // If there is a C definition followed by a redeclaration with this
2738       // attribute then there are two different definitions. In C++, prefer the
2739       // standard diagnostics.
2740       if (!S.getLangOpts().CPlusPlus) {
2741         S.Diag(NewAttribute->getLocation(),
2742                diag::err_loader_uninitialized_redeclaration);
2743         S.Diag(Def->getLocation(), diag::note_previous_definition);
2744         NewAttributes.erase(NewAttributes.begin() + I);
2745         --E;
2746         continue;
2747       }
2748     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2749                cast<VarDecl>(New)->isInline() &&
2750                !cast<VarDecl>(New)->isInlineSpecified()) {
2751       // Don't warn about applying selectany to implicitly inline variables.
2752       // Older compilers and language modes would require the use of selectany
2753       // to make such variables inline, and it would have no effect if we
2754       // honored it.
2755       ++I;
2756       continue;
2757     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2758       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2759       // declarations after defintions.
2760       ++I;
2761       continue;
2762     }
2763 
2764     S.Diag(NewAttribute->getLocation(),
2765            diag::warn_attribute_precede_definition);
2766     S.Diag(Def->getLocation(), diag::note_previous_definition);
2767     NewAttributes.erase(NewAttributes.begin() + I);
2768     --E;
2769   }
2770 }
2771 
2772 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2773                                      const ConstInitAttr *CIAttr,
2774                                      bool AttrBeforeInit) {
2775   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2776 
2777   // Figure out a good way to write this specifier on the old declaration.
2778   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2779   // enough of the attribute list spelling information to extract that without
2780   // heroics.
2781   std::string SuitableSpelling;
2782   if (S.getLangOpts().CPlusPlus20)
2783     SuitableSpelling = std::string(
2784         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2785   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2786     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2787         InsertLoc, {tok::l_square, tok::l_square,
2788                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2789                     S.PP.getIdentifierInfo("require_constant_initialization"),
2790                     tok::r_square, tok::r_square}));
2791   if (SuitableSpelling.empty())
2792     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2793         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2794                     S.PP.getIdentifierInfo("require_constant_initialization"),
2795                     tok::r_paren, tok::r_paren}));
2796   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2797     SuitableSpelling = "constinit";
2798   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2799     SuitableSpelling = "[[clang::require_constant_initialization]]";
2800   if (SuitableSpelling.empty())
2801     SuitableSpelling = "__attribute__((require_constant_initialization))";
2802   SuitableSpelling += " ";
2803 
2804   if (AttrBeforeInit) {
2805     // extern constinit int a;
2806     // int a = 0; // error (missing 'constinit'), accepted as extension
2807     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2808     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2809         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2810     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2811   } else {
2812     // int a = 0;
2813     // constinit extern int a; // error (missing 'constinit')
2814     S.Diag(CIAttr->getLocation(),
2815            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2816                                  : diag::warn_require_const_init_added_too_late)
2817         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2818     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2819         << CIAttr->isConstinit()
2820         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2821   }
2822 }
2823 
2824 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2825 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2826                                AvailabilityMergeKind AMK) {
2827   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2828     UsedAttr *NewAttr = OldAttr->clone(Context);
2829     NewAttr->setInherited(true);
2830     New->addAttr(NewAttr);
2831   }
2832 
2833   if (!Old->hasAttrs() && !New->hasAttrs())
2834     return;
2835 
2836   // [dcl.constinit]p1:
2837   //   If the [constinit] specifier is applied to any declaration of a
2838   //   variable, it shall be applied to the initializing declaration.
2839   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2840   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2841   if (bool(OldConstInit) != bool(NewConstInit)) {
2842     const auto *OldVD = cast<VarDecl>(Old);
2843     auto *NewVD = cast<VarDecl>(New);
2844 
2845     // Find the initializing declaration. Note that we might not have linked
2846     // the new declaration into the redeclaration chain yet.
2847     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2848     if (!InitDecl &&
2849         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2850       InitDecl = NewVD;
2851 
2852     if (InitDecl == NewVD) {
2853       // This is the initializing declaration. If it would inherit 'constinit',
2854       // that's ill-formed. (Note that we do not apply this to the attribute
2855       // form).
2856       if (OldConstInit && OldConstInit->isConstinit())
2857         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2858                                  /*AttrBeforeInit=*/true);
2859     } else if (NewConstInit) {
2860       // This is the first time we've been told that this declaration should
2861       // have a constant initializer. If we already saw the initializing
2862       // declaration, this is too late.
2863       if (InitDecl && InitDecl != NewVD) {
2864         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2865                                  /*AttrBeforeInit=*/false);
2866         NewVD->dropAttr<ConstInitAttr>();
2867       }
2868     }
2869   }
2870 
2871   // Attributes declared post-definition are currently ignored.
2872   checkNewAttributesAfterDef(*this, New, Old);
2873 
2874   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2875     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2876       if (!OldA->isEquivalent(NewA)) {
2877         // This redeclaration changes __asm__ label.
2878         Diag(New->getLocation(), diag::err_different_asm_label);
2879         Diag(OldA->getLocation(), diag::note_previous_declaration);
2880       }
2881     } else if (Old->isUsed()) {
2882       // This redeclaration adds an __asm__ label to a declaration that has
2883       // already been ODR-used.
2884       Diag(New->getLocation(), diag::err_late_asm_label_name)
2885         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2886     }
2887   }
2888 
2889   // Re-declaration cannot add abi_tag's.
2890   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2891     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2892       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2893         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2894                       NewTag) == OldAbiTagAttr->tags_end()) {
2895           Diag(NewAbiTagAttr->getLocation(),
2896                diag::err_new_abi_tag_on_redeclaration)
2897               << NewTag;
2898           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2899         }
2900       }
2901     } else {
2902       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2903       Diag(Old->getLocation(), diag::note_previous_declaration);
2904     }
2905   }
2906 
2907   // This redeclaration adds a section attribute.
2908   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2909     if (auto *VD = dyn_cast<VarDecl>(New)) {
2910       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2911         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2912         Diag(Old->getLocation(), diag::note_previous_declaration);
2913       }
2914     }
2915   }
2916 
2917   // Redeclaration adds code-seg attribute.
2918   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2919   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2920       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2921     Diag(New->getLocation(), diag::warn_mismatched_section)
2922          << 0 /*codeseg*/;
2923     Diag(Old->getLocation(), diag::note_previous_declaration);
2924   }
2925 
2926   if (!Old->hasAttrs())
2927     return;
2928 
2929   bool foundAny = New->hasAttrs();
2930 
2931   // Ensure that any moving of objects within the allocated map is done before
2932   // we process them.
2933   if (!foundAny) New->setAttrs(AttrVec());
2934 
2935   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2936     // Ignore deprecated/unavailable/availability attributes if requested.
2937     AvailabilityMergeKind LocalAMK = AMK_None;
2938     if (isa<DeprecatedAttr>(I) ||
2939         isa<UnavailableAttr>(I) ||
2940         isa<AvailabilityAttr>(I)) {
2941       switch (AMK) {
2942       case AMK_None:
2943         continue;
2944 
2945       case AMK_Redeclaration:
2946       case AMK_Override:
2947       case AMK_ProtocolImplementation:
2948         LocalAMK = AMK;
2949         break;
2950       }
2951     }
2952 
2953     // Already handled.
2954     if (isa<UsedAttr>(I))
2955       continue;
2956 
2957     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2958       foundAny = true;
2959   }
2960 
2961   if (mergeAlignedAttrs(*this, New, Old))
2962     foundAny = true;
2963 
2964   if (!foundAny) New->dropAttrs();
2965 }
2966 
2967 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2968 /// to the new one.
2969 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2970                                      const ParmVarDecl *oldDecl,
2971                                      Sema &S) {
2972   // C++11 [dcl.attr.depend]p2:
2973   //   The first declaration of a function shall specify the
2974   //   carries_dependency attribute for its declarator-id if any declaration
2975   //   of the function specifies the carries_dependency attribute.
2976   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2977   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2978     S.Diag(CDA->getLocation(),
2979            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2980     // Find the first declaration of the parameter.
2981     // FIXME: Should we build redeclaration chains for function parameters?
2982     const FunctionDecl *FirstFD =
2983       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2984     const ParmVarDecl *FirstVD =
2985       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2986     S.Diag(FirstVD->getLocation(),
2987            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2988   }
2989 
2990   if (!oldDecl->hasAttrs())
2991     return;
2992 
2993   bool foundAny = newDecl->hasAttrs();
2994 
2995   // Ensure that any moving of objects within the allocated map is
2996   // done before we process them.
2997   if (!foundAny) newDecl->setAttrs(AttrVec());
2998 
2999   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3000     if (!DeclHasAttr(newDecl, I)) {
3001       InheritableAttr *newAttr =
3002         cast<InheritableParamAttr>(I->clone(S.Context));
3003       newAttr->setInherited(true);
3004       newDecl->addAttr(newAttr);
3005       foundAny = true;
3006     }
3007   }
3008 
3009   if (!foundAny) newDecl->dropAttrs();
3010 }
3011 
3012 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3013                                 const ParmVarDecl *OldParam,
3014                                 Sema &S) {
3015   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3016     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3017       if (*Oldnullability != *Newnullability) {
3018         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3019           << DiagNullabilityKind(
3020                *Newnullability,
3021                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3022                 != 0))
3023           << DiagNullabilityKind(
3024                *Oldnullability,
3025                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3026                 != 0));
3027         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3028       }
3029     } else {
3030       QualType NewT = NewParam->getType();
3031       NewT = S.Context.getAttributedType(
3032                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3033                          NewT, NewT);
3034       NewParam->setType(NewT);
3035     }
3036   }
3037 }
3038 
3039 namespace {
3040 
3041 /// Used in MergeFunctionDecl to keep track of function parameters in
3042 /// C.
3043 struct GNUCompatibleParamWarning {
3044   ParmVarDecl *OldParm;
3045   ParmVarDecl *NewParm;
3046   QualType PromotedType;
3047 };
3048 
3049 } // end anonymous namespace
3050 
3051 // Determine whether the previous declaration was a definition, implicit
3052 // declaration, or a declaration.
3053 template <typename T>
3054 static std::pair<diag::kind, SourceLocation>
3055 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3056   diag::kind PrevDiag;
3057   SourceLocation OldLocation = Old->getLocation();
3058   if (Old->isThisDeclarationADefinition())
3059     PrevDiag = diag::note_previous_definition;
3060   else if (Old->isImplicit()) {
3061     PrevDiag = diag::note_previous_implicit_declaration;
3062     if (OldLocation.isInvalid())
3063       OldLocation = New->getLocation();
3064   } else
3065     PrevDiag = diag::note_previous_declaration;
3066   return std::make_pair(PrevDiag, OldLocation);
3067 }
3068 
3069 /// canRedefineFunction - checks if a function can be redefined. Currently,
3070 /// only extern inline functions can be redefined, and even then only in
3071 /// GNU89 mode.
3072 static bool canRedefineFunction(const FunctionDecl *FD,
3073                                 const LangOptions& LangOpts) {
3074   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3075           !LangOpts.CPlusPlus &&
3076           FD->isInlineSpecified() &&
3077           FD->getStorageClass() == SC_Extern);
3078 }
3079 
3080 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3081   const AttributedType *AT = T->getAs<AttributedType>();
3082   while (AT && !AT->isCallingConv())
3083     AT = AT->getModifiedType()->getAs<AttributedType>();
3084   return AT;
3085 }
3086 
3087 template <typename T>
3088 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3089   const DeclContext *DC = Old->getDeclContext();
3090   if (DC->isRecord())
3091     return false;
3092 
3093   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3094   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3095     return true;
3096   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3097     return true;
3098   return false;
3099 }
3100 
3101 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3102 static bool isExternC(VarTemplateDecl *) { return false; }
3103 
3104 /// Check whether a redeclaration of an entity introduced by a
3105 /// using-declaration is valid, given that we know it's not an overload
3106 /// (nor a hidden tag declaration).
3107 template<typename ExpectedDecl>
3108 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3109                                    ExpectedDecl *New) {
3110   // C++11 [basic.scope.declarative]p4:
3111   //   Given a set of declarations in a single declarative region, each of
3112   //   which specifies the same unqualified name,
3113   //   -- they shall all refer to the same entity, or all refer to functions
3114   //      and function templates; or
3115   //   -- exactly one declaration shall declare a class name or enumeration
3116   //      name that is not a typedef name and the other declarations shall all
3117   //      refer to the same variable or enumerator, or all refer to functions
3118   //      and function templates; in this case the class name or enumeration
3119   //      name is hidden (3.3.10).
3120 
3121   // C++11 [namespace.udecl]p14:
3122   //   If a function declaration in namespace scope or block scope has the
3123   //   same name and the same parameter-type-list as a function introduced
3124   //   by a using-declaration, and the declarations do not declare the same
3125   //   function, the program is ill-formed.
3126 
3127   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3128   if (Old &&
3129       !Old->getDeclContext()->getRedeclContext()->Equals(
3130           New->getDeclContext()->getRedeclContext()) &&
3131       !(isExternC(Old) && isExternC(New)))
3132     Old = nullptr;
3133 
3134   if (!Old) {
3135     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3136     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3137     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3138     return true;
3139   }
3140   return false;
3141 }
3142 
3143 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3144                                             const FunctionDecl *B) {
3145   assert(A->getNumParams() == B->getNumParams());
3146 
3147   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3148     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3149     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3150     if (AttrA == AttrB)
3151       return true;
3152     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3153            AttrA->isDynamic() == AttrB->isDynamic();
3154   };
3155 
3156   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3157 }
3158 
3159 /// If necessary, adjust the semantic declaration context for a qualified
3160 /// declaration to name the correct inline namespace within the qualifier.
3161 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3162                                                DeclaratorDecl *OldD) {
3163   // The only case where we need to update the DeclContext is when
3164   // redeclaration lookup for a qualified name finds a declaration
3165   // in an inline namespace within the context named by the qualifier:
3166   //
3167   //   inline namespace N { int f(); }
3168   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3169   //
3170   // For unqualified declarations, the semantic context *can* change
3171   // along the redeclaration chain (for local extern declarations,
3172   // extern "C" declarations, and friend declarations in particular).
3173   if (!NewD->getQualifier())
3174     return;
3175 
3176   // NewD is probably already in the right context.
3177   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3178   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3179   if (NamedDC->Equals(SemaDC))
3180     return;
3181 
3182   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3183           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3184          "unexpected context for redeclaration");
3185 
3186   auto *LexDC = NewD->getLexicalDeclContext();
3187   auto FixSemaDC = [=](NamedDecl *D) {
3188     if (!D)
3189       return;
3190     D->setDeclContext(SemaDC);
3191     D->setLexicalDeclContext(LexDC);
3192   };
3193 
3194   FixSemaDC(NewD);
3195   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3196     FixSemaDC(FD->getDescribedFunctionTemplate());
3197   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3198     FixSemaDC(VD->getDescribedVarTemplate());
3199 }
3200 
3201 /// MergeFunctionDecl - We just parsed a function 'New' from
3202 /// declarator D which has the same name and scope as a previous
3203 /// declaration 'Old'.  Figure out how to resolve this situation,
3204 /// merging decls or emitting diagnostics as appropriate.
3205 ///
3206 /// In C++, New and Old must be declarations that are not
3207 /// overloaded. Use IsOverload to determine whether New and Old are
3208 /// overloaded, and to select the Old declaration that New should be
3209 /// merged with.
3210 ///
3211 /// Returns true if there was an error, false otherwise.
3212 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3213                              Scope *S, bool MergeTypeWithOld) {
3214   // Verify the old decl was also a function.
3215   FunctionDecl *Old = OldD->getAsFunction();
3216   if (!Old) {
3217     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3218       if (New->getFriendObjectKind()) {
3219         Diag(New->getLocation(), diag::err_using_decl_friend);
3220         Diag(Shadow->getTargetDecl()->getLocation(),
3221              diag::note_using_decl_target);
3222         Diag(Shadow->getUsingDecl()->getLocation(),
3223              diag::note_using_decl) << 0;
3224         return true;
3225       }
3226 
3227       // Check whether the two declarations might declare the same function.
3228       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3229         return true;
3230       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3231     } else {
3232       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3233         << New->getDeclName();
3234       notePreviousDefinition(OldD, New->getLocation());
3235       return true;
3236     }
3237   }
3238 
3239   // If the old declaration is invalid, just give up here.
3240   if (Old->isInvalidDecl())
3241     return true;
3242 
3243   // Disallow redeclaration of some builtins.
3244   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3245     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3246     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3247         << Old << Old->getType();
3248     return true;
3249   }
3250 
3251   diag::kind PrevDiag;
3252   SourceLocation OldLocation;
3253   std::tie(PrevDiag, OldLocation) =
3254       getNoteDiagForInvalidRedeclaration(Old, New);
3255 
3256   // Don't complain about this if we're in GNU89 mode and the old function
3257   // is an extern inline function.
3258   // Don't complain about specializations. They are not supposed to have
3259   // storage classes.
3260   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3261       New->getStorageClass() == SC_Static &&
3262       Old->hasExternalFormalLinkage() &&
3263       !New->getTemplateSpecializationInfo() &&
3264       !canRedefineFunction(Old, getLangOpts())) {
3265     if (getLangOpts().MicrosoftExt) {
3266       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3267       Diag(OldLocation, PrevDiag);
3268     } else {
3269       Diag(New->getLocation(), diag::err_static_non_static) << New;
3270       Diag(OldLocation, PrevDiag);
3271       return true;
3272     }
3273   }
3274 
3275   if (New->hasAttr<InternalLinkageAttr>() &&
3276       !Old->hasAttr<InternalLinkageAttr>()) {
3277     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3278         << New->getDeclName();
3279     notePreviousDefinition(Old, New->getLocation());
3280     New->dropAttr<InternalLinkageAttr>();
3281   }
3282 
3283   if (CheckRedeclarationModuleOwnership(New, Old))
3284     return true;
3285 
3286   if (!getLangOpts().CPlusPlus) {
3287     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3288     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3289       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3290         << New << OldOvl;
3291 
3292       // Try our best to find a decl that actually has the overloadable
3293       // attribute for the note. In most cases (e.g. programs with only one
3294       // broken declaration/definition), this won't matter.
3295       //
3296       // FIXME: We could do this if we juggled some extra state in
3297       // OverloadableAttr, rather than just removing it.
3298       const Decl *DiagOld = Old;
3299       if (OldOvl) {
3300         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3301           const auto *A = D->getAttr<OverloadableAttr>();
3302           return A && !A->isImplicit();
3303         });
3304         // If we've implicitly added *all* of the overloadable attrs to this
3305         // chain, emitting a "previous redecl" note is pointless.
3306         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3307       }
3308 
3309       if (DiagOld)
3310         Diag(DiagOld->getLocation(),
3311              diag::note_attribute_overloadable_prev_overload)
3312           << OldOvl;
3313 
3314       if (OldOvl)
3315         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3316       else
3317         New->dropAttr<OverloadableAttr>();
3318     }
3319   }
3320 
3321   // If a function is first declared with a calling convention, but is later
3322   // declared or defined without one, all following decls assume the calling
3323   // convention of the first.
3324   //
3325   // It's OK if a function is first declared without a calling convention,
3326   // but is later declared or defined with the default calling convention.
3327   //
3328   // To test if either decl has an explicit calling convention, we look for
3329   // AttributedType sugar nodes on the type as written.  If they are missing or
3330   // were canonicalized away, we assume the calling convention was implicit.
3331   //
3332   // Note also that we DO NOT return at this point, because we still have
3333   // other tests to run.
3334   QualType OldQType = Context.getCanonicalType(Old->getType());
3335   QualType NewQType = Context.getCanonicalType(New->getType());
3336   const FunctionType *OldType = cast<FunctionType>(OldQType);
3337   const FunctionType *NewType = cast<FunctionType>(NewQType);
3338   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3339   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3340   bool RequiresAdjustment = false;
3341 
3342   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3343     FunctionDecl *First = Old->getFirstDecl();
3344     const FunctionType *FT =
3345         First->getType().getCanonicalType()->castAs<FunctionType>();
3346     FunctionType::ExtInfo FI = FT->getExtInfo();
3347     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3348     if (!NewCCExplicit) {
3349       // Inherit the CC from the previous declaration if it was specified
3350       // there but not here.
3351       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3352       RequiresAdjustment = true;
3353     } else if (Old->getBuiltinID()) {
3354       // Builtin attribute isn't propagated to the new one yet at this point,
3355       // so we check if the old one is a builtin.
3356 
3357       // Calling Conventions on a Builtin aren't really useful and setting a
3358       // default calling convention and cdecl'ing some builtin redeclarations is
3359       // common, so warn and ignore the calling convention on the redeclaration.
3360       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3361           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3362           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3363       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3364       RequiresAdjustment = true;
3365     } else {
3366       // Calling conventions aren't compatible, so complain.
3367       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3368       Diag(New->getLocation(), diag::err_cconv_change)
3369         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3370         << !FirstCCExplicit
3371         << (!FirstCCExplicit ? "" :
3372             FunctionType::getNameForCallConv(FI.getCC()));
3373 
3374       // Put the note on the first decl, since it is the one that matters.
3375       Diag(First->getLocation(), diag::note_previous_declaration);
3376       return true;
3377     }
3378   }
3379 
3380   // FIXME: diagnose the other way around?
3381   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3382     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3383     RequiresAdjustment = true;
3384   }
3385 
3386   // Merge regparm attribute.
3387   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3388       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3389     if (NewTypeInfo.getHasRegParm()) {
3390       Diag(New->getLocation(), diag::err_regparm_mismatch)
3391         << NewType->getRegParmType()
3392         << OldType->getRegParmType();
3393       Diag(OldLocation, diag::note_previous_declaration);
3394       return true;
3395     }
3396 
3397     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3398     RequiresAdjustment = true;
3399   }
3400 
3401   // Merge ns_returns_retained attribute.
3402   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3403     if (NewTypeInfo.getProducesResult()) {
3404       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3405           << "'ns_returns_retained'";
3406       Diag(OldLocation, diag::note_previous_declaration);
3407       return true;
3408     }
3409 
3410     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3411     RequiresAdjustment = true;
3412   }
3413 
3414   if (OldTypeInfo.getNoCallerSavedRegs() !=
3415       NewTypeInfo.getNoCallerSavedRegs()) {
3416     if (NewTypeInfo.getNoCallerSavedRegs()) {
3417       AnyX86NoCallerSavedRegistersAttr *Attr =
3418         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3419       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3420       Diag(OldLocation, diag::note_previous_declaration);
3421       return true;
3422     }
3423 
3424     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3425     RequiresAdjustment = true;
3426   }
3427 
3428   if (RequiresAdjustment) {
3429     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3430     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3431     New->setType(QualType(AdjustedType, 0));
3432     NewQType = Context.getCanonicalType(New->getType());
3433   }
3434 
3435   // If this redeclaration makes the function inline, we may need to add it to
3436   // UndefinedButUsed.
3437   if (!Old->isInlined() && New->isInlined() &&
3438       !New->hasAttr<GNUInlineAttr>() &&
3439       !getLangOpts().GNUInline &&
3440       Old->isUsed(false) &&
3441       !Old->isDefined() && !New->isThisDeclarationADefinition())
3442     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3443                                            SourceLocation()));
3444 
3445   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3446   // about it.
3447   if (New->hasAttr<GNUInlineAttr>() &&
3448       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3449     UndefinedButUsed.erase(Old->getCanonicalDecl());
3450   }
3451 
3452   // If pass_object_size params don't match up perfectly, this isn't a valid
3453   // redeclaration.
3454   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3455       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3456     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3457         << New->getDeclName();
3458     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3459     return true;
3460   }
3461 
3462   if (getLangOpts().CPlusPlus) {
3463     // C++1z [over.load]p2
3464     //   Certain function declarations cannot be overloaded:
3465     //     -- Function declarations that differ only in the return type,
3466     //        the exception specification, or both cannot be overloaded.
3467 
3468     // Check the exception specifications match. This may recompute the type of
3469     // both Old and New if it resolved exception specifications, so grab the
3470     // types again after this. Because this updates the type, we do this before
3471     // any of the other checks below, which may update the "de facto" NewQType
3472     // but do not necessarily update the type of New.
3473     if (CheckEquivalentExceptionSpec(Old, New))
3474       return true;
3475     OldQType = Context.getCanonicalType(Old->getType());
3476     NewQType = Context.getCanonicalType(New->getType());
3477 
3478     // Go back to the type source info to compare the declared return types,
3479     // per C++1y [dcl.type.auto]p13:
3480     //   Redeclarations or specializations of a function or function template
3481     //   with a declared return type that uses a placeholder type shall also
3482     //   use that placeholder, not a deduced type.
3483     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3484     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3485     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3486         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3487                                        OldDeclaredReturnType)) {
3488       QualType ResQT;
3489       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3490           OldDeclaredReturnType->isObjCObjectPointerType())
3491         // FIXME: This does the wrong thing for a deduced return type.
3492         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3493       if (ResQT.isNull()) {
3494         if (New->isCXXClassMember() && New->isOutOfLine())
3495           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3496               << New << New->getReturnTypeSourceRange();
3497         else
3498           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3499               << New->getReturnTypeSourceRange();
3500         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3501                                     << Old->getReturnTypeSourceRange();
3502         return true;
3503       }
3504       else
3505         NewQType = ResQT;
3506     }
3507 
3508     QualType OldReturnType = OldType->getReturnType();
3509     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3510     if (OldReturnType != NewReturnType) {
3511       // If this function has a deduced return type and has already been
3512       // defined, copy the deduced value from the old declaration.
3513       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3514       if (OldAT && OldAT->isDeduced()) {
3515         New->setType(
3516             SubstAutoType(New->getType(),
3517                           OldAT->isDependentType() ? Context.DependentTy
3518                                                    : OldAT->getDeducedType()));
3519         NewQType = Context.getCanonicalType(
3520             SubstAutoType(NewQType,
3521                           OldAT->isDependentType() ? Context.DependentTy
3522                                                    : OldAT->getDeducedType()));
3523       }
3524     }
3525 
3526     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3527     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3528     if (OldMethod && NewMethod) {
3529       // Preserve triviality.
3530       NewMethod->setTrivial(OldMethod->isTrivial());
3531 
3532       // MSVC allows explicit template specialization at class scope:
3533       // 2 CXXMethodDecls referring to the same function will be injected.
3534       // We don't want a redeclaration error.
3535       bool IsClassScopeExplicitSpecialization =
3536                               OldMethod->isFunctionTemplateSpecialization() &&
3537                               NewMethod->isFunctionTemplateSpecialization();
3538       bool isFriend = NewMethod->getFriendObjectKind();
3539 
3540       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3541           !IsClassScopeExplicitSpecialization) {
3542         //    -- Member function declarations with the same name and the
3543         //       same parameter types cannot be overloaded if any of them
3544         //       is a static member function declaration.
3545         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3546           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3547           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3548           return true;
3549         }
3550 
3551         // C++ [class.mem]p1:
3552         //   [...] A member shall not be declared twice in the
3553         //   member-specification, except that a nested class or member
3554         //   class template can be declared and then later defined.
3555         if (!inTemplateInstantiation()) {
3556           unsigned NewDiag;
3557           if (isa<CXXConstructorDecl>(OldMethod))
3558             NewDiag = diag::err_constructor_redeclared;
3559           else if (isa<CXXDestructorDecl>(NewMethod))
3560             NewDiag = diag::err_destructor_redeclared;
3561           else if (isa<CXXConversionDecl>(NewMethod))
3562             NewDiag = diag::err_conv_function_redeclared;
3563           else
3564             NewDiag = diag::err_member_redeclared;
3565 
3566           Diag(New->getLocation(), NewDiag);
3567         } else {
3568           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3569             << New << New->getType();
3570         }
3571         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3572         return true;
3573 
3574       // Complain if this is an explicit declaration of a special
3575       // member that was initially declared implicitly.
3576       //
3577       // As an exception, it's okay to befriend such methods in order
3578       // to permit the implicit constructor/destructor/operator calls.
3579       } else if (OldMethod->isImplicit()) {
3580         if (isFriend) {
3581           NewMethod->setImplicit();
3582         } else {
3583           Diag(NewMethod->getLocation(),
3584                diag::err_definition_of_implicitly_declared_member)
3585             << New << getSpecialMember(OldMethod);
3586           return true;
3587         }
3588       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3589         Diag(NewMethod->getLocation(),
3590              diag::err_definition_of_explicitly_defaulted_member)
3591           << getSpecialMember(OldMethod);
3592         return true;
3593       }
3594     }
3595 
3596     // C++11 [dcl.attr.noreturn]p1:
3597     //   The first declaration of a function shall specify the noreturn
3598     //   attribute if any declaration of that function specifies the noreturn
3599     //   attribute.
3600     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3601     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3602       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3603       Diag(Old->getFirstDecl()->getLocation(),
3604            diag::note_noreturn_missing_first_decl);
3605     }
3606 
3607     // C++11 [dcl.attr.depend]p2:
3608     //   The first declaration of a function shall specify the
3609     //   carries_dependency attribute for its declarator-id if any declaration
3610     //   of the function specifies the carries_dependency attribute.
3611     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3612     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3613       Diag(CDA->getLocation(),
3614            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3615       Diag(Old->getFirstDecl()->getLocation(),
3616            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3617     }
3618 
3619     // (C++98 8.3.5p3):
3620     //   All declarations for a function shall agree exactly in both the
3621     //   return type and the parameter-type-list.
3622     // We also want to respect all the extended bits except noreturn.
3623 
3624     // noreturn should now match unless the old type info didn't have it.
3625     QualType OldQTypeForComparison = OldQType;
3626     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3627       auto *OldType = OldQType->castAs<FunctionProtoType>();
3628       const FunctionType *OldTypeForComparison
3629         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3630       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3631       assert(OldQTypeForComparison.isCanonical());
3632     }
3633 
3634     if (haveIncompatibleLanguageLinkages(Old, New)) {
3635       // As a special case, retain the language linkage from previous
3636       // declarations of a friend function as an extension.
3637       //
3638       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3639       // and is useful because there's otherwise no way to specify language
3640       // linkage within class scope.
3641       //
3642       // Check cautiously as the friend object kind isn't yet complete.
3643       if (New->getFriendObjectKind() != Decl::FOK_None) {
3644         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3645         Diag(OldLocation, PrevDiag);
3646       } else {
3647         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3648         Diag(OldLocation, PrevDiag);
3649         return true;
3650       }
3651     }
3652 
3653     // If the function types are compatible, merge the declarations. Ignore the
3654     // exception specifier because it was already checked above in
3655     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3656     // about incompatible types under -fms-compatibility.
3657     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3658                                                          NewQType))
3659       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3660 
3661     // If the types are imprecise (due to dependent constructs in friends or
3662     // local extern declarations), it's OK if they differ. We'll check again
3663     // during instantiation.
3664     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3665       return false;
3666 
3667     // Fall through for conflicting redeclarations and redefinitions.
3668   }
3669 
3670   // C: Function types need to be compatible, not identical. This handles
3671   // duplicate function decls like "void f(int); void f(enum X);" properly.
3672   if (!getLangOpts().CPlusPlus &&
3673       Context.typesAreCompatible(OldQType, NewQType)) {
3674     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3675     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3676     const FunctionProtoType *OldProto = nullptr;
3677     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3678         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3679       // The old declaration provided a function prototype, but the
3680       // new declaration does not. Merge in the prototype.
3681       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3682       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3683       NewQType =
3684           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3685                                   OldProto->getExtProtoInfo());
3686       New->setType(NewQType);
3687       New->setHasInheritedPrototype();
3688 
3689       // Synthesize parameters with the same types.
3690       SmallVector<ParmVarDecl*, 16> Params;
3691       for (const auto &ParamType : OldProto->param_types()) {
3692         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3693                                                  SourceLocation(), nullptr,
3694                                                  ParamType, /*TInfo=*/nullptr,
3695                                                  SC_None, nullptr);
3696         Param->setScopeInfo(0, Params.size());
3697         Param->setImplicit();
3698         Params.push_back(Param);
3699       }
3700 
3701       New->setParams(Params);
3702     }
3703 
3704     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3705   }
3706 
3707   // Check if the function types are compatible when pointer size address
3708   // spaces are ignored.
3709   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3710     return false;
3711 
3712   // GNU C permits a K&R definition to follow a prototype declaration
3713   // if the declared types of the parameters in the K&R definition
3714   // match the types in the prototype declaration, even when the
3715   // promoted types of the parameters from the K&R definition differ
3716   // from the types in the prototype. GCC then keeps the types from
3717   // the prototype.
3718   //
3719   // If a variadic prototype is followed by a non-variadic K&R definition,
3720   // the K&R definition becomes variadic.  This is sort of an edge case, but
3721   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3722   // C99 6.9.1p8.
3723   if (!getLangOpts().CPlusPlus &&
3724       Old->hasPrototype() && !New->hasPrototype() &&
3725       New->getType()->getAs<FunctionProtoType>() &&
3726       Old->getNumParams() == New->getNumParams()) {
3727     SmallVector<QualType, 16> ArgTypes;
3728     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3729     const FunctionProtoType *OldProto
3730       = Old->getType()->getAs<FunctionProtoType>();
3731     const FunctionProtoType *NewProto
3732       = New->getType()->getAs<FunctionProtoType>();
3733 
3734     // Determine whether this is the GNU C extension.
3735     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3736                                                NewProto->getReturnType());
3737     bool LooseCompatible = !MergedReturn.isNull();
3738     for (unsigned Idx = 0, End = Old->getNumParams();
3739          LooseCompatible && Idx != End; ++Idx) {
3740       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3741       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3742       if (Context.typesAreCompatible(OldParm->getType(),
3743                                      NewProto->getParamType(Idx))) {
3744         ArgTypes.push_back(NewParm->getType());
3745       } else if (Context.typesAreCompatible(OldParm->getType(),
3746                                             NewParm->getType(),
3747                                             /*CompareUnqualified=*/true)) {
3748         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3749                                            NewProto->getParamType(Idx) };
3750         Warnings.push_back(Warn);
3751         ArgTypes.push_back(NewParm->getType());
3752       } else
3753         LooseCompatible = false;
3754     }
3755 
3756     if (LooseCompatible) {
3757       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3758         Diag(Warnings[Warn].NewParm->getLocation(),
3759              diag::ext_param_promoted_not_compatible_with_prototype)
3760           << Warnings[Warn].PromotedType
3761           << Warnings[Warn].OldParm->getType();
3762         if (Warnings[Warn].OldParm->getLocation().isValid())
3763           Diag(Warnings[Warn].OldParm->getLocation(),
3764                diag::note_previous_declaration);
3765       }
3766 
3767       if (MergeTypeWithOld)
3768         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3769                                              OldProto->getExtProtoInfo()));
3770       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3771     }
3772 
3773     // Fall through to diagnose conflicting types.
3774   }
3775 
3776   // A function that has already been declared has been redeclared or
3777   // defined with a different type; show an appropriate diagnostic.
3778 
3779   // If the previous declaration was an implicitly-generated builtin
3780   // declaration, then at the very least we should use a specialized note.
3781   unsigned BuiltinID;
3782   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3783     // If it's actually a library-defined builtin function like 'malloc'
3784     // or 'printf', just warn about the incompatible redeclaration.
3785     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3786       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3787       Diag(OldLocation, diag::note_previous_builtin_declaration)
3788         << Old << Old->getType();
3789       return false;
3790     }
3791 
3792     PrevDiag = diag::note_previous_builtin_declaration;
3793   }
3794 
3795   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3796   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3797   return true;
3798 }
3799 
3800 /// Completes the merge of two function declarations that are
3801 /// known to be compatible.
3802 ///
3803 /// This routine handles the merging of attributes and other
3804 /// properties of function declarations from the old declaration to
3805 /// the new declaration, once we know that New is in fact a
3806 /// redeclaration of Old.
3807 ///
3808 /// \returns false
3809 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3810                                         Scope *S, bool MergeTypeWithOld) {
3811   // Merge the attributes
3812   mergeDeclAttributes(New, Old);
3813 
3814   // Merge "pure" flag.
3815   if (Old->isPure())
3816     New->setPure();
3817 
3818   // Merge "used" flag.
3819   if (Old->getMostRecentDecl()->isUsed(false))
3820     New->setIsUsed();
3821 
3822   // Merge attributes from the parameters.  These can mismatch with K&R
3823   // declarations.
3824   if (New->getNumParams() == Old->getNumParams())
3825       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3826         ParmVarDecl *NewParam = New->getParamDecl(i);
3827         ParmVarDecl *OldParam = Old->getParamDecl(i);
3828         mergeParamDeclAttributes(NewParam, OldParam, *this);
3829         mergeParamDeclTypes(NewParam, OldParam, *this);
3830       }
3831 
3832   if (getLangOpts().CPlusPlus)
3833     return MergeCXXFunctionDecl(New, Old, S);
3834 
3835   // Merge the function types so the we get the composite types for the return
3836   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3837   // was visible.
3838   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3839   if (!Merged.isNull() && MergeTypeWithOld)
3840     New->setType(Merged);
3841 
3842   return false;
3843 }
3844 
3845 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3846                                 ObjCMethodDecl *oldMethod) {
3847   // Merge the attributes, including deprecated/unavailable
3848   AvailabilityMergeKind MergeKind =
3849     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3850       ? AMK_ProtocolImplementation
3851       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3852                                                        : AMK_Override;
3853 
3854   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3855 
3856   // Merge attributes from the parameters.
3857   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3858                                        oe = oldMethod->param_end();
3859   for (ObjCMethodDecl::param_iterator
3860          ni = newMethod->param_begin(), ne = newMethod->param_end();
3861        ni != ne && oi != oe; ++ni, ++oi)
3862     mergeParamDeclAttributes(*ni, *oi, *this);
3863 
3864   CheckObjCMethodOverride(newMethod, oldMethod);
3865 }
3866 
3867 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3868   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3869 
3870   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3871          ? diag::err_redefinition_different_type
3872          : diag::err_redeclaration_different_type)
3873     << New->getDeclName() << New->getType() << Old->getType();
3874 
3875   diag::kind PrevDiag;
3876   SourceLocation OldLocation;
3877   std::tie(PrevDiag, OldLocation)
3878     = getNoteDiagForInvalidRedeclaration(Old, New);
3879   S.Diag(OldLocation, PrevDiag);
3880   New->setInvalidDecl();
3881 }
3882 
3883 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3884 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3885 /// emitting diagnostics as appropriate.
3886 ///
3887 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3888 /// to here in AddInitializerToDecl. We can't check them before the initializer
3889 /// is attached.
3890 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3891                              bool MergeTypeWithOld) {
3892   if (New->isInvalidDecl() || Old->isInvalidDecl())
3893     return;
3894 
3895   QualType MergedT;
3896   if (getLangOpts().CPlusPlus) {
3897     if (New->getType()->isUndeducedType()) {
3898       // We don't know what the new type is until the initializer is attached.
3899       return;
3900     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3901       // These could still be something that needs exception specs checked.
3902       return MergeVarDeclExceptionSpecs(New, Old);
3903     }
3904     // C++ [basic.link]p10:
3905     //   [...] the types specified by all declarations referring to a given
3906     //   object or function shall be identical, except that declarations for an
3907     //   array object can specify array types that differ by the presence or
3908     //   absence of a major array bound (8.3.4).
3909     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3910       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3911       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3912 
3913       // We are merging a variable declaration New into Old. If it has an array
3914       // bound, and that bound differs from Old's bound, we should diagnose the
3915       // mismatch.
3916       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3917         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3918              PrevVD = PrevVD->getPreviousDecl()) {
3919           QualType PrevVDTy = PrevVD->getType();
3920           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3921             continue;
3922 
3923           if (!Context.hasSameType(New->getType(), PrevVDTy))
3924             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3925         }
3926       }
3927 
3928       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3929         if (Context.hasSameType(OldArray->getElementType(),
3930                                 NewArray->getElementType()))
3931           MergedT = New->getType();
3932       }
3933       // FIXME: Check visibility. New is hidden but has a complete type. If New
3934       // has no array bound, it should not inherit one from Old, if Old is not
3935       // visible.
3936       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3937         if (Context.hasSameType(OldArray->getElementType(),
3938                                 NewArray->getElementType()))
3939           MergedT = Old->getType();
3940       }
3941     }
3942     else if (New->getType()->isObjCObjectPointerType() &&
3943                Old->getType()->isObjCObjectPointerType()) {
3944       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3945                                               Old->getType());
3946     }
3947   } else {
3948     // C 6.2.7p2:
3949     //   All declarations that refer to the same object or function shall have
3950     //   compatible type.
3951     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3952   }
3953   if (MergedT.isNull()) {
3954     // It's OK if we couldn't merge types if either type is dependent, for a
3955     // block-scope variable. In other cases (static data members of class
3956     // templates, variable templates, ...), we require the types to be
3957     // equivalent.
3958     // FIXME: The C++ standard doesn't say anything about this.
3959     if ((New->getType()->isDependentType() ||
3960          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3961       // If the old type was dependent, we can't merge with it, so the new type
3962       // becomes dependent for now. We'll reproduce the original type when we
3963       // instantiate the TypeSourceInfo for the variable.
3964       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3965         New->setType(Context.DependentTy);
3966       return;
3967     }
3968     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3969   }
3970 
3971   // Don't actually update the type on the new declaration if the old
3972   // declaration was an extern declaration in a different scope.
3973   if (MergeTypeWithOld)
3974     New->setType(MergedT);
3975 }
3976 
3977 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3978                                   LookupResult &Previous) {
3979   // C11 6.2.7p4:
3980   //   For an identifier with internal or external linkage declared
3981   //   in a scope in which a prior declaration of that identifier is
3982   //   visible, if the prior declaration specifies internal or
3983   //   external linkage, the type of the identifier at the later
3984   //   declaration becomes the composite type.
3985   //
3986   // If the variable isn't visible, we do not merge with its type.
3987   if (Previous.isShadowed())
3988     return false;
3989 
3990   if (S.getLangOpts().CPlusPlus) {
3991     // C++11 [dcl.array]p3:
3992     //   If there is a preceding declaration of the entity in the same
3993     //   scope in which the bound was specified, an omitted array bound
3994     //   is taken to be the same as in that earlier declaration.
3995     return NewVD->isPreviousDeclInSameBlockScope() ||
3996            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3997             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3998   } else {
3999     // If the old declaration was function-local, don't merge with its
4000     // type unless we're in the same function.
4001     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4002            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4003   }
4004 }
4005 
4006 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4007 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4008 /// situation, merging decls or emitting diagnostics as appropriate.
4009 ///
4010 /// Tentative definition rules (C99 6.9.2p2) are checked by
4011 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4012 /// definitions here, since the initializer hasn't been attached.
4013 ///
4014 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4015   // If the new decl is already invalid, don't do any other checking.
4016   if (New->isInvalidDecl())
4017     return;
4018 
4019   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4020     return;
4021 
4022   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4023 
4024   // Verify the old decl was also a variable or variable template.
4025   VarDecl *Old = nullptr;
4026   VarTemplateDecl *OldTemplate = nullptr;
4027   if (Previous.isSingleResult()) {
4028     if (NewTemplate) {
4029       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4030       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4031 
4032       if (auto *Shadow =
4033               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4034         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4035           return New->setInvalidDecl();
4036     } else {
4037       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4038 
4039       if (auto *Shadow =
4040               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4041         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4042           return New->setInvalidDecl();
4043     }
4044   }
4045   if (!Old) {
4046     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4047         << New->getDeclName();
4048     notePreviousDefinition(Previous.getRepresentativeDecl(),
4049                            New->getLocation());
4050     return New->setInvalidDecl();
4051   }
4052 
4053   // Ensure the template parameters are compatible.
4054   if (NewTemplate &&
4055       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4056                                       OldTemplate->getTemplateParameters(),
4057                                       /*Complain=*/true, TPL_TemplateMatch))
4058     return New->setInvalidDecl();
4059 
4060   // C++ [class.mem]p1:
4061   //   A member shall not be declared twice in the member-specification [...]
4062   //
4063   // Here, we need only consider static data members.
4064   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4065     Diag(New->getLocation(), diag::err_duplicate_member)
4066       << New->getIdentifier();
4067     Diag(Old->getLocation(), diag::note_previous_declaration);
4068     New->setInvalidDecl();
4069   }
4070 
4071   mergeDeclAttributes(New, Old);
4072   // Warn if an already-declared variable is made a weak_import in a subsequent
4073   // declaration
4074   if (New->hasAttr<WeakImportAttr>() &&
4075       Old->getStorageClass() == SC_None &&
4076       !Old->hasAttr<WeakImportAttr>()) {
4077     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4078     notePreviousDefinition(Old, New->getLocation());
4079     // Remove weak_import attribute on new declaration.
4080     New->dropAttr<WeakImportAttr>();
4081   }
4082 
4083   if (New->hasAttr<InternalLinkageAttr>() &&
4084       !Old->hasAttr<InternalLinkageAttr>()) {
4085     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4086         << New->getDeclName();
4087     notePreviousDefinition(Old, New->getLocation());
4088     New->dropAttr<InternalLinkageAttr>();
4089   }
4090 
4091   // Merge the types.
4092   VarDecl *MostRecent = Old->getMostRecentDecl();
4093   if (MostRecent != Old) {
4094     MergeVarDeclTypes(New, MostRecent,
4095                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4096     if (New->isInvalidDecl())
4097       return;
4098   }
4099 
4100   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4101   if (New->isInvalidDecl())
4102     return;
4103 
4104   diag::kind PrevDiag;
4105   SourceLocation OldLocation;
4106   std::tie(PrevDiag, OldLocation) =
4107       getNoteDiagForInvalidRedeclaration(Old, New);
4108 
4109   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4110   if (New->getStorageClass() == SC_Static &&
4111       !New->isStaticDataMember() &&
4112       Old->hasExternalFormalLinkage()) {
4113     if (getLangOpts().MicrosoftExt) {
4114       Diag(New->getLocation(), diag::ext_static_non_static)
4115           << New->getDeclName();
4116       Diag(OldLocation, PrevDiag);
4117     } else {
4118       Diag(New->getLocation(), diag::err_static_non_static)
4119           << New->getDeclName();
4120       Diag(OldLocation, PrevDiag);
4121       return New->setInvalidDecl();
4122     }
4123   }
4124   // C99 6.2.2p4:
4125   //   For an identifier declared with the storage-class specifier
4126   //   extern in a scope in which a prior declaration of that
4127   //   identifier is visible,23) if the prior declaration specifies
4128   //   internal or external linkage, the linkage of the identifier at
4129   //   the later declaration is the same as the linkage specified at
4130   //   the prior declaration. If no prior declaration is visible, or
4131   //   if the prior declaration specifies no linkage, then the
4132   //   identifier has external linkage.
4133   if (New->hasExternalStorage() && Old->hasLinkage())
4134     /* Okay */;
4135   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4136            !New->isStaticDataMember() &&
4137            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4138     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4139     Diag(OldLocation, PrevDiag);
4140     return New->setInvalidDecl();
4141   }
4142 
4143   // Check if extern is followed by non-extern and vice-versa.
4144   if (New->hasExternalStorage() &&
4145       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4146     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4147     Diag(OldLocation, PrevDiag);
4148     return New->setInvalidDecl();
4149   }
4150   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4151       !New->hasExternalStorage()) {
4152     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4153     Diag(OldLocation, PrevDiag);
4154     return New->setInvalidDecl();
4155   }
4156 
4157   if (CheckRedeclarationModuleOwnership(New, Old))
4158     return;
4159 
4160   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4161 
4162   // FIXME: The test for external storage here seems wrong? We still
4163   // need to check for mismatches.
4164   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4165       // Don't complain about out-of-line definitions of static members.
4166       !(Old->getLexicalDeclContext()->isRecord() &&
4167         !New->getLexicalDeclContext()->isRecord())) {
4168     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4169     Diag(OldLocation, PrevDiag);
4170     return New->setInvalidDecl();
4171   }
4172 
4173   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4174     if (VarDecl *Def = Old->getDefinition()) {
4175       // C++1z [dcl.fcn.spec]p4:
4176       //   If the definition of a variable appears in a translation unit before
4177       //   its first declaration as inline, the program is ill-formed.
4178       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4179       Diag(Def->getLocation(), diag::note_previous_definition);
4180     }
4181   }
4182 
4183   // If this redeclaration makes the variable inline, we may need to add it to
4184   // UndefinedButUsed.
4185   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4186       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4187     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4188                                            SourceLocation()));
4189 
4190   if (New->getTLSKind() != Old->getTLSKind()) {
4191     if (!Old->getTLSKind()) {
4192       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4193       Diag(OldLocation, PrevDiag);
4194     } else if (!New->getTLSKind()) {
4195       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4196       Diag(OldLocation, PrevDiag);
4197     } else {
4198       // Do not allow redeclaration to change the variable between requiring
4199       // static and dynamic initialization.
4200       // FIXME: GCC allows this, but uses the TLS keyword on the first
4201       // declaration to determine the kind. Do we need to be compatible here?
4202       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4203         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4204       Diag(OldLocation, PrevDiag);
4205     }
4206   }
4207 
4208   // C++ doesn't have tentative definitions, so go right ahead and check here.
4209   if (getLangOpts().CPlusPlus &&
4210       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4211     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4212         Old->getCanonicalDecl()->isConstexpr()) {
4213       // This definition won't be a definition any more once it's been merged.
4214       Diag(New->getLocation(),
4215            diag::warn_deprecated_redundant_constexpr_static_def);
4216     } else if (VarDecl *Def = Old->getDefinition()) {
4217       if (checkVarDeclRedefinition(Def, New))
4218         return;
4219     }
4220   }
4221 
4222   if (haveIncompatibleLanguageLinkages(Old, New)) {
4223     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4224     Diag(OldLocation, PrevDiag);
4225     New->setInvalidDecl();
4226     return;
4227   }
4228 
4229   // Merge "used" flag.
4230   if (Old->getMostRecentDecl()->isUsed(false))
4231     New->setIsUsed();
4232 
4233   // Keep a chain of previous declarations.
4234   New->setPreviousDecl(Old);
4235   if (NewTemplate)
4236     NewTemplate->setPreviousDecl(OldTemplate);
4237   adjustDeclContextForDeclaratorDecl(New, Old);
4238 
4239   // Inherit access appropriately.
4240   New->setAccess(Old->getAccess());
4241   if (NewTemplate)
4242     NewTemplate->setAccess(New->getAccess());
4243 
4244   if (Old->isInline())
4245     New->setImplicitlyInline();
4246 }
4247 
4248 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4249   SourceManager &SrcMgr = getSourceManager();
4250   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4251   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4252   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4253   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4254   auto &HSI = PP.getHeaderSearchInfo();
4255   StringRef HdrFilename =
4256       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4257 
4258   auto noteFromModuleOrInclude = [&](Module *Mod,
4259                                      SourceLocation IncLoc) -> bool {
4260     // Redefinition errors with modules are common with non modular mapped
4261     // headers, example: a non-modular header H in module A that also gets
4262     // included directly in a TU. Pointing twice to the same header/definition
4263     // is confusing, try to get better diagnostics when modules is on.
4264     if (IncLoc.isValid()) {
4265       if (Mod) {
4266         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4267             << HdrFilename.str() << Mod->getFullModuleName();
4268         if (!Mod->DefinitionLoc.isInvalid())
4269           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4270               << Mod->getFullModuleName();
4271       } else {
4272         Diag(IncLoc, diag::note_redefinition_include_same_file)
4273             << HdrFilename.str();
4274       }
4275       return true;
4276     }
4277 
4278     return false;
4279   };
4280 
4281   // Is it the same file and same offset? Provide more information on why
4282   // this leads to a redefinition error.
4283   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4284     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4285     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4286     bool EmittedDiag =
4287         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4288     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4289 
4290     // If the header has no guards, emit a note suggesting one.
4291     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4292       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4293 
4294     if (EmittedDiag)
4295       return;
4296   }
4297 
4298   // Redefinition coming from different files or couldn't do better above.
4299   if (Old->getLocation().isValid())
4300     Diag(Old->getLocation(), diag::note_previous_definition);
4301 }
4302 
4303 /// We've just determined that \p Old and \p New both appear to be definitions
4304 /// of the same variable. Either diagnose or fix the problem.
4305 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4306   if (!hasVisibleDefinition(Old) &&
4307       (New->getFormalLinkage() == InternalLinkage ||
4308        New->isInline() ||
4309        New->getDescribedVarTemplate() ||
4310        New->getNumTemplateParameterLists() ||
4311        New->getDeclContext()->isDependentContext())) {
4312     // The previous definition is hidden, and multiple definitions are
4313     // permitted (in separate TUs). Demote this to a declaration.
4314     New->demoteThisDefinitionToDeclaration();
4315 
4316     // Make the canonical definition visible.
4317     if (auto *OldTD = Old->getDescribedVarTemplate())
4318       makeMergedDefinitionVisible(OldTD);
4319     makeMergedDefinitionVisible(Old);
4320     return false;
4321   } else {
4322     Diag(New->getLocation(), diag::err_redefinition) << New;
4323     notePreviousDefinition(Old, New->getLocation());
4324     New->setInvalidDecl();
4325     return true;
4326   }
4327 }
4328 
4329 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4330 /// no declarator (e.g. "struct foo;") is parsed.
4331 Decl *
4332 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4333                                  RecordDecl *&AnonRecord) {
4334   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4335                                     AnonRecord);
4336 }
4337 
4338 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4339 // disambiguate entities defined in different scopes.
4340 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4341 // compatibility.
4342 // We will pick our mangling number depending on which version of MSVC is being
4343 // targeted.
4344 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4345   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4346              ? S->getMSCurManglingNumber()
4347              : S->getMSLastManglingNumber();
4348 }
4349 
4350 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4351   if (!Context.getLangOpts().CPlusPlus)
4352     return;
4353 
4354   if (isa<CXXRecordDecl>(Tag->getParent())) {
4355     // If this tag is the direct child of a class, number it if
4356     // it is anonymous.
4357     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4358       return;
4359     MangleNumberingContext &MCtx =
4360         Context.getManglingNumberContext(Tag->getParent());
4361     Context.setManglingNumber(
4362         Tag, MCtx.getManglingNumber(
4363                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4364     return;
4365   }
4366 
4367   // If this tag isn't a direct child of a class, number it if it is local.
4368   MangleNumberingContext *MCtx;
4369   Decl *ManglingContextDecl;
4370   std::tie(MCtx, ManglingContextDecl) =
4371       getCurrentMangleNumberContext(Tag->getDeclContext());
4372   if (MCtx) {
4373     Context.setManglingNumber(
4374         Tag, MCtx->getManglingNumber(
4375                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4376   }
4377 }
4378 
4379 namespace {
4380 struct NonCLikeKind {
4381   enum {
4382     None,
4383     BaseClass,
4384     DefaultMemberInit,
4385     Lambda,
4386     Friend,
4387     OtherMember,
4388     Invalid,
4389   } Kind = None;
4390   SourceRange Range;
4391 
4392   explicit operator bool() { return Kind != None; }
4393 };
4394 }
4395 
4396 /// Determine whether a class is C-like, according to the rules of C++
4397 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4398 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4399   if (RD->isInvalidDecl())
4400     return {NonCLikeKind::Invalid, {}};
4401 
4402   // C++ [dcl.typedef]p9: [P1766R1]
4403   //   An unnamed class with a typedef name for linkage purposes shall not
4404   //
4405   //    -- have any base classes
4406   if (RD->getNumBases())
4407     return {NonCLikeKind::BaseClass,
4408             SourceRange(RD->bases_begin()->getBeginLoc(),
4409                         RD->bases_end()[-1].getEndLoc())};
4410   bool Invalid = false;
4411   for (Decl *D : RD->decls()) {
4412     // Don't complain about things we already diagnosed.
4413     if (D->isInvalidDecl()) {
4414       Invalid = true;
4415       continue;
4416     }
4417 
4418     //  -- have any [...] default member initializers
4419     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4420       if (FD->hasInClassInitializer()) {
4421         auto *Init = FD->getInClassInitializer();
4422         return {NonCLikeKind::DefaultMemberInit,
4423                 Init ? Init->getSourceRange() : D->getSourceRange()};
4424       }
4425       continue;
4426     }
4427 
4428     // FIXME: We don't allow friend declarations. This violates the wording of
4429     // P1766, but not the intent.
4430     if (isa<FriendDecl>(D))
4431       return {NonCLikeKind::Friend, D->getSourceRange()};
4432 
4433     //  -- declare any members other than non-static data members, member
4434     //     enumerations, or member classes,
4435     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4436         isa<EnumDecl>(D))
4437       continue;
4438     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4439     if (!MemberRD) {
4440       if (D->isImplicit())
4441         continue;
4442       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4443     }
4444 
4445     //  -- contain a lambda-expression,
4446     if (MemberRD->isLambda())
4447       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4448 
4449     //  and all member classes shall also satisfy these requirements
4450     //  (recursively).
4451     if (MemberRD->isThisDeclarationADefinition()) {
4452       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4453         return Kind;
4454     }
4455   }
4456 
4457   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4458 }
4459 
4460 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4461                                         TypedefNameDecl *NewTD) {
4462   if (TagFromDeclSpec->isInvalidDecl())
4463     return;
4464 
4465   // Do nothing if the tag already has a name for linkage purposes.
4466   if (TagFromDeclSpec->hasNameForLinkage())
4467     return;
4468 
4469   // A well-formed anonymous tag must always be a TUK_Definition.
4470   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4471 
4472   // The type must match the tag exactly;  no qualifiers allowed.
4473   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4474                            Context.getTagDeclType(TagFromDeclSpec))) {
4475     if (getLangOpts().CPlusPlus)
4476       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4477     return;
4478   }
4479 
4480   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4481   //   An unnamed class with a typedef name for linkage purposes shall [be
4482   //   C-like].
4483   //
4484   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4485   // shouldn't happen, but there are constructs that the language rule doesn't
4486   // disallow for which we can't reasonably avoid computing linkage early.
4487   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4488   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4489                              : NonCLikeKind();
4490   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4491   if (NonCLike || ChangesLinkage) {
4492     if (NonCLike.Kind == NonCLikeKind::Invalid)
4493       return;
4494 
4495     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4496     if (ChangesLinkage) {
4497       // If the linkage changes, we can't accept this as an extension.
4498       if (NonCLike.Kind == NonCLikeKind::None)
4499         DiagID = diag::err_typedef_changes_linkage;
4500       else
4501         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4502     }
4503 
4504     SourceLocation FixitLoc =
4505         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4506     llvm::SmallString<40> TextToInsert;
4507     TextToInsert += ' ';
4508     TextToInsert += NewTD->getIdentifier()->getName();
4509 
4510     Diag(FixitLoc, DiagID)
4511       << isa<TypeAliasDecl>(NewTD)
4512       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4513     if (NonCLike.Kind != NonCLikeKind::None) {
4514       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4515         << NonCLike.Kind - 1 << NonCLike.Range;
4516     }
4517     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4518       << NewTD << isa<TypeAliasDecl>(NewTD);
4519 
4520     if (ChangesLinkage)
4521       return;
4522   }
4523 
4524   // Otherwise, set this as the anon-decl typedef for the tag.
4525   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4526 }
4527 
4528 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4529   switch (T) {
4530   case DeclSpec::TST_class:
4531     return 0;
4532   case DeclSpec::TST_struct:
4533     return 1;
4534   case DeclSpec::TST_interface:
4535     return 2;
4536   case DeclSpec::TST_union:
4537     return 3;
4538   case DeclSpec::TST_enum:
4539     return 4;
4540   default:
4541     llvm_unreachable("unexpected type specifier");
4542   }
4543 }
4544 
4545 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4546 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4547 /// parameters to cope with template friend declarations.
4548 Decl *
4549 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4550                                  MultiTemplateParamsArg TemplateParams,
4551                                  bool IsExplicitInstantiation,
4552                                  RecordDecl *&AnonRecord) {
4553   Decl *TagD = nullptr;
4554   TagDecl *Tag = nullptr;
4555   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4556       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4557       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4558       DS.getTypeSpecType() == DeclSpec::TST_union ||
4559       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4560     TagD = DS.getRepAsDecl();
4561 
4562     if (!TagD) // We probably had an error
4563       return nullptr;
4564 
4565     // Note that the above type specs guarantee that the
4566     // type rep is a Decl, whereas in many of the others
4567     // it's a Type.
4568     if (isa<TagDecl>(TagD))
4569       Tag = cast<TagDecl>(TagD);
4570     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4571       Tag = CTD->getTemplatedDecl();
4572   }
4573 
4574   if (Tag) {
4575     handleTagNumbering(Tag, S);
4576     Tag->setFreeStanding();
4577     if (Tag->isInvalidDecl())
4578       return Tag;
4579   }
4580 
4581   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4582     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4583     // or incomplete types shall not be restrict-qualified."
4584     if (TypeQuals & DeclSpec::TQ_restrict)
4585       Diag(DS.getRestrictSpecLoc(),
4586            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4587            << DS.getSourceRange();
4588   }
4589 
4590   if (DS.isInlineSpecified())
4591     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4592         << getLangOpts().CPlusPlus17;
4593 
4594   if (DS.hasConstexprSpecifier()) {
4595     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4596     // and definitions of functions and variables.
4597     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4598     // the declaration of a function or function template
4599     if (Tag)
4600       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4601           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4602           << DS.getConstexprSpecifier();
4603     else
4604       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4605           << DS.getConstexprSpecifier();
4606     // Don't emit warnings after this error.
4607     return TagD;
4608   }
4609 
4610   DiagnoseFunctionSpecifiers(DS);
4611 
4612   if (DS.isFriendSpecified()) {
4613     // If we're dealing with a decl but not a TagDecl, assume that
4614     // whatever routines created it handled the friendship aspect.
4615     if (TagD && !Tag)
4616       return nullptr;
4617     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4618   }
4619 
4620   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4621   bool IsExplicitSpecialization =
4622     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4623   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4624       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4625       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4626     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4627     // nested-name-specifier unless it is an explicit instantiation
4628     // or an explicit specialization.
4629     //
4630     // FIXME: We allow class template partial specializations here too, per the
4631     // obvious intent of DR1819.
4632     //
4633     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4634     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4635         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4636     return nullptr;
4637   }
4638 
4639   // Track whether this decl-specifier declares anything.
4640   bool DeclaresAnything = true;
4641 
4642   // Handle anonymous struct definitions.
4643   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4644     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4645         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4646       if (getLangOpts().CPlusPlus ||
4647           Record->getDeclContext()->isRecord()) {
4648         // If CurContext is a DeclContext that can contain statements,
4649         // RecursiveASTVisitor won't visit the decls that
4650         // BuildAnonymousStructOrUnion() will put into CurContext.
4651         // Also store them here so that they can be part of the
4652         // DeclStmt that gets created in this case.
4653         // FIXME: Also return the IndirectFieldDecls created by
4654         // BuildAnonymousStructOr union, for the same reason?
4655         if (CurContext->isFunctionOrMethod())
4656           AnonRecord = Record;
4657         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4658                                            Context.getPrintingPolicy());
4659       }
4660 
4661       DeclaresAnything = false;
4662     }
4663   }
4664 
4665   // C11 6.7.2.1p2:
4666   //   A struct-declaration that does not declare an anonymous structure or
4667   //   anonymous union shall contain a struct-declarator-list.
4668   //
4669   // This rule also existed in C89 and C99; the grammar for struct-declaration
4670   // did not permit a struct-declaration without a struct-declarator-list.
4671   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4672       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4673     // Check for Microsoft C extension: anonymous struct/union member.
4674     // Handle 2 kinds of anonymous struct/union:
4675     //   struct STRUCT;
4676     //   union UNION;
4677     // and
4678     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4679     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4680     if ((Tag && Tag->getDeclName()) ||
4681         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4682       RecordDecl *Record = nullptr;
4683       if (Tag)
4684         Record = dyn_cast<RecordDecl>(Tag);
4685       else if (const RecordType *RT =
4686                    DS.getRepAsType().get()->getAsStructureType())
4687         Record = RT->getDecl();
4688       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4689         Record = UT->getDecl();
4690 
4691       if (Record && getLangOpts().MicrosoftExt) {
4692         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4693             << Record->isUnion() << DS.getSourceRange();
4694         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4695       }
4696 
4697       DeclaresAnything = false;
4698     }
4699   }
4700 
4701   // Skip all the checks below if we have a type error.
4702   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4703       (TagD && TagD->isInvalidDecl()))
4704     return TagD;
4705 
4706   if (getLangOpts().CPlusPlus &&
4707       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4708     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4709       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4710           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4711         DeclaresAnything = false;
4712 
4713   if (!DS.isMissingDeclaratorOk()) {
4714     // Customize diagnostic for a typedef missing a name.
4715     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4716       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4717           << DS.getSourceRange();
4718     else
4719       DeclaresAnything = false;
4720   }
4721 
4722   if (DS.isModulePrivateSpecified() &&
4723       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4724     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4725       << Tag->getTagKind()
4726       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4727 
4728   ActOnDocumentableDecl(TagD);
4729 
4730   // C 6.7/2:
4731   //   A declaration [...] shall declare at least a declarator [...], a tag,
4732   //   or the members of an enumeration.
4733   // C++ [dcl.dcl]p3:
4734   //   [If there are no declarators], and except for the declaration of an
4735   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4736   //   names into the program, or shall redeclare a name introduced by a
4737   //   previous declaration.
4738   if (!DeclaresAnything) {
4739     // In C, we allow this as a (popular) extension / bug. Don't bother
4740     // producing further diagnostics for redundant qualifiers after this.
4741     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4742     return TagD;
4743   }
4744 
4745   // C++ [dcl.stc]p1:
4746   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4747   //   init-declarator-list of the declaration shall not be empty.
4748   // C++ [dcl.fct.spec]p1:
4749   //   If a cv-qualifier appears in a decl-specifier-seq, the
4750   //   init-declarator-list of the declaration shall not be empty.
4751   //
4752   // Spurious qualifiers here appear to be valid in C.
4753   unsigned DiagID = diag::warn_standalone_specifier;
4754   if (getLangOpts().CPlusPlus)
4755     DiagID = diag::ext_standalone_specifier;
4756 
4757   // Note that a linkage-specification sets a storage class, but
4758   // 'extern "C" struct foo;' is actually valid and not theoretically
4759   // useless.
4760   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4761     if (SCS == DeclSpec::SCS_mutable)
4762       // Since mutable is not a viable storage class specifier in C, there is
4763       // no reason to treat it as an extension. Instead, diagnose as an error.
4764       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4765     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4766       Diag(DS.getStorageClassSpecLoc(), DiagID)
4767         << DeclSpec::getSpecifierName(SCS);
4768   }
4769 
4770   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4771     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4772       << DeclSpec::getSpecifierName(TSCS);
4773   if (DS.getTypeQualifiers()) {
4774     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4775       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4776     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4777       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4778     // Restrict is covered above.
4779     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4780       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4781     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4782       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4783   }
4784 
4785   // Warn about ignored type attributes, for example:
4786   // __attribute__((aligned)) struct A;
4787   // Attributes should be placed after tag to apply to type declaration.
4788   if (!DS.getAttributes().empty()) {
4789     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4790     if (TypeSpecType == DeclSpec::TST_class ||
4791         TypeSpecType == DeclSpec::TST_struct ||
4792         TypeSpecType == DeclSpec::TST_interface ||
4793         TypeSpecType == DeclSpec::TST_union ||
4794         TypeSpecType == DeclSpec::TST_enum) {
4795       for (const ParsedAttr &AL : DS.getAttributes())
4796         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4797             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4798     }
4799   }
4800 
4801   return TagD;
4802 }
4803 
4804 /// We are trying to inject an anonymous member into the given scope;
4805 /// check if there's an existing declaration that can't be overloaded.
4806 ///
4807 /// \return true if this is a forbidden redeclaration
4808 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4809                                          Scope *S,
4810                                          DeclContext *Owner,
4811                                          DeclarationName Name,
4812                                          SourceLocation NameLoc,
4813                                          bool IsUnion) {
4814   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4815                  Sema::ForVisibleRedeclaration);
4816   if (!SemaRef.LookupName(R, S)) return false;
4817 
4818   // Pick a representative declaration.
4819   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4820   assert(PrevDecl && "Expected a non-null Decl");
4821 
4822   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4823     return false;
4824 
4825   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4826     << IsUnion << Name;
4827   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4828 
4829   return true;
4830 }
4831 
4832 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4833 /// anonymous struct or union AnonRecord into the owning context Owner
4834 /// and scope S. This routine will be invoked just after we realize
4835 /// that an unnamed union or struct is actually an anonymous union or
4836 /// struct, e.g.,
4837 ///
4838 /// @code
4839 /// union {
4840 ///   int i;
4841 ///   float f;
4842 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4843 ///    // f into the surrounding scope.x
4844 /// @endcode
4845 ///
4846 /// This routine is recursive, injecting the names of nested anonymous
4847 /// structs/unions into the owning context and scope as well.
4848 static bool
4849 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4850                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4851                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4852   bool Invalid = false;
4853 
4854   // Look every FieldDecl and IndirectFieldDecl with a name.
4855   for (auto *D : AnonRecord->decls()) {
4856     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4857         cast<NamedDecl>(D)->getDeclName()) {
4858       ValueDecl *VD = cast<ValueDecl>(D);
4859       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4860                                        VD->getLocation(),
4861                                        AnonRecord->isUnion())) {
4862         // C++ [class.union]p2:
4863         //   The names of the members of an anonymous union shall be
4864         //   distinct from the names of any other entity in the
4865         //   scope in which the anonymous union is declared.
4866         Invalid = true;
4867       } else {
4868         // C++ [class.union]p2:
4869         //   For the purpose of name lookup, after the anonymous union
4870         //   definition, the members of the anonymous union are
4871         //   considered to have been defined in the scope in which the
4872         //   anonymous union is declared.
4873         unsigned OldChainingSize = Chaining.size();
4874         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4875           Chaining.append(IF->chain_begin(), IF->chain_end());
4876         else
4877           Chaining.push_back(VD);
4878 
4879         assert(Chaining.size() >= 2);
4880         NamedDecl **NamedChain =
4881           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4882         for (unsigned i = 0; i < Chaining.size(); i++)
4883           NamedChain[i] = Chaining[i];
4884 
4885         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4886             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4887             VD->getType(), {NamedChain, Chaining.size()});
4888 
4889         for (const auto *Attr : VD->attrs())
4890           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4891 
4892         IndirectField->setAccess(AS);
4893         IndirectField->setImplicit();
4894         SemaRef.PushOnScopeChains(IndirectField, S);
4895 
4896         // That includes picking up the appropriate access specifier.
4897         if (AS != AS_none) IndirectField->setAccess(AS);
4898 
4899         Chaining.resize(OldChainingSize);
4900       }
4901     }
4902   }
4903 
4904   return Invalid;
4905 }
4906 
4907 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4908 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4909 /// illegal input values are mapped to SC_None.
4910 static StorageClass
4911 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4912   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4913   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4914          "Parser allowed 'typedef' as storage class VarDecl.");
4915   switch (StorageClassSpec) {
4916   case DeclSpec::SCS_unspecified:    return SC_None;
4917   case DeclSpec::SCS_extern:
4918     if (DS.isExternInLinkageSpec())
4919       return SC_None;
4920     return SC_Extern;
4921   case DeclSpec::SCS_static:         return SC_Static;
4922   case DeclSpec::SCS_auto:           return SC_Auto;
4923   case DeclSpec::SCS_register:       return SC_Register;
4924   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4925     // Illegal SCSs map to None: error reporting is up to the caller.
4926   case DeclSpec::SCS_mutable:        // Fall through.
4927   case DeclSpec::SCS_typedef:        return SC_None;
4928   }
4929   llvm_unreachable("unknown storage class specifier");
4930 }
4931 
4932 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4933   assert(Record->hasInClassInitializer());
4934 
4935   for (const auto *I : Record->decls()) {
4936     const auto *FD = dyn_cast<FieldDecl>(I);
4937     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4938       FD = IFD->getAnonField();
4939     if (FD && FD->hasInClassInitializer())
4940       return FD->getLocation();
4941   }
4942 
4943   llvm_unreachable("couldn't find in-class initializer");
4944 }
4945 
4946 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4947                                       SourceLocation DefaultInitLoc) {
4948   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4949     return;
4950 
4951   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4952   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4953 }
4954 
4955 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4956                                       CXXRecordDecl *AnonUnion) {
4957   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4958     return;
4959 
4960   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4961 }
4962 
4963 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4964 /// anonymous structure or union. Anonymous unions are a C++ feature
4965 /// (C++ [class.union]) and a C11 feature; anonymous structures
4966 /// are a C11 feature and GNU C++ extension.
4967 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4968                                         AccessSpecifier AS,
4969                                         RecordDecl *Record,
4970                                         const PrintingPolicy &Policy) {
4971   DeclContext *Owner = Record->getDeclContext();
4972 
4973   // Diagnose whether this anonymous struct/union is an extension.
4974   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4975     Diag(Record->getLocation(), diag::ext_anonymous_union);
4976   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4977     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4978   else if (!Record->isUnion() && !getLangOpts().C11)
4979     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4980 
4981   // C and C++ require different kinds of checks for anonymous
4982   // structs/unions.
4983   bool Invalid = false;
4984   if (getLangOpts().CPlusPlus) {
4985     const char *PrevSpec = nullptr;
4986     if (Record->isUnion()) {
4987       // C++ [class.union]p6:
4988       // C++17 [class.union.anon]p2:
4989       //   Anonymous unions declared in a named namespace or in the
4990       //   global namespace shall be declared static.
4991       unsigned DiagID;
4992       DeclContext *OwnerScope = Owner->getRedeclContext();
4993       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4994           (OwnerScope->isTranslationUnit() ||
4995            (OwnerScope->isNamespace() &&
4996             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4997         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4998           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4999 
5000         // Recover by adding 'static'.
5001         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5002                                PrevSpec, DiagID, Policy);
5003       }
5004       // C++ [class.union]p6:
5005       //   A storage class is not allowed in a declaration of an
5006       //   anonymous union in a class scope.
5007       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5008                isa<RecordDecl>(Owner)) {
5009         Diag(DS.getStorageClassSpecLoc(),
5010              diag::err_anonymous_union_with_storage_spec)
5011           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5012 
5013         // Recover by removing the storage specifier.
5014         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5015                                SourceLocation(),
5016                                PrevSpec, DiagID, Context.getPrintingPolicy());
5017       }
5018     }
5019 
5020     // Ignore const/volatile/restrict qualifiers.
5021     if (DS.getTypeQualifiers()) {
5022       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5023         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5024           << Record->isUnion() << "const"
5025           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5026       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5027         Diag(DS.getVolatileSpecLoc(),
5028              diag::ext_anonymous_struct_union_qualified)
5029           << Record->isUnion() << "volatile"
5030           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5031       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5032         Diag(DS.getRestrictSpecLoc(),
5033              diag::ext_anonymous_struct_union_qualified)
5034           << Record->isUnion() << "restrict"
5035           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5036       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5037         Diag(DS.getAtomicSpecLoc(),
5038              diag::ext_anonymous_struct_union_qualified)
5039           << Record->isUnion() << "_Atomic"
5040           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5041       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5042         Diag(DS.getUnalignedSpecLoc(),
5043              diag::ext_anonymous_struct_union_qualified)
5044           << Record->isUnion() << "__unaligned"
5045           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5046 
5047       DS.ClearTypeQualifiers();
5048     }
5049 
5050     // C++ [class.union]p2:
5051     //   The member-specification of an anonymous union shall only
5052     //   define non-static data members. [Note: nested types and
5053     //   functions cannot be declared within an anonymous union. ]
5054     for (auto *Mem : Record->decls()) {
5055       // Ignore invalid declarations; we already diagnosed them.
5056       if (Mem->isInvalidDecl())
5057         continue;
5058 
5059       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5060         // C++ [class.union]p3:
5061         //   An anonymous union shall not have private or protected
5062         //   members (clause 11).
5063         assert(FD->getAccess() != AS_none);
5064         if (FD->getAccess() != AS_public) {
5065           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5066             << Record->isUnion() << (FD->getAccess() == AS_protected);
5067           Invalid = true;
5068         }
5069 
5070         // C++ [class.union]p1
5071         //   An object of a class with a non-trivial constructor, a non-trivial
5072         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5073         //   assignment operator cannot be a member of a union, nor can an
5074         //   array of such objects.
5075         if (CheckNontrivialField(FD))
5076           Invalid = true;
5077       } else if (Mem->isImplicit()) {
5078         // Any implicit members are fine.
5079       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5080         // This is a type that showed up in an
5081         // elaborated-type-specifier inside the anonymous struct or
5082         // union, but which actually declares a type outside of the
5083         // anonymous struct or union. It's okay.
5084       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5085         if (!MemRecord->isAnonymousStructOrUnion() &&
5086             MemRecord->getDeclName()) {
5087           // Visual C++ allows type definition in anonymous struct or union.
5088           if (getLangOpts().MicrosoftExt)
5089             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5090               << Record->isUnion();
5091           else {
5092             // This is a nested type declaration.
5093             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5094               << Record->isUnion();
5095             Invalid = true;
5096           }
5097         } else {
5098           // This is an anonymous type definition within another anonymous type.
5099           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5100           // not part of standard C++.
5101           Diag(MemRecord->getLocation(),
5102                diag::ext_anonymous_record_with_anonymous_type)
5103             << Record->isUnion();
5104         }
5105       } else if (isa<AccessSpecDecl>(Mem)) {
5106         // Any access specifier is fine.
5107       } else if (isa<StaticAssertDecl>(Mem)) {
5108         // In C++1z, static_assert declarations are also fine.
5109       } else {
5110         // We have something that isn't a non-static data
5111         // member. Complain about it.
5112         unsigned DK = diag::err_anonymous_record_bad_member;
5113         if (isa<TypeDecl>(Mem))
5114           DK = diag::err_anonymous_record_with_type;
5115         else if (isa<FunctionDecl>(Mem))
5116           DK = diag::err_anonymous_record_with_function;
5117         else if (isa<VarDecl>(Mem))
5118           DK = diag::err_anonymous_record_with_static;
5119 
5120         // Visual C++ allows type definition in anonymous struct or union.
5121         if (getLangOpts().MicrosoftExt &&
5122             DK == diag::err_anonymous_record_with_type)
5123           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5124             << Record->isUnion();
5125         else {
5126           Diag(Mem->getLocation(), DK) << Record->isUnion();
5127           Invalid = true;
5128         }
5129       }
5130     }
5131 
5132     // C++11 [class.union]p8 (DR1460):
5133     //   At most one variant member of a union may have a
5134     //   brace-or-equal-initializer.
5135     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5136         Owner->isRecord())
5137       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5138                                 cast<CXXRecordDecl>(Record));
5139   }
5140 
5141   if (!Record->isUnion() && !Owner->isRecord()) {
5142     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5143       << getLangOpts().CPlusPlus;
5144     Invalid = true;
5145   }
5146 
5147   // C++ [dcl.dcl]p3:
5148   //   [If there are no declarators], and except for the declaration of an
5149   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5150   //   names into the program
5151   // C++ [class.mem]p2:
5152   //   each such member-declaration shall either declare at least one member
5153   //   name of the class or declare at least one unnamed bit-field
5154   //
5155   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5156   if (getLangOpts().CPlusPlus && Record->field_empty())
5157     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5158 
5159   // Mock up a declarator.
5160   Declarator Dc(DS, DeclaratorContext::MemberContext);
5161   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5162   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5163 
5164   // Create a declaration for this anonymous struct/union.
5165   NamedDecl *Anon = nullptr;
5166   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5167     Anon = FieldDecl::Create(
5168         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5169         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5170         /*BitWidth=*/nullptr, /*Mutable=*/false,
5171         /*InitStyle=*/ICIS_NoInit);
5172     Anon->setAccess(AS);
5173     ProcessDeclAttributes(S, Anon, Dc);
5174 
5175     if (getLangOpts().CPlusPlus)
5176       FieldCollector->Add(cast<FieldDecl>(Anon));
5177   } else {
5178     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5179     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5180     if (SCSpec == DeclSpec::SCS_mutable) {
5181       // mutable can only appear on non-static class members, so it's always
5182       // an error here
5183       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5184       Invalid = true;
5185       SC = SC_None;
5186     }
5187 
5188     assert(DS.getAttributes().empty() && "No attribute expected");
5189     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5190                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5191                            Context.getTypeDeclType(Record), TInfo, SC);
5192 
5193     // Default-initialize the implicit variable. This initialization will be
5194     // trivial in almost all cases, except if a union member has an in-class
5195     // initializer:
5196     //   union { int n = 0; };
5197     ActOnUninitializedDecl(Anon);
5198   }
5199   Anon->setImplicit();
5200 
5201   // Mark this as an anonymous struct/union type.
5202   Record->setAnonymousStructOrUnion(true);
5203 
5204   // Add the anonymous struct/union object to the current
5205   // context. We'll be referencing this object when we refer to one of
5206   // its members.
5207   Owner->addDecl(Anon);
5208 
5209   // Inject the members of the anonymous struct/union into the owning
5210   // context and into the identifier resolver chain for name lookup
5211   // purposes.
5212   SmallVector<NamedDecl*, 2> Chain;
5213   Chain.push_back(Anon);
5214 
5215   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5216     Invalid = true;
5217 
5218   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5219     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5220       MangleNumberingContext *MCtx;
5221       Decl *ManglingContextDecl;
5222       std::tie(MCtx, ManglingContextDecl) =
5223           getCurrentMangleNumberContext(NewVD->getDeclContext());
5224       if (MCtx) {
5225         Context.setManglingNumber(
5226             NewVD, MCtx->getManglingNumber(
5227                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5228         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5229       }
5230     }
5231   }
5232 
5233   if (Invalid)
5234     Anon->setInvalidDecl();
5235 
5236   return Anon;
5237 }
5238 
5239 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5240 /// Microsoft C anonymous structure.
5241 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5242 /// Example:
5243 ///
5244 /// struct A { int a; };
5245 /// struct B { struct A; int b; };
5246 ///
5247 /// void foo() {
5248 ///   B var;
5249 ///   var.a = 3;
5250 /// }
5251 ///
5252 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5253                                            RecordDecl *Record) {
5254   assert(Record && "expected a record!");
5255 
5256   // Mock up a declarator.
5257   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5258   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5259   assert(TInfo && "couldn't build declarator info for anonymous struct");
5260 
5261   auto *ParentDecl = cast<RecordDecl>(CurContext);
5262   QualType RecTy = Context.getTypeDeclType(Record);
5263 
5264   // Create a declaration for this anonymous struct.
5265   NamedDecl *Anon =
5266       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5267                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5268                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5269                         /*InitStyle=*/ICIS_NoInit);
5270   Anon->setImplicit();
5271 
5272   // Add the anonymous struct object to the current context.
5273   CurContext->addDecl(Anon);
5274 
5275   // Inject the members of the anonymous struct into the current
5276   // context and into the identifier resolver chain for name lookup
5277   // purposes.
5278   SmallVector<NamedDecl*, 2> Chain;
5279   Chain.push_back(Anon);
5280 
5281   RecordDecl *RecordDef = Record->getDefinition();
5282   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5283                                diag::err_field_incomplete_or_sizeless) ||
5284       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5285                                           AS_none, Chain)) {
5286     Anon->setInvalidDecl();
5287     ParentDecl->setInvalidDecl();
5288   }
5289 
5290   return Anon;
5291 }
5292 
5293 /// GetNameForDeclarator - Determine the full declaration name for the
5294 /// given Declarator.
5295 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5296   return GetNameFromUnqualifiedId(D.getName());
5297 }
5298 
5299 /// Retrieves the declaration name from a parsed unqualified-id.
5300 DeclarationNameInfo
5301 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5302   DeclarationNameInfo NameInfo;
5303   NameInfo.setLoc(Name.StartLocation);
5304 
5305   switch (Name.getKind()) {
5306 
5307   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5308   case UnqualifiedIdKind::IK_Identifier:
5309     NameInfo.setName(Name.Identifier);
5310     return NameInfo;
5311 
5312   case UnqualifiedIdKind::IK_DeductionGuideName: {
5313     // C++ [temp.deduct.guide]p3:
5314     //   The simple-template-id shall name a class template specialization.
5315     //   The template-name shall be the same identifier as the template-name
5316     //   of the simple-template-id.
5317     // These together intend to imply that the template-name shall name a
5318     // class template.
5319     // FIXME: template<typename T> struct X {};
5320     //        template<typename T> using Y = X<T>;
5321     //        Y(int) -> Y<int>;
5322     //   satisfies these rules but does not name a class template.
5323     TemplateName TN = Name.TemplateName.get().get();
5324     auto *Template = TN.getAsTemplateDecl();
5325     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5326       Diag(Name.StartLocation,
5327            diag::err_deduction_guide_name_not_class_template)
5328         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5329       if (Template)
5330         Diag(Template->getLocation(), diag::note_template_decl_here);
5331       return DeclarationNameInfo();
5332     }
5333 
5334     NameInfo.setName(
5335         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5336     return NameInfo;
5337   }
5338 
5339   case UnqualifiedIdKind::IK_OperatorFunctionId:
5340     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5341                                            Name.OperatorFunctionId.Operator));
5342     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5343       = Name.OperatorFunctionId.SymbolLocations[0];
5344     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5345       = Name.EndLocation.getRawEncoding();
5346     return NameInfo;
5347 
5348   case UnqualifiedIdKind::IK_LiteralOperatorId:
5349     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5350                                                            Name.Identifier));
5351     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5352     return NameInfo;
5353 
5354   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5355     TypeSourceInfo *TInfo;
5356     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5357     if (Ty.isNull())
5358       return DeclarationNameInfo();
5359     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5360                                                Context.getCanonicalType(Ty)));
5361     NameInfo.setNamedTypeInfo(TInfo);
5362     return NameInfo;
5363   }
5364 
5365   case UnqualifiedIdKind::IK_ConstructorName: {
5366     TypeSourceInfo *TInfo;
5367     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5368     if (Ty.isNull())
5369       return DeclarationNameInfo();
5370     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5371                                               Context.getCanonicalType(Ty)));
5372     NameInfo.setNamedTypeInfo(TInfo);
5373     return NameInfo;
5374   }
5375 
5376   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5377     // In well-formed code, we can only have a constructor
5378     // template-id that refers to the current context, so go there
5379     // to find the actual type being constructed.
5380     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5381     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5382       return DeclarationNameInfo();
5383 
5384     // Determine the type of the class being constructed.
5385     QualType CurClassType = Context.getTypeDeclType(CurClass);
5386 
5387     // FIXME: Check two things: that the template-id names the same type as
5388     // CurClassType, and that the template-id does not occur when the name
5389     // was qualified.
5390 
5391     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5392                                     Context.getCanonicalType(CurClassType)));
5393     // FIXME: should we retrieve TypeSourceInfo?
5394     NameInfo.setNamedTypeInfo(nullptr);
5395     return NameInfo;
5396   }
5397 
5398   case UnqualifiedIdKind::IK_DestructorName: {
5399     TypeSourceInfo *TInfo;
5400     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5401     if (Ty.isNull())
5402       return DeclarationNameInfo();
5403     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5404                                               Context.getCanonicalType(Ty)));
5405     NameInfo.setNamedTypeInfo(TInfo);
5406     return NameInfo;
5407   }
5408 
5409   case UnqualifiedIdKind::IK_TemplateId: {
5410     TemplateName TName = Name.TemplateId->Template.get();
5411     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5412     return Context.getNameForTemplate(TName, TNameLoc);
5413   }
5414 
5415   } // switch (Name.getKind())
5416 
5417   llvm_unreachable("Unknown name kind");
5418 }
5419 
5420 static QualType getCoreType(QualType Ty) {
5421   do {
5422     if (Ty->isPointerType() || Ty->isReferenceType())
5423       Ty = Ty->getPointeeType();
5424     else if (Ty->isArrayType())
5425       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5426     else
5427       return Ty.withoutLocalFastQualifiers();
5428   } while (true);
5429 }
5430 
5431 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5432 /// and Definition have "nearly" matching parameters. This heuristic is
5433 /// used to improve diagnostics in the case where an out-of-line function
5434 /// definition doesn't match any declaration within the class or namespace.
5435 /// Also sets Params to the list of indices to the parameters that differ
5436 /// between the declaration and the definition. If hasSimilarParameters
5437 /// returns true and Params is empty, then all of the parameters match.
5438 static bool hasSimilarParameters(ASTContext &Context,
5439                                      FunctionDecl *Declaration,
5440                                      FunctionDecl *Definition,
5441                                      SmallVectorImpl<unsigned> &Params) {
5442   Params.clear();
5443   if (Declaration->param_size() != Definition->param_size())
5444     return false;
5445   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5446     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5447     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5448 
5449     // The parameter types are identical
5450     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5451       continue;
5452 
5453     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5454     QualType DefParamBaseTy = getCoreType(DefParamTy);
5455     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5456     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5457 
5458     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5459         (DeclTyName && DeclTyName == DefTyName))
5460       Params.push_back(Idx);
5461     else  // The two parameters aren't even close
5462       return false;
5463   }
5464 
5465   return true;
5466 }
5467 
5468 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5469 /// declarator needs to be rebuilt in the current instantiation.
5470 /// Any bits of declarator which appear before the name are valid for
5471 /// consideration here.  That's specifically the type in the decl spec
5472 /// and the base type in any member-pointer chunks.
5473 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5474                                                     DeclarationName Name) {
5475   // The types we specifically need to rebuild are:
5476   //   - typenames, typeofs, and decltypes
5477   //   - types which will become injected class names
5478   // Of course, we also need to rebuild any type referencing such a
5479   // type.  It's safest to just say "dependent", but we call out a
5480   // few cases here.
5481 
5482   DeclSpec &DS = D.getMutableDeclSpec();
5483   switch (DS.getTypeSpecType()) {
5484   case DeclSpec::TST_typename:
5485   case DeclSpec::TST_typeofType:
5486   case DeclSpec::TST_underlyingType:
5487   case DeclSpec::TST_atomic: {
5488     // Grab the type from the parser.
5489     TypeSourceInfo *TSI = nullptr;
5490     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5491     if (T.isNull() || !T->isDependentType()) break;
5492 
5493     // Make sure there's a type source info.  This isn't really much
5494     // of a waste; most dependent types should have type source info
5495     // attached already.
5496     if (!TSI)
5497       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5498 
5499     // Rebuild the type in the current instantiation.
5500     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5501     if (!TSI) return true;
5502 
5503     // Store the new type back in the decl spec.
5504     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5505     DS.UpdateTypeRep(LocType);
5506     break;
5507   }
5508 
5509   case DeclSpec::TST_decltype:
5510   case DeclSpec::TST_typeofExpr: {
5511     Expr *E = DS.getRepAsExpr();
5512     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5513     if (Result.isInvalid()) return true;
5514     DS.UpdateExprRep(Result.get());
5515     break;
5516   }
5517 
5518   default:
5519     // Nothing to do for these decl specs.
5520     break;
5521   }
5522 
5523   // It doesn't matter what order we do this in.
5524   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5525     DeclaratorChunk &Chunk = D.getTypeObject(I);
5526 
5527     // The only type information in the declarator which can come
5528     // before the declaration name is the base type of a member
5529     // pointer.
5530     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5531       continue;
5532 
5533     // Rebuild the scope specifier in-place.
5534     CXXScopeSpec &SS = Chunk.Mem.Scope();
5535     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5536       return true;
5537   }
5538 
5539   return false;
5540 }
5541 
5542 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5543   D.setFunctionDefinitionKind(FDK_Declaration);
5544   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5545 
5546   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5547       Dcl && Dcl->getDeclContext()->isFileContext())
5548     Dcl->setTopLevelDeclInObjCContainer();
5549 
5550   if (getLangOpts().OpenCL)
5551     setCurrentOpenCLExtensionForDecl(Dcl);
5552 
5553   return Dcl;
5554 }
5555 
5556 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5557 ///   If T is the name of a class, then each of the following shall have a
5558 ///   name different from T:
5559 ///     - every static data member of class T;
5560 ///     - every member function of class T
5561 ///     - every member of class T that is itself a type;
5562 /// \returns true if the declaration name violates these rules.
5563 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5564                                    DeclarationNameInfo NameInfo) {
5565   DeclarationName Name = NameInfo.getName();
5566 
5567   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5568   while (Record && Record->isAnonymousStructOrUnion())
5569     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5570   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5571     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5572     return true;
5573   }
5574 
5575   return false;
5576 }
5577 
5578 /// Diagnose a declaration whose declarator-id has the given
5579 /// nested-name-specifier.
5580 ///
5581 /// \param SS The nested-name-specifier of the declarator-id.
5582 ///
5583 /// \param DC The declaration context to which the nested-name-specifier
5584 /// resolves.
5585 ///
5586 /// \param Name The name of the entity being declared.
5587 ///
5588 /// \param Loc The location of the name of the entity being declared.
5589 ///
5590 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5591 /// we're declaring an explicit / partial specialization / instantiation.
5592 ///
5593 /// \returns true if we cannot safely recover from this error, false otherwise.
5594 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5595                                         DeclarationName Name,
5596                                         SourceLocation Loc, bool IsTemplateId) {
5597   DeclContext *Cur = CurContext;
5598   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5599     Cur = Cur->getParent();
5600 
5601   // If the user provided a superfluous scope specifier that refers back to the
5602   // class in which the entity is already declared, diagnose and ignore it.
5603   //
5604   // class X {
5605   //   void X::f();
5606   // };
5607   //
5608   // Note, it was once ill-formed to give redundant qualification in all
5609   // contexts, but that rule was removed by DR482.
5610   if (Cur->Equals(DC)) {
5611     if (Cur->isRecord()) {
5612       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5613                                       : diag::err_member_extra_qualification)
5614         << Name << FixItHint::CreateRemoval(SS.getRange());
5615       SS.clear();
5616     } else {
5617       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5618     }
5619     return false;
5620   }
5621 
5622   // Check whether the qualifying scope encloses the scope of the original
5623   // declaration. For a template-id, we perform the checks in
5624   // CheckTemplateSpecializationScope.
5625   if (!Cur->Encloses(DC) && !IsTemplateId) {
5626     if (Cur->isRecord())
5627       Diag(Loc, diag::err_member_qualification)
5628         << Name << SS.getRange();
5629     else if (isa<TranslationUnitDecl>(DC))
5630       Diag(Loc, diag::err_invalid_declarator_global_scope)
5631         << Name << SS.getRange();
5632     else if (isa<FunctionDecl>(Cur))
5633       Diag(Loc, diag::err_invalid_declarator_in_function)
5634         << Name << SS.getRange();
5635     else if (isa<BlockDecl>(Cur))
5636       Diag(Loc, diag::err_invalid_declarator_in_block)
5637         << Name << SS.getRange();
5638     else
5639       Diag(Loc, diag::err_invalid_declarator_scope)
5640       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5641 
5642     return true;
5643   }
5644 
5645   if (Cur->isRecord()) {
5646     // Cannot qualify members within a class.
5647     Diag(Loc, diag::err_member_qualification)
5648       << Name << SS.getRange();
5649     SS.clear();
5650 
5651     // C++ constructors and destructors with incorrect scopes can break
5652     // our AST invariants by having the wrong underlying types. If
5653     // that's the case, then drop this declaration entirely.
5654     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5655          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5656         !Context.hasSameType(Name.getCXXNameType(),
5657                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5658       return true;
5659 
5660     return false;
5661   }
5662 
5663   // C++11 [dcl.meaning]p1:
5664   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5665   //   not begin with a decltype-specifer"
5666   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5667   while (SpecLoc.getPrefix())
5668     SpecLoc = SpecLoc.getPrefix();
5669   if (dyn_cast_or_null<DecltypeType>(
5670         SpecLoc.getNestedNameSpecifier()->getAsType()))
5671     Diag(Loc, diag::err_decltype_in_declarator)
5672       << SpecLoc.getTypeLoc().getSourceRange();
5673 
5674   return false;
5675 }
5676 
5677 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5678                                   MultiTemplateParamsArg TemplateParamLists) {
5679   // TODO: consider using NameInfo for diagnostic.
5680   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5681   DeclarationName Name = NameInfo.getName();
5682 
5683   // All of these full declarators require an identifier.  If it doesn't have
5684   // one, the ParsedFreeStandingDeclSpec action should be used.
5685   if (D.isDecompositionDeclarator()) {
5686     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5687   } else if (!Name) {
5688     if (!D.isInvalidType())  // Reject this if we think it is valid.
5689       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5690           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5691     return nullptr;
5692   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5693     return nullptr;
5694 
5695   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5696   // we find one that is.
5697   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5698          (S->getFlags() & Scope::TemplateParamScope) != 0)
5699     S = S->getParent();
5700 
5701   DeclContext *DC = CurContext;
5702   if (D.getCXXScopeSpec().isInvalid())
5703     D.setInvalidType();
5704   else if (D.getCXXScopeSpec().isSet()) {
5705     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5706                                         UPPC_DeclarationQualifier))
5707       return nullptr;
5708 
5709     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5710     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5711     if (!DC || isa<EnumDecl>(DC)) {
5712       // If we could not compute the declaration context, it's because the
5713       // declaration context is dependent but does not refer to a class,
5714       // class template, or class template partial specialization. Complain
5715       // and return early, to avoid the coming semantic disaster.
5716       Diag(D.getIdentifierLoc(),
5717            diag::err_template_qualified_declarator_no_match)
5718         << D.getCXXScopeSpec().getScopeRep()
5719         << D.getCXXScopeSpec().getRange();
5720       return nullptr;
5721     }
5722     bool IsDependentContext = DC->isDependentContext();
5723 
5724     if (!IsDependentContext &&
5725         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5726       return nullptr;
5727 
5728     // If a class is incomplete, do not parse entities inside it.
5729     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5730       Diag(D.getIdentifierLoc(),
5731            diag::err_member_def_undefined_record)
5732         << Name << DC << D.getCXXScopeSpec().getRange();
5733       return nullptr;
5734     }
5735     if (!D.getDeclSpec().isFriendSpecified()) {
5736       if (diagnoseQualifiedDeclaration(
5737               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5738               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5739         if (DC->isRecord())
5740           return nullptr;
5741 
5742         D.setInvalidType();
5743       }
5744     }
5745 
5746     // Check whether we need to rebuild the type of the given
5747     // declaration in the current instantiation.
5748     if (EnteringContext && IsDependentContext &&
5749         TemplateParamLists.size() != 0) {
5750       ContextRAII SavedContext(*this, DC);
5751       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5752         D.setInvalidType();
5753     }
5754   }
5755 
5756   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5757   QualType R = TInfo->getType();
5758 
5759   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5760                                       UPPC_DeclarationType))
5761     D.setInvalidType();
5762 
5763   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5764                         forRedeclarationInCurContext());
5765 
5766   // See if this is a redefinition of a variable in the same scope.
5767   if (!D.getCXXScopeSpec().isSet()) {
5768     bool IsLinkageLookup = false;
5769     bool CreateBuiltins = false;
5770 
5771     // If the declaration we're planning to build will be a function
5772     // or object with linkage, then look for another declaration with
5773     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5774     //
5775     // If the declaration we're planning to build will be declared with
5776     // external linkage in the translation unit, create any builtin with
5777     // the same name.
5778     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5779       /* Do nothing*/;
5780     else if (CurContext->isFunctionOrMethod() &&
5781              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5782               R->isFunctionType())) {
5783       IsLinkageLookup = true;
5784       CreateBuiltins =
5785           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5786     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5787                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5788       CreateBuiltins = true;
5789 
5790     if (IsLinkageLookup) {
5791       Previous.clear(LookupRedeclarationWithLinkage);
5792       Previous.setRedeclarationKind(ForExternalRedeclaration);
5793     }
5794 
5795     LookupName(Previous, S, CreateBuiltins);
5796   } else { // Something like "int foo::x;"
5797     LookupQualifiedName(Previous, DC);
5798 
5799     // C++ [dcl.meaning]p1:
5800     //   When the declarator-id is qualified, the declaration shall refer to a
5801     //  previously declared member of the class or namespace to which the
5802     //  qualifier refers (or, in the case of a namespace, of an element of the
5803     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5804     //  thereof; [...]
5805     //
5806     // Note that we already checked the context above, and that we do not have
5807     // enough information to make sure that Previous contains the declaration
5808     // we want to match. For example, given:
5809     //
5810     //   class X {
5811     //     void f();
5812     //     void f(float);
5813     //   };
5814     //
5815     //   void X::f(int) { } // ill-formed
5816     //
5817     // In this case, Previous will point to the overload set
5818     // containing the two f's declared in X, but neither of them
5819     // matches.
5820 
5821     // C++ [dcl.meaning]p1:
5822     //   [...] the member shall not merely have been introduced by a
5823     //   using-declaration in the scope of the class or namespace nominated by
5824     //   the nested-name-specifier of the declarator-id.
5825     RemoveUsingDecls(Previous);
5826   }
5827 
5828   if (Previous.isSingleResult() &&
5829       Previous.getFoundDecl()->isTemplateParameter()) {
5830     // Maybe we will complain about the shadowed template parameter.
5831     if (!D.isInvalidType())
5832       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5833                                       Previous.getFoundDecl());
5834 
5835     // Just pretend that we didn't see the previous declaration.
5836     Previous.clear();
5837   }
5838 
5839   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5840     // Forget that the previous declaration is the injected-class-name.
5841     Previous.clear();
5842 
5843   // In C++, the previous declaration we find might be a tag type
5844   // (class or enum). In this case, the new declaration will hide the
5845   // tag type. Note that this applies to functions, function templates, and
5846   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5847   if (Previous.isSingleTagDecl() &&
5848       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5849       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5850     Previous.clear();
5851 
5852   // Check that there are no default arguments other than in the parameters
5853   // of a function declaration (C++ only).
5854   if (getLangOpts().CPlusPlus)
5855     CheckExtraCXXDefaultArguments(D);
5856 
5857   NamedDecl *New;
5858 
5859   bool AddToScope = true;
5860   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5861     if (TemplateParamLists.size()) {
5862       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5863       return nullptr;
5864     }
5865 
5866     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5867   } else if (R->isFunctionType()) {
5868     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5869                                   TemplateParamLists,
5870                                   AddToScope);
5871   } else {
5872     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5873                                   AddToScope);
5874   }
5875 
5876   if (!New)
5877     return nullptr;
5878 
5879   // If this has an identifier and is not a function template specialization,
5880   // add it to the scope stack.
5881   if (New->getDeclName() && AddToScope)
5882     PushOnScopeChains(New, S);
5883 
5884   if (isInOpenMPDeclareTargetContext())
5885     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5886 
5887   return New;
5888 }
5889 
5890 /// Helper method to turn variable array types into constant array
5891 /// types in certain situations which would otherwise be errors (for
5892 /// GCC compatibility).
5893 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5894                                                     ASTContext &Context,
5895                                                     bool &SizeIsNegative,
5896                                                     llvm::APSInt &Oversized) {
5897   // This method tries to turn a variable array into a constant
5898   // array even when the size isn't an ICE.  This is necessary
5899   // for compatibility with code that depends on gcc's buggy
5900   // constant expression folding, like struct {char x[(int)(char*)2];}
5901   SizeIsNegative = false;
5902   Oversized = 0;
5903 
5904   if (T->isDependentType())
5905     return QualType();
5906 
5907   QualifierCollector Qs;
5908   const Type *Ty = Qs.strip(T);
5909 
5910   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5911     QualType Pointee = PTy->getPointeeType();
5912     QualType FixedType =
5913         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5914                                             Oversized);
5915     if (FixedType.isNull()) return FixedType;
5916     FixedType = Context.getPointerType(FixedType);
5917     return Qs.apply(Context, FixedType);
5918   }
5919   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5920     QualType Inner = PTy->getInnerType();
5921     QualType FixedType =
5922         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5923                                             Oversized);
5924     if (FixedType.isNull()) return FixedType;
5925     FixedType = Context.getParenType(FixedType);
5926     return Qs.apply(Context, FixedType);
5927   }
5928 
5929   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5930   if (!VLATy)
5931     return QualType();
5932   // FIXME: We should probably handle this case
5933   if (VLATy->getElementType()->isVariablyModifiedType())
5934     return QualType();
5935 
5936   Expr::EvalResult Result;
5937   if (!VLATy->getSizeExpr() ||
5938       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5939     return QualType();
5940 
5941   llvm::APSInt Res = Result.Val.getInt();
5942 
5943   // Check whether the array size is negative.
5944   if (Res.isSigned() && Res.isNegative()) {
5945     SizeIsNegative = true;
5946     return QualType();
5947   }
5948 
5949   // Check whether the array is too large to be addressed.
5950   unsigned ActiveSizeBits
5951     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5952                                               Res);
5953   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5954     Oversized = Res;
5955     return QualType();
5956   }
5957 
5958   return Context.getConstantArrayType(
5959       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5960 }
5961 
5962 static void
5963 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5964   SrcTL = SrcTL.getUnqualifiedLoc();
5965   DstTL = DstTL.getUnqualifiedLoc();
5966   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5967     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5968     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5969                                       DstPTL.getPointeeLoc());
5970     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5971     return;
5972   }
5973   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5974     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5975     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5976                                       DstPTL.getInnerLoc());
5977     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5978     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5979     return;
5980   }
5981   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5982   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5983   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5984   TypeLoc DstElemTL = DstATL.getElementLoc();
5985   DstElemTL.initializeFullCopy(SrcElemTL);
5986   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5987   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5988   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5989 }
5990 
5991 /// Helper method to turn variable array types into constant array
5992 /// types in certain situations which would otherwise be errors (for
5993 /// GCC compatibility).
5994 static TypeSourceInfo*
5995 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5996                                               ASTContext &Context,
5997                                               bool &SizeIsNegative,
5998                                               llvm::APSInt &Oversized) {
5999   QualType FixedTy
6000     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6001                                           SizeIsNegative, Oversized);
6002   if (FixedTy.isNull())
6003     return nullptr;
6004   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6005   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6006                                     FixedTInfo->getTypeLoc());
6007   return FixedTInfo;
6008 }
6009 
6010 /// Register the given locally-scoped extern "C" declaration so
6011 /// that it can be found later for redeclarations. We include any extern "C"
6012 /// declaration that is not visible in the translation unit here, not just
6013 /// function-scope declarations.
6014 void
6015 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6016   if (!getLangOpts().CPlusPlus &&
6017       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6018     // Don't need to track declarations in the TU in C.
6019     return;
6020 
6021   // Note that we have a locally-scoped external with this name.
6022   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6023 }
6024 
6025 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6026   // FIXME: We can have multiple results via __attribute__((overloadable)).
6027   auto Result = Context.getExternCContextDecl()->lookup(Name);
6028   return Result.empty() ? nullptr : *Result.begin();
6029 }
6030 
6031 /// Diagnose function specifiers on a declaration of an identifier that
6032 /// does not identify a function.
6033 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6034   // FIXME: We should probably indicate the identifier in question to avoid
6035   // confusion for constructs like "virtual int a(), b;"
6036   if (DS.isVirtualSpecified())
6037     Diag(DS.getVirtualSpecLoc(),
6038          diag::err_virtual_non_function);
6039 
6040   if (DS.hasExplicitSpecifier())
6041     Diag(DS.getExplicitSpecLoc(),
6042          diag::err_explicit_non_function);
6043 
6044   if (DS.isNoreturnSpecified())
6045     Diag(DS.getNoreturnSpecLoc(),
6046          diag::err_noreturn_non_function);
6047 }
6048 
6049 NamedDecl*
6050 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6051                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6052   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6053   if (D.getCXXScopeSpec().isSet()) {
6054     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6055       << D.getCXXScopeSpec().getRange();
6056     D.setInvalidType();
6057     // Pretend we didn't see the scope specifier.
6058     DC = CurContext;
6059     Previous.clear();
6060   }
6061 
6062   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6063 
6064   if (D.getDeclSpec().isInlineSpecified())
6065     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6066         << getLangOpts().CPlusPlus17;
6067   if (D.getDeclSpec().hasConstexprSpecifier())
6068     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6069         << 1 << D.getDeclSpec().getConstexprSpecifier();
6070 
6071   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6072     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6073       Diag(D.getName().StartLocation,
6074            diag::err_deduction_guide_invalid_specifier)
6075           << "typedef";
6076     else
6077       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6078           << D.getName().getSourceRange();
6079     return nullptr;
6080   }
6081 
6082   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6083   if (!NewTD) return nullptr;
6084 
6085   // Handle attributes prior to checking for duplicates in MergeVarDecl
6086   ProcessDeclAttributes(S, NewTD, D);
6087 
6088   CheckTypedefForVariablyModifiedType(S, NewTD);
6089 
6090   bool Redeclaration = D.isRedeclaration();
6091   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6092   D.setRedeclaration(Redeclaration);
6093   return ND;
6094 }
6095 
6096 void
6097 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6098   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6099   // then it shall have block scope.
6100   // Note that variably modified types must be fixed before merging the decl so
6101   // that redeclarations will match.
6102   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6103   QualType T = TInfo->getType();
6104   if (T->isVariablyModifiedType()) {
6105     setFunctionHasBranchProtectedScope();
6106 
6107     if (S->getFnParent() == nullptr) {
6108       bool SizeIsNegative;
6109       llvm::APSInt Oversized;
6110       TypeSourceInfo *FixedTInfo =
6111         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6112                                                       SizeIsNegative,
6113                                                       Oversized);
6114       if (FixedTInfo) {
6115         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6116         NewTD->setTypeSourceInfo(FixedTInfo);
6117       } else {
6118         if (SizeIsNegative)
6119           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6120         else if (T->isVariableArrayType())
6121           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6122         else if (Oversized.getBoolValue())
6123           Diag(NewTD->getLocation(), diag::err_array_too_large)
6124             << Oversized.toString(10);
6125         else
6126           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6127         NewTD->setInvalidDecl();
6128       }
6129     }
6130   }
6131 }
6132 
6133 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6134 /// declares a typedef-name, either using the 'typedef' type specifier or via
6135 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6136 NamedDecl*
6137 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6138                            LookupResult &Previous, bool &Redeclaration) {
6139 
6140   // Find the shadowed declaration before filtering for scope.
6141   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6142 
6143   // Merge the decl with the existing one if appropriate. If the decl is
6144   // in an outer scope, it isn't the same thing.
6145   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6146                        /*AllowInlineNamespace*/false);
6147   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6148   if (!Previous.empty()) {
6149     Redeclaration = true;
6150     MergeTypedefNameDecl(S, NewTD, Previous);
6151   } else {
6152     inferGslPointerAttribute(NewTD);
6153   }
6154 
6155   if (ShadowedDecl && !Redeclaration)
6156     CheckShadow(NewTD, ShadowedDecl, Previous);
6157 
6158   // If this is the C FILE type, notify the AST context.
6159   if (IdentifierInfo *II = NewTD->getIdentifier())
6160     if (!NewTD->isInvalidDecl() &&
6161         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6162       if (II->isStr("FILE"))
6163         Context.setFILEDecl(NewTD);
6164       else if (II->isStr("jmp_buf"))
6165         Context.setjmp_bufDecl(NewTD);
6166       else if (II->isStr("sigjmp_buf"))
6167         Context.setsigjmp_bufDecl(NewTD);
6168       else if (II->isStr("ucontext_t"))
6169         Context.setucontext_tDecl(NewTD);
6170     }
6171 
6172   return NewTD;
6173 }
6174 
6175 /// Determines whether the given declaration is an out-of-scope
6176 /// previous declaration.
6177 ///
6178 /// This routine should be invoked when name lookup has found a
6179 /// previous declaration (PrevDecl) that is not in the scope where a
6180 /// new declaration by the same name is being introduced. If the new
6181 /// declaration occurs in a local scope, previous declarations with
6182 /// linkage may still be considered previous declarations (C99
6183 /// 6.2.2p4-5, C++ [basic.link]p6).
6184 ///
6185 /// \param PrevDecl the previous declaration found by name
6186 /// lookup
6187 ///
6188 /// \param DC the context in which the new declaration is being
6189 /// declared.
6190 ///
6191 /// \returns true if PrevDecl is an out-of-scope previous declaration
6192 /// for a new delcaration with the same name.
6193 static bool
6194 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6195                                 ASTContext &Context) {
6196   if (!PrevDecl)
6197     return false;
6198 
6199   if (!PrevDecl->hasLinkage())
6200     return false;
6201 
6202   if (Context.getLangOpts().CPlusPlus) {
6203     // C++ [basic.link]p6:
6204     //   If there is a visible declaration of an entity with linkage
6205     //   having the same name and type, ignoring entities declared
6206     //   outside the innermost enclosing namespace scope, the block
6207     //   scope declaration declares that same entity and receives the
6208     //   linkage of the previous declaration.
6209     DeclContext *OuterContext = DC->getRedeclContext();
6210     if (!OuterContext->isFunctionOrMethod())
6211       // This rule only applies to block-scope declarations.
6212       return false;
6213 
6214     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6215     if (PrevOuterContext->isRecord())
6216       // We found a member function: ignore it.
6217       return false;
6218 
6219     // Find the innermost enclosing namespace for the new and
6220     // previous declarations.
6221     OuterContext = OuterContext->getEnclosingNamespaceContext();
6222     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6223 
6224     // The previous declaration is in a different namespace, so it
6225     // isn't the same function.
6226     if (!OuterContext->Equals(PrevOuterContext))
6227       return false;
6228   }
6229 
6230   return true;
6231 }
6232 
6233 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6234   CXXScopeSpec &SS = D.getCXXScopeSpec();
6235   if (!SS.isSet()) return;
6236   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6237 }
6238 
6239 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6240   QualType type = decl->getType();
6241   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6242   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6243     // Various kinds of declaration aren't allowed to be __autoreleasing.
6244     unsigned kind = -1U;
6245     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6246       if (var->hasAttr<BlocksAttr>())
6247         kind = 0; // __block
6248       else if (!var->hasLocalStorage())
6249         kind = 1; // global
6250     } else if (isa<ObjCIvarDecl>(decl)) {
6251       kind = 3; // ivar
6252     } else if (isa<FieldDecl>(decl)) {
6253       kind = 2; // field
6254     }
6255 
6256     if (kind != -1U) {
6257       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6258         << kind;
6259     }
6260   } else if (lifetime == Qualifiers::OCL_None) {
6261     // Try to infer lifetime.
6262     if (!type->isObjCLifetimeType())
6263       return false;
6264 
6265     lifetime = type->getObjCARCImplicitLifetime();
6266     type = Context.getLifetimeQualifiedType(type, lifetime);
6267     decl->setType(type);
6268   }
6269 
6270   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6271     // Thread-local variables cannot have lifetime.
6272     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6273         var->getTLSKind()) {
6274       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6275         << var->getType();
6276       return true;
6277     }
6278   }
6279 
6280   return false;
6281 }
6282 
6283 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6284   if (Decl->getType().hasAddressSpace())
6285     return;
6286   if (Decl->getType()->isDependentType())
6287     return;
6288   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6289     QualType Type = Var->getType();
6290     if (Type->isSamplerT() || Type->isVoidType())
6291       return;
6292     LangAS ImplAS = LangAS::opencl_private;
6293     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6294         Var->hasGlobalStorage())
6295       ImplAS = LangAS::opencl_global;
6296     // If the original type from a decayed type is an array type and that array
6297     // type has no address space yet, deduce it now.
6298     if (auto DT = dyn_cast<DecayedType>(Type)) {
6299       auto OrigTy = DT->getOriginalType();
6300       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6301         // Add the address space to the original array type and then propagate
6302         // that to the element type through `getAsArrayType`.
6303         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6304         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6305         // Re-generate the decayed type.
6306         Type = Context.getDecayedType(OrigTy);
6307       }
6308     }
6309     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6310     // Apply any qualifiers (including address space) from the array type to
6311     // the element type. This implements C99 6.7.3p8: "If the specification of
6312     // an array type includes any type qualifiers, the element type is so
6313     // qualified, not the array type."
6314     if (Type->isArrayType())
6315       Type = QualType(Context.getAsArrayType(Type), 0);
6316     Decl->setType(Type);
6317   }
6318 }
6319 
6320 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6321   // Ensure that an auto decl is deduced otherwise the checks below might cache
6322   // the wrong linkage.
6323   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6324 
6325   // 'weak' only applies to declarations with external linkage.
6326   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6327     if (!ND.isExternallyVisible()) {
6328       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6329       ND.dropAttr<WeakAttr>();
6330     }
6331   }
6332   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6333     if (ND.isExternallyVisible()) {
6334       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6335       ND.dropAttr<WeakRefAttr>();
6336       ND.dropAttr<AliasAttr>();
6337     }
6338   }
6339 
6340   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6341     if (VD->hasInit()) {
6342       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6343         assert(VD->isThisDeclarationADefinition() &&
6344                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6345         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6346         VD->dropAttr<AliasAttr>();
6347       }
6348     }
6349   }
6350 
6351   // 'selectany' only applies to externally visible variable declarations.
6352   // It does not apply to functions.
6353   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6354     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6355       S.Diag(Attr->getLocation(),
6356              diag::err_attribute_selectany_non_extern_data);
6357       ND.dropAttr<SelectAnyAttr>();
6358     }
6359   }
6360 
6361   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6362     auto *VD = dyn_cast<VarDecl>(&ND);
6363     bool IsAnonymousNS = false;
6364     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6365     if (VD) {
6366       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6367       while (NS && !IsAnonymousNS) {
6368         IsAnonymousNS = NS->isAnonymousNamespace();
6369         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6370       }
6371     }
6372     // dll attributes require external linkage. Static locals may have external
6373     // linkage but still cannot be explicitly imported or exported.
6374     // In Microsoft mode, a variable defined in anonymous namespace must have
6375     // external linkage in order to be exported.
6376     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6377     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6378         (!AnonNSInMicrosoftMode &&
6379          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6380       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6381         << &ND << Attr;
6382       ND.setInvalidDecl();
6383     }
6384   }
6385 
6386   // Virtual functions cannot be marked as 'notail'.
6387   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6388     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6389       if (MD->isVirtual()) {
6390         S.Diag(ND.getLocation(),
6391                diag::err_invalid_attribute_on_virtual_function)
6392             << Attr;
6393         ND.dropAttr<NotTailCalledAttr>();
6394       }
6395 
6396   // Check the attributes on the function type, if any.
6397   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6398     // Don't declare this variable in the second operand of the for-statement;
6399     // GCC miscompiles that by ending its lifetime before evaluating the
6400     // third operand. See gcc.gnu.org/PR86769.
6401     AttributedTypeLoc ATL;
6402     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6403          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6404          TL = ATL.getModifiedLoc()) {
6405       // The [[lifetimebound]] attribute can be applied to the implicit object
6406       // parameter of a non-static member function (other than a ctor or dtor)
6407       // by applying it to the function type.
6408       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6409         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6410         if (!MD || MD->isStatic()) {
6411           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6412               << !MD << A->getRange();
6413         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6414           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6415               << isa<CXXDestructorDecl>(MD) << A->getRange();
6416         }
6417       }
6418     }
6419   }
6420 }
6421 
6422 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6423                                            NamedDecl *NewDecl,
6424                                            bool IsSpecialization,
6425                                            bool IsDefinition) {
6426   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6427     return;
6428 
6429   bool IsTemplate = false;
6430   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6431     OldDecl = OldTD->getTemplatedDecl();
6432     IsTemplate = true;
6433     if (!IsSpecialization)
6434       IsDefinition = false;
6435   }
6436   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6437     NewDecl = NewTD->getTemplatedDecl();
6438     IsTemplate = true;
6439   }
6440 
6441   if (!OldDecl || !NewDecl)
6442     return;
6443 
6444   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6445   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6446   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6447   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6448 
6449   // dllimport and dllexport are inheritable attributes so we have to exclude
6450   // inherited attribute instances.
6451   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6452                     (NewExportAttr && !NewExportAttr->isInherited());
6453 
6454   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6455   // the only exception being explicit specializations.
6456   // Implicitly generated declarations are also excluded for now because there
6457   // is no other way to switch these to use dllimport or dllexport.
6458   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6459 
6460   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6461     // Allow with a warning for free functions and global variables.
6462     bool JustWarn = false;
6463     if (!OldDecl->isCXXClassMember()) {
6464       auto *VD = dyn_cast<VarDecl>(OldDecl);
6465       if (VD && !VD->getDescribedVarTemplate())
6466         JustWarn = true;
6467       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6468       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6469         JustWarn = true;
6470     }
6471 
6472     // We cannot change a declaration that's been used because IR has already
6473     // been emitted. Dllimported functions will still work though (modulo
6474     // address equality) as they can use the thunk.
6475     if (OldDecl->isUsed())
6476       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6477         JustWarn = false;
6478 
6479     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6480                                : diag::err_attribute_dll_redeclaration;
6481     S.Diag(NewDecl->getLocation(), DiagID)
6482         << NewDecl
6483         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6484     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6485     if (!JustWarn) {
6486       NewDecl->setInvalidDecl();
6487       return;
6488     }
6489   }
6490 
6491   // A redeclaration is not allowed to drop a dllimport attribute, the only
6492   // exceptions being inline function definitions (except for function
6493   // templates), local extern declarations, qualified friend declarations or
6494   // special MSVC extension: in the last case, the declaration is treated as if
6495   // it were marked dllexport.
6496   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6497   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6498   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6499     // Ignore static data because out-of-line definitions are diagnosed
6500     // separately.
6501     IsStaticDataMember = VD->isStaticDataMember();
6502     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6503                    VarDecl::DeclarationOnly;
6504   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6505     IsInline = FD->isInlined();
6506     IsQualifiedFriend = FD->getQualifier() &&
6507                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6508   }
6509 
6510   if (OldImportAttr && !HasNewAttr &&
6511       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6512       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6513     if (IsMicrosoft && IsDefinition) {
6514       S.Diag(NewDecl->getLocation(),
6515              diag::warn_redeclaration_without_import_attribute)
6516           << NewDecl;
6517       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6518       NewDecl->dropAttr<DLLImportAttr>();
6519       NewDecl->addAttr(
6520           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6521     } else {
6522       S.Diag(NewDecl->getLocation(),
6523              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6524           << NewDecl << OldImportAttr;
6525       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6526       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6527       OldDecl->dropAttr<DLLImportAttr>();
6528       NewDecl->dropAttr<DLLImportAttr>();
6529     }
6530   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6531     // In MinGW, seeing a function declared inline drops the dllimport
6532     // attribute.
6533     OldDecl->dropAttr<DLLImportAttr>();
6534     NewDecl->dropAttr<DLLImportAttr>();
6535     S.Diag(NewDecl->getLocation(),
6536            diag::warn_dllimport_dropped_from_inline_function)
6537         << NewDecl << OldImportAttr;
6538   }
6539 
6540   // A specialization of a class template member function is processed here
6541   // since it's a redeclaration. If the parent class is dllexport, the
6542   // specialization inherits that attribute. This doesn't happen automatically
6543   // since the parent class isn't instantiated until later.
6544   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6545     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6546         !NewImportAttr && !NewExportAttr) {
6547       if (const DLLExportAttr *ParentExportAttr =
6548               MD->getParent()->getAttr<DLLExportAttr>()) {
6549         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6550         NewAttr->setInherited(true);
6551         NewDecl->addAttr(NewAttr);
6552       }
6553     }
6554   }
6555 }
6556 
6557 /// Given that we are within the definition of the given function,
6558 /// will that definition behave like C99's 'inline', where the
6559 /// definition is discarded except for optimization purposes?
6560 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6561   // Try to avoid calling GetGVALinkageForFunction.
6562 
6563   // All cases of this require the 'inline' keyword.
6564   if (!FD->isInlined()) return false;
6565 
6566   // This is only possible in C++ with the gnu_inline attribute.
6567   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6568     return false;
6569 
6570   // Okay, go ahead and call the relatively-more-expensive function.
6571   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6572 }
6573 
6574 /// Determine whether a variable is extern "C" prior to attaching
6575 /// an initializer. We can't just call isExternC() here, because that
6576 /// will also compute and cache whether the declaration is externally
6577 /// visible, which might change when we attach the initializer.
6578 ///
6579 /// This can only be used if the declaration is known to not be a
6580 /// redeclaration of an internal linkage declaration.
6581 ///
6582 /// For instance:
6583 ///
6584 ///   auto x = []{};
6585 ///
6586 /// Attaching the initializer here makes this declaration not externally
6587 /// visible, because its type has internal linkage.
6588 ///
6589 /// FIXME: This is a hack.
6590 template<typename T>
6591 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6592   if (S.getLangOpts().CPlusPlus) {
6593     // In C++, the overloadable attribute negates the effects of extern "C".
6594     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6595       return false;
6596 
6597     // So do CUDA's host/device attributes.
6598     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6599                                  D->template hasAttr<CUDAHostAttr>()))
6600       return false;
6601   }
6602   return D->isExternC();
6603 }
6604 
6605 static bool shouldConsiderLinkage(const VarDecl *VD) {
6606   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6607   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6608       isa<OMPDeclareMapperDecl>(DC))
6609     return VD->hasExternalStorage();
6610   if (DC->isFileContext())
6611     return true;
6612   if (DC->isRecord())
6613     return false;
6614   if (isa<RequiresExprBodyDecl>(DC))
6615     return false;
6616   llvm_unreachable("Unexpected context");
6617 }
6618 
6619 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6620   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6621   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6622       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6623     return true;
6624   if (DC->isRecord())
6625     return false;
6626   llvm_unreachable("Unexpected context");
6627 }
6628 
6629 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6630                           ParsedAttr::Kind Kind) {
6631   // Check decl attributes on the DeclSpec.
6632   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6633     return true;
6634 
6635   // Walk the declarator structure, checking decl attributes that were in a type
6636   // position to the decl itself.
6637   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6638     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6639       return true;
6640   }
6641 
6642   // Finally, check attributes on the decl itself.
6643   return PD.getAttributes().hasAttribute(Kind);
6644 }
6645 
6646 /// Adjust the \c DeclContext for a function or variable that might be a
6647 /// function-local external declaration.
6648 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6649   if (!DC->isFunctionOrMethod())
6650     return false;
6651 
6652   // If this is a local extern function or variable declared within a function
6653   // template, don't add it into the enclosing namespace scope until it is
6654   // instantiated; it might have a dependent type right now.
6655   if (DC->isDependentContext())
6656     return true;
6657 
6658   // C++11 [basic.link]p7:
6659   //   When a block scope declaration of an entity with linkage is not found to
6660   //   refer to some other declaration, then that entity is a member of the
6661   //   innermost enclosing namespace.
6662   //
6663   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6664   // semantically-enclosing namespace, not a lexically-enclosing one.
6665   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6666     DC = DC->getParent();
6667   return true;
6668 }
6669 
6670 /// Returns true if given declaration has external C language linkage.
6671 static bool isDeclExternC(const Decl *D) {
6672   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6673     return FD->isExternC();
6674   if (const auto *VD = dyn_cast<VarDecl>(D))
6675     return VD->isExternC();
6676 
6677   llvm_unreachable("Unknown type of decl!");
6678 }
6679 /// Returns true if there hasn't been any invalid type diagnosed.
6680 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6681                                 DeclContext *DC, QualType R) {
6682   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6683   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6684   // argument.
6685   if (R->isImageType() || R->isPipeType()) {
6686     Se.Diag(D.getIdentifierLoc(),
6687             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6688         << R;
6689     D.setInvalidType();
6690     return false;
6691   }
6692 
6693   // OpenCL v1.2 s6.9.r:
6694   // The event type cannot be used to declare a program scope variable.
6695   // OpenCL v2.0 s6.9.q:
6696   // The clk_event_t and reserve_id_t types cannot be declared in program
6697   // scope.
6698   if (NULL == S->getParent()) {
6699     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6700       Se.Diag(D.getIdentifierLoc(),
6701               diag::err_invalid_type_for_program_scope_var)
6702           << R;
6703       D.setInvalidType();
6704       return false;
6705     }
6706   }
6707 
6708   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6709   QualType NR = R;
6710   while (NR->isPointerType()) {
6711     if (NR->isFunctionPointerType()) {
6712       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6713       D.setInvalidType();
6714       return false;
6715     }
6716     NR = NR->getPointeeType();
6717   }
6718 
6719   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6720     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6721     // half array type (unless the cl_khr_fp16 extension is enabled).
6722     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6723       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6724       D.setInvalidType();
6725       return false;
6726     }
6727   }
6728 
6729   // OpenCL v1.2 s6.9.r:
6730   // The event type cannot be used with the __local, __constant and __global
6731   // address space qualifiers.
6732   if (R->isEventT()) {
6733     if (R.getAddressSpace() != LangAS::opencl_private) {
6734       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6735       D.setInvalidType();
6736       return false;
6737     }
6738   }
6739 
6740   // C++ for OpenCL does not allow the thread_local storage qualifier.
6741   // OpenCL C does not support thread_local either, and
6742   // also reject all other thread storage class specifiers.
6743   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6744   if (TSC != TSCS_unspecified) {
6745     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6746     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6747             diag::err_opencl_unknown_type_specifier)
6748         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6749         << DeclSpec::getSpecifierName(TSC) << 1;
6750     D.setInvalidType();
6751     return false;
6752   }
6753 
6754   if (R->isSamplerT()) {
6755     // OpenCL v1.2 s6.9.b p4:
6756     // The sampler type cannot be used with the __local and __global address
6757     // space qualifiers.
6758     if (R.getAddressSpace() == LangAS::opencl_local ||
6759         R.getAddressSpace() == LangAS::opencl_global) {
6760       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6761       D.setInvalidType();
6762     }
6763 
6764     // OpenCL v1.2 s6.12.14.1:
6765     // A global sampler must be declared with either the constant address
6766     // space qualifier or with the const qualifier.
6767     if (DC->isTranslationUnit() &&
6768         !(R.getAddressSpace() == LangAS::opencl_constant ||
6769           R.isConstQualified())) {
6770       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6771       D.setInvalidType();
6772     }
6773     if (D.isInvalidType())
6774       return false;
6775   }
6776   return true;
6777 }
6778 
6779 NamedDecl *Sema::ActOnVariableDeclarator(
6780     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6781     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6782     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6783   QualType R = TInfo->getType();
6784   DeclarationName Name = GetNameForDeclarator(D).getName();
6785 
6786   IdentifierInfo *II = Name.getAsIdentifierInfo();
6787 
6788   if (D.isDecompositionDeclarator()) {
6789     // Take the name of the first declarator as our name for diagnostic
6790     // purposes.
6791     auto &Decomp = D.getDecompositionDeclarator();
6792     if (!Decomp.bindings().empty()) {
6793       II = Decomp.bindings()[0].Name;
6794       Name = II;
6795     }
6796   } else if (!II) {
6797     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6798     return nullptr;
6799   }
6800 
6801 
6802   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6803   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6804 
6805   // dllimport globals without explicit storage class are treated as extern. We
6806   // have to change the storage class this early to get the right DeclContext.
6807   if (SC == SC_None && !DC->isRecord() &&
6808       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6809       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6810     SC = SC_Extern;
6811 
6812   DeclContext *OriginalDC = DC;
6813   bool IsLocalExternDecl = SC == SC_Extern &&
6814                            adjustContextForLocalExternDecl(DC);
6815 
6816   if (SCSpec == DeclSpec::SCS_mutable) {
6817     // mutable can only appear on non-static class members, so it's always
6818     // an error here
6819     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6820     D.setInvalidType();
6821     SC = SC_None;
6822   }
6823 
6824   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6825       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6826                               D.getDeclSpec().getStorageClassSpecLoc())) {
6827     // In C++11, the 'register' storage class specifier is deprecated.
6828     // Suppress the warning in system macros, it's used in macros in some
6829     // popular C system headers, such as in glibc's htonl() macro.
6830     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6831          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6832                                    : diag::warn_deprecated_register)
6833       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6834   }
6835 
6836   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6837 
6838   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6839     // C99 6.9p2: The storage-class specifiers auto and register shall not
6840     // appear in the declaration specifiers in an external declaration.
6841     // Global Register+Asm is a GNU extension we support.
6842     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6843       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6844       D.setInvalidType();
6845     }
6846   }
6847 
6848   bool IsMemberSpecialization = false;
6849   bool IsVariableTemplateSpecialization = false;
6850   bool IsPartialSpecialization = false;
6851   bool IsVariableTemplate = false;
6852   VarDecl *NewVD = nullptr;
6853   VarTemplateDecl *NewTemplate = nullptr;
6854   TemplateParameterList *TemplateParams = nullptr;
6855   if (!getLangOpts().CPlusPlus) {
6856     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6857                             II, R, TInfo, SC);
6858 
6859     if (R->getContainedDeducedType())
6860       ParsingInitForAutoVars.insert(NewVD);
6861 
6862     if (D.isInvalidType())
6863       NewVD->setInvalidDecl();
6864 
6865     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6866         NewVD->hasLocalStorage())
6867       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6868                             NTCUC_AutoVar, NTCUK_Destruct);
6869   } else {
6870     bool Invalid = false;
6871 
6872     if (DC->isRecord() && !CurContext->isRecord()) {
6873       // This is an out-of-line definition of a static data member.
6874       switch (SC) {
6875       case SC_None:
6876         break;
6877       case SC_Static:
6878         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6879              diag::err_static_out_of_line)
6880           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6881         break;
6882       case SC_Auto:
6883       case SC_Register:
6884       case SC_Extern:
6885         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6886         // to names of variables declared in a block or to function parameters.
6887         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6888         // of class members
6889 
6890         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6891              diag::err_storage_class_for_static_member)
6892           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6893         break;
6894       case SC_PrivateExtern:
6895         llvm_unreachable("C storage class in c++!");
6896       }
6897     }
6898 
6899     if (SC == SC_Static && CurContext->isRecord()) {
6900       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6901         // Walk up the enclosing DeclContexts to check for any that are
6902         // incompatible with static data members.
6903         const DeclContext *FunctionOrMethod = nullptr;
6904         const CXXRecordDecl *AnonStruct = nullptr;
6905         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6906           if (Ctxt->isFunctionOrMethod()) {
6907             FunctionOrMethod = Ctxt;
6908             break;
6909           }
6910           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6911           if (ParentDecl && !ParentDecl->getDeclName()) {
6912             AnonStruct = ParentDecl;
6913             break;
6914           }
6915         }
6916         if (FunctionOrMethod) {
6917           // C++ [class.static.data]p5: A local class shall not have static data
6918           // members.
6919           Diag(D.getIdentifierLoc(),
6920                diag::err_static_data_member_not_allowed_in_local_class)
6921             << Name << RD->getDeclName() << RD->getTagKind();
6922         } else if (AnonStruct) {
6923           // C++ [class.static.data]p4: Unnamed classes and classes contained
6924           // directly or indirectly within unnamed classes shall not contain
6925           // static data members.
6926           Diag(D.getIdentifierLoc(),
6927                diag::err_static_data_member_not_allowed_in_anon_struct)
6928             << Name << AnonStruct->getTagKind();
6929           Invalid = true;
6930         } else if (RD->isUnion()) {
6931           // C++98 [class.union]p1: If a union contains a static data member,
6932           // the program is ill-formed. C++11 drops this restriction.
6933           Diag(D.getIdentifierLoc(),
6934                getLangOpts().CPlusPlus11
6935                  ? diag::warn_cxx98_compat_static_data_member_in_union
6936                  : diag::ext_static_data_member_in_union) << Name;
6937         }
6938       }
6939     }
6940 
6941     // Match up the template parameter lists with the scope specifier, then
6942     // determine whether we have a template or a template specialization.
6943     bool InvalidScope = false;
6944     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6945         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6946         D.getCXXScopeSpec(),
6947         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6948             ? D.getName().TemplateId
6949             : nullptr,
6950         TemplateParamLists,
6951         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6952     Invalid |= InvalidScope;
6953 
6954     if (TemplateParams) {
6955       if (!TemplateParams->size() &&
6956           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6957         // There is an extraneous 'template<>' for this variable. Complain
6958         // about it, but allow the declaration of the variable.
6959         Diag(TemplateParams->getTemplateLoc(),
6960              diag::err_template_variable_noparams)
6961           << II
6962           << SourceRange(TemplateParams->getTemplateLoc(),
6963                          TemplateParams->getRAngleLoc());
6964         TemplateParams = nullptr;
6965       } else {
6966         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6967           // This is an explicit specialization or a partial specialization.
6968           // FIXME: Check that we can declare a specialization here.
6969           IsVariableTemplateSpecialization = true;
6970           IsPartialSpecialization = TemplateParams->size() > 0;
6971         } else { // if (TemplateParams->size() > 0)
6972           // This is a template declaration.
6973           IsVariableTemplate = true;
6974 
6975           // Check that we can declare a template here.
6976           if (CheckTemplateDeclScope(S, TemplateParams))
6977             return nullptr;
6978 
6979           // Only C++1y supports variable templates (N3651).
6980           Diag(D.getIdentifierLoc(),
6981                getLangOpts().CPlusPlus14
6982                    ? diag::warn_cxx11_compat_variable_template
6983                    : diag::ext_variable_template);
6984         }
6985       }
6986     } else {
6987       assert((Invalid ||
6988               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6989              "should have a 'template<>' for this decl");
6990     }
6991 
6992     if (IsVariableTemplateSpecialization) {
6993       SourceLocation TemplateKWLoc =
6994           TemplateParamLists.size() > 0
6995               ? TemplateParamLists[0]->getTemplateLoc()
6996               : SourceLocation();
6997       DeclResult Res = ActOnVarTemplateSpecialization(
6998           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6999           IsPartialSpecialization);
7000       if (Res.isInvalid())
7001         return nullptr;
7002       NewVD = cast<VarDecl>(Res.get());
7003       AddToScope = false;
7004     } else if (D.isDecompositionDeclarator()) {
7005       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7006                                         D.getIdentifierLoc(), R, TInfo, SC,
7007                                         Bindings);
7008     } else
7009       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7010                               D.getIdentifierLoc(), II, R, TInfo, SC);
7011 
7012     // If this is supposed to be a variable template, create it as such.
7013     if (IsVariableTemplate) {
7014       NewTemplate =
7015           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7016                                   TemplateParams, NewVD);
7017       NewVD->setDescribedVarTemplate(NewTemplate);
7018     }
7019 
7020     // If this decl has an auto type in need of deduction, make a note of the
7021     // Decl so we can diagnose uses of it in its own initializer.
7022     if (R->getContainedDeducedType())
7023       ParsingInitForAutoVars.insert(NewVD);
7024 
7025     if (D.isInvalidType() || Invalid) {
7026       NewVD->setInvalidDecl();
7027       if (NewTemplate)
7028         NewTemplate->setInvalidDecl();
7029     }
7030 
7031     SetNestedNameSpecifier(*this, NewVD, D);
7032 
7033     // If we have any template parameter lists that don't directly belong to
7034     // the variable (matching the scope specifier), store them.
7035     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7036     if (TemplateParamLists.size() > VDTemplateParamLists)
7037       NewVD->setTemplateParameterListsInfo(
7038           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7039   }
7040 
7041   if (D.getDeclSpec().isInlineSpecified()) {
7042     if (!getLangOpts().CPlusPlus) {
7043       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7044           << 0;
7045     } else if (CurContext->isFunctionOrMethod()) {
7046       // 'inline' is not allowed on block scope variable declaration.
7047       Diag(D.getDeclSpec().getInlineSpecLoc(),
7048            diag::err_inline_declaration_block_scope) << Name
7049         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7050     } else {
7051       Diag(D.getDeclSpec().getInlineSpecLoc(),
7052            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7053                                      : diag::ext_inline_variable);
7054       NewVD->setInlineSpecified();
7055     }
7056   }
7057 
7058   // Set the lexical context. If the declarator has a C++ scope specifier, the
7059   // lexical context will be different from the semantic context.
7060   NewVD->setLexicalDeclContext(CurContext);
7061   if (NewTemplate)
7062     NewTemplate->setLexicalDeclContext(CurContext);
7063 
7064   if (IsLocalExternDecl) {
7065     if (D.isDecompositionDeclarator())
7066       for (auto *B : Bindings)
7067         B->setLocalExternDecl();
7068     else
7069       NewVD->setLocalExternDecl();
7070   }
7071 
7072   bool EmitTLSUnsupportedError = false;
7073   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7074     // C++11 [dcl.stc]p4:
7075     //   When thread_local is applied to a variable of block scope the
7076     //   storage-class-specifier static is implied if it does not appear
7077     //   explicitly.
7078     // Core issue: 'static' is not implied if the variable is declared
7079     //   'extern'.
7080     if (NewVD->hasLocalStorage() &&
7081         (SCSpec != DeclSpec::SCS_unspecified ||
7082          TSCS != DeclSpec::TSCS_thread_local ||
7083          !DC->isFunctionOrMethod()))
7084       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7085            diag::err_thread_non_global)
7086         << DeclSpec::getSpecifierName(TSCS);
7087     else if (!Context.getTargetInfo().isTLSSupported()) {
7088       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7089           getLangOpts().SYCLIsDevice) {
7090         // Postpone error emission until we've collected attributes required to
7091         // figure out whether it's a host or device variable and whether the
7092         // error should be ignored.
7093         EmitTLSUnsupportedError = true;
7094         // We still need to mark the variable as TLS so it shows up in AST with
7095         // proper storage class for other tools to use even if we're not going
7096         // to emit any code for it.
7097         NewVD->setTSCSpec(TSCS);
7098       } else
7099         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7100              diag::err_thread_unsupported);
7101     } else
7102       NewVD->setTSCSpec(TSCS);
7103   }
7104 
7105   switch (D.getDeclSpec().getConstexprSpecifier()) {
7106   case CSK_unspecified:
7107     break;
7108 
7109   case CSK_consteval:
7110     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7111         diag::err_constexpr_wrong_decl_kind)
7112       << D.getDeclSpec().getConstexprSpecifier();
7113     LLVM_FALLTHROUGH;
7114 
7115   case CSK_constexpr:
7116     NewVD->setConstexpr(true);
7117     MaybeAddCUDAConstantAttr(NewVD);
7118     // C++1z [dcl.spec.constexpr]p1:
7119     //   A static data member declared with the constexpr specifier is
7120     //   implicitly an inline variable.
7121     if (NewVD->isStaticDataMember() &&
7122         (getLangOpts().CPlusPlus17 ||
7123          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7124       NewVD->setImplicitlyInline();
7125     break;
7126 
7127   case CSK_constinit:
7128     if (!NewVD->hasGlobalStorage())
7129       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7130            diag::err_constinit_local_variable);
7131     else
7132       NewVD->addAttr(ConstInitAttr::Create(
7133           Context, D.getDeclSpec().getConstexprSpecLoc(),
7134           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7135     break;
7136   }
7137 
7138   // C99 6.7.4p3
7139   //   An inline definition of a function with external linkage shall
7140   //   not contain a definition of a modifiable object with static or
7141   //   thread storage duration...
7142   // We only apply this when the function is required to be defined
7143   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7144   // that a local variable with thread storage duration still has to
7145   // be marked 'static'.  Also note that it's possible to get these
7146   // semantics in C++ using __attribute__((gnu_inline)).
7147   if (SC == SC_Static && S->getFnParent() != nullptr &&
7148       !NewVD->getType().isConstQualified()) {
7149     FunctionDecl *CurFD = getCurFunctionDecl();
7150     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7151       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7152            diag::warn_static_local_in_extern_inline);
7153       MaybeSuggestAddingStaticToDecl(CurFD);
7154     }
7155   }
7156 
7157   if (D.getDeclSpec().isModulePrivateSpecified()) {
7158     if (IsVariableTemplateSpecialization)
7159       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7160           << (IsPartialSpecialization ? 1 : 0)
7161           << FixItHint::CreateRemoval(
7162                  D.getDeclSpec().getModulePrivateSpecLoc());
7163     else if (IsMemberSpecialization)
7164       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7165         << 2
7166         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7167     else if (NewVD->hasLocalStorage())
7168       Diag(NewVD->getLocation(), diag::err_module_private_local)
7169         << 0 << NewVD->getDeclName()
7170         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7171         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7172     else {
7173       NewVD->setModulePrivate();
7174       if (NewTemplate)
7175         NewTemplate->setModulePrivate();
7176       for (auto *B : Bindings)
7177         B->setModulePrivate();
7178     }
7179   }
7180 
7181   if (getLangOpts().OpenCL) {
7182 
7183     deduceOpenCLAddressSpace(NewVD);
7184 
7185     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7186   }
7187 
7188   // Handle attributes prior to checking for duplicates in MergeVarDecl
7189   ProcessDeclAttributes(S, NewVD, D);
7190 
7191   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7192       getLangOpts().SYCLIsDevice) {
7193     if (EmitTLSUnsupportedError &&
7194         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7195          (getLangOpts().OpenMPIsDevice &&
7196           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7197       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7198            diag::err_thread_unsupported);
7199 
7200     if (EmitTLSUnsupportedError &&
7201         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7202       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7203     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7204     // storage [duration]."
7205     if (SC == SC_None && S->getFnParent() != nullptr &&
7206         (NewVD->hasAttr<CUDASharedAttr>() ||
7207          NewVD->hasAttr<CUDAConstantAttr>())) {
7208       NewVD->setStorageClass(SC_Static);
7209     }
7210   }
7211 
7212   // Ensure that dllimport globals without explicit storage class are treated as
7213   // extern. The storage class is set above using parsed attributes. Now we can
7214   // check the VarDecl itself.
7215   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7216          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7217          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7218 
7219   // In auto-retain/release, infer strong retension for variables of
7220   // retainable type.
7221   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7222     NewVD->setInvalidDecl();
7223 
7224   // Handle GNU asm-label extension (encoded as an attribute).
7225   if (Expr *E = (Expr*)D.getAsmLabel()) {
7226     // The parser guarantees this is a string.
7227     StringLiteral *SE = cast<StringLiteral>(E);
7228     StringRef Label = SE->getString();
7229     if (S->getFnParent() != nullptr) {
7230       switch (SC) {
7231       case SC_None:
7232       case SC_Auto:
7233         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7234         break;
7235       case SC_Register:
7236         // Local Named register
7237         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7238             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7239           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7240         break;
7241       case SC_Static:
7242       case SC_Extern:
7243       case SC_PrivateExtern:
7244         break;
7245       }
7246     } else if (SC == SC_Register) {
7247       // Global Named register
7248       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7249         const auto &TI = Context.getTargetInfo();
7250         bool HasSizeMismatch;
7251 
7252         if (!TI.isValidGCCRegisterName(Label))
7253           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7254         else if (!TI.validateGlobalRegisterVariable(Label,
7255                                                     Context.getTypeSize(R),
7256                                                     HasSizeMismatch))
7257           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7258         else if (HasSizeMismatch)
7259           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7260       }
7261 
7262       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7263         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7264         NewVD->setInvalidDecl(true);
7265       }
7266     }
7267 
7268     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7269                                         /*IsLiteralLabel=*/true,
7270                                         SE->getStrTokenLoc(0)));
7271   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7272     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7273       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7274     if (I != ExtnameUndeclaredIdentifiers.end()) {
7275       if (isDeclExternC(NewVD)) {
7276         NewVD->addAttr(I->second);
7277         ExtnameUndeclaredIdentifiers.erase(I);
7278       } else
7279         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7280             << /*Variable*/1 << NewVD;
7281     }
7282   }
7283 
7284   // Find the shadowed declaration before filtering for scope.
7285   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7286                                 ? getShadowedDeclaration(NewVD, Previous)
7287                                 : nullptr;
7288 
7289   // Don't consider existing declarations that are in a different
7290   // scope and are out-of-semantic-context declarations (if the new
7291   // declaration has linkage).
7292   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7293                        D.getCXXScopeSpec().isNotEmpty() ||
7294                        IsMemberSpecialization ||
7295                        IsVariableTemplateSpecialization);
7296 
7297   // Check whether the previous declaration is in the same block scope. This
7298   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7299   if (getLangOpts().CPlusPlus &&
7300       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7301     NewVD->setPreviousDeclInSameBlockScope(
7302         Previous.isSingleResult() && !Previous.isShadowed() &&
7303         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7304 
7305   if (!getLangOpts().CPlusPlus) {
7306     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7307   } else {
7308     // If this is an explicit specialization of a static data member, check it.
7309     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7310         CheckMemberSpecialization(NewVD, Previous))
7311       NewVD->setInvalidDecl();
7312 
7313     // Merge the decl with the existing one if appropriate.
7314     if (!Previous.empty()) {
7315       if (Previous.isSingleResult() &&
7316           isa<FieldDecl>(Previous.getFoundDecl()) &&
7317           D.getCXXScopeSpec().isSet()) {
7318         // The user tried to define a non-static data member
7319         // out-of-line (C++ [dcl.meaning]p1).
7320         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7321           << D.getCXXScopeSpec().getRange();
7322         Previous.clear();
7323         NewVD->setInvalidDecl();
7324       }
7325     } else if (D.getCXXScopeSpec().isSet()) {
7326       // No previous declaration in the qualifying scope.
7327       Diag(D.getIdentifierLoc(), diag::err_no_member)
7328         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7329         << D.getCXXScopeSpec().getRange();
7330       NewVD->setInvalidDecl();
7331     }
7332 
7333     if (!IsVariableTemplateSpecialization)
7334       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7335 
7336     if (NewTemplate) {
7337       VarTemplateDecl *PrevVarTemplate =
7338           NewVD->getPreviousDecl()
7339               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7340               : nullptr;
7341 
7342       // Check the template parameter list of this declaration, possibly
7343       // merging in the template parameter list from the previous variable
7344       // template declaration.
7345       if (CheckTemplateParameterList(
7346               TemplateParams,
7347               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7348                               : nullptr,
7349               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7350                DC->isDependentContext())
7351                   ? TPC_ClassTemplateMember
7352                   : TPC_VarTemplate))
7353         NewVD->setInvalidDecl();
7354 
7355       // If we are providing an explicit specialization of a static variable
7356       // template, make a note of that.
7357       if (PrevVarTemplate &&
7358           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7359         PrevVarTemplate->setMemberSpecialization();
7360     }
7361   }
7362 
7363   // Diagnose shadowed variables iff this isn't a redeclaration.
7364   if (ShadowedDecl && !D.isRedeclaration())
7365     CheckShadow(NewVD, ShadowedDecl, Previous);
7366 
7367   ProcessPragmaWeak(S, NewVD);
7368 
7369   // If this is the first declaration of an extern C variable, update
7370   // the map of such variables.
7371   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7372       isIncompleteDeclExternC(*this, NewVD))
7373     RegisterLocallyScopedExternCDecl(NewVD, S);
7374 
7375   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7376     MangleNumberingContext *MCtx;
7377     Decl *ManglingContextDecl;
7378     std::tie(MCtx, ManglingContextDecl) =
7379         getCurrentMangleNumberContext(NewVD->getDeclContext());
7380     if (MCtx) {
7381       Context.setManglingNumber(
7382           NewVD, MCtx->getManglingNumber(
7383                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7384       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7385     }
7386   }
7387 
7388   // Special handling of variable named 'main'.
7389   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7390       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7391       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7392 
7393     // C++ [basic.start.main]p3
7394     // A program that declares a variable main at global scope is ill-formed.
7395     if (getLangOpts().CPlusPlus)
7396       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7397 
7398     // In C, and external-linkage variable named main results in undefined
7399     // behavior.
7400     else if (NewVD->hasExternalFormalLinkage())
7401       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7402   }
7403 
7404   if (D.isRedeclaration() && !Previous.empty()) {
7405     NamedDecl *Prev = Previous.getRepresentativeDecl();
7406     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7407                                    D.isFunctionDefinition());
7408   }
7409 
7410   if (NewTemplate) {
7411     if (NewVD->isInvalidDecl())
7412       NewTemplate->setInvalidDecl();
7413     ActOnDocumentableDecl(NewTemplate);
7414     return NewTemplate;
7415   }
7416 
7417   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7418     CompleteMemberSpecialization(NewVD, Previous);
7419 
7420   return NewVD;
7421 }
7422 
7423 /// Enum describing the %select options in diag::warn_decl_shadow.
7424 enum ShadowedDeclKind {
7425   SDK_Local,
7426   SDK_Global,
7427   SDK_StaticMember,
7428   SDK_Field,
7429   SDK_Typedef,
7430   SDK_Using
7431 };
7432 
7433 /// Determine what kind of declaration we're shadowing.
7434 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7435                                                 const DeclContext *OldDC) {
7436   if (isa<TypeAliasDecl>(ShadowedDecl))
7437     return SDK_Using;
7438   else if (isa<TypedefDecl>(ShadowedDecl))
7439     return SDK_Typedef;
7440   else if (isa<RecordDecl>(OldDC))
7441     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7442 
7443   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7444 }
7445 
7446 /// Return the location of the capture if the given lambda captures the given
7447 /// variable \p VD, or an invalid source location otherwise.
7448 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7449                                          const VarDecl *VD) {
7450   for (const Capture &Capture : LSI->Captures) {
7451     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7452       return Capture.getLocation();
7453   }
7454   return SourceLocation();
7455 }
7456 
7457 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7458                                      const LookupResult &R) {
7459   // Only diagnose if we're shadowing an unambiguous field or variable.
7460   if (R.getResultKind() != LookupResult::Found)
7461     return false;
7462 
7463   // Return false if warning is ignored.
7464   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7465 }
7466 
7467 /// Return the declaration shadowed by the given variable \p D, or null
7468 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7469 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7470                                         const LookupResult &R) {
7471   if (!shouldWarnIfShadowedDecl(Diags, R))
7472     return nullptr;
7473 
7474   // Don't diagnose declarations at file scope.
7475   if (D->hasGlobalStorage())
7476     return nullptr;
7477 
7478   NamedDecl *ShadowedDecl = R.getFoundDecl();
7479   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7480              ? ShadowedDecl
7481              : nullptr;
7482 }
7483 
7484 /// Return the declaration shadowed by the given typedef \p D, or null
7485 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7486 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7487                                         const LookupResult &R) {
7488   // Don't warn if typedef declaration is part of a class
7489   if (D->getDeclContext()->isRecord())
7490     return nullptr;
7491 
7492   if (!shouldWarnIfShadowedDecl(Diags, R))
7493     return nullptr;
7494 
7495   NamedDecl *ShadowedDecl = R.getFoundDecl();
7496   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7497 }
7498 
7499 /// Diagnose variable or built-in function shadowing.  Implements
7500 /// -Wshadow.
7501 ///
7502 /// This method is called whenever a VarDecl is added to a "useful"
7503 /// scope.
7504 ///
7505 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7506 /// \param R the lookup of the name
7507 ///
7508 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7509                        const LookupResult &R) {
7510   DeclContext *NewDC = D->getDeclContext();
7511 
7512   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7513     // Fields are not shadowed by variables in C++ static methods.
7514     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7515       if (MD->isStatic())
7516         return;
7517 
7518     // Fields shadowed by constructor parameters are a special case. Usually
7519     // the constructor initializes the field with the parameter.
7520     if (isa<CXXConstructorDecl>(NewDC))
7521       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7522         // Remember that this was shadowed so we can either warn about its
7523         // modification or its existence depending on warning settings.
7524         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7525         return;
7526       }
7527   }
7528 
7529   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7530     if (shadowedVar->isExternC()) {
7531       // For shadowing external vars, make sure that we point to the global
7532       // declaration, not a locally scoped extern declaration.
7533       for (auto I : shadowedVar->redecls())
7534         if (I->isFileVarDecl()) {
7535           ShadowedDecl = I;
7536           break;
7537         }
7538     }
7539 
7540   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7541 
7542   unsigned WarningDiag = diag::warn_decl_shadow;
7543   SourceLocation CaptureLoc;
7544   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7545       isa<CXXMethodDecl>(NewDC)) {
7546     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7547       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7548         if (RD->getLambdaCaptureDefault() == LCD_None) {
7549           // Try to avoid warnings for lambdas with an explicit capture list.
7550           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7551           // Warn only when the lambda captures the shadowed decl explicitly.
7552           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7553           if (CaptureLoc.isInvalid())
7554             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7555         } else {
7556           // Remember that this was shadowed so we can avoid the warning if the
7557           // shadowed decl isn't captured and the warning settings allow it.
7558           cast<LambdaScopeInfo>(getCurFunction())
7559               ->ShadowingDecls.push_back(
7560                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7561           return;
7562         }
7563       }
7564 
7565       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7566         // A variable can't shadow a local variable in an enclosing scope, if
7567         // they are separated by a non-capturing declaration context.
7568         for (DeclContext *ParentDC = NewDC;
7569              ParentDC && !ParentDC->Equals(OldDC);
7570              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7571           // Only block literals, captured statements, and lambda expressions
7572           // can capture; other scopes don't.
7573           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7574               !isLambdaCallOperator(ParentDC)) {
7575             return;
7576           }
7577         }
7578       }
7579     }
7580   }
7581 
7582   // Only warn about certain kinds of shadowing for class members.
7583   if (NewDC && NewDC->isRecord()) {
7584     // In particular, don't warn about shadowing non-class members.
7585     if (!OldDC->isRecord())
7586       return;
7587 
7588     // TODO: should we warn about static data members shadowing
7589     // static data members from base classes?
7590 
7591     // TODO: don't diagnose for inaccessible shadowed members.
7592     // This is hard to do perfectly because we might friend the
7593     // shadowing context, but that's just a false negative.
7594   }
7595 
7596 
7597   DeclarationName Name = R.getLookupName();
7598 
7599   // Emit warning and note.
7600   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7601     return;
7602   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7603   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7604   if (!CaptureLoc.isInvalid())
7605     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7606         << Name << /*explicitly*/ 1;
7607   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7608 }
7609 
7610 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7611 /// when these variables are captured by the lambda.
7612 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7613   for (const auto &Shadow : LSI->ShadowingDecls) {
7614     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7615     // Try to avoid the warning when the shadowed decl isn't captured.
7616     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7617     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7618     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7619                                        ? diag::warn_decl_shadow_uncaptured_local
7620                                        : diag::warn_decl_shadow)
7621         << Shadow.VD->getDeclName()
7622         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7623     if (!CaptureLoc.isInvalid())
7624       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7625           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7626     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7627   }
7628 }
7629 
7630 /// Check -Wshadow without the advantage of a previous lookup.
7631 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7632   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7633     return;
7634 
7635   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7636                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7637   LookupName(R, S);
7638   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7639     CheckShadow(D, ShadowedDecl, R);
7640 }
7641 
7642 /// Check if 'E', which is an expression that is about to be modified, refers
7643 /// to a constructor parameter that shadows a field.
7644 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7645   // Quickly ignore expressions that can't be shadowing ctor parameters.
7646   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7647     return;
7648   E = E->IgnoreParenImpCasts();
7649   auto *DRE = dyn_cast<DeclRefExpr>(E);
7650   if (!DRE)
7651     return;
7652   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7653   auto I = ShadowingDecls.find(D);
7654   if (I == ShadowingDecls.end())
7655     return;
7656   const NamedDecl *ShadowedDecl = I->second;
7657   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7658   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7659   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7660   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7661 
7662   // Avoid issuing multiple warnings about the same decl.
7663   ShadowingDecls.erase(I);
7664 }
7665 
7666 /// Check for conflict between this global or extern "C" declaration and
7667 /// previous global or extern "C" declarations. This is only used in C++.
7668 template<typename T>
7669 static bool checkGlobalOrExternCConflict(
7670     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7671   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7672   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7673 
7674   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7675     // The common case: this global doesn't conflict with any extern "C"
7676     // declaration.
7677     return false;
7678   }
7679 
7680   if (Prev) {
7681     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7682       // Both the old and new declarations have C language linkage. This is a
7683       // redeclaration.
7684       Previous.clear();
7685       Previous.addDecl(Prev);
7686       return true;
7687     }
7688 
7689     // This is a global, non-extern "C" declaration, and there is a previous
7690     // non-global extern "C" declaration. Diagnose if this is a variable
7691     // declaration.
7692     if (!isa<VarDecl>(ND))
7693       return false;
7694   } else {
7695     // The declaration is extern "C". Check for any declaration in the
7696     // translation unit which might conflict.
7697     if (IsGlobal) {
7698       // We have already performed the lookup into the translation unit.
7699       IsGlobal = false;
7700       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7701            I != E; ++I) {
7702         if (isa<VarDecl>(*I)) {
7703           Prev = *I;
7704           break;
7705         }
7706       }
7707     } else {
7708       DeclContext::lookup_result R =
7709           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7710       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7711            I != E; ++I) {
7712         if (isa<VarDecl>(*I)) {
7713           Prev = *I;
7714           break;
7715         }
7716         // FIXME: If we have any other entity with this name in global scope,
7717         // the declaration is ill-formed, but that is a defect: it breaks the
7718         // 'stat' hack, for instance. Only variables can have mangled name
7719         // clashes with extern "C" declarations, so only they deserve a
7720         // diagnostic.
7721       }
7722     }
7723 
7724     if (!Prev)
7725       return false;
7726   }
7727 
7728   // Use the first declaration's location to ensure we point at something which
7729   // is lexically inside an extern "C" linkage-spec.
7730   assert(Prev && "should have found a previous declaration to diagnose");
7731   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7732     Prev = FD->getFirstDecl();
7733   else
7734     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7735 
7736   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7737     << IsGlobal << ND;
7738   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7739     << IsGlobal;
7740   return false;
7741 }
7742 
7743 /// Apply special rules for handling extern "C" declarations. Returns \c true
7744 /// if we have found that this is a redeclaration of some prior entity.
7745 ///
7746 /// Per C++ [dcl.link]p6:
7747 ///   Two declarations [for a function or variable] with C language linkage
7748 ///   with the same name that appear in different scopes refer to the same
7749 ///   [entity]. An entity with C language linkage shall not be declared with
7750 ///   the same name as an entity in global scope.
7751 template<typename T>
7752 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7753                                                   LookupResult &Previous) {
7754   if (!S.getLangOpts().CPlusPlus) {
7755     // In C, when declaring a global variable, look for a corresponding 'extern'
7756     // variable declared in function scope. We don't need this in C++, because
7757     // we find local extern decls in the surrounding file-scope DeclContext.
7758     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7759       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7760         Previous.clear();
7761         Previous.addDecl(Prev);
7762         return true;
7763       }
7764     }
7765     return false;
7766   }
7767 
7768   // A declaration in the translation unit can conflict with an extern "C"
7769   // declaration.
7770   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7771     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7772 
7773   // An extern "C" declaration can conflict with a declaration in the
7774   // translation unit or can be a redeclaration of an extern "C" declaration
7775   // in another scope.
7776   if (isIncompleteDeclExternC(S,ND))
7777     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7778 
7779   // Neither global nor extern "C": nothing to do.
7780   return false;
7781 }
7782 
7783 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7784   // If the decl is already known invalid, don't check it.
7785   if (NewVD->isInvalidDecl())
7786     return;
7787 
7788   QualType T = NewVD->getType();
7789 
7790   // Defer checking an 'auto' type until its initializer is attached.
7791   if (T->isUndeducedType())
7792     return;
7793 
7794   if (NewVD->hasAttrs())
7795     CheckAlignasUnderalignment(NewVD);
7796 
7797   if (T->isObjCObjectType()) {
7798     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7799       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7800     T = Context.getObjCObjectPointerType(T);
7801     NewVD->setType(T);
7802   }
7803 
7804   // Emit an error if an address space was applied to decl with local storage.
7805   // This includes arrays of objects with address space qualifiers, but not
7806   // automatic variables that point to other address spaces.
7807   // ISO/IEC TR 18037 S5.1.2
7808   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7809       T.getAddressSpace() != LangAS::Default) {
7810     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7811     NewVD->setInvalidDecl();
7812     return;
7813   }
7814 
7815   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7816   // scope.
7817   if (getLangOpts().OpenCLVersion == 120 &&
7818       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7819       NewVD->isStaticLocal()) {
7820     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7821     NewVD->setInvalidDecl();
7822     return;
7823   }
7824 
7825   if (getLangOpts().OpenCL) {
7826     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7827     if (NewVD->hasAttr<BlocksAttr>()) {
7828       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7829       return;
7830     }
7831 
7832     if (T->isBlockPointerType()) {
7833       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7834       // can't use 'extern' storage class.
7835       if (!T.isConstQualified()) {
7836         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7837             << 0 /*const*/;
7838         NewVD->setInvalidDecl();
7839         return;
7840       }
7841       if (NewVD->hasExternalStorage()) {
7842         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7843         NewVD->setInvalidDecl();
7844         return;
7845       }
7846     }
7847     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7848     // __constant address space.
7849     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7850     // variables inside a function can also be declared in the global
7851     // address space.
7852     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7853     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7854     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7855         NewVD->hasExternalStorage()) {
7856       if (!T->isSamplerT() &&
7857           !T->isDependentType() &&
7858           !(T.getAddressSpace() == LangAS::opencl_constant ||
7859             (T.getAddressSpace() == LangAS::opencl_global &&
7860              (getLangOpts().OpenCLVersion == 200 ||
7861               getLangOpts().OpenCLCPlusPlus)))) {
7862         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7863         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7864           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7865               << Scope << "global or constant";
7866         else
7867           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7868               << Scope << "constant";
7869         NewVD->setInvalidDecl();
7870         return;
7871       }
7872     } else {
7873       if (T.getAddressSpace() == LangAS::opencl_global) {
7874         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7875             << 1 /*is any function*/ << "global";
7876         NewVD->setInvalidDecl();
7877         return;
7878       }
7879       if (T.getAddressSpace() == LangAS::opencl_constant ||
7880           T.getAddressSpace() == LangAS::opencl_local) {
7881         FunctionDecl *FD = getCurFunctionDecl();
7882         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7883         // in functions.
7884         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7885           if (T.getAddressSpace() == LangAS::opencl_constant)
7886             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7887                 << 0 /*non-kernel only*/ << "constant";
7888           else
7889             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7890                 << 0 /*non-kernel only*/ << "local";
7891           NewVD->setInvalidDecl();
7892           return;
7893         }
7894         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7895         // in the outermost scope of a kernel function.
7896         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7897           if (!getCurScope()->isFunctionScope()) {
7898             if (T.getAddressSpace() == LangAS::opencl_constant)
7899               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7900                   << "constant";
7901             else
7902               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7903                   << "local";
7904             NewVD->setInvalidDecl();
7905             return;
7906           }
7907         }
7908       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7909                  // If we are parsing a template we didn't deduce an addr
7910                  // space yet.
7911                  T.getAddressSpace() != LangAS::Default) {
7912         // Do not allow other address spaces on automatic variable.
7913         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7914         NewVD->setInvalidDecl();
7915         return;
7916       }
7917     }
7918   }
7919 
7920   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7921       && !NewVD->hasAttr<BlocksAttr>()) {
7922     if (getLangOpts().getGC() != LangOptions::NonGC)
7923       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7924     else {
7925       assert(!getLangOpts().ObjCAutoRefCount);
7926       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7927     }
7928   }
7929 
7930   bool isVM = T->isVariablyModifiedType();
7931   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7932       NewVD->hasAttr<BlocksAttr>())
7933     setFunctionHasBranchProtectedScope();
7934 
7935   if ((isVM && NewVD->hasLinkage()) ||
7936       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7937     bool SizeIsNegative;
7938     llvm::APSInt Oversized;
7939     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7940         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7941     QualType FixedT;
7942     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7943       FixedT = FixedTInfo->getType();
7944     else if (FixedTInfo) {
7945       // Type and type-as-written are canonically different. We need to fix up
7946       // both types separately.
7947       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7948                                                    Oversized);
7949     }
7950     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7951       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7952       // FIXME: This won't give the correct result for
7953       // int a[10][n];
7954       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7955 
7956       if (NewVD->isFileVarDecl())
7957         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7958         << SizeRange;
7959       else if (NewVD->isStaticLocal())
7960         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7961         << SizeRange;
7962       else
7963         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7964         << SizeRange;
7965       NewVD->setInvalidDecl();
7966       return;
7967     }
7968 
7969     if (!FixedTInfo) {
7970       if (NewVD->isFileVarDecl())
7971         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7972       else
7973         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7974       NewVD->setInvalidDecl();
7975       return;
7976     }
7977 
7978     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7979     NewVD->setType(FixedT);
7980     NewVD->setTypeSourceInfo(FixedTInfo);
7981   }
7982 
7983   if (T->isVoidType()) {
7984     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7985     //                    of objects and functions.
7986     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7987       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7988         << T;
7989       NewVD->setInvalidDecl();
7990       return;
7991     }
7992   }
7993 
7994   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7995     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7996     NewVD->setInvalidDecl();
7997     return;
7998   }
7999 
8000   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8001     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8002     NewVD->setInvalidDecl();
8003     return;
8004   }
8005 
8006   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8007     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8008     NewVD->setInvalidDecl();
8009     return;
8010   }
8011 
8012   if (NewVD->isConstexpr() && !T->isDependentType() &&
8013       RequireLiteralType(NewVD->getLocation(), T,
8014                          diag::err_constexpr_var_non_literal)) {
8015     NewVD->setInvalidDecl();
8016     return;
8017   }
8018 }
8019 
8020 /// Perform semantic checking on a newly-created variable
8021 /// declaration.
8022 ///
8023 /// This routine performs all of the type-checking required for a
8024 /// variable declaration once it has been built. It is used both to
8025 /// check variables after they have been parsed and their declarators
8026 /// have been translated into a declaration, and to check variables
8027 /// that have been instantiated from a template.
8028 ///
8029 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8030 ///
8031 /// Returns true if the variable declaration is a redeclaration.
8032 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8033   CheckVariableDeclarationType(NewVD);
8034 
8035   // If the decl is already known invalid, don't check it.
8036   if (NewVD->isInvalidDecl())
8037     return false;
8038 
8039   // If we did not find anything by this name, look for a non-visible
8040   // extern "C" declaration with the same name.
8041   if (Previous.empty() &&
8042       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8043     Previous.setShadowed();
8044 
8045   if (!Previous.empty()) {
8046     MergeVarDecl(NewVD, Previous);
8047     return true;
8048   }
8049   return false;
8050 }
8051 
8052 namespace {
8053 struct FindOverriddenMethod {
8054   Sema *S;
8055   CXXMethodDecl *Method;
8056 
8057   /// Member lookup function that determines whether a given C++
8058   /// method overrides a method in a base class, to be used with
8059   /// CXXRecordDecl::lookupInBases().
8060   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8061     RecordDecl *BaseRecord =
8062         Specifier->getType()->castAs<RecordType>()->getDecl();
8063 
8064     DeclarationName Name = Method->getDeclName();
8065 
8066     // FIXME: Do we care about other names here too?
8067     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8068       // We really want to find the base class destructor here.
8069       QualType T = S->Context.getTypeDeclType(BaseRecord);
8070       CanQualType CT = S->Context.getCanonicalType(T);
8071 
8072       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8073     }
8074 
8075     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8076          Path.Decls = Path.Decls.slice(1)) {
8077       NamedDecl *D = Path.Decls.front();
8078       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8079         if (MD->isVirtual() &&
8080             !S->IsOverload(
8081                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8082                 /*ConsiderCudaAttrs=*/true,
8083                 // C++2a [class.virtual]p2 does not consider requires clauses
8084                 // when overriding.
8085                 /*ConsiderRequiresClauses=*/false))
8086           return true;
8087       }
8088     }
8089 
8090     return false;
8091   }
8092 };
8093 } // end anonymous namespace
8094 
8095 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8096 /// and if so, check that it's a valid override and remember it.
8097 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8098   // Look for methods in base classes that this method might override.
8099   CXXBasePaths Paths;
8100   FindOverriddenMethod FOM;
8101   FOM.Method = MD;
8102   FOM.S = this;
8103   bool AddedAny = false;
8104   if (DC->lookupInBases(FOM, Paths)) {
8105     for (auto *I : Paths.found_decls()) {
8106       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8107         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8108         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8109             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8110             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8111             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8112           AddedAny = true;
8113         }
8114       }
8115     }
8116   }
8117 
8118   return AddedAny;
8119 }
8120 
8121 namespace {
8122   // Struct for holding all of the extra arguments needed by
8123   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8124   struct ActOnFDArgs {
8125     Scope *S;
8126     Declarator &D;
8127     MultiTemplateParamsArg TemplateParamLists;
8128     bool AddToScope;
8129   };
8130 } // end anonymous namespace
8131 
8132 namespace {
8133 
8134 // Callback to only accept typo corrections that have a non-zero edit distance.
8135 // Also only accept corrections that have the same parent decl.
8136 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8137  public:
8138   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8139                             CXXRecordDecl *Parent)
8140       : Context(Context), OriginalFD(TypoFD),
8141         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8142 
8143   bool ValidateCandidate(const TypoCorrection &candidate) override {
8144     if (candidate.getEditDistance() == 0)
8145       return false;
8146 
8147     SmallVector<unsigned, 1> MismatchedParams;
8148     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8149                                           CDeclEnd = candidate.end();
8150          CDecl != CDeclEnd; ++CDecl) {
8151       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8152 
8153       if (FD && !FD->hasBody() &&
8154           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8155         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8156           CXXRecordDecl *Parent = MD->getParent();
8157           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8158             return true;
8159         } else if (!ExpectedParent) {
8160           return true;
8161         }
8162       }
8163     }
8164 
8165     return false;
8166   }
8167 
8168   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8169     return std::make_unique<DifferentNameValidatorCCC>(*this);
8170   }
8171 
8172  private:
8173   ASTContext &Context;
8174   FunctionDecl *OriginalFD;
8175   CXXRecordDecl *ExpectedParent;
8176 };
8177 
8178 } // end anonymous namespace
8179 
8180 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8181   TypoCorrectedFunctionDefinitions.insert(F);
8182 }
8183 
8184 /// Generate diagnostics for an invalid function redeclaration.
8185 ///
8186 /// This routine handles generating the diagnostic messages for an invalid
8187 /// function redeclaration, including finding possible similar declarations
8188 /// or performing typo correction if there are no previous declarations with
8189 /// the same name.
8190 ///
8191 /// Returns a NamedDecl iff typo correction was performed and substituting in
8192 /// the new declaration name does not cause new errors.
8193 static NamedDecl *DiagnoseInvalidRedeclaration(
8194     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8195     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8196   DeclarationName Name = NewFD->getDeclName();
8197   DeclContext *NewDC = NewFD->getDeclContext();
8198   SmallVector<unsigned, 1> MismatchedParams;
8199   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8200   TypoCorrection Correction;
8201   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8202   unsigned DiagMsg =
8203     IsLocalFriend ? diag::err_no_matching_local_friend :
8204     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8205     diag::err_member_decl_does_not_match;
8206   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8207                     IsLocalFriend ? Sema::LookupLocalFriendName
8208                                   : Sema::LookupOrdinaryName,
8209                     Sema::ForVisibleRedeclaration);
8210 
8211   NewFD->setInvalidDecl();
8212   if (IsLocalFriend)
8213     SemaRef.LookupName(Prev, S);
8214   else
8215     SemaRef.LookupQualifiedName(Prev, NewDC);
8216   assert(!Prev.isAmbiguous() &&
8217          "Cannot have an ambiguity in previous-declaration lookup");
8218   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8219   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8220                                 MD ? MD->getParent() : nullptr);
8221   if (!Prev.empty()) {
8222     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8223          Func != FuncEnd; ++Func) {
8224       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8225       if (FD &&
8226           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8227         // Add 1 to the index so that 0 can mean the mismatch didn't
8228         // involve a parameter
8229         unsigned ParamNum =
8230             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8231         NearMatches.push_back(std::make_pair(FD, ParamNum));
8232       }
8233     }
8234   // If the qualified name lookup yielded nothing, try typo correction
8235   } else if ((Correction = SemaRef.CorrectTypo(
8236                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8237                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8238                   IsLocalFriend ? nullptr : NewDC))) {
8239     // Set up everything for the call to ActOnFunctionDeclarator
8240     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8241                               ExtraArgs.D.getIdentifierLoc());
8242     Previous.clear();
8243     Previous.setLookupName(Correction.getCorrection());
8244     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8245                                     CDeclEnd = Correction.end();
8246          CDecl != CDeclEnd; ++CDecl) {
8247       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8248       if (FD && !FD->hasBody() &&
8249           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8250         Previous.addDecl(FD);
8251       }
8252     }
8253     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8254 
8255     NamedDecl *Result;
8256     // Retry building the function declaration with the new previous
8257     // declarations, and with errors suppressed.
8258     {
8259       // Trap errors.
8260       Sema::SFINAETrap Trap(SemaRef);
8261 
8262       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8263       // pieces need to verify the typo-corrected C++ declaration and hopefully
8264       // eliminate the need for the parameter pack ExtraArgs.
8265       Result = SemaRef.ActOnFunctionDeclarator(
8266           ExtraArgs.S, ExtraArgs.D,
8267           Correction.getCorrectionDecl()->getDeclContext(),
8268           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8269           ExtraArgs.AddToScope);
8270 
8271       if (Trap.hasErrorOccurred())
8272         Result = nullptr;
8273     }
8274 
8275     if (Result) {
8276       // Determine which correction we picked.
8277       Decl *Canonical = Result->getCanonicalDecl();
8278       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8279            I != E; ++I)
8280         if ((*I)->getCanonicalDecl() == Canonical)
8281           Correction.setCorrectionDecl(*I);
8282 
8283       // Let Sema know about the correction.
8284       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8285       SemaRef.diagnoseTypo(
8286           Correction,
8287           SemaRef.PDiag(IsLocalFriend
8288                           ? diag::err_no_matching_local_friend_suggest
8289                           : diag::err_member_decl_does_not_match_suggest)
8290             << Name << NewDC << IsDefinition);
8291       return Result;
8292     }
8293 
8294     // Pretend the typo correction never occurred
8295     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8296                               ExtraArgs.D.getIdentifierLoc());
8297     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8298     Previous.clear();
8299     Previous.setLookupName(Name);
8300   }
8301 
8302   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8303       << Name << NewDC << IsDefinition << NewFD->getLocation();
8304 
8305   bool NewFDisConst = false;
8306   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8307     NewFDisConst = NewMD->isConst();
8308 
8309   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8310        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8311        NearMatch != NearMatchEnd; ++NearMatch) {
8312     FunctionDecl *FD = NearMatch->first;
8313     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8314     bool FDisConst = MD && MD->isConst();
8315     bool IsMember = MD || !IsLocalFriend;
8316 
8317     // FIXME: These notes are poorly worded for the local friend case.
8318     if (unsigned Idx = NearMatch->second) {
8319       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8320       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8321       if (Loc.isInvalid()) Loc = FD->getLocation();
8322       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8323                                  : diag::note_local_decl_close_param_match)
8324         << Idx << FDParam->getType()
8325         << NewFD->getParamDecl(Idx - 1)->getType();
8326     } else if (FDisConst != NewFDisConst) {
8327       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8328           << NewFDisConst << FD->getSourceRange().getEnd();
8329     } else
8330       SemaRef.Diag(FD->getLocation(),
8331                    IsMember ? diag::note_member_def_close_match
8332                             : diag::note_local_decl_close_match);
8333   }
8334   return nullptr;
8335 }
8336 
8337 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8338   switch (D.getDeclSpec().getStorageClassSpec()) {
8339   default: llvm_unreachable("Unknown storage class!");
8340   case DeclSpec::SCS_auto:
8341   case DeclSpec::SCS_register:
8342   case DeclSpec::SCS_mutable:
8343     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8344                  diag::err_typecheck_sclass_func);
8345     D.getMutableDeclSpec().ClearStorageClassSpecs();
8346     D.setInvalidType();
8347     break;
8348   case DeclSpec::SCS_unspecified: break;
8349   case DeclSpec::SCS_extern:
8350     if (D.getDeclSpec().isExternInLinkageSpec())
8351       return SC_None;
8352     return SC_Extern;
8353   case DeclSpec::SCS_static: {
8354     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8355       // C99 6.7.1p5:
8356       //   The declaration of an identifier for a function that has
8357       //   block scope shall have no explicit storage-class specifier
8358       //   other than extern
8359       // See also (C++ [dcl.stc]p4).
8360       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8361                    diag::err_static_block_func);
8362       break;
8363     } else
8364       return SC_Static;
8365   }
8366   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8367   }
8368 
8369   // No explicit storage class has already been returned
8370   return SC_None;
8371 }
8372 
8373 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8374                                            DeclContext *DC, QualType &R,
8375                                            TypeSourceInfo *TInfo,
8376                                            StorageClass SC,
8377                                            bool &IsVirtualOkay) {
8378   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8379   DeclarationName Name = NameInfo.getName();
8380 
8381   FunctionDecl *NewFD = nullptr;
8382   bool isInline = D.getDeclSpec().isInlineSpecified();
8383 
8384   if (!SemaRef.getLangOpts().CPlusPlus) {
8385     // Determine whether the function was written with a
8386     // prototype. This true when:
8387     //   - there is a prototype in the declarator, or
8388     //   - the type R of the function is some kind of typedef or other non-
8389     //     attributed reference to a type name (which eventually refers to a
8390     //     function type).
8391     bool HasPrototype =
8392       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8393       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8394 
8395     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8396                                  R, TInfo, SC, isInline, HasPrototype,
8397                                  CSK_unspecified,
8398                                  /*TrailingRequiresClause=*/nullptr);
8399     if (D.isInvalidType())
8400       NewFD->setInvalidDecl();
8401 
8402     return NewFD;
8403   }
8404 
8405   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8406 
8407   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8408   if (ConstexprKind == CSK_constinit) {
8409     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8410                  diag::err_constexpr_wrong_decl_kind)
8411         << ConstexprKind;
8412     ConstexprKind = CSK_unspecified;
8413     D.getMutableDeclSpec().ClearConstexprSpec();
8414   }
8415   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8416 
8417   // Check that the return type is not an abstract class type.
8418   // For record types, this is done by the AbstractClassUsageDiagnoser once
8419   // the class has been completely parsed.
8420   if (!DC->isRecord() &&
8421       SemaRef.RequireNonAbstractType(
8422           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8423           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8424     D.setInvalidType();
8425 
8426   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8427     // This is a C++ constructor declaration.
8428     assert(DC->isRecord() &&
8429            "Constructors can only be declared in a member context");
8430 
8431     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8432     return CXXConstructorDecl::Create(
8433         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8434         TInfo, ExplicitSpecifier, isInline,
8435         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8436         TrailingRequiresClause);
8437 
8438   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8439     // This is a C++ destructor declaration.
8440     if (DC->isRecord()) {
8441       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8442       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8443       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8444           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8445           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8446           TrailingRequiresClause);
8447 
8448       // If the destructor needs an implicit exception specification, set it
8449       // now. FIXME: It'd be nice to be able to create the right type to start
8450       // with, but the type needs to reference the destructor declaration.
8451       if (SemaRef.getLangOpts().CPlusPlus11)
8452         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8453 
8454       IsVirtualOkay = true;
8455       return NewDD;
8456 
8457     } else {
8458       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8459       D.setInvalidType();
8460 
8461       // Create a FunctionDecl to satisfy the function definition parsing
8462       // code path.
8463       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8464                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8465                                   isInline,
8466                                   /*hasPrototype=*/true, ConstexprKind,
8467                                   TrailingRequiresClause);
8468     }
8469 
8470   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8471     if (!DC->isRecord()) {
8472       SemaRef.Diag(D.getIdentifierLoc(),
8473            diag::err_conv_function_not_member);
8474       return nullptr;
8475     }
8476 
8477     SemaRef.CheckConversionDeclarator(D, R, SC);
8478     if (D.isInvalidType())
8479       return nullptr;
8480 
8481     IsVirtualOkay = true;
8482     return CXXConversionDecl::Create(
8483         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8484         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8485         TrailingRequiresClause);
8486 
8487   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8488     if (TrailingRequiresClause)
8489       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8490                    diag::err_trailing_requires_clause_on_deduction_guide)
8491           << TrailingRequiresClause->getSourceRange();
8492     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8493 
8494     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8495                                          ExplicitSpecifier, NameInfo, R, TInfo,
8496                                          D.getEndLoc());
8497   } else if (DC->isRecord()) {
8498     // If the name of the function is the same as the name of the record,
8499     // then this must be an invalid constructor that has a return type.
8500     // (The parser checks for a return type and makes the declarator a
8501     // constructor if it has no return type).
8502     if (Name.getAsIdentifierInfo() &&
8503         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8504       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8505         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8506         << SourceRange(D.getIdentifierLoc());
8507       return nullptr;
8508     }
8509 
8510     // This is a C++ method declaration.
8511     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8512         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8513         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8514         TrailingRequiresClause);
8515     IsVirtualOkay = !Ret->isStatic();
8516     return Ret;
8517   } else {
8518     bool isFriend =
8519         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8520     if (!isFriend && SemaRef.CurContext->isRecord())
8521       return nullptr;
8522 
8523     // Determine whether the function was written with a
8524     // prototype. This true when:
8525     //   - we're in C++ (where every function has a prototype),
8526     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8527                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8528                                 ConstexprKind, TrailingRequiresClause);
8529   }
8530 }
8531 
8532 enum OpenCLParamType {
8533   ValidKernelParam,
8534   PtrPtrKernelParam,
8535   PtrKernelParam,
8536   InvalidAddrSpacePtrKernelParam,
8537   InvalidKernelParam,
8538   RecordKernelParam
8539 };
8540 
8541 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8542   // Size dependent types are just typedefs to normal integer types
8543   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8544   // integers other than by their names.
8545   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8546 
8547   // Remove typedefs one by one until we reach a typedef
8548   // for a size dependent type.
8549   QualType DesugaredTy = Ty;
8550   do {
8551     ArrayRef<StringRef> Names(SizeTypeNames);
8552     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8553     if (Names.end() != Match)
8554       return true;
8555 
8556     Ty = DesugaredTy;
8557     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8558   } while (DesugaredTy != Ty);
8559 
8560   return false;
8561 }
8562 
8563 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8564   if (PT->isPointerType()) {
8565     QualType PointeeType = PT->getPointeeType();
8566     if (PointeeType->isPointerType())
8567       return PtrPtrKernelParam;
8568     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8569         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8570         PointeeType.getAddressSpace() == LangAS::Default)
8571       return InvalidAddrSpacePtrKernelParam;
8572     return PtrKernelParam;
8573   }
8574 
8575   // OpenCL v1.2 s6.9.k:
8576   // Arguments to kernel functions in a program cannot be declared with the
8577   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8578   // uintptr_t or a struct and/or union that contain fields declared to be one
8579   // of these built-in scalar types.
8580   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8581     return InvalidKernelParam;
8582 
8583   if (PT->isImageType())
8584     return PtrKernelParam;
8585 
8586   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8587     return InvalidKernelParam;
8588 
8589   // OpenCL extension spec v1.2 s9.5:
8590   // This extension adds support for half scalar and vector types as built-in
8591   // types that can be used for arithmetic operations, conversions etc.
8592   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8593     return InvalidKernelParam;
8594 
8595   if (PT->isRecordType())
8596     return RecordKernelParam;
8597 
8598   // Look into an array argument to check if it has a forbidden type.
8599   if (PT->isArrayType()) {
8600     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8601     // Call ourself to check an underlying type of an array. Since the
8602     // getPointeeOrArrayElementType returns an innermost type which is not an
8603     // array, this recursive call only happens once.
8604     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8605   }
8606 
8607   return ValidKernelParam;
8608 }
8609 
8610 static void checkIsValidOpenCLKernelParameter(
8611   Sema &S,
8612   Declarator &D,
8613   ParmVarDecl *Param,
8614   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8615   QualType PT = Param->getType();
8616 
8617   // Cache the valid types we encounter to avoid rechecking structs that are
8618   // used again
8619   if (ValidTypes.count(PT.getTypePtr()))
8620     return;
8621 
8622   switch (getOpenCLKernelParameterType(S, PT)) {
8623   case PtrPtrKernelParam:
8624     // OpenCL v1.2 s6.9.a:
8625     // A kernel function argument cannot be declared as a
8626     // pointer to a pointer type.
8627     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8628     D.setInvalidType();
8629     return;
8630 
8631   case InvalidAddrSpacePtrKernelParam:
8632     // OpenCL v1.0 s6.5:
8633     // __kernel function arguments declared to be a pointer of a type can point
8634     // to one of the following address spaces only : __global, __local or
8635     // __constant.
8636     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8637     D.setInvalidType();
8638     return;
8639 
8640     // OpenCL v1.2 s6.9.k:
8641     // Arguments to kernel functions in a program cannot be declared with the
8642     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8643     // uintptr_t or a struct and/or union that contain fields declared to be
8644     // one of these built-in scalar types.
8645 
8646   case InvalidKernelParam:
8647     // OpenCL v1.2 s6.8 n:
8648     // A kernel function argument cannot be declared
8649     // of event_t type.
8650     // Do not diagnose half type since it is diagnosed as invalid argument
8651     // type for any function elsewhere.
8652     if (!PT->isHalfType()) {
8653       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8654 
8655       // Explain what typedefs are involved.
8656       const TypedefType *Typedef = nullptr;
8657       while ((Typedef = PT->getAs<TypedefType>())) {
8658         SourceLocation Loc = Typedef->getDecl()->getLocation();
8659         // SourceLocation may be invalid for a built-in type.
8660         if (Loc.isValid())
8661           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8662         PT = Typedef->desugar();
8663       }
8664     }
8665 
8666     D.setInvalidType();
8667     return;
8668 
8669   case PtrKernelParam:
8670   case ValidKernelParam:
8671     ValidTypes.insert(PT.getTypePtr());
8672     return;
8673 
8674   case RecordKernelParam:
8675     break;
8676   }
8677 
8678   // Track nested structs we will inspect
8679   SmallVector<const Decl *, 4> VisitStack;
8680 
8681   // Track where we are in the nested structs. Items will migrate from
8682   // VisitStack to HistoryStack as we do the DFS for bad field.
8683   SmallVector<const FieldDecl *, 4> HistoryStack;
8684   HistoryStack.push_back(nullptr);
8685 
8686   // At this point we already handled everything except of a RecordType or
8687   // an ArrayType of a RecordType.
8688   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8689   const RecordType *RecTy =
8690       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8691   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8692 
8693   VisitStack.push_back(RecTy->getDecl());
8694   assert(VisitStack.back() && "First decl null?");
8695 
8696   do {
8697     const Decl *Next = VisitStack.pop_back_val();
8698     if (!Next) {
8699       assert(!HistoryStack.empty());
8700       // Found a marker, we have gone up a level
8701       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8702         ValidTypes.insert(Hist->getType().getTypePtr());
8703 
8704       continue;
8705     }
8706 
8707     // Adds everything except the original parameter declaration (which is not a
8708     // field itself) to the history stack.
8709     const RecordDecl *RD;
8710     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8711       HistoryStack.push_back(Field);
8712 
8713       QualType FieldTy = Field->getType();
8714       // Other field types (known to be valid or invalid) are handled while we
8715       // walk around RecordDecl::fields().
8716       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8717              "Unexpected type.");
8718       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8719 
8720       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8721     } else {
8722       RD = cast<RecordDecl>(Next);
8723     }
8724 
8725     // Add a null marker so we know when we've gone back up a level
8726     VisitStack.push_back(nullptr);
8727 
8728     for (const auto *FD : RD->fields()) {
8729       QualType QT = FD->getType();
8730 
8731       if (ValidTypes.count(QT.getTypePtr()))
8732         continue;
8733 
8734       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8735       if (ParamType == ValidKernelParam)
8736         continue;
8737 
8738       if (ParamType == RecordKernelParam) {
8739         VisitStack.push_back(FD);
8740         continue;
8741       }
8742 
8743       // OpenCL v1.2 s6.9.p:
8744       // Arguments to kernel functions that are declared to be a struct or union
8745       // do not allow OpenCL objects to be passed as elements of the struct or
8746       // union.
8747       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8748           ParamType == InvalidAddrSpacePtrKernelParam) {
8749         S.Diag(Param->getLocation(),
8750                diag::err_record_with_pointers_kernel_param)
8751           << PT->isUnionType()
8752           << PT;
8753       } else {
8754         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8755       }
8756 
8757       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8758           << OrigRecDecl->getDeclName();
8759 
8760       // We have an error, now let's go back up through history and show where
8761       // the offending field came from
8762       for (ArrayRef<const FieldDecl *>::const_iterator
8763                I = HistoryStack.begin() + 1,
8764                E = HistoryStack.end();
8765            I != E; ++I) {
8766         const FieldDecl *OuterField = *I;
8767         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8768           << OuterField->getType();
8769       }
8770 
8771       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8772         << QT->isPointerType()
8773         << QT;
8774       D.setInvalidType();
8775       return;
8776     }
8777   } while (!VisitStack.empty());
8778 }
8779 
8780 /// Find the DeclContext in which a tag is implicitly declared if we see an
8781 /// elaborated type specifier in the specified context, and lookup finds
8782 /// nothing.
8783 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8784   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8785     DC = DC->getParent();
8786   return DC;
8787 }
8788 
8789 /// Find the Scope in which a tag is implicitly declared if we see an
8790 /// elaborated type specifier in the specified context, and lookup finds
8791 /// nothing.
8792 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8793   while (S->isClassScope() ||
8794          (LangOpts.CPlusPlus &&
8795           S->isFunctionPrototypeScope()) ||
8796          ((S->getFlags() & Scope::DeclScope) == 0) ||
8797          (S->getEntity() && S->getEntity()->isTransparentContext()))
8798     S = S->getParent();
8799   return S;
8800 }
8801 
8802 NamedDecl*
8803 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8804                               TypeSourceInfo *TInfo, LookupResult &Previous,
8805                               MultiTemplateParamsArg TemplateParamListsRef,
8806                               bool &AddToScope) {
8807   QualType R = TInfo->getType();
8808 
8809   assert(R->isFunctionType());
8810   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8811     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8812 
8813   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8814   for (TemplateParameterList *TPL : TemplateParamListsRef)
8815     TemplateParamLists.push_back(TPL);
8816   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8817     if (!TemplateParamLists.empty() &&
8818         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8819       TemplateParamLists.back() = Invented;
8820     else
8821       TemplateParamLists.push_back(Invented);
8822   }
8823 
8824   // TODO: consider using NameInfo for diagnostic.
8825   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8826   DeclarationName Name = NameInfo.getName();
8827   StorageClass SC = getFunctionStorageClass(*this, D);
8828 
8829   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8830     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8831          diag::err_invalid_thread)
8832       << DeclSpec::getSpecifierName(TSCS);
8833 
8834   if (D.isFirstDeclarationOfMember())
8835     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8836                            D.getIdentifierLoc());
8837 
8838   bool isFriend = false;
8839   FunctionTemplateDecl *FunctionTemplate = nullptr;
8840   bool isMemberSpecialization = false;
8841   bool isFunctionTemplateSpecialization = false;
8842 
8843   bool isDependentClassScopeExplicitSpecialization = false;
8844   bool HasExplicitTemplateArgs = false;
8845   TemplateArgumentListInfo TemplateArgs;
8846 
8847   bool isVirtualOkay = false;
8848 
8849   DeclContext *OriginalDC = DC;
8850   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8851 
8852   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8853                                               isVirtualOkay);
8854   if (!NewFD) return nullptr;
8855 
8856   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8857     NewFD->setTopLevelDeclInObjCContainer();
8858 
8859   // Set the lexical context. If this is a function-scope declaration, or has a
8860   // C++ scope specifier, or is the object of a friend declaration, the lexical
8861   // context will be different from the semantic context.
8862   NewFD->setLexicalDeclContext(CurContext);
8863 
8864   if (IsLocalExternDecl)
8865     NewFD->setLocalExternDecl();
8866 
8867   if (getLangOpts().CPlusPlus) {
8868     bool isInline = D.getDeclSpec().isInlineSpecified();
8869     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8870     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8871     isFriend = D.getDeclSpec().isFriendSpecified();
8872     if (isFriend && !isInline && D.isFunctionDefinition()) {
8873       // C++ [class.friend]p5
8874       //   A function can be defined in a friend declaration of a
8875       //   class . . . . Such a function is implicitly inline.
8876       NewFD->setImplicitlyInline();
8877     }
8878 
8879     // If this is a method defined in an __interface, and is not a constructor
8880     // or an overloaded operator, then set the pure flag (isVirtual will already
8881     // return true).
8882     if (const CXXRecordDecl *Parent =
8883           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8884       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8885         NewFD->setPure(true);
8886 
8887       // C++ [class.union]p2
8888       //   A union can have member functions, but not virtual functions.
8889       if (isVirtual && Parent->isUnion())
8890         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8891     }
8892 
8893     SetNestedNameSpecifier(*this, NewFD, D);
8894     isMemberSpecialization = false;
8895     isFunctionTemplateSpecialization = false;
8896     if (D.isInvalidType())
8897       NewFD->setInvalidDecl();
8898 
8899     // Match up the template parameter lists with the scope specifier, then
8900     // determine whether we have a template or a template specialization.
8901     bool Invalid = false;
8902     TemplateParameterList *TemplateParams =
8903         MatchTemplateParametersToScopeSpecifier(
8904             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8905             D.getCXXScopeSpec(),
8906             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8907                 ? D.getName().TemplateId
8908                 : nullptr,
8909             TemplateParamLists, isFriend, isMemberSpecialization,
8910             Invalid);
8911     if (TemplateParams) {
8912       if (TemplateParams->size() > 0) {
8913         // This is a function template
8914 
8915         // Check that we can declare a template here.
8916         if (CheckTemplateDeclScope(S, TemplateParams))
8917           NewFD->setInvalidDecl();
8918 
8919         // A destructor cannot be a template.
8920         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8921           Diag(NewFD->getLocation(), diag::err_destructor_template);
8922           NewFD->setInvalidDecl();
8923         }
8924 
8925         // If we're adding a template to a dependent context, we may need to
8926         // rebuilding some of the types used within the template parameter list,
8927         // now that we know what the current instantiation is.
8928         if (DC->isDependentContext()) {
8929           ContextRAII SavedContext(*this, DC);
8930           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8931             Invalid = true;
8932         }
8933 
8934         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8935                                                         NewFD->getLocation(),
8936                                                         Name, TemplateParams,
8937                                                         NewFD);
8938         FunctionTemplate->setLexicalDeclContext(CurContext);
8939         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8940 
8941         // For source fidelity, store the other template param lists.
8942         if (TemplateParamLists.size() > 1) {
8943           NewFD->setTemplateParameterListsInfo(Context,
8944               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8945                   .drop_back(1));
8946         }
8947       } else {
8948         // This is a function template specialization.
8949         isFunctionTemplateSpecialization = true;
8950         // For source fidelity, store all the template param lists.
8951         if (TemplateParamLists.size() > 0)
8952           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8953 
8954         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8955         if (isFriend) {
8956           // We want to remove the "template<>", found here.
8957           SourceRange RemoveRange = TemplateParams->getSourceRange();
8958 
8959           // If we remove the template<> and the name is not a
8960           // template-id, we're actually silently creating a problem:
8961           // the friend declaration will refer to an untemplated decl,
8962           // and clearly the user wants a template specialization.  So
8963           // we need to insert '<>' after the name.
8964           SourceLocation InsertLoc;
8965           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8966             InsertLoc = D.getName().getSourceRange().getEnd();
8967             InsertLoc = getLocForEndOfToken(InsertLoc);
8968           }
8969 
8970           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8971             << Name << RemoveRange
8972             << FixItHint::CreateRemoval(RemoveRange)
8973             << FixItHint::CreateInsertion(InsertLoc, "<>");
8974         }
8975       }
8976     } else {
8977       // All template param lists were matched against the scope specifier:
8978       // this is NOT (an explicit specialization of) a template.
8979       if (TemplateParamLists.size() > 0)
8980         // For source fidelity, store all the template param lists.
8981         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8982     }
8983 
8984     if (Invalid) {
8985       NewFD->setInvalidDecl();
8986       if (FunctionTemplate)
8987         FunctionTemplate->setInvalidDecl();
8988     }
8989 
8990     // C++ [dcl.fct.spec]p5:
8991     //   The virtual specifier shall only be used in declarations of
8992     //   nonstatic class member functions that appear within a
8993     //   member-specification of a class declaration; see 10.3.
8994     //
8995     if (isVirtual && !NewFD->isInvalidDecl()) {
8996       if (!isVirtualOkay) {
8997         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8998              diag::err_virtual_non_function);
8999       } else if (!CurContext->isRecord()) {
9000         // 'virtual' was specified outside of the class.
9001         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9002              diag::err_virtual_out_of_class)
9003           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9004       } else if (NewFD->getDescribedFunctionTemplate()) {
9005         // C++ [temp.mem]p3:
9006         //  A member function template shall not be virtual.
9007         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9008              diag::err_virtual_member_function_template)
9009           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9010       } else {
9011         // Okay: Add virtual to the method.
9012         NewFD->setVirtualAsWritten(true);
9013       }
9014 
9015       if (getLangOpts().CPlusPlus14 &&
9016           NewFD->getReturnType()->isUndeducedType())
9017         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9018     }
9019 
9020     if (getLangOpts().CPlusPlus14 &&
9021         (NewFD->isDependentContext() ||
9022          (isFriend && CurContext->isDependentContext())) &&
9023         NewFD->getReturnType()->isUndeducedType()) {
9024       // If the function template is referenced directly (for instance, as a
9025       // member of the current instantiation), pretend it has a dependent type.
9026       // This is not really justified by the standard, but is the only sane
9027       // thing to do.
9028       // FIXME: For a friend function, we have not marked the function as being
9029       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9030       const FunctionProtoType *FPT =
9031           NewFD->getType()->castAs<FunctionProtoType>();
9032       QualType Result =
9033           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9034       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9035                                              FPT->getExtProtoInfo()));
9036     }
9037 
9038     // C++ [dcl.fct.spec]p3:
9039     //  The inline specifier shall not appear on a block scope function
9040     //  declaration.
9041     if (isInline && !NewFD->isInvalidDecl()) {
9042       if (CurContext->isFunctionOrMethod()) {
9043         // 'inline' is not allowed on block scope function declaration.
9044         Diag(D.getDeclSpec().getInlineSpecLoc(),
9045              diag::err_inline_declaration_block_scope) << Name
9046           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9047       }
9048     }
9049 
9050     // C++ [dcl.fct.spec]p6:
9051     //  The explicit specifier shall be used only in the declaration of a
9052     //  constructor or conversion function within its class definition;
9053     //  see 12.3.1 and 12.3.2.
9054     if (hasExplicit && !NewFD->isInvalidDecl() &&
9055         !isa<CXXDeductionGuideDecl>(NewFD)) {
9056       if (!CurContext->isRecord()) {
9057         // 'explicit' was specified outside of the class.
9058         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9059              diag::err_explicit_out_of_class)
9060             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9061       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9062                  !isa<CXXConversionDecl>(NewFD)) {
9063         // 'explicit' was specified on a function that wasn't a constructor
9064         // or conversion function.
9065         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9066              diag::err_explicit_non_ctor_or_conv_function)
9067             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9068       }
9069     }
9070 
9071     if (ConstexprSpecKind ConstexprKind =
9072             D.getDeclSpec().getConstexprSpecifier()) {
9073       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9074       // are implicitly inline.
9075       NewFD->setImplicitlyInline();
9076 
9077       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9078       // be either constructors or to return a literal type. Therefore,
9079       // destructors cannot be declared constexpr.
9080       if (isa<CXXDestructorDecl>(NewFD) &&
9081           (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9082         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9083             << ConstexprKind;
9084         NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9085       }
9086       // C++20 [dcl.constexpr]p2: An allocation function, or a
9087       // deallocation function shall not be declared with the consteval
9088       // specifier.
9089       if (ConstexprKind == CSK_consteval &&
9090           (NewFD->getOverloadedOperator() == OO_New ||
9091            NewFD->getOverloadedOperator() == OO_Array_New ||
9092            NewFD->getOverloadedOperator() == OO_Delete ||
9093            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9094         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9095              diag::err_invalid_consteval_decl_kind)
9096             << NewFD;
9097         NewFD->setConstexprKind(CSK_constexpr);
9098       }
9099     }
9100 
9101     // If __module_private__ was specified, mark the function accordingly.
9102     if (D.getDeclSpec().isModulePrivateSpecified()) {
9103       if (isFunctionTemplateSpecialization) {
9104         SourceLocation ModulePrivateLoc
9105           = D.getDeclSpec().getModulePrivateSpecLoc();
9106         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9107           << 0
9108           << FixItHint::CreateRemoval(ModulePrivateLoc);
9109       } else {
9110         NewFD->setModulePrivate();
9111         if (FunctionTemplate)
9112           FunctionTemplate->setModulePrivate();
9113       }
9114     }
9115 
9116     if (isFriend) {
9117       if (FunctionTemplate) {
9118         FunctionTemplate->setObjectOfFriendDecl();
9119         FunctionTemplate->setAccess(AS_public);
9120       }
9121       NewFD->setObjectOfFriendDecl();
9122       NewFD->setAccess(AS_public);
9123     }
9124 
9125     // If a function is defined as defaulted or deleted, mark it as such now.
9126     // We'll do the relevant checks on defaulted / deleted functions later.
9127     switch (D.getFunctionDefinitionKind()) {
9128       case FDK_Declaration:
9129       case FDK_Definition:
9130         break;
9131 
9132       case FDK_Defaulted:
9133         NewFD->setDefaulted();
9134         break;
9135 
9136       case FDK_Deleted:
9137         NewFD->setDeletedAsWritten();
9138         break;
9139     }
9140 
9141     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9142         D.isFunctionDefinition()) {
9143       // C++ [class.mfct]p2:
9144       //   A member function may be defined (8.4) in its class definition, in
9145       //   which case it is an inline member function (7.1.2)
9146       NewFD->setImplicitlyInline();
9147     }
9148 
9149     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9150         !CurContext->isRecord()) {
9151       // C++ [class.static]p1:
9152       //   A data or function member of a class may be declared static
9153       //   in a class definition, in which case it is a static member of
9154       //   the class.
9155 
9156       // Complain about the 'static' specifier if it's on an out-of-line
9157       // member function definition.
9158 
9159       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9160       // member function template declaration and class member template
9161       // declaration (MSVC versions before 2015), warn about this.
9162       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9163            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9164              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9165            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9166            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9167         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9168     }
9169 
9170     // C++11 [except.spec]p15:
9171     //   A deallocation function with no exception-specification is treated
9172     //   as if it were specified with noexcept(true).
9173     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9174     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9175          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9176         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9177       NewFD->setType(Context.getFunctionType(
9178           FPT->getReturnType(), FPT->getParamTypes(),
9179           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9180   }
9181 
9182   // Filter out previous declarations that don't match the scope.
9183   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9184                        D.getCXXScopeSpec().isNotEmpty() ||
9185                        isMemberSpecialization ||
9186                        isFunctionTemplateSpecialization);
9187 
9188   // Handle GNU asm-label extension (encoded as an attribute).
9189   if (Expr *E = (Expr*) D.getAsmLabel()) {
9190     // The parser guarantees this is a string.
9191     StringLiteral *SE = cast<StringLiteral>(E);
9192     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9193                                         /*IsLiteralLabel=*/true,
9194                                         SE->getStrTokenLoc(0)));
9195   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9196     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9197       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9198     if (I != ExtnameUndeclaredIdentifiers.end()) {
9199       if (isDeclExternC(NewFD)) {
9200         NewFD->addAttr(I->second);
9201         ExtnameUndeclaredIdentifiers.erase(I);
9202       } else
9203         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9204             << /*Variable*/0 << NewFD;
9205     }
9206   }
9207 
9208   // Copy the parameter declarations from the declarator D to the function
9209   // declaration NewFD, if they are available.  First scavenge them into Params.
9210   SmallVector<ParmVarDecl*, 16> Params;
9211   unsigned FTIIdx;
9212   if (D.isFunctionDeclarator(FTIIdx)) {
9213     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9214 
9215     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9216     // function that takes no arguments, not a function that takes a
9217     // single void argument.
9218     // We let through "const void" here because Sema::GetTypeForDeclarator
9219     // already checks for that case.
9220     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9221       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9222         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9223         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9224         Param->setDeclContext(NewFD);
9225         Params.push_back(Param);
9226 
9227         if (Param->isInvalidDecl())
9228           NewFD->setInvalidDecl();
9229       }
9230     }
9231 
9232     if (!getLangOpts().CPlusPlus) {
9233       // In C, find all the tag declarations from the prototype and move them
9234       // into the function DeclContext. Remove them from the surrounding tag
9235       // injection context of the function, which is typically but not always
9236       // the TU.
9237       DeclContext *PrototypeTagContext =
9238           getTagInjectionContext(NewFD->getLexicalDeclContext());
9239       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9240         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9241 
9242         // We don't want to reparent enumerators. Look at their parent enum
9243         // instead.
9244         if (!TD) {
9245           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9246             TD = cast<EnumDecl>(ECD->getDeclContext());
9247         }
9248         if (!TD)
9249           continue;
9250         DeclContext *TagDC = TD->getLexicalDeclContext();
9251         if (!TagDC->containsDecl(TD))
9252           continue;
9253         TagDC->removeDecl(TD);
9254         TD->setDeclContext(NewFD);
9255         NewFD->addDecl(TD);
9256 
9257         // Preserve the lexical DeclContext if it is not the surrounding tag
9258         // injection context of the FD. In this example, the semantic context of
9259         // E will be f and the lexical context will be S, while both the
9260         // semantic and lexical contexts of S will be f:
9261         //   void f(struct S { enum E { a } f; } s);
9262         if (TagDC != PrototypeTagContext)
9263           TD->setLexicalDeclContext(TagDC);
9264       }
9265     }
9266   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9267     // When we're declaring a function with a typedef, typeof, etc as in the
9268     // following example, we'll need to synthesize (unnamed)
9269     // parameters for use in the declaration.
9270     //
9271     // @code
9272     // typedef void fn(int);
9273     // fn f;
9274     // @endcode
9275 
9276     // Synthesize a parameter for each argument type.
9277     for (const auto &AI : FT->param_types()) {
9278       ParmVarDecl *Param =
9279           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9280       Param->setScopeInfo(0, Params.size());
9281       Params.push_back(Param);
9282     }
9283   } else {
9284     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9285            "Should not need args for typedef of non-prototype fn");
9286   }
9287 
9288   // Finally, we know we have the right number of parameters, install them.
9289   NewFD->setParams(Params);
9290 
9291   if (D.getDeclSpec().isNoreturnSpecified())
9292     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9293                                            D.getDeclSpec().getNoreturnSpecLoc(),
9294                                            AttributeCommonInfo::AS_Keyword));
9295 
9296   // Functions returning a variably modified type violate C99 6.7.5.2p2
9297   // because all functions have linkage.
9298   if (!NewFD->isInvalidDecl() &&
9299       NewFD->getReturnType()->isVariablyModifiedType()) {
9300     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9301     NewFD->setInvalidDecl();
9302   }
9303 
9304   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9305   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9306       !NewFD->hasAttr<SectionAttr>())
9307     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9308         Context, PragmaClangTextSection.SectionName,
9309         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9310 
9311   // Apply an implicit SectionAttr if #pragma code_seg is active.
9312   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9313       !NewFD->hasAttr<SectionAttr>()) {
9314     NewFD->addAttr(SectionAttr::CreateImplicit(
9315         Context, CodeSegStack.CurrentValue->getString(),
9316         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9317         SectionAttr::Declspec_allocate));
9318     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9319                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9320                          ASTContext::PSF_Read,
9321                      NewFD))
9322       NewFD->dropAttr<SectionAttr>();
9323   }
9324 
9325   // Apply an implicit CodeSegAttr from class declspec or
9326   // apply an implicit SectionAttr from #pragma code_seg if active.
9327   if (!NewFD->hasAttr<CodeSegAttr>()) {
9328     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9329                                                                  D.isFunctionDefinition())) {
9330       NewFD->addAttr(SAttr);
9331     }
9332   }
9333 
9334   // Handle attributes.
9335   ProcessDeclAttributes(S, NewFD, D);
9336 
9337   if (getLangOpts().OpenCL) {
9338     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9339     // type declaration will generate a compilation error.
9340     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9341     if (AddressSpace != LangAS::Default) {
9342       Diag(NewFD->getLocation(),
9343            diag::err_opencl_return_value_with_address_space);
9344       NewFD->setInvalidDecl();
9345     }
9346   }
9347 
9348   if (!getLangOpts().CPlusPlus) {
9349     // Perform semantic checking on the function declaration.
9350     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9351       CheckMain(NewFD, D.getDeclSpec());
9352 
9353     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9354       CheckMSVCRTEntryPoint(NewFD);
9355 
9356     if (!NewFD->isInvalidDecl())
9357       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9358                                                   isMemberSpecialization));
9359     else if (!Previous.empty())
9360       // Recover gracefully from an invalid redeclaration.
9361       D.setRedeclaration(true);
9362     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9363             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9364            "previous declaration set still overloaded");
9365 
9366     // Diagnose no-prototype function declarations with calling conventions that
9367     // don't support variadic calls. Only do this in C and do it after merging
9368     // possibly prototyped redeclarations.
9369     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9370     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9371       CallingConv CC = FT->getExtInfo().getCC();
9372       if (!supportsVariadicCall(CC)) {
9373         // Windows system headers sometimes accidentally use stdcall without
9374         // (void) parameters, so we relax this to a warning.
9375         int DiagID =
9376             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9377         Diag(NewFD->getLocation(), DiagID)
9378             << FunctionType::getNameForCallConv(CC);
9379       }
9380     }
9381 
9382    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9383        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9384      checkNonTrivialCUnion(NewFD->getReturnType(),
9385                            NewFD->getReturnTypeSourceRange().getBegin(),
9386                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9387   } else {
9388     // C++11 [replacement.functions]p3:
9389     //  The program's definitions shall not be specified as inline.
9390     //
9391     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9392     //
9393     // Suppress the diagnostic if the function is __attribute__((used)), since
9394     // that forces an external definition to be emitted.
9395     if (D.getDeclSpec().isInlineSpecified() &&
9396         NewFD->isReplaceableGlobalAllocationFunction() &&
9397         !NewFD->hasAttr<UsedAttr>())
9398       Diag(D.getDeclSpec().getInlineSpecLoc(),
9399            diag::ext_operator_new_delete_declared_inline)
9400         << NewFD->getDeclName();
9401 
9402     // If the declarator is a template-id, translate the parser's template
9403     // argument list into our AST format.
9404     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9405       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9406       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9407       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9408       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9409                                          TemplateId->NumArgs);
9410       translateTemplateArguments(TemplateArgsPtr,
9411                                  TemplateArgs);
9412 
9413       HasExplicitTemplateArgs = true;
9414 
9415       if (NewFD->isInvalidDecl()) {
9416         HasExplicitTemplateArgs = false;
9417       } else if (FunctionTemplate) {
9418         // Function template with explicit template arguments.
9419         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9420           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9421 
9422         HasExplicitTemplateArgs = false;
9423       } else {
9424         assert((isFunctionTemplateSpecialization ||
9425                 D.getDeclSpec().isFriendSpecified()) &&
9426                "should have a 'template<>' for this decl");
9427         // "friend void foo<>(int);" is an implicit specialization decl.
9428         isFunctionTemplateSpecialization = true;
9429       }
9430     } else if (isFriend && isFunctionTemplateSpecialization) {
9431       // This combination is only possible in a recovery case;  the user
9432       // wrote something like:
9433       //   template <> friend void foo(int);
9434       // which we're recovering from as if the user had written:
9435       //   friend void foo<>(int);
9436       // Go ahead and fake up a template id.
9437       HasExplicitTemplateArgs = true;
9438       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9439       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9440     }
9441 
9442     // We do not add HD attributes to specializations here because
9443     // they may have different constexpr-ness compared to their
9444     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9445     // may end up with different effective targets. Instead, a
9446     // specialization inherits its target attributes from its template
9447     // in the CheckFunctionTemplateSpecialization() call below.
9448     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9449       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9450 
9451     // If it's a friend (and only if it's a friend), it's possible
9452     // that either the specialized function type or the specialized
9453     // template is dependent, and therefore matching will fail.  In
9454     // this case, don't check the specialization yet.
9455     bool InstantiationDependent = false;
9456     if (isFunctionTemplateSpecialization && isFriend &&
9457         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9458          TemplateSpecializationType::anyDependentTemplateArguments(
9459             TemplateArgs,
9460             InstantiationDependent))) {
9461       assert(HasExplicitTemplateArgs &&
9462              "friend function specialization without template args");
9463       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9464                                                        Previous))
9465         NewFD->setInvalidDecl();
9466     } else if (isFunctionTemplateSpecialization) {
9467       if (CurContext->isDependentContext() && CurContext->isRecord()
9468           && !isFriend) {
9469         isDependentClassScopeExplicitSpecialization = true;
9470       } else if (!NewFD->isInvalidDecl() &&
9471                  CheckFunctionTemplateSpecialization(
9472                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9473                      Previous))
9474         NewFD->setInvalidDecl();
9475 
9476       // C++ [dcl.stc]p1:
9477       //   A storage-class-specifier shall not be specified in an explicit
9478       //   specialization (14.7.3)
9479       FunctionTemplateSpecializationInfo *Info =
9480           NewFD->getTemplateSpecializationInfo();
9481       if (Info && SC != SC_None) {
9482         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9483           Diag(NewFD->getLocation(),
9484                diag::err_explicit_specialization_inconsistent_storage_class)
9485             << SC
9486             << FixItHint::CreateRemoval(
9487                                       D.getDeclSpec().getStorageClassSpecLoc());
9488 
9489         else
9490           Diag(NewFD->getLocation(),
9491                diag::ext_explicit_specialization_storage_class)
9492             << FixItHint::CreateRemoval(
9493                                       D.getDeclSpec().getStorageClassSpecLoc());
9494       }
9495     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9496       if (CheckMemberSpecialization(NewFD, Previous))
9497           NewFD->setInvalidDecl();
9498     }
9499 
9500     // Perform semantic checking on the function declaration.
9501     if (!isDependentClassScopeExplicitSpecialization) {
9502       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9503         CheckMain(NewFD, D.getDeclSpec());
9504 
9505       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9506         CheckMSVCRTEntryPoint(NewFD);
9507 
9508       if (!NewFD->isInvalidDecl())
9509         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9510                                                     isMemberSpecialization));
9511       else if (!Previous.empty())
9512         // Recover gracefully from an invalid redeclaration.
9513         D.setRedeclaration(true);
9514     }
9515 
9516     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9517             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9518            "previous declaration set still overloaded");
9519 
9520     NamedDecl *PrincipalDecl = (FunctionTemplate
9521                                 ? cast<NamedDecl>(FunctionTemplate)
9522                                 : NewFD);
9523 
9524     if (isFriend && NewFD->getPreviousDecl()) {
9525       AccessSpecifier Access = AS_public;
9526       if (!NewFD->isInvalidDecl())
9527         Access = NewFD->getPreviousDecl()->getAccess();
9528 
9529       NewFD->setAccess(Access);
9530       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9531     }
9532 
9533     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9534         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9535       PrincipalDecl->setNonMemberOperator();
9536 
9537     // If we have a function template, check the template parameter
9538     // list. This will check and merge default template arguments.
9539     if (FunctionTemplate) {
9540       FunctionTemplateDecl *PrevTemplate =
9541                                      FunctionTemplate->getPreviousDecl();
9542       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9543                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9544                                     : nullptr,
9545                             D.getDeclSpec().isFriendSpecified()
9546                               ? (D.isFunctionDefinition()
9547                                    ? TPC_FriendFunctionTemplateDefinition
9548                                    : TPC_FriendFunctionTemplate)
9549                               : (D.getCXXScopeSpec().isSet() &&
9550                                  DC && DC->isRecord() &&
9551                                  DC->isDependentContext())
9552                                   ? TPC_ClassTemplateMember
9553                                   : TPC_FunctionTemplate);
9554     }
9555 
9556     if (NewFD->isInvalidDecl()) {
9557       // Ignore all the rest of this.
9558     } else if (!D.isRedeclaration()) {
9559       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9560                                        AddToScope };
9561       // Fake up an access specifier if it's supposed to be a class member.
9562       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9563         NewFD->setAccess(AS_public);
9564 
9565       // Qualified decls generally require a previous declaration.
9566       if (D.getCXXScopeSpec().isSet()) {
9567         // ...with the major exception of templated-scope or
9568         // dependent-scope friend declarations.
9569 
9570         // TODO: we currently also suppress this check in dependent
9571         // contexts because (1) the parameter depth will be off when
9572         // matching friend templates and (2) we might actually be
9573         // selecting a friend based on a dependent factor.  But there
9574         // are situations where these conditions don't apply and we
9575         // can actually do this check immediately.
9576         //
9577         // Unless the scope is dependent, it's always an error if qualified
9578         // redeclaration lookup found nothing at all. Diagnose that now;
9579         // nothing will diagnose that error later.
9580         if (isFriend &&
9581             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9582              (!Previous.empty() && CurContext->isDependentContext()))) {
9583           // ignore these
9584         } else {
9585           // The user tried to provide an out-of-line definition for a
9586           // function that is a member of a class or namespace, but there
9587           // was no such member function declared (C++ [class.mfct]p2,
9588           // C++ [namespace.memdef]p2). For example:
9589           //
9590           // class X {
9591           //   void f() const;
9592           // };
9593           //
9594           // void X::f() { } // ill-formed
9595           //
9596           // Complain about this problem, and attempt to suggest close
9597           // matches (e.g., those that differ only in cv-qualifiers and
9598           // whether the parameter types are references).
9599 
9600           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9601                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9602             AddToScope = ExtraArgs.AddToScope;
9603             return Result;
9604           }
9605         }
9606 
9607         // Unqualified local friend declarations are required to resolve
9608         // to something.
9609       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9610         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9611                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9612           AddToScope = ExtraArgs.AddToScope;
9613           return Result;
9614         }
9615       }
9616     } else if (!D.isFunctionDefinition() &&
9617                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9618                !isFriend && !isFunctionTemplateSpecialization &&
9619                !isMemberSpecialization) {
9620       // An out-of-line member function declaration must also be a
9621       // definition (C++ [class.mfct]p2).
9622       // Note that this is not the case for explicit specializations of
9623       // function templates or member functions of class templates, per
9624       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9625       // extension for compatibility with old SWIG code which likes to
9626       // generate them.
9627       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9628         << D.getCXXScopeSpec().getRange();
9629     }
9630   }
9631 
9632   // If this is the first declaration of a library builtin function, add
9633   // attributes as appropriate.
9634   if (!D.isRedeclaration() &&
9635       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9636     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9637       if (unsigned BuiltinID = II->getBuiltinID()) {
9638         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9639           // Validate the type matches unless this builtin is specified as
9640           // matching regardless of its declared type.
9641           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9642             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9643           } else {
9644             ASTContext::GetBuiltinTypeError Error;
9645             LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
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