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__Float16:
142   case tok::kw___float128:
143   case tok::kw_wchar_t:
144   case tok::kw_bool:
145   case tok::kw___underlying_type:
146   case tok::kw___auto_type:
147     return true;
148 
149   case tok::annot_typename:
150   case tok::kw_char16_t:
151   case tok::kw_char32_t:
152   case tok::kw_typeof:
153   case tok::annot_decltype:
154   case tok::kw_decltype:
155     return getLangOpts().CPlusPlus;
156 
157   case tok::kw_char8_t:
158     return getLangOpts().Char8;
159 
160   default:
161     break;
162   }
163 
164   return false;
165 }
166 
167 namespace {
168 enum class UnqualifiedTypeNameLookupResult {
169   NotFound,
170   FoundNonType,
171   FoundType
172 };
173 } // end anonymous namespace
174 
175 /// Tries to perform unqualified lookup of the type decls in bases for
176 /// dependent class.
177 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
178 /// type decl, \a FoundType if only type decls are found.
179 static UnqualifiedTypeNameLookupResult
180 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
181                                 SourceLocation NameLoc,
182                                 const CXXRecordDecl *RD) {
183   if (!RD->hasDefinition())
184     return UnqualifiedTypeNameLookupResult::NotFound;
185   // Look for type decls in base classes.
186   UnqualifiedTypeNameLookupResult FoundTypeDecl =
187       UnqualifiedTypeNameLookupResult::NotFound;
188   for (const auto &Base : RD->bases()) {
189     const CXXRecordDecl *BaseRD = nullptr;
190     if (auto *BaseTT = Base.getType()->getAs<TagType>())
191       BaseRD = BaseTT->getAsCXXRecordDecl();
192     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
193       // Look for type decls in dependent base classes that have known primary
194       // templates.
195       if (!TST || !TST->isDependentType())
196         continue;
197       auto *TD = TST->getTemplateName().getAsTemplateDecl();
198       if (!TD)
199         continue;
200       if (auto *BasePrimaryTemplate =
201           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
202         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
203           BaseRD = BasePrimaryTemplate;
204         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
205           if (const ClassTemplatePartialSpecializationDecl *PS =
206                   CTD->findPartialSpecialization(Base.getType()))
207             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
208               BaseRD = PS;
209         }
210       }
211     }
212     if (BaseRD) {
213       for (NamedDecl *ND : BaseRD->lookup(&II)) {
214         if (!isa<TypeDecl>(ND))
215           return UnqualifiedTypeNameLookupResult::FoundNonType;
216         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217       }
218       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
219         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
220         case UnqualifiedTypeNameLookupResult::FoundNonType:
221           return UnqualifiedTypeNameLookupResult::FoundNonType;
222         case UnqualifiedTypeNameLookupResult::FoundType:
223           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224           break;
225         case UnqualifiedTypeNameLookupResult::NotFound:
226           break;
227         }
228       }
229     }
230   }
231 
232   return FoundTypeDecl;
233 }
234 
235 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
236                                                       const IdentifierInfo &II,
237                                                       SourceLocation NameLoc) {
238   // Lookup in the parent class template context, if any.
239   const CXXRecordDecl *RD = nullptr;
240   UnqualifiedTypeNameLookupResult FoundTypeDecl =
241       UnqualifiedTypeNameLookupResult::NotFound;
242   for (DeclContext *DC = S.CurContext;
243        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
244        DC = DC->getParent()) {
245     // Look for type decls in dependent base classes that have known primary
246     // templates.
247     RD = dyn_cast<CXXRecordDecl>(DC);
248     if (RD && RD->getDescribedClassTemplate())
249       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
250   }
251   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
252     return nullptr;
253 
254   // We found some types in dependent base classes.  Recover as if the user
255   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
256   // lookup during template instantiation.
257   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
258 
259   ASTContext &Context = S.Context;
260   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
261                                           cast<Type>(Context.getRecordType(RD)));
262   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
263 
264   CXXScopeSpec SS;
265   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
266 
267   TypeLocBuilder Builder;
268   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
269   DepTL.setNameLoc(NameLoc);
270   DepTL.setElaboratedKeywordLoc(SourceLocation());
271   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
272   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
273 }
274 
275 /// If the identifier refers to a type name within this scope,
276 /// return the declaration of that type.
277 ///
278 /// This routine performs ordinary name lookup of the identifier II
279 /// within the given scope, with optional C++ scope specifier SS, to
280 /// determine whether the name refers to a type. If so, returns an
281 /// opaque pointer (actually a QualType) corresponding to that
282 /// type. Otherwise, returns NULL.
283 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
284                              Scope *S, CXXScopeSpec *SS,
285                              bool isClassName, bool HasTrailingDot,
286                              ParsedType ObjectTypePtr,
287                              bool IsCtorOrDtorName,
288                              bool WantNontrivialTypeSourceInfo,
289                              bool IsClassTemplateDeductionContext,
290                              IdentifierInfo **CorrectedII) {
291   // FIXME: Consider allowing this outside C++1z mode as an extension.
292   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
293                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
294                               !isClassName && !HasTrailingDot;
295 
296   // Determine where we will perform name lookup.
297   DeclContext *LookupCtx = nullptr;
298   if (ObjectTypePtr) {
299     QualType ObjectType = ObjectTypePtr.get();
300     if (ObjectType->isRecordType())
301       LookupCtx = computeDeclContext(ObjectType);
302   } else if (SS && SS->isNotEmpty()) {
303     LookupCtx = computeDeclContext(*SS, false);
304 
305     if (!LookupCtx) {
306       if (isDependentScopeSpecifier(*SS)) {
307         // C++ [temp.res]p3:
308         //   A qualified-id that refers to a type and in which the
309         //   nested-name-specifier depends on a template-parameter (14.6.2)
310         //   shall be prefixed by the keyword typename to indicate that the
311         //   qualified-id denotes a type, forming an
312         //   elaborated-type-specifier (7.1.5.3).
313         //
314         // We therefore do not perform any name lookup if the result would
315         // refer to a member of an unknown specialization.
316         if (!isClassName && !IsCtorOrDtorName)
317           return nullptr;
318 
319         // We know from the grammar that this name refers to a type,
320         // so build a dependent node to describe the type.
321         if (WantNontrivialTypeSourceInfo)
322           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
323 
324         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
325         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
326                                        II, NameLoc);
327         return ParsedType::make(T);
328       }
329 
330       return nullptr;
331     }
332 
333     if (!LookupCtx->isDependentContext() &&
334         RequireCompleteDeclContext(*SS, LookupCtx))
335       return nullptr;
336   }
337 
338   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
339   // lookup for class-names.
340   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
341                                       LookupOrdinaryName;
342   LookupResult Result(*this, &II, NameLoc, Kind);
343   if (LookupCtx) {
344     // Perform "qualified" name lookup into the declaration context we
345     // computed, which is either the type of the base of a member access
346     // expression or the declaration context associated with a prior
347     // nested-name-specifier.
348     LookupQualifiedName(Result, LookupCtx);
349 
350     if (ObjectTypePtr && Result.empty()) {
351       // C++ [basic.lookup.classref]p3:
352       //   If the unqualified-id is ~type-name, the type-name is looked up
353       //   in the context of the entire postfix-expression. If the type T of
354       //   the object expression is of a class type C, the type-name is also
355       //   looked up in the scope of class C. At least one of the lookups shall
356       //   find a name that refers to (possibly cv-qualified) T.
357       LookupName(Result, S);
358     }
359   } else {
360     // Perform unqualified name lookup.
361     LookupName(Result, S);
362 
363     // For unqualified lookup in a class template in MSVC mode, look into
364     // dependent base classes where the primary class template is known.
365     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
366       if (ParsedType TypeInBase =
367               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
368         return TypeInBase;
369     }
370   }
371 
372   NamedDecl *IIDecl = nullptr;
373   switch (Result.getResultKind()) {
374   case LookupResult::NotFound:
375   case LookupResult::NotFoundInCurrentInstantiation:
376     if (CorrectedII) {
377       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
378                                AllowDeducedTemplate);
379       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
380                                               S, SS, CCC, CTK_ErrorRecovery);
381       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
382       TemplateTy Template;
383       bool MemberOfUnknownSpecialization;
384       UnqualifiedId TemplateName;
385       TemplateName.setIdentifier(NewII, NameLoc);
386       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
387       CXXScopeSpec NewSS, *NewSSPtr = SS;
388       if (SS && NNS) {
389         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
390         NewSSPtr = &NewSS;
391       }
392       if (Correction && (NNS || NewII != &II) &&
393           // Ignore a correction to a template type as the to-be-corrected
394           // identifier is not a template (typo correction for template names
395           // is handled elsewhere).
396           !(getLangOpts().CPlusPlus && NewSSPtr &&
397             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
398                            Template, MemberOfUnknownSpecialization))) {
399         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
400                                     isClassName, HasTrailingDot, ObjectTypePtr,
401                                     IsCtorOrDtorName,
402                                     WantNontrivialTypeSourceInfo,
403                                     IsClassTemplateDeductionContext);
404         if (Ty) {
405           diagnoseTypo(Correction,
406                        PDiag(diag::err_unknown_type_or_class_name_suggest)
407                          << Result.getLookupName() << isClassName);
408           if (SS && NNS)
409             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
410           *CorrectedII = NewII;
411           return Ty;
412         }
413       }
414     }
415     // If typo correction failed or was not performed, fall through
416     LLVM_FALLTHROUGH;
417   case LookupResult::FoundOverloaded:
418   case LookupResult::FoundUnresolvedValue:
419     Result.suppressDiagnostics();
420     return nullptr;
421 
422   case LookupResult::Ambiguous:
423     // Recover from type-hiding ambiguities by hiding the type.  We'll
424     // do the lookup again when looking for an object, and we can
425     // diagnose the error then.  If we don't do this, then the error
426     // about hiding the type will be immediately followed by an error
427     // that only makes sense if the identifier was treated like a type.
428     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
429       Result.suppressDiagnostics();
430       return nullptr;
431     }
432 
433     // Look to see if we have a type anywhere in the list of results.
434     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
435          Res != ResEnd; ++Res) {
436       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
437           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
438         if (!IIDecl ||
439             (*Res)->getLocation().getRawEncoding() <
440               IIDecl->getLocation().getRawEncoding())
441           IIDecl = *Res;
442       }
443     }
444 
445     if (!IIDecl) {
446       // None of the entities we found is a type, so there is no way
447       // to even assume that the result is a type. In this case, don't
448       // complain about the ambiguity. The parser will either try to
449       // perform this lookup again (e.g., as an object name), which
450       // will produce the ambiguity, or will complain that it expected
451       // a type name.
452       Result.suppressDiagnostics();
453       return nullptr;
454     }
455 
456     // We found a type within the ambiguous lookup; diagnose the
457     // ambiguity and then return that type. This might be the right
458     // answer, or it might not be, but it suppresses any attempt to
459     // perform the name lookup again.
460     break;
461 
462   case LookupResult::Found:
463     IIDecl = Result.getFoundDecl();
464     break;
465   }
466 
467   assert(IIDecl && "Didn't find decl");
468 
469   QualType T;
470   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
471     // C++ [class.qual]p2: A lookup that would find the injected-class-name
472     // instead names the constructors of the class, except when naming a class.
473     // This is ill-formed when we're not actually forming a ctor or dtor name.
474     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
475     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
476     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
477         FoundRD->isInjectedClassName() &&
478         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
479       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
480           << &II << /*Type*/1;
481 
482     DiagnoseUseOfDecl(IIDecl, NameLoc);
483 
484     T = Context.getTypeDeclType(TD);
485     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
486   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
487     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
488     if (!HasTrailingDot)
489       T = Context.getObjCInterfaceType(IDecl);
490   } else if (AllowDeducedTemplate) {
491     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
492       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
493                                                        QualType(), false);
494   }
495 
496   if (T.isNull()) {
497     // If it's not plausibly a type, suppress diagnostics.
498     Result.suppressDiagnostics();
499     return nullptr;
500   }
501 
502   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
503   // constructor or destructor name (in such a case, the scope specifier
504   // will be attached to the enclosing Expr or Decl node).
505   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
506       !isa<ObjCInterfaceDecl>(IIDecl)) {
507     if (WantNontrivialTypeSourceInfo) {
508       // Construct a type with type-source information.
509       TypeLocBuilder Builder;
510       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
511 
512       T = getElaboratedType(ETK_None, *SS, T);
513       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
514       ElabTL.setElaboratedKeywordLoc(SourceLocation());
515       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
516       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
517     } else {
518       T = getElaboratedType(ETK_None, *SS, T);
519     }
520   }
521 
522   return ParsedType::make(T);
523 }
524 
525 // Builds a fake NNS for the given decl context.
526 static NestedNameSpecifier *
527 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
528   for (;; DC = DC->getLookupParent()) {
529     DC = DC->getPrimaryContext();
530     auto *ND = dyn_cast<NamespaceDecl>(DC);
531     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
532       return NestedNameSpecifier::Create(Context, nullptr, ND);
533     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
534       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
535                                          RD->getTypeForDecl());
536     else if (isa<TranslationUnitDecl>(DC))
537       return NestedNameSpecifier::GlobalSpecifier(Context);
538   }
539   llvm_unreachable("something isn't in TU scope?");
540 }
541 
542 /// Find the parent class with dependent bases of the innermost enclosing method
543 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
544 /// up allowing unqualified dependent type names at class-level, which MSVC
545 /// correctly rejects.
546 static const CXXRecordDecl *
547 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
548   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
549     DC = DC->getPrimaryContext();
550     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
551       if (MD->getParent()->hasAnyDependentBases())
552         return MD->getParent();
553   }
554   return nullptr;
555 }
556 
557 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
558                                           SourceLocation NameLoc,
559                                           bool IsTemplateTypeArg) {
560   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
561 
562   NestedNameSpecifier *NNS = nullptr;
563   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
564     // If we weren't able to parse a default template argument, delay lookup
565     // until instantiation time by making a non-dependent DependentTypeName. We
566     // pretend we saw a NestedNameSpecifier referring to the current scope, and
567     // lookup is retried.
568     // FIXME: This hurts our diagnostic quality, since we get errors like "no
569     // type named 'Foo' in 'current_namespace'" when the user didn't write any
570     // name specifiers.
571     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
572     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
573   } else if (const CXXRecordDecl *RD =
574                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
575     // Build a DependentNameType that will perform lookup into RD at
576     // instantiation time.
577     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
578                                       RD->getTypeForDecl());
579 
580     // Diagnose that this identifier was undeclared, and retry the lookup during
581     // template instantiation.
582     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
583                                                                       << RD;
584   } else {
585     // This is not a situation that we should recover from.
586     return ParsedType();
587   }
588 
589   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
590 
591   // Build type location information.  We synthesized the qualifier, so we have
592   // to build a fake NestedNameSpecifierLoc.
593   NestedNameSpecifierLocBuilder NNSLocBuilder;
594   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
595   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
596 
597   TypeLocBuilder Builder;
598   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
599   DepTL.setNameLoc(NameLoc);
600   DepTL.setElaboratedKeywordLoc(SourceLocation());
601   DepTL.setQualifierLoc(QualifierLoc);
602   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
603 }
604 
605 /// isTagName() - This method is called *for error recovery purposes only*
606 /// to determine if the specified name is a valid tag name ("struct foo").  If
607 /// so, this returns the TST for the tag corresponding to it (TST_enum,
608 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
609 /// cases in C where the user forgot to specify the tag.
610 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
611   // Do a tag name lookup in this scope.
612   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
613   LookupName(R, S, false);
614   R.suppressDiagnostics();
615   if (R.getResultKind() == LookupResult::Found)
616     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
617       switch (TD->getTagKind()) {
618       case TTK_Struct: return DeclSpec::TST_struct;
619       case TTK_Interface: return DeclSpec::TST_interface;
620       case TTK_Union:  return DeclSpec::TST_union;
621       case TTK_Class:  return DeclSpec::TST_class;
622       case TTK_Enum:   return DeclSpec::TST_enum;
623       }
624     }
625 
626   return DeclSpec::TST_unspecified;
627 }
628 
629 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
630 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
631 /// then downgrade the missing typename error to a warning.
632 /// This is needed for MSVC compatibility; Example:
633 /// @code
634 /// template<class T> class A {
635 /// public:
636 ///   typedef int TYPE;
637 /// };
638 /// template<class T> class B : public A<T> {
639 /// public:
640 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
641 /// };
642 /// @endcode
643 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
644   if (CurContext->isRecord()) {
645     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
646       return true;
647 
648     const Type *Ty = SS->getScopeRep()->getAsType();
649 
650     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
651     for (const auto &Base : RD->bases())
652       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
653         return true;
654     return S->isFunctionPrototypeScope();
655   }
656   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
657 }
658 
659 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
660                                    SourceLocation IILoc,
661                                    Scope *S,
662                                    CXXScopeSpec *SS,
663                                    ParsedType &SuggestedType,
664                                    bool IsTemplateName) {
665   // Don't report typename errors for editor placeholders.
666   if (II->isEditorPlaceholder())
667     return;
668   // We don't have anything to suggest (yet).
669   SuggestedType = nullptr;
670 
671   // There may have been a typo in the name of the type. Look up typo
672   // results, in case we have something that we can suggest.
673   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
674                            /*AllowTemplates=*/IsTemplateName,
675                            /*AllowNonTemplates=*/!IsTemplateName);
676   if (TypoCorrection Corrected =
677           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
678                       CCC, CTK_ErrorRecovery)) {
679     // FIXME: Support error recovery for the template-name case.
680     bool CanRecover = !IsTemplateName;
681     if (Corrected.isKeyword()) {
682       // We corrected to a keyword.
683       diagnoseTypo(Corrected,
684                    PDiag(IsTemplateName ? diag::err_no_template_suggest
685                                         : diag::err_unknown_typename_suggest)
686                        << II);
687       II = Corrected.getCorrectionAsIdentifierInfo();
688     } else {
689       // We found a similarly-named type or interface; suggest that.
690       if (!SS || !SS->isSet()) {
691         diagnoseTypo(Corrected,
692                      PDiag(IsTemplateName ? diag::err_no_template_suggest
693                                           : diag::err_unknown_typename_suggest)
694                          << II, CanRecover);
695       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
696         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
697         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
698                                 II->getName().equals(CorrectedStr);
699         diagnoseTypo(Corrected,
700                      PDiag(IsTemplateName
701                                ? diag::err_no_member_template_suggest
702                                : diag::err_unknown_nested_typename_suggest)
703                          << II << DC << DroppedSpecifier << SS->getRange(),
704                      CanRecover);
705       } else {
706         llvm_unreachable("could not have corrected a typo here");
707       }
708 
709       if (!CanRecover)
710         return;
711 
712       CXXScopeSpec tmpSS;
713       if (Corrected.getCorrectionSpecifier())
714         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
715                           SourceRange(IILoc));
716       // FIXME: Support class template argument deduction here.
717       SuggestedType =
718           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
719                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
720                       /*IsCtorOrDtorName=*/false,
721                       /*WantNontrivialTypeSourceInfo=*/true);
722     }
723     return;
724   }
725 
726   if (getLangOpts().CPlusPlus && !IsTemplateName) {
727     // See if II is a class template that the user forgot to pass arguments to.
728     UnqualifiedId Name;
729     Name.setIdentifier(II, IILoc);
730     CXXScopeSpec EmptySS;
731     TemplateTy TemplateResult;
732     bool MemberOfUnknownSpecialization;
733     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
734                        Name, nullptr, true, TemplateResult,
735                        MemberOfUnknownSpecialization) == TNK_Type_template) {
736       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
737       return;
738     }
739   }
740 
741   // FIXME: Should we move the logic that tries to recover from a missing tag
742   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
743 
744   if (!SS || (!SS->isSet() && !SS->isInvalid()))
745     Diag(IILoc, IsTemplateName ? diag::err_no_template
746                                : diag::err_unknown_typename)
747         << II;
748   else if (DeclContext *DC = computeDeclContext(*SS, false))
749     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
750                                : diag::err_typename_nested_not_found)
751         << II << DC << SS->getRange();
752   else if (isDependentScopeSpecifier(*SS)) {
753     unsigned DiagID = diag::err_typename_missing;
754     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
755       DiagID = diag::ext_typename_missing;
756 
757     Diag(SS->getRange().getBegin(), DiagID)
758       << SS->getScopeRep() << II->getName()
759       << SourceRange(SS->getRange().getBegin(), IILoc)
760       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
761     SuggestedType = ActOnTypenameType(S, SourceLocation(),
762                                       *SS, *II, IILoc).get();
763   } else {
764     assert(SS && SS->isInvalid() &&
765            "Invalid scope specifier has already been diagnosed");
766   }
767 }
768 
769 /// Determine whether the given result set contains either a type name
770 /// or
771 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
772   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
773                        NextToken.is(tok::less);
774 
775   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
776     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
777       return true;
778 
779     if (CheckTemplate && isa<TemplateDecl>(*I))
780       return true;
781   }
782 
783   return false;
784 }
785 
786 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
787                                     Scope *S, CXXScopeSpec &SS,
788                                     IdentifierInfo *&Name,
789                                     SourceLocation NameLoc) {
790   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
791   SemaRef.LookupParsedName(R, S, &SS);
792   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
793     StringRef FixItTagName;
794     switch (Tag->getTagKind()) {
795       case TTK_Class:
796         FixItTagName = "class ";
797         break;
798 
799       case TTK_Enum:
800         FixItTagName = "enum ";
801         break;
802 
803       case TTK_Struct:
804         FixItTagName = "struct ";
805         break;
806 
807       case TTK_Interface:
808         FixItTagName = "__interface ";
809         break;
810 
811       case TTK_Union:
812         FixItTagName = "union ";
813         break;
814     }
815 
816     StringRef TagName = FixItTagName.drop_back();
817     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
818       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
819       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
820 
821     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
822          I != IEnd; ++I)
823       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
824         << Name << TagName;
825 
826     // Replace lookup results with just the tag decl.
827     Result.clear(Sema::LookupTagName);
828     SemaRef.LookupParsedName(Result, S, &SS);
829     return true;
830   }
831 
832   return false;
833 }
834 
835 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
836 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
837                                   QualType T, SourceLocation NameLoc) {
838   ASTContext &Context = S.Context;
839 
840   TypeLocBuilder Builder;
841   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
842 
843   T = S.getElaboratedType(ETK_None, SS, T);
844   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
845   ElabTL.setElaboratedKeywordLoc(SourceLocation());
846   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
847   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
848 }
849 
850 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
851                                             IdentifierInfo *&Name,
852                                             SourceLocation NameLoc,
853                                             const Token &NextToken,
854                                             CorrectionCandidateCallback *CCC) {
855   DeclarationNameInfo NameInfo(Name, NameLoc);
856   ObjCMethodDecl *CurMethod = getCurMethodDecl();
857 
858   assert(NextToken.isNot(tok::coloncolon) &&
859          "parse nested name specifiers before calling ClassifyName");
860   if (getLangOpts().CPlusPlus && SS.isSet() &&
861       isCurrentClassName(*Name, S, &SS)) {
862     // Per [class.qual]p2, this names the constructors of SS, not the
863     // injected-class-name. We don't have a classification for that.
864     // There's not much point caching this result, since the parser
865     // will reject it later.
866     return NameClassification::Unknown();
867   }
868 
869   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
870   LookupParsedName(Result, S, &SS, !CurMethod);
871 
872   if (SS.isInvalid())
873     return NameClassification::Error();
874 
875   // For unqualified lookup in a class template in MSVC mode, look into
876   // dependent base classes where the primary class template is known.
877   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
878     if (ParsedType TypeInBase =
879             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
880       return TypeInBase;
881   }
882 
883   // Perform lookup for Objective-C instance variables (including automatically
884   // synthesized instance variables), if we're in an Objective-C method.
885   // FIXME: This lookup really, really needs to be folded in to the normal
886   // unqualified lookup mechanism.
887   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
888     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
889     if (Ivar.isInvalid())
890       return NameClassification::Error();
891     if (Ivar.isUsable())
892       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
893 
894     // We defer builtin creation until after ivar lookup inside ObjC methods.
895     if (Result.empty())
896       LookupBuiltin(Result);
897   }
898 
899   bool SecondTry = false;
900   bool IsFilteredTemplateName = false;
901 
902 Corrected:
903   switch (Result.getResultKind()) {
904   case LookupResult::NotFound:
905     // If an unqualified-id is followed by a '(', then we have a function
906     // call.
907     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
908       // In C++, this is an ADL-only call.
909       // FIXME: Reference?
910       if (getLangOpts().CPlusPlus)
911         return NameClassification::UndeclaredNonType();
912 
913       // C90 6.3.2.2:
914       //   If the expression that precedes the parenthesized argument list in a
915       //   function call consists solely of an identifier, and if no
916       //   declaration is visible for this identifier, the identifier is
917       //   implicitly declared exactly as if, in the innermost block containing
918       //   the function call, the declaration
919       //
920       //     extern int identifier ();
921       //
922       //   appeared.
923       //
924       // We also allow this in C99 as an extension.
925       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
926         return NameClassification::NonType(D);
927     }
928 
929     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
930       // In C++20 onwards, this could be an ADL-only call to a function
931       // template, and we're required to assume that this is a template name.
932       //
933       // FIXME: Find a way to still do typo correction in this case.
934       TemplateName Template =
935           Context.getAssumedTemplateName(NameInfo.getName());
936       return NameClassification::UndeclaredTemplate(Template);
937     }
938 
939     // In C, we first see whether there is a tag type by the same name, in
940     // which case it's likely that the user just forgot to write "enum",
941     // "struct", or "union".
942     if (!getLangOpts().CPlusPlus && !SecondTry &&
943         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
944       break;
945     }
946 
947     // Perform typo correction to determine if there is another name that is
948     // close to this name.
949     if (!SecondTry && CCC) {
950       SecondTry = true;
951       if (TypoCorrection Corrected =
952               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
953                           &SS, *CCC, CTK_ErrorRecovery)) {
954         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
955         unsigned QualifiedDiag = diag::err_no_member_suggest;
956 
957         NamedDecl *FirstDecl = Corrected.getFoundDecl();
958         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
959         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
960             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
961           UnqualifiedDiag = diag::err_no_template_suggest;
962           QualifiedDiag = diag::err_no_member_template_suggest;
963         } else if (UnderlyingFirstDecl &&
964                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
965                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
966                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
967           UnqualifiedDiag = diag::err_unknown_typename_suggest;
968           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
969         }
970 
971         if (SS.isEmpty()) {
972           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
973         } else {// FIXME: is this even reachable? Test it.
974           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
975           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
976                                   Name->getName().equals(CorrectedStr);
977           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
978                                     << Name << computeDeclContext(SS, false)
979                                     << DroppedSpecifier << SS.getRange());
980         }
981 
982         // Update the name, so that the caller has the new name.
983         Name = Corrected.getCorrectionAsIdentifierInfo();
984 
985         // Typo correction corrected to a keyword.
986         if (Corrected.isKeyword())
987           return Name;
988 
989         // Also update the LookupResult...
990         // FIXME: This should probably go away at some point
991         Result.clear();
992         Result.setLookupName(Corrected.getCorrection());
993         if (FirstDecl)
994           Result.addDecl(FirstDecl);
995 
996         // If we found an Objective-C instance variable, let
997         // LookupInObjCMethod build the appropriate expression to
998         // reference the ivar.
999         // FIXME: This is a gross hack.
1000         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1001           DeclResult R =
1002               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1003           if (R.isInvalid())
1004             return NameClassification::Error();
1005           if (R.isUsable())
1006             return NameClassification::NonType(Ivar);
1007         }
1008 
1009         goto Corrected;
1010       }
1011     }
1012 
1013     // We failed to correct; just fall through and let the parser deal with it.
1014     Result.suppressDiagnostics();
1015     return NameClassification::Unknown();
1016 
1017   case LookupResult::NotFoundInCurrentInstantiation: {
1018     // We performed name lookup into the current instantiation, and there were
1019     // dependent bases, so we treat this result the same way as any other
1020     // dependent nested-name-specifier.
1021 
1022     // C++ [temp.res]p2:
1023     //   A name used in a template declaration or definition and that is
1024     //   dependent on a template-parameter is assumed not to name a type
1025     //   unless the applicable name lookup finds a type name or the name is
1026     //   qualified by the keyword typename.
1027     //
1028     // FIXME: If the next token is '<', we might want to ask the parser to
1029     // perform some heroics to see if we actually have a
1030     // template-argument-list, which would indicate a missing 'template'
1031     // keyword here.
1032     return NameClassification::DependentNonType();
1033   }
1034 
1035   case LookupResult::Found:
1036   case LookupResult::FoundOverloaded:
1037   case LookupResult::FoundUnresolvedValue:
1038     break;
1039 
1040   case LookupResult::Ambiguous:
1041     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1042         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1043                                       /*AllowDependent=*/false)) {
1044       // C++ [temp.local]p3:
1045       //   A lookup that finds an injected-class-name (10.2) can result in an
1046       //   ambiguity in certain cases (for example, if it is found in more than
1047       //   one base class). If all of the injected-class-names that are found
1048       //   refer to specializations of the same class template, and if the name
1049       //   is followed by a template-argument-list, the reference refers to the
1050       //   class template itself and not a specialization thereof, and is not
1051       //   ambiguous.
1052       //
1053       // This filtering can make an ambiguous result into an unambiguous one,
1054       // so try again after filtering out template names.
1055       FilterAcceptableTemplateNames(Result);
1056       if (!Result.isAmbiguous()) {
1057         IsFilteredTemplateName = true;
1058         break;
1059       }
1060     }
1061 
1062     // Diagnose the ambiguity and return an error.
1063     return NameClassification::Error();
1064   }
1065 
1066   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1067       (IsFilteredTemplateName ||
1068        hasAnyAcceptableTemplateNames(
1069            Result, /*AllowFunctionTemplates=*/true,
1070            /*AllowDependent=*/false,
1071            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1072                getLangOpts().CPlusPlus20))) {
1073     // C++ [temp.names]p3:
1074     //   After name lookup (3.4) finds that a name is a template-name or that
1075     //   an operator-function-id or a literal- operator-id refers to a set of
1076     //   overloaded functions any member of which is a function template if
1077     //   this is followed by a <, the < is always taken as the delimiter of a
1078     //   template-argument-list and never as the less-than operator.
1079     // C++2a [temp.names]p2:
1080     //   A name is also considered to refer to a template if it is an
1081     //   unqualified-id followed by a < and name lookup finds either one
1082     //   or more functions or finds nothing.
1083     if (!IsFilteredTemplateName)
1084       FilterAcceptableTemplateNames(Result);
1085 
1086     bool IsFunctionTemplate;
1087     bool IsVarTemplate;
1088     TemplateName Template;
1089     if (Result.end() - Result.begin() > 1) {
1090       IsFunctionTemplate = true;
1091       Template = Context.getOverloadedTemplateName(Result.begin(),
1092                                                    Result.end());
1093     } else if (!Result.empty()) {
1094       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1095           *Result.begin(), /*AllowFunctionTemplates=*/true,
1096           /*AllowDependent=*/false));
1097       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1098       IsVarTemplate = isa<VarTemplateDecl>(TD);
1099 
1100       if (SS.isNotEmpty())
1101         Template =
1102             Context.getQualifiedTemplateName(SS.getScopeRep(),
1103                                              /*TemplateKeyword=*/false, TD);
1104       else
1105         Template = TemplateName(TD);
1106     } else {
1107       // All results were non-template functions. This is a function template
1108       // name.
1109       IsFunctionTemplate = true;
1110       Template = Context.getAssumedTemplateName(NameInfo.getName());
1111     }
1112 
1113     if (IsFunctionTemplate) {
1114       // Function templates always go through overload resolution, at which
1115       // point we'll perform the various checks (e.g., accessibility) we need
1116       // to based on which function we selected.
1117       Result.suppressDiagnostics();
1118 
1119       return NameClassification::FunctionTemplate(Template);
1120     }
1121 
1122     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1123                          : NameClassification::TypeTemplate(Template);
1124   }
1125 
1126   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1127   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1128     DiagnoseUseOfDecl(Type, NameLoc);
1129     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1130     QualType T = Context.getTypeDeclType(Type);
1131     if (SS.isNotEmpty())
1132       return buildNestedType(*this, SS, T, NameLoc);
1133     return ParsedType::make(T);
1134   }
1135 
1136   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1137   if (!Class) {
1138     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1139     if (ObjCCompatibleAliasDecl *Alias =
1140             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1141       Class = Alias->getClassInterface();
1142   }
1143 
1144   if (Class) {
1145     DiagnoseUseOfDecl(Class, NameLoc);
1146 
1147     if (NextToken.is(tok::period)) {
1148       // Interface. <something> is parsed as a property reference expression.
1149       // Just return "unknown" as a fall-through for now.
1150       Result.suppressDiagnostics();
1151       return NameClassification::Unknown();
1152     }
1153 
1154     QualType T = Context.getObjCInterfaceType(Class);
1155     return ParsedType::make(T);
1156   }
1157 
1158   if (isa<ConceptDecl>(FirstDecl))
1159     return NameClassification::Concept(
1160         TemplateName(cast<TemplateDecl>(FirstDecl)));
1161 
1162   // We can have a type template here if we're classifying a template argument.
1163   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1164       !isa<VarTemplateDecl>(FirstDecl))
1165     return NameClassification::TypeTemplate(
1166         TemplateName(cast<TemplateDecl>(FirstDecl)));
1167 
1168   // Check for a tag type hidden by a non-type decl in a few cases where it
1169   // seems likely a type is wanted instead of the non-type that was found.
1170   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1171   if ((NextToken.is(tok::identifier) ||
1172        (NextIsOp &&
1173         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1174       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1175     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1176     DiagnoseUseOfDecl(Type, NameLoc);
1177     QualType T = Context.getTypeDeclType(Type);
1178     if (SS.isNotEmpty())
1179       return buildNestedType(*this, SS, T, NameLoc);
1180     return ParsedType::make(T);
1181   }
1182 
1183   // FIXME: This is context-dependent. We need to defer building the member
1184   // expression until the classification is consumed.
1185   if (FirstDecl->isCXXClassMember())
1186     return NameClassification::ContextIndependentExpr(
1187         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1188                                         S));
1189 
1190   // If we already know which single declaration is referenced, just annotate
1191   // that declaration directly.
1192   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1193   if (Result.isSingleResult() && !ADL)
1194     return NameClassification::NonType(Result.getRepresentativeDecl());
1195 
1196   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1197   // context in which we performed classification, so it's safe to do now.
1198   return NameClassification::ContextIndependentExpr(
1199       BuildDeclarationNameExpr(SS, Result, ADL));
1200 }
1201 
1202 ExprResult
1203 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1204                                              SourceLocation NameLoc) {
1205   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1206   CXXScopeSpec SS;
1207   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1208   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1209 }
1210 
1211 ExprResult
1212 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1213                                             IdentifierInfo *Name,
1214                                             SourceLocation NameLoc,
1215                                             bool IsAddressOfOperand) {
1216   DeclarationNameInfo NameInfo(Name, NameLoc);
1217   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1218                                     NameInfo, IsAddressOfOperand,
1219                                     /*TemplateArgs=*/nullptr);
1220 }
1221 
1222 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1223                                               NamedDecl *Found,
1224                                               SourceLocation NameLoc,
1225                                               const Token &NextToken) {
1226   if (getCurMethodDecl() && SS.isEmpty())
1227     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1228       return BuildIvarRefExpr(S, NameLoc, Ivar);
1229 
1230   // Reconstruct the lookup result.
1231   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1232   Result.addDecl(Found);
1233   Result.resolveKind();
1234 
1235   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1236   return BuildDeclarationNameExpr(SS, Result, ADL);
1237 }
1238 
1239 Sema::TemplateNameKindForDiagnostics
1240 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1241   auto *TD = Name.getAsTemplateDecl();
1242   if (!TD)
1243     return TemplateNameKindForDiagnostics::DependentTemplate;
1244   if (isa<ClassTemplateDecl>(TD))
1245     return TemplateNameKindForDiagnostics::ClassTemplate;
1246   if (isa<FunctionTemplateDecl>(TD))
1247     return TemplateNameKindForDiagnostics::FunctionTemplate;
1248   if (isa<VarTemplateDecl>(TD))
1249     return TemplateNameKindForDiagnostics::VarTemplate;
1250   if (isa<TypeAliasTemplateDecl>(TD))
1251     return TemplateNameKindForDiagnostics::AliasTemplate;
1252   if (isa<TemplateTemplateParmDecl>(TD))
1253     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1254   if (isa<ConceptDecl>(TD))
1255     return TemplateNameKindForDiagnostics::Concept;
1256   return TemplateNameKindForDiagnostics::DependentTemplate;
1257 }
1258 
1259 // Determines the context to return to after temporarily entering a
1260 // context.  This depends in an unnecessarily complicated way on the
1261 // exact ordering of callbacks from the parser.
1262 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1263 
1264   // Functions defined inline within classes aren't parsed until we've
1265   // finished parsing the top-level class, so the top-level class is
1266   // the context we'll need to return to.
1267   // A Lambda call operator whose parent is a class must not be treated
1268   // as an inline member function.  A Lambda can be used legally
1269   // either as an in-class member initializer or a default argument.  These
1270   // are parsed once the class has been marked complete and so the containing
1271   // context would be the nested class (when the lambda is defined in one);
1272   // If the class is not complete, then the lambda is being used in an
1273   // ill-formed fashion (such as to specify the width of a bit-field, or
1274   // in an array-bound) - in which case we still want to return the
1275   // lexically containing DC (which could be a nested class).
1276   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1277     DC = DC->getLexicalParent();
1278 
1279     // A function not defined within a class will always return to its
1280     // lexical context.
1281     if (!isa<CXXRecordDecl>(DC))
1282       return DC;
1283 
1284     // A C++ inline method/friend is parsed *after* the topmost class
1285     // it was declared in is fully parsed ("complete");  the topmost
1286     // class is the context we need to return to.
1287     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1288       DC = RD;
1289 
1290     // Return the declaration context of the topmost class the inline method is
1291     // declared in.
1292     return DC;
1293   }
1294 
1295   return DC->getLexicalParent();
1296 }
1297 
1298 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1299   assert(getContainingDC(DC) == CurContext &&
1300       "The next DeclContext should be lexically contained in the current one.");
1301   CurContext = DC;
1302   S->setEntity(DC);
1303 }
1304 
1305 void Sema::PopDeclContext() {
1306   assert(CurContext && "DeclContext imbalance!");
1307 
1308   CurContext = getContainingDC(CurContext);
1309   assert(CurContext && "Popped translation unit!");
1310 }
1311 
1312 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1313                                                                     Decl *D) {
1314   // Unlike PushDeclContext, the context to which we return is not necessarily
1315   // the containing DC of TD, because the new context will be some pre-existing
1316   // TagDecl definition instead of a fresh one.
1317   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1318   CurContext = cast<TagDecl>(D)->getDefinition();
1319   assert(CurContext && "skipping definition of undefined tag");
1320   // Start lookups from the parent of the current context; we don't want to look
1321   // into the pre-existing complete definition.
1322   S->setEntity(CurContext->getLookupParent());
1323   return Result;
1324 }
1325 
1326 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1327   CurContext = static_cast<decltype(CurContext)>(Context);
1328 }
1329 
1330 /// EnterDeclaratorContext - Used when we must lookup names in the context
1331 /// of a declarator's nested name specifier.
1332 ///
1333 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1334   // C++0x [basic.lookup.unqual]p13:
1335   //   A name used in the definition of a static data member of class
1336   //   X (after the qualified-id of the static member) is looked up as
1337   //   if the name was used in a member function of X.
1338   // C++0x [basic.lookup.unqual]p14:
1339   //   If a variable member of a namespace is defined outside of the
1340   //   scope of its namespace then any name used in the definition of
1341   //   the variable member (after the declarator-id) is looked up as
1342   //   if the definition of the variable member occurred in its
1343   //   namespace.
1344   // Both of these imply that we should push a scope whose context
1345   // is the semantic context of the declaration.  We can't use
1346   // PushDeclContext here because that context is not necessarily
1347   // lexically contained in the current context.  Fortunately,
1348   // the containing scope should have the appropriate information.
1349 
1350   assert(!S->getEntity() && "scope already has entity");
1351 
1352 #ifndef NDEBUG
1353   Scope *Ancestor = S->getParent();
1354   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1355   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1356 #endif
1357 
1358   CurContext = DC;
1359   S->setEntity(DC);
1360 }
1361 
1362 void Sema::ExitDeclaratorContext(Scope *S) {
1363   assert(S->getEntity() == CurContext && "Context imbalance!");
1364 
1365   // Switch back to the lexical context.  The safety of this is
1366   // enforced by an assert in EnterDeclaratorContext.
1367   Scope *Ancestor = S->getParent();
1368   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1369   CurContext = Ancestor->getEntity();
1370 
1371   // We don't need to do anything with the scope, which is going to
1372   // disappear.
1373 }
1374 
1375 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1376   // We assume that the caller has already called
1377   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1378   FunctionDecl *FD = D->getAsFunction();
1379   if (!FD)
1380     return;
1381 
1382   // Same implementation as PushDeclContext, but enters the context
1383   // from the lexical parent, rather than the top-level class.
1384   assert(CurContext == FD->getLexicalParent() &&
1385     "The next DeclContext should be lexically contained in the current one.");
1386   CurContext = FD;
1387   S->setEntity(CurContext);
1388 
1389   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1390     ParmVarDecl *Param = FD->getParamDecl(P);
1391     // If the parameter has an identifier, then add it to the scope
1392     if (Param->getIdentifier()) {
1393       S->AddDecl(Param);
1394       IdResolver.AddDecl(Param);
1395     }
1396   }
1397 }
1398 
1399 void Sema::ActOnExitFunctionContext() {
1400   // Same implementation as PopDeclContext, but returns to the lexical parent,
1401   // rather than the top-level class.
1402   assert(CurContext && "DeclContext imbalance!");
1403   CurContext = CurContext->getLexicalParent();
1404   assert(CurContext && "Popped translation unit!");
1405 }
1406 
1407 /// Determine whether we allow overloading of the function
1408 /// PrevDecl with another declaration.
1409 ///
1410 /// This routine determines whether overloading is possible, not
1411 /// whether some new function is actually an overload. It will return
1412 /// true in C++ (where we can always provide overloads) or, as an
1413 /// extension, in C when the previous function is already an
1414 /// overloaded function declaration or has the "overloadable"
1415 /// attribute.
1416 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1417                                        ASTContext &Context,
1418                                        const FunctionDecl *New) {
1419   if (Context.getLangOpts().CPlusPlus)
1420     return true;
1421 
1422   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1423     return true;
1424 
1425   return Previous.getResultKind() == LookupResult::Found &&
1426          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1427           New->hasAttr<OverloadableAttr>());
1428 }
1429 
1430 /// Add this decl to the scope shadowed decl chains.
1431 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1432   // Move up the scope chain until we find the nearest enclosing
1433   // non-transparent context. The declaration will be introduced into this
1434   // scope.
1435   while (S->getEntity() && S->getEntity()->isTransparentContext())
1436     S = S->getParent();
1437 
1438   // Add scoped declarations into their context, so that they can be
1439   // found later. Declarations without a context won't be inserted
1440   // into any context.
1441   if (AddToContext)
1442     CurContext->addDecl(D);
1443 
1444   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1445   // are function-local declarations.
1446   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1447       !D->getDeclContext()->getRedeclContext()->Equals(
1448         D->getLexicalDeclContext()->getRedeclContext()) &&
1449       !D->getLexicalDeclContext()->isFunctionOrMethod())
1450     return;
1451 
1452   // Template instantiations should also not be pushed into scope.
1453   if (isa<FunctionDecl>(D) &&
1454       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1455     return;
1456 
1457   // If this replaces anything in the current scope,
1458   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1459                                IEnd = IdResolver.end();
1460   for (; I != IEnd; ++I) {
1461     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1462       S->RemoveDecl(*I);
1463       IdResolver.RemoveDecl(*I);
1464 
1465       // Should only need to replace one decl.
1466       break;
1467     }
1468   }
1469 
1470   S->AddDecl(D);
1471 
1472   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1473     // Implicitly-generated labels may end up getting generated in an order that
1474     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1475     // the label at the appropriate place in the identifier chain.
1476     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1477       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1478       if (IDC == CurContext) {
1479         if (!S->isDeclScope(*I))
1480           continue;
1481       } else if (IDC->Encloses(CurContext))
1482         break;
1483     }
1484 
1485     IdResolver.InsertDeclAfter(I, D);
1486   } else {
1487     IdResolver.AddDecl(D);
1488   }
1489 }
1490 
1491 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1492                          bool AllowInlineNamespace) {
1493   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1494 }
1495 
1496 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1497   DeclContext *TargetDC = DC->getPrimaryContext();
1498   do {
1499     if (DeclContext *ScopeDC = S->getEntity())
1500       if (ScopeDC->getPrimaryContext() == TargetDC)
1501         return S;
1502   } while ((S = S->getParent()));
1503 
1504   return nullptr;
1505 }
1506 
1507 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1508                                             DeclContext*,
1509                                             ASTContext&);
1510 
1511 /// Filters out lookup results that don't fall within the given scope
1512 /// as determined by isDeclInScope.
1513 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1514                                 bool ConsiderLinkage,
1515                                 bool AllowInlineNamespace) {
1516   LookupResult::Filter F = R.makeFilter();
1517   while (F.hasNext()) {
1518     NamedDecl *D = F.next();
1519 
1520     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1521       continue;
1522 
1523     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1524       continue;
1525 
1526     F.erase();
1527   }
1528 
1529   F.done();
1530 }
1531 
1532 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1533 /// have compatible owning modules.
1534 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1535   // FIXME: The Modules TS is not clear about how friend declarations are
1536   // to be treated. It's not meaningful to have different owning modules for
1537   // linkage in redeclarations of the same entity, so for now allow the
1538   // redeclaration and change the owning modules to match.
1539   if (New->getFriendObjectKind() &&
1540       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1541     New->setLocalOwningModule(Old->getOwningModule());
1542     makeMergedDefinitionVisible(New);
1543     return false;
1544   }
1545 
1546   Module *NewM = New->getOwningModule();
1547   Module *OldM = Old->getOwningModule();
1548 
1549   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1550     NewM = NewM->Parent;
1551   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1552     OldM = OldM->Parent;
1553 
1554   if (NewM == OldM)
1555     return false;
1556 
1557   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1558   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1559   if (NewIsModuleInterface || OldIsModuleInterface) {
1560     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1561     //   if a declaration of D [...] appears in the purview of a module, all
1562     //   other such declarations shall appear in the purview of the same module
1563     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1564       << New
1565       << NewIsModuleInterface
1566       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1567       << OldIsModuleInterface
1568       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1569     Diag(Old->getLocation(), diag::note_previous_declaration);
1570     New->setInvalidDecl();
1571     return true;
1572   }
1573 
1574   return false;
1575 }
1576 
1577 static bool isUsingDecl(NamedDecl *D) {
1578   return isa<UsingShadowDecl>(D) ||
1579          isa<UnresolvedUsingTypenameDecl>(D) ||
1580          isa<UnresolvedUsingValueDecl>(D);
1581 }
1582 
1583 /// Removes using shadow declarations from the lookup results.
1584 static void RemoveUsingDecls(LookupResult &R) {
1585   LookupResult::Filter F = R.makeFilter();
1586   while (F.hasNext())
1587     if (isUsingDecl(F.next()))
1588       F.erase();
1589 
1590   F.done();
1591 }
1592 
1593 /// Check for this common pattern:
1594 /// @code
1595 /// class S {
1596 ///   S(const S&); // DO NOT IMPLEMENT
1597 ///   void operator=(const S&); // DO NOT IMPLEMENT
1598 /// };
1599 /// @endcode
1600 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1601   // FIXME: Should check for private access too but access is set after we get
1602   // the decl here.
1603   if (D->doesThisDeclarationHaveABody())
1604     return false;
1605 
1606   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1607     return CD->isCopyConstructor();
1608   return D->isCopyAssignmentOperator();
1609 }
1610 
1611 // We need this to handle
1612 //
1613 // typedef struct {
1614 //   void *foo() { return 0; }
1615 // } A;
1616 //
1617 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1618 // for example. If 'A', foo will have external linkage. If we have '*A',
1619 // foo will have no linkage. Since we can't know until we get to the end
1620 // of the typedef, this function finds out if D might have non-external linkage.
1621 // Callers should verify at the end of the TU if it D has external linkage or
1622 // not.
1623 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1624   const DeclContext *DC = D->getDeclContext();
1625   while (!DC->isTranslationUnit()) {
1626     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1627       if (!RD->hasNameForLinkage())
1628         return true;
1629     }
1630     DC = DC->getParent();
1631   }
1632 
1633   return !D->isExternallyVisible();
1634 }
1635 
1636 // FIXME: This needs to be refactored; some other isInMainFile users want
1637 // these semantics.
1638 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1639   if (S.TUKind != TU_Complete)
1640     return false;
1641   return S.SourceMgr.isInMainFile(Loc);
1642 }
1643 
1644 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1645   assert(D);
1646 
1647   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1648     return false;
1649 
1650   // Ignore all entities declared within templates, and out-of-line definitions
1651   // of members of class templates.
1652   if (D->getDeclContext()->isDependentContext() ||
1653       D->getLexicalDeclContext()->isDependentContext())
1654     return false;
1655 
1656   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1657     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1658       return false;
1659     // A non-out-of-line declaration of a member specialization was implicitly
1660     // instantiated; it's the out-of-line declaration that we're interested in.
1661     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1662         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1663       return false;
1664 
1665     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1666       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1667         return false;
1668     } else {
1669       // 'static inline' functions are defined in headers; don't warn.
1670       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1671         return false;
1672     }
1673 
1674     if (FD->doesThisDeclarationHaveABody() &&
1675         Context.DeclMustBeEmitted(FD))
1676       return false;
1677   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1678     // Constants and utility variables are defined in headers with internal
1679     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1680     // like "inline".)
1681     if (!isMainFileLoc(*this, VD->getLocation()))
1682       return false;
1683 
1684     if (Context.DeclMustBeEmitted(VD))
1685       return false;
1686 
1687     if (VD->isStaticDataMember() &&
1688         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1689       return false;
1690     if (VD->isStaticDataMember() &&
1691         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1692         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1693       return false;
1694 
1695     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1696       return false;
1697   } else {
1698     return false;
1699   }
1700 
1701   // Only warn for unused decls internal to the translation unit.
1702   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1703   // for inline functions defined in the main source file, for instance.
1704   return mightHaveNonExternalLinkage(D);
1705 }
1706 
1707 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1708   if (!D)
1709     return;
1710 
1711   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1712     const FunctionDecl *First = FD->getFirstDecl();
1713     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1714       return; // First should already be in the vector.
1715   }
1716 
1717   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1718     const VarDecl *First = VD->getFirstDecl();
1719     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1720       return; // First should already be in the vector.
1721   }
1722 
1723   if (ShouldWarnIfUnusedFileScopedDecl(D))
1724     UnusedFileScopedDecls.push_back(D);
1725 }
1726 
1727 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1728   if (D->isInvalidDecl())
1729     return false;
1730 
1731   bool Referenced = false;
1732   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1733     // For a decomposition declaration, warn if none of the bindings are
1734     // referenced, instead of if the variable itself is referenced (which
1735     // it is, by the bindings' expressions).
1736     for (auto *BD : DD->bindings()) {
1737       if (BD->isReferenced()) {
1738         Referenced = true;
1739         break;
1740       }
1741     }
1742   } else if (!D->getDeclName()) {
1743     return false;
1744   } else if (D->isReferenced() || D->isUsed()) {
1745     Referenced = true;
1746   }
1747 
1748   if (Referenced || D->hasAttr<UnusedAttr>() ||
1749       D->hasAttr<ObjCPreciseLifetimeAttr>())
1750     return false;
1751 
1752   if (isa<LabelDecl>(D))
1753     return true;
1754 
1755   // Except for labels, we only care about unused decls that are local to
1756   // functions.
1757   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1758   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1759     // For dependent types, the diagnostic is deferred.
1760     WithinFunction =
1761         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1762   if (!WithinFunction)
1763     return false;
1764 
1765   if (isa<TypedefNameDecl>(D))
1766     return true;
1767 
1768   // White-list anything that isn't a local variable.
1769   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1770     return false;
1771 
1772   // Types of valid local variables should be complete, so this should succeed.
1773   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1774 
1775     // White-list anything with an __attribute__((unused)) type.
1776     const auto *Ty = VD->getType().getTypePtr();
1777 
1778     // Only look at the outermost level of typedef.
1779     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1780       if (TT->getDecl()->hasAttr<UnusedAttr>())
1781         return false;
1782     }
1783 
1784     // If we failed to complete the type for some reason, or if the type is
1785     // dependent, don't diagnose the variable.
1786     if (Ty->isIncompleteType() || Ty->isDependentType())
1787       return false;
1788 
1789     // Look at the element type to ensure that the warning behaviour is
1790     // consistent for both scalars and arrays.
1791     Ty = Ty->getBaseElementTypeUnsafe();
1792 
1793     if (const TagType *TT = Ty->getAs<TagType>()) {
1794       const TagDecl *Tag = TT->getDecl();
1795       if (Tag->hasAttr<UnusedAttr>())
1796         return false;
1797 
1798       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1799         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1800           return false;
1801 
1802         if (const Expr *Init = VD->getInit()) {
1803           if (const ExprWithCleanups *Cleanups =
1804                   dyn_cast<ExprWithCleanups>(Init))
1805             Init = Cleanups->getSubExpr();
1806           const CXXConstructExpr *Construct =
1807             dyn_cast<CXXConstructExpr>(Init);
1808           if (Construct && !Construct->isElidable()) {
1809             CXXConstructorDecl *CD = Construct->getConstructor();
1810             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1811                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1812               return false;
1813           }
1814 
1815           // Suppress the warning if we don't know how this is constructed, and
1816           // it could possibly be non-trivial constructor.
1817           if (Init->isTypeDependent())
1818             for (const CXXConstructorDecl *Ctor : RD->ctors())
1819               if (!Ctor->isTrivial())
1820                 return false;
1821         }
1822       }
1823     }
1824 
1825     // TODO: __attribute__((unused)) templates?
1826   }
1827 
1828   return true;
1829 }
1830 
1831 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1832                                      FixItHint &Hint) {
1833   if (isa<LabelDecl>(D)) {
1834     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1835         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1836         true);
1837     if (AfterColon.isInvalid())
1838       return;
1839     Hint = FixItHint::CreateRemoval(
1840         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1841   }
1842 }
1843 
1844 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1845   if (D->getTypeForDecl()->isDependentType())
1846     return;
1847 
1848   for (auto *TmpD : D->decls()) {
1849     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1850       DiagnoseUnusedDecl(T);
1851     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1852       DiagnoseUnusedNestedTypedefs(R);
1853   }
1854 }
1855 
1856 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1857 /// unless they are marked attr(unused).
1858 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1859   if (!ShouldDiagnoseUnusedDecl(D))
1860     return;
1861 
1862   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1863     // typedefs can be referenced later on, so the diagnostics are emitted
1864     // at end-of-translation-unit.
1865     UnusedLocalTypedefNameCandidates.insert(TD);
1866     return;
1867   }
1868 
1869   FixItHint Hint;
1870   GenerateFixForUnusedDecl(D, Context, Hint);
1871 
1872   unsigned DiagID;
1873   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1874     DiagID = diag::warn_unused_exception_param;
1875   else if (isa<LabelDecl>(D))
1876     DiagID = diag::warn_unused_label;
1877   else
1878     DiagID = diag::warn_unused_variable;
1879 
1880   Diag(D->getLocation(), DiagID) << D << Hint;
1881 }
1882 
1883 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1884   // Verify that we have no forward references left.  If so, there was a goto
1885   // or address of a label taken, but no definition of it.  Label fwd
1886   // definitions are indicated with a null substmt which is also not a resolved
1887   // MS inline assembly label name.
1888   bool Diagnose = false;
1889   if (L->isMSAsmLabel())
1890     Diagnose = !L->isResolvedMSAsmLabel();
1891   else
1892     Diagnose = L->getStmt() == nullptr;
1893   if (Diagnose)
1894     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1895 }
1896 
1897 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1898   S->mergeNRVOIntoParent();
1899 
1900   if (S->decl_empty()) return;
1901   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1902          "Scope shouldn't contain decls!");
1903 
1904   for (auto *TmpD : S->decls()) {
1905     assert(TmpD && "This decl didn't get pushed??");
1906 
1907     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1908     NamedDecl *D = cast<NamedDecl>(TmpD);
1909 
1910     // Diagnose unused variables in this scope.
1911     if (!S->hasUnrecoverableErrorOccurred()) {
1912       DiagnoseUnusedDecl(D);
1913       if (const auto *RD = dyn_cast<RecordDecl>(D))
1914         DiagnoseUnusedNestedTypedefs(RD);
1915     }
1916 
1917     if (!D->getDeclName()) continue;
1918 
1919     // If this was a forward reference to a label, verify it was defined.
1920     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1921       CheckPoppedLabel(LD, *this);
1922 
1923     // Remove this name from our lexical scope, and warn on it if we haven't
1924     // already.
1925     IdResolver.RemoveDecl(D);
1926     auto ShadowI = ShadowingDecls.find(D);
1927     if (ShadowI != ShadowingDecls.end()) {
1928       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1929         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1930             << D << FD << FD->getParent();
1931         Diag(FD->getLocation(), diag::note_previous_declaration);
1932       }
1933       ShadowingDecls.erase(ShadowI);
1934     }
1935   }
1936 }
1937 
1938 /// Look for an Objective-C class in the translation unit.
1939 ///
1940 /// \param Id The name of the Objective-C class we're looking for. If
1941 /// typo-correction fixes this name, the Id will be updated
1942 /// to the fixed name.
1943 ///
1944 /// \param IdLoc The location of the name in the translation unit.
1945 ///
1946 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1947 /// if there is no class with the given name.
1948 ///
1949 /// \returns The declaration of the named Objective-C class, or NULL if the
1950 /// class could not be found.
1951 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1952                                               SourceLocation IdLoc,
1953                                               bool DoTypoCorrection) {
1954   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1955   // creation from this context.
1956   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1957 
1958   if (!IDecl && DoTypoCorrection) {
1959     // Perform typo correction at the given location, but only if we
1960     // find an Objective-C class name.
1961     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1962     if (TypoCorrection C =
1963             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1964                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1965       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1966       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1967       Id = IDecl->getIdentifier();
1968     }
1969   }
1970   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1971   // This routine must always return a class definition, if any.
1972   if (Def && Def->getDefinition())
1973       Def = Def->getDefinition();
1974   return Def;
1975 }
1976 
1977 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1978 /// from S, where a non-field would be declared. This routine copes
1979 /// with the difference between C and C++ scoping rules in structs and
1980 /// unions. For example, the following code is well-formed in C but
1981 /// ill-formed in C++:
1982 /// @code
1983 /// struct S6 {
1984 ///   enum { BAR } e;
1985 /// };
1986 ///
1987 /// void test_S6() {
1988 ///   struct S6 a;
1989 ///   a.e = BAR;
1990 /// }
1991 /// @endcode
1992 /// For the declaration of BAR, this routine will return a different
1993 /// scope. The scope S will be the scope of the unnamed enumeration
1994 /// within S6. In C++, this routine will return the scope associated
1995 /// with S6, because the enumeration's scope is a transparent
1996 /// context but structures can contain non-field names. In C, this
1997 /// routine will return the translation unit scope, since the
1998 /// enumeration's scope is a transparent context and structures cannot
1999 /// contain non-field names.
2000 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2001   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2002          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2003          (S->isClassScope() && !getLangOpts().CPlusPlus))
2004     S = S->getParent();
2005   return S;
2006 }
2007 
2008 /// Looks up the declaration of "struct objc_super" and
2009 /// saves it for later use in building builtin declaration of
2010 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2011 /// pre-existing declaration exists no action takes place.
2012 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2013                                         IdentifierInfo *II) {
2014   if (!II->isStr("objc_msgSendSuper"))
2015     return;
2016   ASTContext &Context = ThisSema.Context;
2017 
2018   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2019                       SourceLocation(), Sema::LookupTagName);
2020   ThisSema.LookupName(Result, S);
2021   if (Result.getResultKind() == LookupResult::Found)
2022     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2023       Context.setObjCSuperType(Context.getTagDeclType(TD));
2024 }
2025 
2026 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2027                                ASTContext::GetBuiltinTypeError Error) {
2028   switch (Error) {
2029   case ASTContext::GE_None:
2030     return "";
2031   case ASTContext::GE_Missing_type:
2032     return BuiltinInfo.getHeaderName(ID);
2033   case ASTContext::GE_Missing_stdio:
2034     return "stdio.h";
2035   case ASTContext::GE_Missing_setjmp:
2036     return "setjmp.h";
2037   case ASTContext::GE_Missing_ucontext:
2038     return "ucontext.h";
2039   }
2040   llvm_unreachable("unhandled error kind");
2041 }
2042 
2043 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2044 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2045 /// if we're creating this built-in in anticipation of redeclaring the
2046 /// built-in.
2047 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2048                                      Scope *S, bool ForRedeclaration,
2049                                      SourceLocation Loc) {
2050   LookupPredefedObjCSuperType(*this, S, II);
2051 
2052   ASTContext::GetBuiltinTypeError Error;
2053   QualType R = Context.GetBuiltinType(ID, Error);
2054   if (Error) {
2055     if (!ForRedeclaration)
2056       return nullptr;
2057 
2058     // If we have a builtin without an associated type we should not emit a
2059     // warning when we were not able to find a type for it.
2060     if (Error == ASTContext::GE_Missing_type)
2061       return nullptr;
2062 
2063     // If we could not find a type for setjmp it is because the jmp_buf type was
2064     // not defined prior to the setjmp declaration.
2065     if (Error == ASTContext::GE_Missing_setjmp) {
2066       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2067           << Context.BuiltinInfo.getName(ID);
2068       return nullptr;
2069     }
2070 
2071     // Generally, we emit a warning that the declaration requires the
2072     // appropriate header.
2073     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2074         << getHeaderName(Context.BuiltinInfo, ID, Error)
2075         << Context.BuiltinInfo.getName(ID);
2076     return nullptr;
2077   }
2078 
2079   if (!ForRedeclaration &&
2080       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2081        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2082     Diag(Loc, diag::ext_implicit_lib_function_decl)
2083         << Context.BuiltinInfo.getName(ID) << R;
2084     if (Context.BuiltinInfo.getHeaderName(ID) &&
2085         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2086       Diag(Loc, diag::note_include_header_or_declare)
2087           << Context.BuiltinInfo.getHeaderName(ID)
2088           << Context.BuiltinInfo.getName(ID);
2089   }
2090 
2091   if (R.isNull())
2092     return nullptr;
2093 
2094   DeclContext *Parent = Context.getTranslationUnitDecl();
2095   if (getLangOpts().CPlusPlus) {
2096     LinkageSpecDecl *CLinkageDecl =
2097         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2098                                 LinkageSpecDecl::lang_c, false);
2099     CLinkageDecl->setImplicit();
2100     Parent->addDecl(CLinkageDecl);
2101     Parent = CLinkageDecl;
2102   }
2103 
2104   FunctionDecl *New = FunctionDecl::Create(Context,
2105                                            Parent,
2106                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2107                                            SC_Extern,
2108                                            false,
2109                                            R->isFunctionProtoType());
2110   New->setImplicit();
2111 
2112   // Create Decl objects for each parameter, adding them to the
2113   // FunctionDecl.
2114   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2115     SmallVector<ParmVarDecl*, 16> Params;
2116     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2117       ParmVarDecl *parm =
2118           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2119                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2120                               SC_None, nullptr);
2121       parm->setScopeInfo(0, i);
2122       Params.push_back(parm);
2123     }
2124     New->setParams(Params);
2125   }
2126 
2127   AddKnownFunctionAttributes(New);
2128   RegisterLocallyScopedExternCDecl(New, S);
2129 
2130   // TUScope is the translation-unit scope to insert this function into.
2131   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2132   // relate Scopes to DeclContexts, and probably eliminate CurContext
2133   // entirely, but we're not there yet.
2134   DeclContext *SavedContext = CurContext;
2135   CurContext = Parent;
2136   PushOnScopeChains(New, TUScope);
2137   CurContext = SavedContext;
2138   return New;
2139 }
2140 
2141 /// Typedef declarations don't have linkage, but they still denote the same
2142 /// entity if their types are the same.
2143 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2144 /// isSameEntity.
2145 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2146                                                      TypedefNameDecl *Decl,
2147                                                      LookupResult &Previous) {
2148   // This is only interesting when modules are enabled.
2149   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2150     return;
2151 
2152   // Empty sets are uninteresting.
2153   if (Previous.empty())
2154     return;
2155 
2156   LookupResult::Filter Filter = Previous.makeFilter();
2157   while (Filter.hasNext()) {
2158     NamedDecl *Old = Filter.next();
2159 
2160     // Non-hidden declarations are never ignored.
2161     if (S.isVisible(Old))
2162       continue;
2163 
2164     // Declarations of the same entity are not ignored, even if they have
2165     // different linkages.
2166     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2167       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2168                                 Decl->getUnderlyingType()))
2169         continue;
2170 
2171       // If both declarations give a tag declaration a typedef name for linkage
2172       // purposes, then they declare the same entity.
2173       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2174           Decl->getAnonDeclWithTypedefName())
2175         continue;
2176     }
2177 
2178     Filter.erase();
2179   }
2180 
2181   Filter.done();
2182 }
2183 
2184 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2185   QualType OldType;
2186   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2187     OldType = OldTypedef->getUnderlyingType();
2188   else
2189     OldType = Context.getTypeDeclType(Old);
2190   QualType NewType = New->getUnderlyingType();
2191 
2192   if (NewType->isVariablyModifiedType()) {
2193     // Must not redefine a typedef with a variably-modified type.
2194     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2195     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2196       << Kind << NewType;
2197     if (Old->getLocation().isValid())
2198       notePreviousDefinition(Old, New->getLocation());
2199     New->setInvalidDecl();
2200     return true;
2201   }
2202 
2203   if (OldType != NewType &&
2204       !OldType->isDependentType() &&
2205       !NewType->isDependentType() &&
2206       !Context.hasSameType(OldType, NewType)) {
2207     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2208     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2209       << Kind << NewType << OldType;
2210     if (Old->getLocation().isValid())
2211       notePreviousDefinition(Old, New->getLocation());
2212     New->setInvalidDecl();
2213     return true;
2214   }
2215   return false;
2216 }
2217 
2218 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2219 /// same name and scope as a previous declaration 'Old'.  Figure out
2220 /// how to resolve this situation, merging decls or emitting
2221 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2222 ///
2223 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2224                                 LookupResult &OldDecls) {
2225   // If the new decl is known invalid already, don't bother doing any
2226   // merging checks.
2227   if (New->isInvalidDecl()) return;
2228 
2229   // Allow multiple definitions for ObjC built-in typedefs.
2230   // FIXME: Verify the underlying types are equivalent!
2231   if (getLangOpts().ObjC) {
2232     const IdentifierInfo *TypeID = New->getIdentifier();
2233     switch (TypeID->getLength()) {
2234     default: break;
2235     case 2:
2236       {
2237         if (!TypeID->isStr("id"))
2238           break;
2239         QualType T = New->getUnderlyingType();
2240         if (!T->isPointerType())
2241           break;
2242         if (!T->isVoidPointerType()) {
2243           QualType PT = T->castAs<PointerType>()->getPointeeType();
2244           if (!PT->isStructureType())
2245             break;
2246         }
2247         Context.setObjCIdRedefinitionType(T);
2248         // Install the built-in type for 'id', ignoring the current definition.
2249         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2250         return;
2251       }
2252     case 5:
2253       if (!TypeID->isStr("Class"))
2254         break;
2255       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2256       // Install the built-in type for 'Class', ignoring the current definition.
2257       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2258       return;
2259     case 3:
2260       if (!TypeID->isStr("SEL"))
2261         break;
2262       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2263       // Install the built-in type for 'SEL', ignoring the current definition.
2264       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2265       return;
2266     }
2267     // Fall through - the typedef name was not a builtin type.
2268   }
2269 
2270   // Verify the old decl was also a type.
2271   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2272   if (!Old) {
2273     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2274       << New->getDeclName();
2275 
2276     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2277     if (OldD->getLocation().isValid())
2278       notePreviousDefinition(OldD, New->getLocation());
2279 
2280     return New->setInvalidDecl();
2281   }
2282 
2283   // If the old declaration is invalid, just give up here.
2284   if (Old->isInvalidDecl())
2285     return New->setInvalidDecl();
2286 
2287   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2288     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2289     auto *NewTag = New->getAnonDeclWithTypedefName();
2290     NamedDecl *Hidden = nullptr;
2291     if (OldTag && NewTag &&
2292         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2293         !hasVisibleDefinition(OldTag, &Hidden)) {
2294       // There is a definition of this tag, but it is not visible. Use it
2295       // instead of our tag.
2296       New->setTypeForDecl(OldTD->getTypeForDecl());
2297       if (OldTD->isModed())
2298         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2299                                     OldTD->getUnderlyingType());
2300       else
2301         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2302 
2303       // Make the old tag definition visible.
2304       makeMergedDefinitionVisible(Hidden);
2305 
2306       // If this was an unscoped enumeration, yank all of its enumerators
2307       // out of the scope.
2308       if (isa<EnumDecl>(NewTag)) {
2309         Scope *EnumScope = getNonFieldDeclScope(S);
2310         for (auto *D : NewTag->decls()) {
2311           auto *ED = cast<EnumConstantDecl>(D);
2312           assert(EnumScope->isDeclScope(ED));
2313           EnumScope->RemoveDecl(ED);
2314           IdResolver.RemoveDecl(ED);
2315           ED->getLexicalDeclContext()->removeDecl(ED);
2316         }
2317       }
2318     }
2319   }
2320 
2321   // If the typedef types are not identical, reject them in all languages and
2322   // with any extensions enabled.
2323   if (isIncompatibleTypedef(Old, New))
2324     return;
2325 
2326   // The types match.  Link up the redeclaration chain and merge attributes if
2327   // the old declaration was a typedef.
2328   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2329     New->setPreviousDecl(Typedef);
2330     mergeDeclAttributes(New, Old);
2331   }
2332 
2333   if (getLangOpts().MicrosoftExt)
2334     return;
2335 
2336   if (getLangOpts().CPlusPlus) {
2337     // C++ [dcl.typedef]p2:
2338     //   In a given non-class scope, a typedef specifier can be used to
2339     //   redefine the name of any type declared in that scope to refer
2340     //   to the type to which it already refers.
2341     if (!isa<CXXRecordDecl>(CurContext))
2342       return;
2343 
2344     // C++0x [dcl.typedef]p4:
2345     //   In a given class scope, a typedef specifier can be used to redefine
2346     //   any class-name declared in that scope that is not also a typedef-name
2347     //   to refer to the type to which it already refers.
2348     //
2349     // This wording came in via DR424, which was a correction to the
2350     // wording in DR56, which accidentally banned code like:
2351     //
2352     //   struct S {
2353     //     typedef struct A { } A;
2354     //   };
2355     //
2356     // in the C++03 standard. We implement the C++0x semantics, which
2357     // allow the above but disallow
2358     //
2359     //   struct S {
2360     //     typedef int I;
2361     //     typedef int I;
2362     //   };
2363     //
2364     // since that was the intent of DR56.
2365     if (!isa<TypedefNameDecl>(Old))
2366       return;
2367 
2368     Diag(New->getLocation(), diag::err_redefinition)
2369       << New->getDeclName();
2370     notePreviousDefinition(Old, New->getLocation());
2371     return New->setInvalidDecl();
2372   }
2373 
2374   // Modules always permit redefinition of typedefs, as does C11.
2375   if (getLangOpts().Modules || getLangOpts().C11)
2376     return;
2377 
2378   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2379   // is normally mapped to an error, but can be controlled with
2380   // -Wtypedef-redefinition.  If either the original or the redefinition is
2381   // in a system header, don't emit this for compatibility with GCC.
2382   if (getDiagnostics().getSuppressSystemWarnings() &&
2383       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2384       (Old->isImplicit() ||
2385        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2386        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2387     return;
2388 
2389   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2390     << New->getDeclName();
2391   notePreviousDefinition(Old, New->getLocation());
2392 }
2393 
2394 /// DeclhasAttr - returns true if decl Declaration already has the target
2395 /// attribute.
2396 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2397   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2398   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2399   for (const auto *i : D->attrs())
2400     if (i->getKind() == A->getKind()) {
2401       if (Ann) {
2402         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2403           return true;
2404         continue;
2405       }
2406       // FIXME: Don't hardcode this check
2407       if (OA && isa<OwnershipAttr>(i))
2408         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2409       return true;
2410     }
2411 
2412   return false;
2413 }
2414 
2415 static bool isAttributeTargetADefinition(Decl *D) {
2416   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2417     return VD->isThisDeclarationADefinition();
2418   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2419     return TD->isCompleteDefinition() || TD->isBeingDefined();
2420   return true;
2421 }
2422 
2423 /// Merge alignment attributes from \p Old to \p New, taking into account the
2424 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2425 ///
2426 /// \return \c true if any attributes were added to \p New.
2427 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2428   // Look for alignas attributes on Old, and pick out whichever attribute
2429   // specifies the strictest alignment requirement.
2430   AlignedAttr *OldAlignasAttr = nullptr;
2431   AlignedAttr *OldStrictestAlignAttr = nullptr;
2432   unsigned OldAlign = 0;
2433   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2434     // FIXME: We have no way of representing inherited dependent alignments
2435     // in a case like:
2436     //   template<int A, int B> struct alignas(A) X;
2437     //   template<int A, int B> struct alignas(B) X {};
2438     // For now, we just ignore any alignas attributes which are not on the
2439     // definition in such a case.
2440     if (I->isAlignmentDependent())
2441       return false;
2442 
2443     if (I->isAlignas())
2444       OldAlignasAttr = I;
2445 
2446     unsigned Align = I->getAlignment(S.Context);
2447     if (Align > OldAlign) {
2448       OldAlign = Align;
2449       OldStrictestAlignAttr = I;
2450     }
2451   }
2452 
2453   // Look for alignas attributes on New.
2454   AlignedAttr *NewAlignasAttr = nullptr;
2455   unsigned NewAlign = 0;
2456   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2457     if (I->isAlignmentDependent())
2458       return false;
2459 
2460     if (I->isAlignas())
2461       NewAlignasAttr = I;
2462 
2463     unsigned Align = I->getAlignment(S.Context);
2464     if (Align > NewAlign)
2465       NewAlign = Align;
2466   }
2467 
2468   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2469     // Both declarations have 'alignas' attributes. We require them to match.
2470     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2471     // fall short. (If two declarations both have alignas, they must both match
2472     // every definition, and so must match each other if there is a definition.)
2473 
2474     // If either declaration only contains 'alignas(0)' specifiers, then it
2475     // specifies the natural alignment for the type.
2476     if (OldAlign == 0 || NewAlign == 0) {
2477       QualType Ty;
2478       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2479         Ty = VD->getType();
2480       else
2481         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2482 
2483       if (OldAlign == 0)
2484         OldAlign = S.Context.getTypeAlign(Ty);
2485       if (NewAlign == 0)
2486         NewAlign = S.Context.getTypeAlign(Ty);
2487     }
2488 
2489     if (OldAlign != NewAlign) {
2490       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2491         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2492         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2493       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2494     }
2495   }
2496 
2497   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2498     // C++11 [dcl.align]p6:
2499     //   if any declaration of an entity has an alignment-specifier,
2500     //   every defining declaration of that entity shall specify an
2501     //   equivalent alignment.
2502     // C11 6.7.5/7:
2503     //   If the definition of an object does not have an alignment
2504     //   specifier, any other declaration of that object shall also
2505     //   have no alignment specifier.
2506     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2507       << OldAlignasAttr;
2508     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2509       << OldAlignasAttr;
2510   }
2511 
2512   bool AnyAdded = false;
2513 
2514   // Ensure we have an attribute representing the strictest alignment.
2515   if (OldAlign > NewAlign) {
2516     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2517     Clone->setInherited(true);
2518     New->addAttr(Clone);
2519     AnyAdded = true;
2520   }
2521 
2522   // Ensure we have an alignas attribute if the old declaration had one.
2523   if (OldAlignasAttr && !NewAlignasAttr &&
2524       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2525     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2526     Clone->setInherited(true);
2527     New->addAttr(Clone);
2528     AnyAdded = true;
2529   }
2530 
2531   return AnyAdded;
2532 }
2533 
2534 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2535                                const InheritableAttr *Attr,
2536                                Sema::AvailabilityMergeKind AMK) {
2537   // This function copies an attribute Attr from a previous declaration to the
2538   // new declaration D if the new declaration doesn't itself have that attribute
2539   // yet or if that attribute allows duplicates.
2540   // If you're adding a new attribute that requires logic different from
2541   // "use explicit attribute on decl if present, else use attribute from
2542   // previous decl", for example if the attribute needs to be consistent
2543   // between redeclarations, you need to call a custom merge function here.
2544   InheritableAttr *NewAttr = nullptr;
2545   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2546     NewAttr = S.mergeAvailabilityAttr(
2547         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2548         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2549         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2550         AA->getPriority());
2551   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2552     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2553   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2554     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2555   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2556     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2557   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2558     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2559   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2560     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2561                                 FA->getFirstArg());
2562   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2563     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2564   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2565     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2566   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2567     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2568                                        IA->getInheritanceModel());
2569   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2570     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2571                                       &S.Context.Idents.get(AA->getSpelling()));
2572   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2573            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2574             isa<CUDAGlobalAttr>(Attr))) {
2575     // CUDA target attributes are part of function signature for
2576     // overloading purposes and must not be merged.
2577     return false;
2578   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2579     NewAttr = S.mergeMinSizeAttr(D, *MA);
2580   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2581     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2582   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2583     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2584   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2585     NewAttr = S.mergeCommonAttr(D, *CommonA);
2586   else if (isa<AlignedAttr>(Attr))
2587     // AlignedAttrs are handled separately, because we need to handle all
2588     // such attributes on a declaration at the same time.
2589     NewAttr = nullptr;
2590   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2591            (AMK == Sema::AMK_Override ||
2592             AMK == Sema::AMK_ProtocolImplementation))
2593     NewAttr = nullptr;
2594   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2595     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2596   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2597     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2598   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2599     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2600   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2601     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2602 
2603   if (NewAttr) {
2604     NewAttr->setInherited(true);
2605     D->addAttr(NewAttr);
2606     if (isa<MSInheritanceAttr>(NewAttr))
2607       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2608     return true;
2609   }
2610 
2611   return false;
2612 }
2613 
2614 static const NamedDecl *getDefinition(const Decl *D) {
2615   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2616     return TD->getDefinition();
2617   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2618     const VarDecl *Def = VD->getDefinition();
2619     if (Def)
2620       return Def;
2621     return VD->getActingDefinition();
2622   }
2623   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2624     return FD->getDefinition();
2625   return nullptr;
2626 }
2627 
2628 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2629   for (const auto *Attribute : D->attrs())
2630     if (Attribute->getKind() == Kind)
2631       return true;
2632   return false;
2633 }
2634 
2635 /// checkNewAttributesAfterDef - If we already have a definition, check that
2636 /// there are no new attributes in this declaration.
2637 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2638   if (!New->hasAttrs())
2639     return;
2640 
2641   const NamedDecl *Def = getDefinition(Old);
2642   if (!Def || Def == New)
2643     return;
2644 
2645   AttrVec &NewAttributes = New->getAttrs();
2646   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2647     const Attr *NewAttribute = NewAttributes[I];
2648 
2649     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2650       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2651         Sema::SkipBodyInfo SkipBody;
2652         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2653 
2654         // If we're skipping this definition, drop the "alias" attribute.
2655         if (SkipBody.ShouldSkip) {
2656           NewAttributes.erase(NewAttributes.begin() + I);
2657           --E;
2658           continue;
2659         }
2660       } else {
2661         VarDecl *VD = cast<VarDecl>(New);
2662         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2663                                 VarDecl::TentativeDefinition
2664                             ? diag::err_alias_after_tentative
2665                             : diag::err_redefinition;
2666         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2667         if (Diag == diag::err_redefinition)
2668           S.notePreviousDefinition(Def, VD->getLocation());
2669         else
2670           S.Diag(Def->getLocation(), diag::note_previous_definition);
2671         VD->setInvalidDecl();
2672       }
2673       ++I;
2674       continue;
2675     }
2676 
2677     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2678       // Tentative definitions are only interesting for the alias check above.
2679       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2680         ++I;
2681         continue;
2682       }
2683     }
2684 
2685     if (hasAttribute(Def, NewAttribute->getKind())) {
2686       ++I;
2687       continue; // regular attr merging will take care of validating this.
2688     }
2689 
2690     if (isa<C11NoReturnAttr>(NewAttribute)) {
2691       // C's _Noreturn is allowed to be added to a function after it is defined.
2692       ++I;
2693       continue;
2694     } else if (isa<UuidAttr>(NewAttribute)) {
2695       // msvc will allow a subsequent definition to add an uuid to a class
2696       ++I;
2697       continue;
2698     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2699       if (AA->isAlignas()) {
2700         // C++11 [dcl.align]p6:
2701         //   if any declaration of an entity has an alignment-specifier,
2702         //   every defining declaration of that entity shall specify an
2703         //   equivalent alignment.
2704         // C11 6.7.5/7:
2705         //   If the definition of an object does not have an alignment
2706         //   specifier, any other declaration of that object shall also
2707         //   have no alignment specifier.
2708         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2709           << AA;
2710         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2711           << AA;
2712         NewAttributes.erase(NewAttributes.begin() + I);
2713         --E;
2714         continue;
2715       }
2716     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2717       // If there is a C definition followed by a redeclaration with this
2718       // attribute then there are two different definitions. In C++, prefer the
2719       // standard diagnostics.
2720       if (!S.getLangOpts().CPlusPlus) {
2721         S.Diag(NewAttribute->getLocation(),
2722                diag::err_loader_uninitialized_redeclaration);
2723         S.Diag(Def->getLocation(), diag::note_previous_definition);
2724         NewAttributes.erase(NewAttributes.begin() + I);
2725         --E;
2726         continue;
2727       }
2728     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2729                cast<VarDecl>(New)->isInline() &&
2730                !cast<VarDecl>(New)->isInlineSpecified()) {
2731       // Don't warn about applying selectany to implicitly inline variables.
2732       // Older compilers and language modes would require the use of selectany
2733       // to make such variables inline, and it would have no effect if we
2734       // honored it.
2735       ++I;
2736       continue;
2737     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2738       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2739       // declarations after defintions.
2740       ++I;
2741       continue;
2742     }
2743 
2744     S.Diag(NewAttribute->getLocation(),
2745            diag::warn_attribute_precede_definition);
2746     S.Diag(Def->getLocation(), diag::note_previous_definition);
2747     NewAttributes.erase(NewAttributes.begin() + I);
2748     --E;
2749   }
2750 }
2751 
2752 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2753                                      const ConstInitAttr *CIAttr,
2754                                      bool AttrBeforeInit) {
2755   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2756 
2757   // Figure out a good way to write this specifier on the old declaration.
2758   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2759   // enough of the attribute list spelling information to extract that without
2760   // heroics.
2761   std::string SuitableSpelling;
2762   if (S.getLangOpts().CPlusPlus20)
2763     SuitableSpelling = std::string(
2764         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2765   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2766     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2767         InsertLoc, {tok::l_square, tok::l_square,
2768                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2769                     S.PP.getIdentifierInfo("require_constant_initialization"),
2770                     tok::r_square, tok::r_square}));
2771   if (SuitableSpelling.empty())
2772     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2773         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2774                     S.PP.getIdentifierInfo("require_constant_initialization"),
2775                     tok::r_paren, tok::r_paren}));
2776   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2777     SuitableSpelling = "constinit";
2778   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2779     SuitableSpelling = "[[clang::require_constant_initialization]]";
2780   if (SuitableSpelling.empty())
2781     SuitableSpelling = "__attribute__((require_constant_initialization))";
2782   SuitableSpelling += " ";
2783 
2784   if (AttrBeforeInit) {
2785     // extern constinit int a;
2786     // int a = 0; // error (missing 'constinit'), accepted as extension
2787     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2788     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2789         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2790     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2791   } else {
2792     // int a = 0;
2793     // constinit extern int a; // error (missing 'constinit')
2794     S.Diag(CIAttr->getLocation(),
2795            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2796                                  : diag::warn_require_const_init_added_too_late)
2797         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2798     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2799         << CIAttr->isConstinit()
2800         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2801   }
2802 }
2803 
2804 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2805 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2806                                AvailabilityMergeKind AMK) {
2807   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2808     UsedAttr *NewAttr = OldAttr->clone(Context);
2809     NewAttr->setInherited(true);
2810     New->addAttr(NewAttr);
2811   }
2812 
2813   if (!Old->hasAttrs() && !New->hasAttrs())
2814     return;
2815 
2816   // [dcl.constinit]p1:
2817   //   If the [constinit] specifier is applied to any declaration of a
2818   //   variable, it shall be applied to the initializing declaration.
2819   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2820   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2821   if (bool(OldConstInit) != bool(NewConstInit)) {
2822     const auto *OldVD = cast<VarDecl>(Old);
2823     auto *NewVD = cast<VarDecl>(New);
2824 
2825     // Find the initializing declaration. Note that we might not have linked
2826     // the new declaration into the redeclaration chain yet.
2827     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2828     if (!InitDecl &&
2829         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2830       InitDecl = NewVD;
2831 
2832     if (InitDecl == NewVD) {
2833       // This is the initializing declaration. If it would inherit 'constinit',
2834       // that's ill-formed. (Note that we do not apply this to the attribute
2835       // form).
2836       if (OldConstInit && OldConstInit->isConstinit())
2837         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2838                                  /*AttrBeforeInit=*/true);
2839     } else if (NewConstInit) {
2840       // This is the first time we've been told that this declaration should
2841       // have a constant initializer. If we already saw the initializing
2842       // declaration, this is too late.
2843       if (InitDecl && InitDecl != NewVD) {
2844         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2845                                  /*AttrBeforeInit=*/false);
2846         NewVD->dropAttr<ConstInitAttr>();
2847       }
2848     }
2849   }
2850 
2851   // Attributes declared post-definition are currently ignored.
2852   checkNewAttributesAfterDef(*this, New, Old);
2853 
2854   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2855     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2856       if (!OldA->isEquivalent(NewA)) {
2857         // This redeclaration changes __asm__ label.
2858         Diag(New->getLocation(), diag::err_different_asm_label);
2859         Diag(OldA->getLocation(), diag::note_previous_declaration);
2860       }
2861     } else if (Old->isUsed()) {
2862       // This redeclaration adds an __asm__ label to a declaration that has
2863       // already been ODR-used.
2864       Diag(New->getLocation(), diag::err_late_asm_label_name)
2865         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2866     }
2867   }
2868 
2869   // Re-declaration cannot add abi_tag's.
2870   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2871     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2872       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2873         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2874                       NewTag) == OldAbiTagAttr->tags_end()) {
2875           Diag(NewAbiTagAttr->getLocation(),
2876                diag::err_new_abi_tag_on_redeclaration)
2877               << NewTag;
2878           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2879         }
2880       }
2881     } else {
2882       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2883       Diag(Old->getLocation(), diag::note_previous_declaration);
2884     }
2885   }
2886 
2887   // This redeclaration adds a section attribute.
2888   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2889     if (auto *VD = dyn_cast<VarDecl>(New)) {
2890       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2891         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2892         Diag(Old->getLocation(), diag::note_previous_declaration);
2893       }
2894     }
2895   }
2896 
2897   // Redeclaration adds code-seg attribute.
2898   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2899   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2900       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2901     Diag(New->getLocation(), diag::warn_mismatched_section)
2902          << 0 /*codeseg*/;
2903     Diag(Old->getLocation(), diag::note_previous_declaration);
2904   }
2905 
2906   if (!Old->hasAttrs())
2907     return;
2908 
2909   bool foundAny = New->hasAttrs();
2910 
2911   // Ensure that any moving of objects within the allocated map is done before
2912   // we process them.
2913   if (!foundAny) New->setAttrs(AttrVec());
2914 
2915   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2916     // Ignore deprecated/unavailable/availability attributes if requested.
2917     AvailabilityMergeKind LocalAMK = AMK_None;
2918     if (isa<DeprecatedAttr>(I) ||
2919         isa<UnavailableAttr>(I) ||
2920         isa<AvailabilityAttr>(I)) {
2921       switch (AMK) {
2922       case AMK_None:
2923         continue;
2924 
2925       case AMK_Redeclaration:
2926       case AMK_Override:
2927       case AMK_ProtocolImplementation:
2928         LocalAMK = AMK;
2929         break;
2930       }
2931     }
2932 
2933     // Already handled.
2934     if (isa<UsedAttr>(I))
2935       continue;
2936 
2937     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2938       foundAny = true;
2939   }
2940 
2941   if (mergeAlignedAttrs(*this, New, Old))
2942     foundAny = true;
2943 
2944   if (!foundAny) New->dropAttrs();
2945 }
2946 
2947 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2948 /// to the new one.
2949 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2950                                      const ParmVarDecl *oldDecl,
2951                                      Sema &S) {
2952   // C++11 [dcl.attr.depend]p2:
2953   //   The first declaration of a function shall specify the
2954   //   carries_dependency attribute for its declarator-id if any declaration
2955   //   of the function specifies the carries_dependency attribute.
2956   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2957   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2958     S.Diag(CDA->getLocation(),
2959            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2960     // Find the first declaration of the parameter.
2961     // FIXME: Should we build redeclaration chains for function parameters?
2962     const FunctionDecl *FirstFD =
2963       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2964     const ParmVarDecl *FirstVD =
2965       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2966     S.Diag(FirstVD->getLocation(),
2967            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2968   }
2969 
2970   if (!oldDecl->hasAttrs())
2971     return;
2972 
2973   bool foundAny = newDecl->hasAttrs();
2974 
2975   // Ensure that any moving of objects within the allocated map is
2976   // done before we process them.
2977   if (!foundAny) newDecl->setAttrs(AttrVec());
2978 
2979   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2980     if (!DeclHasAttr(newDecl, I)) {
2981       InheritableAttr *newAttr =
2982         cast<InheritableParamAttr>(I->clone(S.Context));
2983       newAttr->setInherited(true);
2984       newDecl->addAttr(newAttr);
2985       foundAny = true;
2986     }
2987   }
2988 
2989   if (!foundAny) newDecl->dropAttrs();
2990 }
2991 
2992 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2993                                 const ParmVarDecl *OldParam,
2994                                 Sema &S) {
2995   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2996     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2997       if (*Oldnullability != *Newnullability) {
2998         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2999           << DiagNullabilityKind(
3000                *Newnullability,
3001                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3002                 != 0))
3003           << DiagNullabilityKind(
3004                *Oldnullability,
3005                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3006                 != 0));
3007         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3008       }
3009     } else {
3010       QualType NewT = NewParam->getType();
3011       NewT = S.Context.getAttributedType(
3012                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3013                          NewT, NewT);
3014       NewParam->setType(NewT);
3015     }
3016   }
3017 }
3018 
3019 namespace {
3020 
3021 /// Used in MergeFunctionDecl to keep track of function parameters in
3022 /// C.
3023 struct GNUCompatibleParamWarning {
3024   ParmVarDecl *OldParm;
3025   ParmVarDecl *NewParm;
3026   QualType PromotedType;
3027 };
3028 
3029 } // end anonymous namespace
3030 
3031 // Determine whether the previous declaration was a definition, implicit
3032 // declaration, or a declaration.
3033 template <typename T>
3034 static std::pair<diag::kind, SourceLocation>
3035 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3036   diag::kind PrevDiag;
3037   SourceLocation OldLocation = Old->getLocation();
3038   if (Old->isThisDeclarationADefinition())
3039     PrevDiag = diag::note_previous_definition;
3040   else if (Old->isImplicit()) {
3041     PrevDiag = diag::note_previous_implicit_declaration;
3042     if (OldLocation.isInvalid())
3043       OldLocation = New->getLocation();
3044   } else
3045     PrevDiag = diag::note_previous_declaration;
3046   return std::make_pair(PrevDiag, OldLocation);
3047 }
3048 
3049 /// canRedefineFunction - checks if a function can be redefined. Currently,
3050 /// only extern inline functions can be redefined, and even then only in
3051 /// GNU89 mode.
3052 static bool canRedefineFunction(const FunctionDecl *FD,
3053                                 const LangOptions& LangOpts) {
3054   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3055           !LangOpts.CPlusPlus &&
3056           FD->isInlineSpecified() &&
3057           FD->getStorageClass() == SC_Extern);
3058 }
3059 
3060 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3061   const AttributedType *AT = T->getAs<AttributedType>();
3062   while (AT && !AT->isCallingConv())
3063     AT = AT->getModifiedType()->getAs<AttributedType>();
3064   return AT;
3065 }
3066 
3067 template <typename T>
3068 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3069   const DeclContext *DC = Old->getDeclContext();
3070   if (DC->isRecord())
3071     return false;
3072 
3073   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3074   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3075     return true;
3076   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3077     return true;
3078   return false;
3079 }
3080 
3081 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3082 static bool isExternC(VarTemplateDecl *) { return false; }
3083 
3084 /// Check whether a redeclaration of an entity introduced by a
3085 /// using-declaration is valid, given that we know it's not an overload
3086 /// (nor a hidden tag declaration).
3087 template<typename ExpectedDecl>
3088 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3089                                    ExpectedDecl *New) {
3090   // C++11 [basic.scope.declarative]p4:
3091   //   Given a set of declarations in a single declarative region, each of
3092   //   which specifies the same unqualified name,
3093   //   -- they shall all refer to the same entity, or all refer to functions
3094   //      and function templates; or
3095   //   -- exactly one declaration shall declare a class name or enumeration
3096   //      name that is not a typedef name and the other declarations shall all
3097   //      refer to the same variable or enumerator, or all refer to functions
3098   //      and function templates; in this case the class name or enumeration
3099   //      name is hidden (3.3.10).
3100 
3101   // C++11 [namespace.udecl]p14:
3102   //   If a function declaration in namespace scope or block scope has the
3103   //   same name and the same parameter-type-list as a function introduced
3104   //   by a using-declaration, and the declarations do not declare the same
3105   //   function, the program is ill-formed.
3106 
3107   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3108   if (Old &&
3109       !Old->getDeclContext()->getRedeclContext()->Equals(
3110           New->getDeclContext()->getRedeclContext()) &&
3111       !(isExternC(Old) && isExternC(New)))
3112     Old = nullptr;
3113 
3114   if (!Old) {
3115     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3116     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3117     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3118     return true;
3119   }
3120   return false;
3121 }
3122 
3123 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3124                                             const FunctionDecl *B) {
3125   assert(A->getNumParams() == B->getNumParams());
3126 
3127   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3128     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3129     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3130     if (AttrA == AttrB)
3131       return true;
3132     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3133            AttrA->isDynamic() == AttrB->isDynamic();
3134   };
3135 
3136   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3137 }
3138 
3139 /// If necessary, adjust the semantic declaration context for a qualified
3140 /// declaration to name the correct inline namespace within the qualifier.
3141 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3142                                                DeclaratorDecl *OldD) {
3143   // The only case where we need to update the DeclContext is when
3144   // redeclaration lookup for a qualified name finds a declaration
3145   // in an inline namespace within the context named by the qualifier:
3146   //
3147   //   inline namespace N { int f(); }
3148   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3149   //
3150   // For unqualified declarations, the semantic context *can* change
3151   // along the redeclaration chain (for local extern declarations,
3152   // extern "C" declarations, and friend declarations in particular).
3153   if (!NewD->getQualifier())
3154     return;
3155 
3156   // NewD is probably already in the right context.
3157   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3158   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3159   if (NamedDC->Equals(SemaDC))
3160     return;
3161 
3162   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3163           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3164          "unexpected context for redeclaration");
3165 
3166   auto *LexDC = NewD->getLexicalDeclContext();
3167   auto FixSemaDC = [=](NamedDecl *D) {
3168     if (!D)
3169       return;
3170     D->setDeclContext(SemaDC);
3171     D->setLexicalDeclContext(LexDC);
3172   };
3173 
3174   FixSemaDC(NewD);
3175   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3176     FixSemaDC(FD->getDescribedFunctionTemplate());
3177   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3178     FixSemaDC(VD->getDescribedVarTemplate());
3179 }
3180 
3181 /// MergeFunctionDecl - We just parsed a function 'New' from
3182 /// declarator D which has the same name and scope as a previous
3183 /// declaration 'Old'.  Figure out how to resolve this situation,
3184 /// merging decls or emitting diagnostics as appropriate.
3185 ///
3186 /// In C++, New and Old must be declarations that are not
3187 /// overloaded. Use IsOverload to determine whether New and Old are
3188 /// overloaded, and to select the Old declaration that New should be
3189 /// merged with.
3190 ///
3191 /// Returns true if there was an error, false otherwise.
3192 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3193                              Scope *S, bool MergeTypeWithOld) {
3194   // Verify the old decl was also a function.
3195   FunctionDecl *Old = OldD->getAsFunction();
3196   if (!Old) {
3197     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3198       if (New->getFriendObjectKind()) {
3199         Diag(New->getLocation(), diag::err_using_decl_friend);
3200         Diag(Shadow->getTargetDecl()->getLocation(),
3201              diag::note_using_decl_target);
3202         Diag(Shadow->getUsingDecl()->getLocation(),
3203              diag::note_using_decl) << 0;
3204         return true;
3205       }
3206 
3207       // Check whether the two declarations might declare the same function.
3208       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3209         return true;
3210       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3211     } else {
3212       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3213         << New->getDeclName();
3214       notePreviousDefinition(OldD, New->getLocation());
3215       return true;
3216     }
3217   }
3218 
3219   // If the old declaration is invalid, just give up here.
3220   if (Old->isInvalidDecl())
3221     return true;
3222 
3223   // Disallow redeclaration of some builtins.
3224   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3225     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3226     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3227         << Old << Old->getType();
3228     return true;
3229   }
3230 
3231   diag::kind PrevDiag;
3232   SourceLocation OldLocation;
3233   std::tie(PrevDiag, OldLocation) =
3234       getNoteDiagForInvalidRedeclaration(Old, New);
3235 
3236   // Don't complain about this if we're in GNU89 mode and the old function
3237   // is an extern inline function.
3238   // Don't complain about specializations. They are not supposed to have
3239   // storage classes.
3240   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3241       New->getStorageClass() == SC_Static &&
3242       Old->hasExternalFormalLinkage() &&
3243       !New->getTemplateSpecializationInfo() &&
3244       !canRedefineFunction(Old, getLangOpts())) {
3245     if (getLangOpts().MicrosoftExt) {
3246       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3247       Diag(OldLocation, PrevDiag);
3248     } else {
3249       Diag(New->getLocation(), diag::err_static_non_static) << New;
3250       Diag(OldLocation, PrevDiag);
3251       return true;
3252     }
3253   }
3254 
3255   if (New->hasAttr<InternalLinkageAttr>() &&
3256       !Old->hasAttr<InternalLinkageAttr>()) {
3257     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3258         << New->getDeclName();
3259     notePreviousDefinition(Old, New->getLocation());
3260     New->dropAttr<InternalLinkageAttr>();
3261   }
3262 
3263   if (CheckRedeclarationModuleOwnership(New, Old))
3264     return true;
3265 
3266   if (!getLangOpts().CPlusPlus) {
3267     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3268     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3269       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3270         << New << OldOvl;
3271 
3272       // Try our best to find a decl that actually has the overloadable
3273       // attribute for the note. In most cases (e.g. programs with only one
3274       // broken declaration/definition), this won't matter.
3275       //
3276       // FIXME: We could do this if we juggled some extra state in
3277       // OverloadableAttr, rather than just removing it.
3278       const Decl *DiagOld = Old;
3279       if (OldOvl) {
3280         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3281           const auto *A = D->getAttr<OverloadableAttr>();
3282           return A && !A->isImplicit();
3283         });
3284         // If we've implicitly added *all* of the overloadable attrs to this
3285         // chain, emitting a "previous redecl" note is pointless.
3286         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3287       }
3288 
3289       if (DiagOld)
3290         Diag(DiagOld->getLocation(),
3291              diag::note_attribute_overloadable_prev_overload)
3292           << OldOvl;
3293 
3294       if (OldOvl)
3295         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3296       else
3297         New->dropAttr<OverloadableAttr>();
3298     }
3299   }
3300 
3301   // If a function is first declared with a calling convention, but is later
3302   // declared or defined without one, all following decls assume the calling
3303   // convention of the first.
3304   //
3305   // It's OK if a function is first declared without a calling convention,
3306   // but is later declared or defined with the default calling convention.
3307   //
3308   // To test if either decl has an explicit calling convention, we look for
3309   // AttributedType sugar nodes on the type as written.  If they are missing or
3310   // were canonicalized away, we assume the calling convention was implicit.
3311   //
3312   // Note also that we DO NOT return at this point, because we still have
3313   // other tests to run.
3314   QualType OldQType = Context.getCanonicalType(Old->getType());
3315   QualType NewQType = Context.getCanonicalType(New->getType());
3316   const FunctionType *OldType = cast<FunctionType>(OldQType);
3317   const FunctionType *NewType = cast<FunctionType>(NewQType);
3318   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3319   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3320   bool RequiresAdjustment = false;
3321 
3322   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3323     FunctionDecl *First = Old->getFirstDecl();
3324     const FunctionType *FT =
3325         First->getType().getCanonicalType()->castAs<FunctionType>();
3326     FunctionType::ExtInfo FI = FT->getExtInfo();
3327     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3328     if (!NewCCExplicit) {
3329       // Inherit the CC from the previous declaration if it was specified
3330       // there but not here.
3331       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3332       RequiresAdjustment = true;
3333     } else if (New->getBuiltinID()) {
3334       // Calling Conventions on a Builtin aren't really useful and setting a
3335       // default calling convention and cdecl'ing some builtin redeclarations is
3336       // common, so warn and ignore the calling convention on the redeclaration.
3337       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3338           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3339           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3340       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3341       RequiresAdjustment = true;
3342     } else {
3343       // Calling conventions aren't compatible, so complain.
3344       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3345       Diag(New->getLocation(), diag::err_cconv_change)
3346         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3347         << !FirstCCExplicit
3348         << (!FirstCCExplicit ? "" :
3349             FunctionType::getNameForCallConv(FI.getCC()));
3350 
3351       // Put the note on the first decl, since it is the one that matters.
3352       Diag(First->getLocation(), diag::note_previous_declaration);
3353       return true;
3354     }
3355   }
3356 
3357   // FIXME: diagnose the other way around?
3358   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3359     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3360     RequiresAdjustment = true;
3361   }
3362 
3363   // Merge regparm attribute.
3364   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3365       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3366     if (NewTypeInfo.getHasRegParm()) {
3367       Diag(New->getLocation(), diag::err_regparm_mismatch)
3368         << NewType->getRegParmType()
3369         << OldType->getRegParmType();
3370       Diag(OldLocation, diag::note_previous_declaration);
3371       return true;
3372     }
3373 
3374     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3375     RequiresAdjustment = true;
3376   }
3377 
3378   // Merge ns_returns_retained attribute.
3379   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3380     if (NewTypeInfo.getProducesResult()) {
3381       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3382           << "'ns_returns_retained'";
3383       Diag(OldLocation, diag::note_previous_declaration);
3384       return true;
3385     }
3386 
3387     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3388     RequiresAdjustment = true;
3389   }
3390 
3391   if (OldTypeInfo.getNoCallerSavedRegs() !=
3392       NewTypeInfo.getNoCallerSavedRegs()) {
3393     if (NewTypeInfo.getNoCallerSavedRegs()) {
3394       AnyX86NoCallerSavedRegistersAttr *Attr =
3395         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3396       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3397       Diag(OldLocation, diag::note_previous_declaration);
3398       return true;
3399     }
3400 
3401     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3402     RequiresAdjustment = true;
3403   }
3404 
3405   if (RequiresAdjustment) {
3406     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3407     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3408     New->setType(QualType(AdjustedType, 0));
3409     NewQType = Context.getCanonicalType(New->getType());
3410   }
3411 
3412   // If this redeclaration makes the function inline, we may need to add it to
3413   // UndefinedButUsed.
3414   if (!Old->isInlined() && New->isInlined() &&
3415       !New->hasAttr<GNUInlineAttr>() &&
3416       !getLangOpts().GNUInline &&
3417       Old->isUsed(false) &&
3418       !Old->isDefined() && !New->isThisDeclarationADefinition())
3419     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3420                                            SourceLocation()));
3421 
3422   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3423   // about it.
3424   if (New->hasAttr<GNUInlineAttr>() &&
3425       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3426     UndefinedButUsed.erase(Old->getCanonicalDecl());
3427   }
3428 
3429   // If pass_object_size params don't match up perfectly, this isn't a valid
3430   // redeclaration.
3431   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3432       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3433     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3434         << New->getDeclName();
3435     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3436     return true;
3437   }
3438 
3439   if (getLangOpts().CPlusPlus) {
3440     // C++1z [over.load]p2
3441     //   Certain function declarations cannot be overloaded:
3442     //     -- Function declarations that differ only in the return type,
3443     //        the exception specification, or both cannot be overloaded.
3444 
3445     // Check the exception specifications match. This may recompute the type of
3446     // both Old and New if it resolved exception specifications, so grab the
3447     // types again after this. Because this updates the type, we do this before
3448     // any of the other checks below, which may update the "de facto" NewQType
3449     // but do not necessarily update the type of New.
3450     if (CheckEquivalentExceptionSpec(Old, New))
3451       return true;
3452     OldQType = Context.getCanonicalType(Old->getType());
3453     NewQType = Context.getCanonicalType(New->getType());
3454 
3455     // Go back to the type source info to compare the declared return types,
3456     // per C++1y [dcl.type.auto]p13:
3457     //   Redeclarations or specializations of a function or function template
3458     //   with a declared return type that uses a placeholder type shall also
3459     //   use that placeholder, not a deduced type.
3460     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3461     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3462     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3463         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3464                                        OldDeclaredReturnType)) {
3465       QualType ResQT;
3466       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3467           OldDeclaredReturnType->isObjCObjectPointerType())
3468         // FIXME: This does the wrong thing for a deduced return type.
3469         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3470       if (ResQT.isNull()) {
3471         if (New->isCXXClassMember() && New->isOutOfLine())
3472           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3473               << New << New->getReturnTypeSourceRange();
3474         else
3475           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3476               << New->getReturnTypeSourceRange();
3477         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3478                                     << Old->getReturnTypeSourceRange();
3479         return true;
3480       }
3481       else
3482         NewQType = ResQT;
3483     }
3484 
3485     QualType OldReturnType = OldType->getReturnType();
3486     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3487     if (OldReturnType != NewReturnType) {
3488       // If this function has a deduced return type and has already been
3489       // defined, copy the deduced value from the old declaration.
3490       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3491       if (OldAT && OldAT->isDeduced()) {
3492         New->setType(
3493             SubstAutoType(New->getType(),
3494                           OldAT->isDependentType() ? Context.DependentTy
3495                                                    : OldAT->getDeducedType()));
3496         NewQType = Context.getCanonicalType(
3497             SubstAutoType(NewQType,
3498                           OldAT->isDependentType() ? Context.DependentTy
3499                                                    : OldAT->getDeducedType()));
3500       }
3501     }
3502 
3503     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3504     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3505     if (OldMethod && NewMethod) {
3506       // Preserve triviality.
3507       NewMethod->setTrivial(OldMethod->isTrivial());
3508 
3509       // MSVC allows explicit template specialization at class scope:
3510       // 2 CXXMethodDecls referring to the same function will be injected.
3511       // We don't want a redeclaration error.
3512       bool IsClassScopeExplicitSpecialization =
3513                               OldMethod->isFunctionTemplateSpecialization() &&
3514                               NewMethod->isFunctionTemplateSpecialization();
3515       bool isFriend = NewMethod->getFriendObjectKind();
3516 
3517       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3518           !IsClassScopeExplicitSpecialization) {
3519         //    -- Member function declarations with the same name and the
3520         //       same parameter types cannot be overloaded if any of them
3521         //       is a static member function declaration.
3522         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3523           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3524           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3525           return true;
3526         }
3527 
3528         // C++ [class.mem]p1:
3529         //   [...] A member shall not be declared twice in the
3530         //   member-specification, except that a nested class or member
3531         //   class template can be declared and then later defined.
3532         if (!inTemplateInstantiation()) {
3533           unsigned NewDiag;
3534           if (isa<CXXConstructorDecl>(OldMethod))
3535             NewDiag = diag::err_constructor_redeclared;
3536           else if (isa<CXXDestructorDecl>(NewMethod))
3537             NewDiag = diag::err_destructor_redeclared;
3538           else if (isa<CXXConversionDecl>(NewMethod))
3539             NewDiag = diag::err_conv_function_redeclared;
3540           else
3541             NewDiag = diag::err_member_redeclared;
3542 
3543           Diag(New->getLocation(), NewDiag);
3544         } else {
3545           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3546             << New << New->getType();
3547         }
3548         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3549         return true;
3550 
3551       // Complain if this is an explicit declaration of a special
3552       // member that was initially declared implicitly.
3553       //
3554       // As an exception, it's okay to befriend such methods in order
3555       // to permit the implicit constructor/destructor/operator calls.
3556       } else if (OldMethod->isImplicit()) {
3557         if (isFriend) {
3558           NewMethod->setImplicit();
3559         } else {
3560           Diag(NewMethod->getLocation(),
3561                diag::err_definition_of_implicitly_declared_member)
3562             << New << getSpecialMember(OldMethod);
3563           return true;
3564         }
3565       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3566         Diag(NewMethod->getLocation(),
3567              diag::err_definition_of_explicitly_defaulted_member)
3568           << getSpecialMember(OldMethod);
3569         return true;
3570       }
3571     }
3572 
3573     // C++11 [dcl.attr.noreturn]p1:
3574     //   The first declaration of a function shall specify the noreturn
3575     //   attribute if any declaration of that function specifies the noreturn
3576     //   attribute.
3577     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3578     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3579       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3580       Diag(Old->getFirstDecl()->getLocation(),
3581            diag::note_noreturn_missing_first_decl);
3582     }
3583 
3584     // C++11 [dcl.attr.depend]p2:
3585     //   The first declaration of a function shall specify the
3586     //   carries_dependency attribute for its declarator-id if any declaration
3587     //   of the function specifies the carries_dependency attribute.
3588     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3589     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3590       Diag(CDA->getLocation(),
3591            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3592       Diag(Old->getFirstDecl()->getLocation(),
3593            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3594     }
3595 
3596     // (C++98 8.3.5p3):
3597     //   All declarations for a function shall agree exactly in both the
3598     //   return type and the parameter-type-list.
3599     // We also want to respect all the extended bits except noreturn.
3600 
3601     // noreturn should now match unless the old type info didn't have it.
3602     QualType OldQTypeForComparison = OldQType;
3603     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3604       auto *OldType = OldQType->castAs<FunctionProtoType>();
3605       const FunctionType *OldTypeForComparison
3606         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3607       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3608       assert(OldQTypeForComparison.isCanonical());
3609     }
3610 
3611     if (haveIncompatibleLanguageLinkages(Old, New)) {
3612       // As a special case, retain the language linkage from previous
3613       // declarations of a friend function as an extension.
3614       //
3615       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3616       // and is useful because there's otherwise no way to specify language
3617       // linkage within class scope.
3618       //
3619       // Check cautiously as the friend object kind isn't yet complete.
3620       if (New->getFriendObjectKind() != Decl::FOK_None) {
3621         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3622         Diag(OldLocation, PrevDiag);
3623       } else {
3624         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3625         Diag(OldLocation, PrevDiag);
3626         return true;
3627       }
3628     }
3629 
3630     // If the function types are compatible, merge the declarations. Ignore the
3631     // exception specifier because it was already checked above in
3632     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3633     // about incompatible types under -fms-compatibility.
3634     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3635                                                          NewQType))
3636       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3637 
3638     // If the types are imprecise (due to dependent constructs in friends or
3639     // local extern declarations), it's OK if they differ. We'll check again
3640     // during instantiation.
3641     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3642       return false;
3643 
3644     // Fall through for conflicting redeclarations and redefinitions.
3645   }
3646 
3647   // C: Function types need to be compatible, not identical. This handles
3648   // duplicate function decls like "void f(int); void f(enum X);" properly.
3649   if (!getLangOpts().CPlusPlus &&
3650       Context.typesAreCompatible(OldQType, NewQType)) {
3651     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3652     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3653     const FunctionProtoType *OldProto = nullptr;
3654     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3655         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3656       // The old declaration provided a function prototype, but the
3657       // new declaration does not. Merge in the prototype.
3658       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3659       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3660       NewQType =
3661           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3662                                   OldProto->getExtProtoInfo());
3663       New->setType(NewQType);
3664       New->setHasInheritedPrototype();
3665 
3666       // Synthesize parameters with the same types.
3667       SmallVector<ParmVarDecl*, 16> Params;
3668       for (const auto &ParamType : OldProto->param_types()) {
3669         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3670                                                  SourceLocation(), nullptr,
3671                                                  ParamType, /*TInfo=*/nullptr,
3672                                                  SC_None, nullptr);
3673         Param->setScopeInfo(0, Params.size());
3674         Param->setImplicit();
3675         Params.push_back(Param);
3676       }
3677 
3678       New->setParams(Params);
3679     }
3680 
3681     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3682   }
3683 
3684   // Check if the function types are compatible when pointer size address
3685   // spaces are ignored.
3686   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3687     return false;
3688 
3689   // GNU C permits a K&R definition to follow a prototype declaration
3690   // if the declared types of the parameters in the K&R definition
3691   // match the types in the prototype declaration, even when the
3692   // promoted types of the parameters from the K&R definition differ
3693   // from the types in the prototype. GCC then keeps the types from
3694   // the prototype.
3695   //
3696   // If a variadic prototype is followed by a non-variadic K&R definition,
3697   // the K&R definition becomes variadic.  This is sort of an edge case, but
3698   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3699   // C99 6.9.1p8.
3700   if (!getLangOpts().CPlusPlus &&
3701       Old->hasPrototype() && !New->hasPrototype() &&
3702       New->getType()->getAs<FunctionProtoType>() &&
3703       Old->getNumParams() == New->getNumParams()) {
3704     SmallVector<QualType, 16> ArgTypes;
3705     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3706     const FunctionProtoType *OldProto
3707       = Old->getType()->getAs<FunctionProtoType>();
3708     const FunctionProtoType *NewProto
3709       = New->getType()->getAs<FunctionProtoType>();
3710 
3711     // Determine whether this is the GNU C extension.
3712     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3713                                                NewProto->getReturnType());
3714     bool LooseCompatible = !MergedReturn.isNull();
3715     for (unsigned Idx = 0, End = Old->getNumParams();
3716          LooseCompatible && Idx != End; ++Idx) {
3717       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3718       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3719       if (Context.typesAreCompatible(OldParm->getType(),
3720                                      NewProto->getParamType(Idx))) {
3721         ArgTypes.push_back(NewParm->getType());
3722       } else if (Context.typesAreCompatible(OldParm->getType(),
3723                                             NewParm->getType(),
3724                                             /*CompareUnqualified=*/true)) {
3725         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3726                                            NewProto->getParamType(Idx) };
3727         Warnings.push_back(Warn);
3728         ArgTypes.push_back(NewParm->getType());
3729       } else
3730         LooseCompatible = false;
3731     }
3732 
3733     if (LooseCompatible) {
3734       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3735         Diag(Warnings[Warn].NewParm->getLocation(),
3736              diag::ext_param_promoted_not_compatible_with_prototype)
3737           << Warnings[Warn].PromotedType
3738           << Warnings[Warn].OldParm->getType();
3739         if (Warnings[Warn].OldParm->getLocation().isValid())
3740           Diag(Warnings[Warn].OldParm->getLocation(),
3741                diag::note_previous_declaration);
3742       }
3743 
3744       if (MergeTypeWithOld)
3745         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3746                                              OldProto->getExtProtoInfo()));
3747       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3748     }
3749 
3750     // Fall through to diagnose conflicting types.
3751   }
3752 
3753   // A function that has already been declared has been redeclared or
3754   // defined with a different type; show an appropriate diagnostic.
3755 
3756   // If the previous declaration was an implicitly-generated builtin
3757   // declaration, then at the very least we should use a specialized note.
3758   unsigned BuiltinID;
3759   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3760     // If it's actually a library-defined builtin function like 'malloc'
3761     // or 'printf', just warn about the incompatible redeclaration.
3762     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3763       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3764       Diag(OldLocation, diag::note_previous_builtin_declaration)
3765         << Old << Old->getType();
3766 
3767       // If this is a global redeclaration, just forget hereafter
3768       // about the "builtin-ness" of the function.
3769       //
3770       // Doing this for local extern declarations is problematic.  If
3771       // the builtin declaration remains visible, a second invalid
3772       // local declaration will produce a hard error; if it doesn't
3773       // remain visible, a single bogus local redeclaration (which is
3774       // actually only a warning) could break all the downstream code.
3775       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3776         New->getIdentifier()->revertBuiltin();
3777 
3778       return false;
3779     }
3780 
3781     PrevDiag = diag::note_previous_builtin_declaration;
3782   }
3783 
3784   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3785   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3786   return true;
3787 }
3788 
3789 /// Completes the merge of two function declarations that are
3790 /// known to be compatible.
3791 ///
3792 /// This routine handles the merging of attributes and other
3793 /// properties of function declarations from the old declaration to
3794 /// the new declaration, once we know that New is in fact a
3795 /// redeclaration of Old.
3796 ///
3797 /// \returns false
3798 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3799                                         Scope *S, bool MergeTypeWithOld) {
3800   // Merge the attributes
3801   mergeDeclAttributes(New, Old);
3802 
3803   // Merge "pure" flag.
3804   if (Old->isPure())
3805     New->setPure();
3806 
3807   // Merge "used" flag.
3808   if (Old->getMostRecentDecl()->isUsed(false))
3809     New->setIsUsed();
3810 
3811   // Merge attributes from the parameters.  These can mismatch with K&R
3812   // declarations.
3813   if (New->getNumParams() == Old->getNumParams())
3814       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3815         ParmVarDecl *NewParam = New->getParamDecl(i);
3816         ParmVarDecl *OldParam = Old->getParamDecl(i);
3817         mergeParamDeclAttributes(NewParam, OldParam, *this);
3818         mergeParamDeclTypes(NewParam, OldParam, *this);
3819       }
3820 
3821   if (getLangOpts().CPlusPlus)
3822     return MergeCXXFunctionDecl(New, Old, S);
3823 
3824   // Merge the function types so the we get the composite types for the return
3825   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3826   // was visible.
3827   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3828   if (!Merged.isNull() && MergeTypeWithOld)
3829     New->setType(Merged);
3830 
3831   return false;
3832 }
3833 
3834 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3835                                 ObjCMethodDecl *oldMethod) {
3836   // Merge the attributes, including deprecated/unavailable
3837   AvailabilityMergeKind MergeKind =
3838     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3839       ? AMK_ProtocolImplementation
3840       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3841                                                        : AMK_Override;
3842 
3843   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3844 
3845   // Merge attributes from the parameters.
3846   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3847                                        oe = oldMethod->param_end();
3848   for (ObjCMethodDecl::param_iterator
3849          ni = newMethod->param_begin(), ne = newMethod->param_end();
3850        ni != ne && oi != oe; ++ni, ++oi)
3851     mergeParamDeclAttributes(*ni, *oi, *this);
3852 
3853   CheckObjCMethodOverride(newMethod, oldMethod);
3854 }
3855 
3856 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3857   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3858 
3859   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3860          ? diag::err_redefinition_different_type
3861          : diag::err_redeclaration_different_type)
3862     << New->getDeclName() << New->getType() << Old->getType();
3863 
3864   diag::kind PrevDiag;
3865   SourceLocation OldLocation;
3866   std::tie(PrevDiag, OldLocation)
3867     = getNoteDiagForInvalidRedeclaration(Old, New);
3868   S.Diag(OldLocation, PrevDiag);
3869   New->setInvalidDecl();
3870 }
3871 
3872 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3873 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3874 /// emitting diagnostics as appropriate.
3875 ///
3876 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3877 /// to here in AddInitializerToDecl. We can't check them before the initializer
3878 /// is attached.
3879 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3880                              bool MergeTypeWithOld) {
3881   if (New->isInvalidDecl() || Old->isInvalidDecl())
3882     return;
3883 
3884   QualType MergedT;
3885   if (getLangOpts().CPlusPlus) {
3886     if (New->getType()->isUndeducedType()) {
3887       // We don't know what the new type is until the initializer is attached.
3888       return;
3889     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3890       // These could still be something that needs exception specs checked.
3891       return MergeVarDeclExceptionSpecs(New, Old);
3892     }
3893     // C++ [basic.link]p10:
3894     //   [...] the types specified by all declarations referring to a given
3895     //   object or function shall be identical, except that declarations for an
3896     //   array object can specify array types that differ by the presence or
3897     //   absence of a major array bound (8.3.4).
3898     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3899       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3900       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3901 
3902       // We are merging a variable declaration New into Old. If it has an array
3903       // bound, and that bound differs from Old's bound, we should diagnose the
3904       // mismatch.
3905       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3906         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3907              PrevVD = PrevVD->getPreviousDecl()) {
3908           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3909           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3910             continue;
3911 
3912           if (!Context.hasSameType(NewArray, PrevVDTy))
3913             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3914         }
3915       }
3916 
3917       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3918         if (Context.hasSameType(OldArray->getElementType(),
3919                                 NewArray->getElementType()))
3920           MergedT = New->getType();
3921       }
3922       // FIXME: Check visibility. New is hidden but has a complete type. If New
3923       // has no array bound, it should not inherit one from Old, if Old is not
3924       // visible.
3925       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3926         if (Context.hasSameType(OldArray->getElementType(),
3927                                 NewArray->getElementType()))
3928           MergedT = Old->getType();
3929       }
3930     }
3931     else if (New->getType()->isObjCObjectPointerType() &&
3932                Old->getType()->isObjCObjectPointerType()) {
3933       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3934                                               Old->getType());
3935     }
3936   } else {
3937     // C 6.2.7p2:
3938     //   All declarations that refer to the same object or function shall have
3939     //   compatible type.
3940     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3941   }
3942   if (MergedT.isNull()) {
3943     // It's OK if we couldn't merge types if either type is dependent, for a
3944     // block-scope variable. In other cases (static data members of class
3945     // templates, variable templates, ...), we require the types to be
3946     // equivalent.
3947     // FIXME: The C++ standard doesn't say anything about this.
3948     if ((New->getType()->isDependentType() ||
3949          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3950       // If the old type was dependent, we can't merge with it, so the new type
3951       // becomes dependent for now. We'll reproduce the original type when we
3952       // instantiate the TypeSourceInfo for the variable.
3953       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3954         New->setType(Context.DependentTy);
3955       return;
3956     }
3957     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3958   }
3959 
3960   // Don't actually update the type on the new declaration if the old
3961   // declaration was an extern declaration in a different scope.
3962   if (MergeTypeWithOld)
3963     New->setType(MergedT);
3964 }
3965 
3966 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3967                                   LookupResult &Previous) {
3968   // C11 6.2.7p4:
3969   //   For an identifier with internal or external linkage declared
3970   //   in a scope in which a prior declaration of that identifier is
3971   //   visible, if the prior declaration specifies internal or
3972   //   external linkage, the type of the identifier at the later
3973   //   declaration becomes the composite type.
3974   //
3975   // If the variable isn't visible, we do not merge with its type.
3976   if (Previous.isShadowed())
3977     return false;
3978 
3979   if (S.getLangOpts().CPlusPlus) {
3980     // C++11 [dcl.array]p3:
3981     //   If there is a preceding declaration of the entity in the same
3982     //   scope in which the bound was specified, an omitted array bound
3983     //   is taken to be the same as in that earlier declaration.
3984     return NewVD->isPreviousDeclInSameBlockScope() ||
3985            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3986             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3987   } else {
3988     // If the old declaration was function-local, don't merge with its
3989     // type unless we're in the same function.
3990     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3991            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3992   }
3993 }
3994 
3995 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3996 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3997 /// situation, merging decls or emitting diagnostics as appropriate.
3998 ///
3999 /// Tentative definition rules (C99 6.9.2p2) are checked by
4000 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4001 /// definitions here, since the initializer hasn't been attached.
4002 ///
4003 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4004   // If the new decl is already invalid, don't do any other checking.
4005   if (New->isInvalidDecl())
4006     return;
4007 
4008   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4009     return;
4010 
4011   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4012 
4013   // Verify the old decl was also a variable or variable template.
4014   VarDecl *Old = nullptr;
4015   VarTemplateDecl *OldTemplate = nullptr;
4016   if (Previous.isSingleResult()) {
4017     if (NewTemplate) {
4018       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4019       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4020 
4021       if (auto *Shadow =
4022               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4023         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4024           return New->setInvalidDecl();
4025     } else {
4026       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4027 
4028       if (auto *Shadow =
4029               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4030         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4031           return New->setInvalidDecl();
4032     }
4033   }
4034   if (!Old) {
4035     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4036         << New->getDeclName();
4037     notePreviousDefinition(Previous.getRepresentativeDecl(),
4038                            New->getLocation());
4039     return New->setInvalidDecl();
4040   }
4041 
4042   // Ensure the template parameters are compatible.
4043   if (NewTemplate &&
4044       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4045                                       OldTemplate->getTemplateParameters(),
4046                                       /*Complain=*/true, TPL_TemplateMatch))
4047     return New->setInvalidDecl();
4048 
4049   // C++ [class.mem]p1:
4050   //   A member shall not be declared twice in the member-specification [...]
4051   //
4052   // Here, we need only consider static data members.
4053   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4054     Diag(New->getLocation(), diag::err_duplicate_member)
4055       << New->getIdentifier();
4056     Diag(Old->getLocation(), diag::note_previous_declaration);
4057     New->setInvalidDecl();
4058   }
4059 
4060   mergeDeclAttributes(New, Old);
4061   // Warn if an already-declared variable is made a weak_import in a subsequent
4062   // declaration
4063   if (New->hasAttr<WeakImportAttr>() &&
4064       Old->getStorageClass() == SC_None &&
4065       !Old->hasAttr<WeakImportAttr>()) {
4066     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4067     notePreviousDefinition(Old, New->getLocation());
4068     // Remove weak_import attribute on new declaration.
4069     New->dropAttr<WeakImportAttr>();
4070   }
4071 
4072   if (New->hasAttr<InternalLinkageAttr>() &&
4073       !Old->hasAttr<InternalLinkageAttr>()) {
4074     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4075         << New->getDeclName();
4076     notePreviousDefinition(Old, New->getLocation());
4077     New->dropAttr<InternalLinkageAttr>();
4078   }
4079 
4080   // Merge the types.
4081   VarDecl *MostRecent = Old->getMostRecentDecl();
4082   if (MostRecent != Old) {
4083     MergeVarDeclTypes(New, MostRecent,
4084                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4085     if (New->isInvalidDecl())
4086       return;
4087   }
4088 
4089   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4090   if (New->isInvalidDecl())
4091     return;
4092 
4093   diag::kind PrevDiag;
4094   SourceLocation OldLocation;
4095   std::tie(PrevDiag, OldLocation) =
4096       getNoteDiagForInvalidRedeclaration(Old, New);
4097 
4098   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4099   if (New->getStorageClass() == SC_Static &&
4100       !New->isStaticDataMember() &&
4101       Old->hasExternalFormalLinkage()) {
4102     if (getLangOpts().MicrosoftExt) {
4103       Diag(New->getLocation(), diag::ext_static_non_static)
4104           << New->getDeclName();
4105       Diag(OldLocation, PrevDiag);
4106     } else {
4107       Diag(New->getLocation(), diag::err_static_non_static)
4108           << New->getDeclName();
4109       Diag(OldLocation, PrevDiag);
4110       return New->setInvalidDecl();
4111     }
4112   }
4113   // C99 6.2.2p4:
4114   //   For an identifier declared with the storage-class specifier
4115   //   extern in a scope in which a prior declaration of that
4116   //   identifier is visible,23) if the prior declaration specifies
4117   //   internal or external linkage, the linkage of the identifier at
4118   //   the later declaration is the same as the linkage specified at
4119   //   the prior declaration. If no prior declaration is visible, or
4120   //   if the prior declaration specifies no linkage, then the
4121   //   identifier has external linkage.
4122   if (New->hasExternalStorage() && Old->hasLinkage())
4123     /* Okay */;
4124   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4125            !New->isStaticDataMember() &&
4126            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4127     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4128     Diag(OldLocation, PrevDiag);
4129     return New->setInvalidDecl();
4130   }
4131 
4132   // Check if extern is followed by non-extern and vice-versa.
4133   if (New->hasExternalStorage() &&
4134       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4135     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4136     Diag(OldLocation, PrevDiag);
4137     return New->setInvalidDecl();
4138   }
4139   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4140       !New->hasExternalStorage()) {
4141     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4142     Diag(OldLocation, PrevDiag);
4143     return New->setInvalidDecl();
4144   }
4145 
4146   if (CheckRedeclarationModuleOwnership(New, Old))
4147     return;
4148 
4149   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4150 
4151   // FIXME: The test for external storage here seems wrong? We still
4152   // need to check for mismatches.
4153   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4154       // Don't complain about out-of-line definitions of static members.
4155       !(Old->getLexicalDeclContext()->isRecord() &&
4156         !New->getLexicalDeclContext()->isRecord())) {
4157     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4158     Diag(OldLocation, PrevDiag);
4159     return New->setInvalidDecl();
4160   }
4161 
4162   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4163     if (VarDecl *Def = Old->getDefinition()) {
4164       // C++1z [dcl.fcn.spec]p4:
4165       //   If the definition of a variable appears in a translation unit before
4166       //   its first declaration as inline, the program is ill-formed.
4167       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4168       Diag(Def->getLocation(), diag::note_previous_definition);
4169     }
4170   }
4171 
4172   // If this redeclaration makes the variable inline, we may need to add it to
4173   // UndefinedButUsed.
4174   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4175       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4176     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4177                                            SourceLocation()));
4178 
4179   if (New->getTLSKind() != Old->getTLSKind()) {
4180     if (!Old->getTLSKind()) {
4181       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4182       Diag(OldLocation, PrevDiag);
4183     } else if (!New->getTLSKind()) {
4184       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4185       Diag(OldLocation, PrevDiag);
4186     } else {
4187       // Do not allow redeclaration to change the variable between requiring
4188       // static and dynamic initialization.
4189       // FIXME: GCC allows this, but uses the TLS keyword on the first
4190       // declaration to determine the kind. Do we need to be compatible here?
4191       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4192         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4193       Diag(OldLocation, PrevDiag);
4194     }
4195   }
4196 
4197   // C++ doesn't have tentative definitions, so go right ahead and check here.
4198   if (getLangOpts().CPlusPlus &&
4199       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4200     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4201         Old->getCanonicalDecl()->isConstexpr()) {
4202       // This definition won't be a definition any more once it's been merged.
4203       Diag(New->getLocation(),
4204            diag::warn_deprecated_redundant_constexpr_static_def);
4205     } else if (VarDecl *Def = Old->getDefinition()) {
4206       if (checkVarDeclRedefinition(Def, New))
4207         return;
4208     }
4209   }
4210 
4211   if (haveIncompatibleLanguageLinkages(Old, New)) {
4212     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4213     Diag(OldLocation, PrevDiag);
4214     New->setInvalidDecl();
4215     return;
4216   }
4217 
4218   // Merge "used" flag.
4219   if (Old->getMostRecentDecl()->isUsed(false))
4220     New->setIsUsed();
4221 
4222   // Keep a chain of previous declarations.
4223   New->setPreviousDecl(Old);
4224   if (NewTemplate)
4225     NewTemplate->setPreviousDecl(OldTemplate);
4226   adjustDeclContextForDeclaratorDecl(New, Old);
4227 
4228   // Inherit access appropriately.
4229   New->setAccess(Old->getAccess());
4230   if (NewTemplate)
4231     NewTemplate->setAccess(New->getAccess());
4232 
4233   if (Old->isInline())
4234     New->setImplicitlyInline();
4235 }
4236 
4237 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4238   SourceManager &SrcMgr = getSourceManager();
4239   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4240   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4241   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4242   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4243   auto &HSI = PP.getHeaderSearchInfo();
4244   StringRef HdrFilename =
4245       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4246 
4247   auto noteFromModuleOrInclude = [&](Module *Mod,
4248                                      SourceLocation IncLoc) -> bool {
4249     // Redefinition errors with modules are common with non modular mapped
4250     // headers, example: a non-modular header H in module A that also gets
4251     // included directly in a TU. Pointing twice to the same header/definition
4252     // is confusing, try to get better diagnostics when modules is on.
4253     if (IncLoc.isValid()) {
4254       if (Mod) {
4255         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4256             << HdrFilename.str() << Mod->getFullModuleName();
4257         if (!Mod->DefinitionLoc.isInvalid())
4258           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4259               << Mod->getFullModuleName();
4260       } else {
4261         Diag(IncLoc, diag::note_redefinition_include_same_file)
4262             << HdrFilename.str();
4263       }
4264       return true;
4265     }
4266 
4267     return false;
4268   };
4269 
4270   // Is it the same file and same offset? Provide more information on why
4271   // this leads to a redefinition error.
4272   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4273     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4274     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4275     bool EmittedDiag =
4276         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4277     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4278 
4279     // If the header has no guards, emit a note suggesting one.
4280     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4281       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4282 
4283     if (EmittedDiag)
4284       return;
4285   }
4286 
4287   // Redefinition coming from different files or couldn't do better above.
4288   if (Old->getLocation().isValid())
4289     Diag(Old->getLocation(), diag::note_previous_definition);
4290 }
4291 
4292 /// We've just determined that \p Old and \p New both appear to be definitions
4293 /// of the same variable. Either diagnose or fix the problem.
4294 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4295   if (!hasVisibleDefinition(Old) &&
4296       (New->getFormalLinkage() == InternalLinkage ||
4297        New->isInline() ||
4298        New->getDescribedVarTemplate() ||
4299        New->getNumTemplateParameterLists() ||
4300        New->getDeclContext()->isDependentContext())) {
4301     // The previous definition is hidden, and multiple definitions are
4302     // permitted (in separate TUs). Demote this to a declaration.
4303     New->demoteThisDefinitionToDeclaration();
4304 
4305     // Make the canonical definition visible.
4306     if (auto *OldTD = Old->getDescribedVarTemplate())
4307       makeMergedDefinitionVisible(OldTD);
4308     makeMergedDefinitionVisible(Old);
4309     return false;
4310   } else {
4311     Diag(New->getLocation(), diag::err_redefinition) << New;
4312     notePreviousDefinition(Old, New->getLocation());
4313     New->setInvalidDecl();
4314     return true;
4315   }
4316 }
4317 
4318 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4319 /// no declarator (e.g. "struct foo;") is parsed.
4320 Decl *
4321 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4322                                  RecordDecl *&AnonRecord) {
4323   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4324                                     AnonRecord);
4325 }
4326 
4327 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4328 // disambiguate entities defined in different scopes.
4329 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4330 // compatibility.
4331 // We will pick our mangling number depending on which version of MSVC is being
4332 // targeted.
4333 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4334   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4335              ? S->getMSCurManglingNumber()
4336              : S->getMSLastManglingNumber();
4337 }
4338 
4339 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4340   if (!Context.getLangOpts().CPlusPlus)
4341     return;
4342 
4343   if (isa<CXXRecordDecl>(Tag->getParent())) {
4344     // If this tag is the direct child of a class, number it if
4345     // it is anonymous.
4346     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4347       return;
4348     MangleNumberingContext &MCtx =
4349         Context.getManglingNumberContext(Tag->getParent());
4350     Context.setManglingNumber(
4351         Tag, MCtx.getManglingNumber(
4352                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4353     return;
4354   }
4355 
4356   // If this tag isn't a direct child of a class, number it if it is local.
4357   MangleNumberingContext *MCtx;
4358   Decl *ManglingContextDecl;
4359   std::tie(MCtx, ManglingContextDecl) =
4360       getCurrentMangleNumberContext(Tag->getDeclContext());
4361   if (MCtx) {
4362     Context.setManglingNumber(
4363         Tag, MCtx->getManglingNumber(
4364                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4365   }
4366 }
4367 
4368 namespace {
4369 struct NonCLikeKind {
4370   enum {
4371     None,
4372     BaseClass,
4373     DefaultMemberInit,
4374     Lambda,
4375     Friend,
4376     OtherMember,
4377     Invalid,
4378   } Kind = None;
4379   SourceRange Range;
4380 
4381   explicit operator bool() { return Kind != None; }
4382 };
4383 }
4384 
4385 /// Determine whether a class is C-like, according to the rules of C++
4386 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4387 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4388   if (RD->isInvalidDecl())
4389     return {NonCLikeKind::Invalid, {}};
4390 
4391   // C++ [dcl.typedef]p9: [P1766R1]
4392   //   An unnamed class with a typedef name for linkage purposes shall not
4393   //
4394   //    -- have any base classes
4395   if (RD->getNumBases())
4396     return {NonCLikeKind::BaseClass,
4397             SourceRange(RD->bases_begin()->getBeginLoc(),
4398                         RD->bases_end()[-1].getEndLoc())};
4399   bool Invalid = false;
4400   for (Decl *D : RD->decls()) {
4401     // Don't complain about things we already diagnosed.
4402     if (D->isInvalidDecl()) {
4403       Invalid = true;
4404       continue;
4405     }
4406 
4407     //  -- have any [...] default member initializers
4408     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4409       if (FD->hasInClassInitializer()) {
4410         auto *Init = FD->getInClassInitializer();
4411         return {NonCLikeKind::DefaultMemberInit,
4412                 Init ? Init->getSourceRange() : D->getSourceRange()};
4413       }
4414       continue;
4415     }
4416 
4417     // FIXME: We don't allow friend declarations. This violates the wording of
4418     // P1766, but not the intent.
4419     if (isa<FriendDecl>(D))
4420       return {NonCLikeKind::Friend, D->getSourceRange()};
4421 
4422     //  -- declare any members other than non-static data members, member
4423     //     enumerations, or member classes,
4424     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4425         isa<EnumDecl>(D))
4426       continue;
4427     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4428     if (!MemberRD) {
4429       if (D->isImplicit())
4430         continue;
4431       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4432     }
4433 
4434     //  -- contain a lambda-expression,
4435     if (MemberRD->isLambda())
4436       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4437 
4438     //  and all member classes shall also satisfy these requirements
4439     //  (recursively).
4440     if (MemberRD->isThisDeclarationADefinition()) {
4441       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4442         return Kind;
4443     }
4444   }
4445 
4446   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4447 }
4448 
4449 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4450                                         TypedefNameDecl *NewTD) {
4451   if (TagFromDeclSpec->isInvalidDecl())
4452     return;
4453 
4454   // Do nothing if the tag already has a name for linkage purposes.
4455   if (TagFromDeclSpec->hasNameForLinkage())
4456     return;
4457 
4458   // A well-formed anonymous tag must always be a TUK_Definition.
4459   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4460 
4461   // The type must match the tag exactly;  no qualifiers allowed.
4462   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4463                            Context.getTagDeclType(TagFromDeclSpec))) {
4464     if (getLangOpts().CPlusPlus)
4465       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4466     return;
4467   }
4468 
4469   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4470   //   An unnamed class with a typedef name for linkage purposes shall [be
4471   //   C-like].
4472   //
4473   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4474   // shouldn't happen, but there are constructs that the language rule doesn't
4475   // disallow for which we can't reasonably avoid computing linkage early.
4476   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4477   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4478                              : NonCLikeKind();
4479   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4480   if (NonCLike || ChangesLinkage) {
4481     if (NonCLike.Kind == NonCLikeKind::Invalid)
4482       return;
4483 
4484     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4485     if (ChangesLinkage) {
4486       // If the linkage changes, we can't accept this as an extension.
4487       if (NonCLike.Kind == NonCLikeKind::None)
4488         DiagID = diag::err_typedef_changes_linkage;
4489       else
4490         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4491     }
4492 
4493     SourceLocation FixitLoc =
4494         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4495     llvm::SmallString<40> TextToInsert;
4496     TextToInsert += ' ';
4497     TextToInsert += NewTD->getIdentifier()->getName();
4498 
4499     Diag(FixitLoc, DiagID)
4500       << isa<TypeAliasDecl>(NewTD)
4501       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4502     if (NonCLike.Kind != NonCLikeKind::None) {
4503       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4504         << NonCLike.Kind - 1 << NonCLike.Range;
4505     }
4506     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4507       << NewTD << isa<TypeAliasDecl>(NewTD);
4508 
4509     if (ChangesLinkage)
4510       return;
4511   }
4512 
4513   // Otherwise, set this as the anon-decl typedef for the tag.
4514   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4515 }
4516 
4517 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4518   switch (T) {
4519   case DeclSpec::TST_class:
4520     return 0;
4521   case DeclSpec::TST_struct:
4522     return 1;
4523   case DeclSpec::TST_interface:
4524     return 2;
4525   case DeclSpec::TST_union:
4526     return 3;
4527   case DeclSpec::TST_enum:
4528     return 4;
4529   default:
4530     llvm_unreachable("unexpected type specifier");
4531   }
4532 }
4533 
4534 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4535 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4536 /// parameters to cope with template friend declarations.
4537 Decl *
4538 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4539                                  MultiTemplateParamsArg TemplateParams,
4540                                  bool IsExplicitInstantiation,
4541                                  RecordDecl *&AnonRecord) {
4542   Decl *TagD = nullptr;
4543   TagDecl *Tag = nullptr;
4544   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4545       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4546       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4547       DS.getTypeSpecType() == DeclSpec::TST_union ||
4548       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4549     TagD = DS.getRepAsDecl();
4550 
4551     if (!TagD) // We probably had an error
4552       return nullptr;
4553 
4554     // Note that the above type specs guarantee that the
4555     // type rep is a Decl, whereas in many of the others
4556     // it's a Type.
4557     if (isa<TagDecl>(TagD))
4558       Tag = cast<TagDecl>(TagD);
4559     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4560       Tag = CTD->getTemplatedDecl();
4561   }
4562 
4563   if (Tag) {
4564     handleTagNumbering(Tag, S);
4565     Tag->setFreeStanding();
4566     if (Tag->isInvalidDecl())
4567       return Tag;
4568   }
4569 
4570   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4571     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4572     // or incomplete types shall not be restrict-qualified."
4573     if (TypeQuals & DeclSpec::TQ_restrict)
4574       Diag(DS.getRestrictSpecLoc(),
4575            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4576            << DS.getSourceRange();
4577   }
4578 
4579   if (DS.isInlineSpecified())
4580     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4581         << getLangOpts().CPlusPlus17;
4582 
4583   if (DS.hasConstexprSpecifier()) {
4584     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4585     // and definitions of functions and variables.
4586     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4587     // the declaration of a function or function template
4588     if (Tag)
4589       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4590           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4591           << DS.getConstexprSpecifier();
4592     else
4593       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4594           << DS.getConstexprSpecifier();
4595     // Don't emit warnings after this error.
4596     return TagD;
4597   }
4598 
4599   DiagnoseFunctionSpecifiers(DS);
4600 
4601   if (DS.isFriendSpecified()) {
4602     // If we're dealing with a decl but not a TagDecl, assume that
4603     // whatever routines created it handled the friendship aspect.
4604     if (TagD && !Tag)
4605       return nullptr;
4606     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4607   }
4608 
4609   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4610   bool IsExplicitSpecialization =
4611     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4612   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4613       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4614       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4615     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4616     // nested-name-specifier unless it is an explicit instantiation
4617     // or an explicit specialization.
4618     //
4619     // FIXME: We allow class template partial specializations here too, per the
4620     // obvious intent of DR1819.
4621     //
4622     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4623     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4624         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4625     return nullptr;
4626   }
4627 
4628   // Track whether this decl-specifier declares anything.
4629   bool DeclaresAnything = true;
4630 
4631   // Handle anonymous struct definitions.
4632   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4633     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4634         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4635       if (getLangOpts().CPlusPlus ||
4636           Record->getDeclContext()->isRecord()) {
4637         // If CurContext is a DeclContext that can contain statements,
4638         // RecursiveASTVisitor won't visit the decls that
4639         // BuildAnonymousStructOrUnion() will put into CurContext.
4640         // Also store them here so that they can be part of the
4641         // DeclStmt that gets created in this case.
4642         // FIXME: Also return the IndirectFieldDecls created by
4643         // BuildAnonymousStructOr union, for the same reason?
4644         if (CurContext->isFunctionOrMethod())
4645           AnonRecord = Record;
4646         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4647                                            Context.getPrintingPolicy());
4648       }
4649 
4650       DeclaresAnything = false;
4651     }
4652   }
4653 
4654   // C11 6.7.2.1p2:
4655   //   A struct-declaration that does not declare an anonymous structure or
4656   //   anonymous union shall contain a struct-declarator-list.
4657   //
4658   // This rule also existed in C89 and C99; the grammar for struct-declaration
4659   // did not permit a struct-declaration without a struct-declarator-list.
4660   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4661       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4662     // Check for Microsoft C extension: anonymous struct/union member.
4663     // Handle 2 kinds of anonymous struct/union:
4664     //   struct STRUCT;
4665     //   union UNION;
4666     // and
4667     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4668     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4669     if ((Tag && Tag->getDeclName()) ||
4670         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4671       RecordDecl *Record = nullptr;
4672       if (Tag)
4673         Record = dyn_cast<RecordDecl>(Tag);
4674       else if (const RecordType *RT =
4675                    DS.getRepAsType().get()->getAsStructureType())
4676         Record = RT->getDecl();
4677       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4678         Record = UT->getDecl();
4679 
4680       if (Record && getLangOpts().MicrosoftExt) {
4681         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4682             << Record->isUnion() << DS.getSourceRange();
4683         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4684       }
4685 
4686       DeclaresAnything = false;
4687     }
4688   }
4689 
4690   // Skip all the checks below if we have a type error.
4691   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4692       (TagD && TagD->isInvalidDecl()))
4693     return TagD;
4694 
4695   if (getLangOpts().CPlusPlus &&
4696       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4697     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4698       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4699           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4700         DeclaresAnything = false;
4701 
4702   if (!DS.isMissingDeclaratorOk()) {
4703     // Customize diagnostic for a typedef missing a name.
4704     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4705       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4706           << DS.getSourceRange();
4707     else
4708       DeclaresAnything = false;
4709   }
4710 
4711   if (DS.isModulePrivateSpecified() &&
4712       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4713     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4714       << Tag->getTagKind()
4715       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4716 
4717   ActOnDocumentableDecl(TagD);
4718 
4719   // C 6.7/2:
4720   //   A declaration [...] shall declare at least a declarator [...], a tag,
4721   //   or the members of an enumeration.
4722   // C++ [dcl.dcl]p3:
4723   //   [If there are no declarators], and except for the declaration of an
4724   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4725   //   names into the program, or shall redeclare a name introduced by a
4726   //   previous declaration.
4727   if (!DeclaresAnything) {
4728     // In C, we allow this as a (popular) extension / bug. Don't bother
4729     // producing further diagnostics for redundant qualifiers after this.
4730     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4731     return TagD;
4732   }
4733 
4734   // C++ [dcl.stc]p1:
4735   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4736   //   init-declarator-list of the declaration shall not be empty.
4737   // C++ [dcl.fct.spec]p1:
4738   //   If a cv-qualifier appears in a decl-specifier-seq, the
4739   //   init-declarator-list of the declaration shall not be empty.
4740   //
4741   // Spurious qualifiers here appear to be valid in C.
4742   unsigned DiagID = diag::warn_standalone_specifier;
4743   if (getLangOpts().CPlusPlus)
4744     DiagID = diag::ext_standalone_specifier;
4745 
4746   // Note that a linkage-specification sets a storage class, but
4747   // 'extern "C" struct foo;' is actually valid and not theoretically
4748   // useless.
4749   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4750     if (SCS == DeclSpec::SCS_mutable)
4751       // Since mutable is not a viable storage class specifier in C, there is
4752       // no reason to treat it as an extension. Instead, diagnose as an error.
4753       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4754     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4755       Diag(DS.getStorageClassSpecLoc(), DiagID)
4756         << DeclSpec::getSpecifierName(SCS);
4757   }
4758 
4759   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4760     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4761       << DeclSpec::getSpecifierName(TSCS);
4762   if (DS.getTypeQualifiers()) {
4763     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4764       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4765     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4766       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4767     // Restrict is covered above.
4768     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4769       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4770     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4771       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4772   }
4773 
4774   // Warn about ignored type attributes, for example:
4775   // __attribute__((aligned)) struct A;
4776   // Attributes should be placed after tag to apply to type declaration.
4777   if (!DS.getAttributes().empty()) {
4778     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4779     if (TypeSpecType == DeclSpec::TST_class ||
4780         TypeSpecType == DeclSpec::TST_struct ||
4781         TypeSpecType == DeclSpec::TST_interface ||
4782         TypeSpecType == DeclSpec::TST_union ||
4783         TypeSpecType == DeclSpec::TST_enum) {
4784       for (const ParsedAttr &AL : DS.getAttributes())
4785         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4786             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4787     }
4788   }
4789 
4790   return TagD;
4791 }
4792 
4793 /// We are trying to inject an anonymous member into the given scope;
4794 /// check if there's an existing declaration that can't be overloaded.
4795 ///
4796 /// \return true if this is a forbidden redeclaration
4797 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4798                                          Scope *S,
4799                                          DeclContext *Owner,
4800                                          DeclarationName Name,
4801                                          SourceLocation NameLoc,
4802                                          bool IsUnion) {
4803   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4804                  Sema::ForVisibleRedeclaration);
4805   if (!SemaRef.LookupName(R, S)) return false;
4806 
4807   // Pick a representative declaration.
4808   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4809   assert(PrevDecl && "Expected a non-null Decl");
4810 
4811   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4812     return false;
4813 
4814   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4815     << IsUnion << Name;
4816   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4817 
4818   return true;
4819 }
4820 
4821 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4822 /// anonymous struct or union AnonRecord into the owning context Owner
4823 /// and scope S. This routine will be invoked just after we realize
4824 /// that an unnamed union or struct is actually an anonymous union or
4825 /// struct, e.g.,
4826 ///
4827 /// @code
4828 /// union {
4829 ///   int i;
4830 ///   float f;
4831 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4832 ///    // f into the surrounding scope.x
4833 /// @endcode
4834 ///
4835 /// This routine is recursive, injecting the names of nested anonymous
4836 /// structs/unions into the owning context and scope as well.
4837 static bool
4838 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4839                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4840                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4841   bool Invalid = false;
4842 
4843   // Look every FieldDecl and IndirectFieldDecl with a name.
4844   for (auto *D : AnonRecord->decls()) {
4845     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4846         cast<NamedDecl>(D)->getDeclName()) {
4847       ValueDecl *VD = cast<ValueDecl>(D);
4848       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4849                                        VD->getLocation(),
4850                                        AnonRecord->isUnion())) {
4851         // C++ [class.union]p2:
4852         //   The names of the members of an anonymous union shall be
4853         //   distinct from the names of any other entity in the
4854         //   scope in which the anonymous union is declared.
4855         Invalid = true;
4856       } else {
4857         // C++ [class.union]p2:
4858         //   For the purpose of name lookup, after the anonymous union
4859         //   definition, the members of the anonymous union are
4860         //   considered to have been defined in the scope in which the
4861         //   anonymous union is declared.
4862         unsigned OldChainingSize = Chaining.size();
4863         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4864           Chaining.append(IF->chain_begin(), IF->chain_end());
4865         else
4866           Chaining.push_back(VD);
4867 
4868         assert(Chaining.size() >= 2);
4869         NamedDecl **NamedChain =
4870           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4871         for (unsigned i = 0; i < Chaining.size(); i++)
4872           NamedChain[i] = Chaining[i];
4873 
4874         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4875             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4876             VD->getType(), {NamedChain, Chaining.size()});
4877 
4878         for (const auto *Attr : VD->attrs())
4879           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4880 
4881         IndirectField->setAccess(AS);
4882         IndirectField->setImplicit();
4883         SemaRef.PushOnScopeChains(IndirectField, S);
4884 
4885         // That includes picking up the appropriate access specifier.
4886         if (AS != AS_none) IndirectField->setAccess(AS);
4887 
4888         Chaining.resize(OldChainingSize);
4889       }
4890     }
4891   }
4892 
4893   return Invalid;
4894 }
4895 
4896 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4897 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4898 /// illegal input values are mapped to SC_None.
4899 static StorageClass
4900 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4901   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4902   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4903          "Parser allowed 'typedef' as storage class VarDecl.");
4904   switch (StorageClassSpec) {
4905   case DeclSpec::SCS_unspecified:    return SC_None;
4906   case DeclSpec::SCS_extern:
4907     if (DS.isExternInLinkageSpec())
4908       return SC_None;
4909     return SC_Extern;
4910   case DeclSpec::SCS_static:         return SC_Static;
4911   case DeclSpec::SCS_auto:           return SC_Auto;
4912   case DeclSpec::SCS_register:       return SC_Register;
4913   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4914     // Illegal SCSs map to None: error reporting is up to the caller.
4915   case DeclSpec::SCS_mutable:        // Fall through.
4916   case DeclSpec::SCS_typedef:        return SC_None;
4917   }
4918   llvm_unreachable("unknown storage class specifier");
4919 }
4920 
4921 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4922   assert(Record->hasInClassInitializer());
4923 
4924   for (const auto *I : Record->decls()) {
4925     const auto *FD = dyn_cast<FieldDecl>(I);
4926     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4927       FD = IFD->getAnonField();
4928     if (FD && FD->hasInClassInitializer())
4929       return FD->getLocation();
4930   }
4931 
4932   llvm_unreachable("couldn't find in-class initializer");
4933 }
4934 
4935 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4936                                       SourceLocation DefaultInitLoc) {
4937   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4938     return;
4939 
4940   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4941   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4942 }
4943 
4944 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4945                                       CXXRecordDecl *AnonUnion) {
4946   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4947     return;
4948 
4949   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4950 }
4951 
4952 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4953 /// anonymous structure or union. Anonymous unions are a C++ feature
4954 /// (C++ [class.union]) and a C11 feature; anonymous structures
4955 /// are a C11 feature and GNU C++ extension.
4956 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4957                                         AccessSpecifier AS,
4958                                         RecordDecl *Record,
4959                                         const PrintingPolicy &Policy) {
4960   DeclContext *Owner = Record->getDeclContext();
4961 
4962   // Diagnose whether this anonymous struct/union is an extension.
4963   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4964     Diag(Record->getLocation(), diag::ext_anonymous_union);
4965   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4966     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4967   else if (!Record->isUnion() && !getLangOpts().C11)
4968     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4969 
4970   // C and C++ require different kinds of checks for anonymous
4971   // structs/unions.
4972   bool Invalid = false;
4973   if (getLangOpts().CPlusPlus) {
4974     const char *PrevSpec = nullptr;
4975     if (Record->isUnion()) {
4976       // C++ [class.union]p6:
4977       // C++17 [class.union.anon]p2:
4978       //   Anonymous unions declared in a named namespace or in the
4979       //   global namespace shall be declared static.
4980       unsigned DiagID;
4981       DeclContext *OwnerScope = Owner->getRedeclContext();
4982       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4983           (OwnerScope->isTranslationUnit() ||
4984            (OwnerScope->isNamespace() &&
4985             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4986         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4987           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4988 
4989         // Recover by adding 'static'.
4990         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4991                                PrevSpec, DiagID, Policy);
4992       }
4993       // C++ [class.union]p6:
4994       //   A storage class is not allowed in a declaration of an
4995       //   anonymous union in a class scope.
4996       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4997                isa<RecordDecl>(Owner)) {
4998         Diag(DS.getStorageClassSpecLoc(),
4999              diag::err_anonymous_union_with_storage_spec)
5000           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5001 
5002         // Recover by removing the storage specifier.
5003         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5004                                SourceLocation(),
5005                                PrevSpec, DiagID, Context.getPrintingPolicy());
5006       }
5007     }
5008 
5009     // Ignore const/volatile/restrict qualifiers.
5010     if (DS.getTypeQualifiers()) {
5011       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5012         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5013           << Record->isUnion() << "const"
5014           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5015       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5016         Diag(DS.getVolatileSpecLoc(),
5017              diag::ext_anonymous_struct_union_qualified)
5018           << Record->isUnion() << "volatile"
5019           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5020       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5021         Diag(DS.getRestrictSpecLoc(),
5022              diag::ext_anonymous_struct_union_qualified)
5023           << Record->isUnion() << "restrict"
5024           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5025       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5026         Diag(DS.getAtomicSpecLoc(),
5027              diag::ext_anonymous_struct_union_qualified)
5028           << Record->isUnion() << "_Atomic"
5029           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5030       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5031         Diag(DS.getUnalignedSpecLoc(),
5032              diag::ext_anonymous_struct_union_qualified)
5033           << Record->isUnion() << "__unaligned"
5034           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5035 
5036       DS.ClearTypeQualifiers();
5037     }
5038 
5039     // C++ [class.union]p2:
5040     //   The member-specification of an anonymous union shall only
5041     //   define non-static data members. [Note: nested types and
5042     //   functions cannot be declared within an anonymous union. ]
5043     for (auto *Mem : Record->decls()) {
5044       // Ignore invalid declarations; we already diagnosed them.
5045       if (Mem->isInvalidDecl())
5046         continue;
5047 
5048       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5049         // C++ [class.union]p3:
5050         //   An anonymous union shall not have private or protected
5051         //   members (clause 11).
5052         assert(FD->getAccess() != AS_none);
5053         if (FD->getAccess() != AS_public) {
5054           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5055             << Record->isUnion() << (FD->getAccess() == AS_protected);
5056           Invalid = true;
5057         }
5058 
5059         // C++ [class.union]p1
5060         //   An object of a class with a non-trivial constructor, a non-trivial
5061         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5062         //   assignment operator cannot be a member of a union, nor can an
5063         //   array of such objects.
5064         if (CheckNontrivialField(FD))
5065           Invalid = true;
5066       } else if (Mem->isImplicit()) {
5067         // Any implicit members are fine.
5068       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5069         // This is a type that showed up in an
5070         // elaborated-type-specifier inside the anonymous struct or
5071         // union, but which actually declares a type outside of the
5072         // anonymous struct or union. It's okay.
5073       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5074         if (!MemRecord->isAnonymousStructOrUnion() &&
5075             MemRecord->getDeclName()) {
5076           // Visual C++ allows type definition in anonymous struct or union.
5077           if (getLangOpts().MicrosoftExt)
5078             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5079               << Record->isUnion();
5080           else {
5081             // This is a nested type declaration.
5082             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5083               << Record->isUnion();
5084             Invalid = true;
5085           }
5086         } else {
5087           // This is an anonymous type definition within another anonymous type.
5088           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5089           // not part of standard C++.
5090           Diag(MemRecord->getLocation(),
5091                diag::ext_anonymous_record_with_anonymous_type)
5092             << Record->isUnion();
5093         }
5094       } else if (isa<AccessSpecDecl>(Mem)) {
5095         // Any access specifier is fine.
5096       } else if (isa<StaticAssertDecl>(Mem)) {
5097         // In C++1z, static_assert declarations are also fine.
5098       } else {
5099         // We have something that isn't a non-static data
5100         // member. Complain about it.
5101         unsigned DK = diag::err_anonymous_record_bad_member;
5102         if (isa<TypeDecl>(Mem))
5103           DK = diag::err_anonymous_record_with_type;
5104         else if (isa<FunctionDecl>(Mem))
5105           DK = diag::err_anonymous_record_with_function;
5106         else if (isa<VarDecl>(Mem))
5107           DK = diag::err_anonymous_record_with_static;
5108 
5109         // Visual C++ allows type definition in anonymous struct or union.
5110         if (getLangOpts().MicrosoftExt &&
5111             DK == diag::err_anonymous_record_with_type)
5112           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5113             << Record->isUnion();
5114         else {
5115           Diag(Mem->getLocation(), DK) << Record->isUnion();
5116           Invalid = true;
5117         }
5118       }
5119     }
5120 
5121     // C++11 [class.union]p8 (DR1460):
5122     //   At most one variant member of a union may have a
5123     //   brace-or-equal-initializer.
5124     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5125         Owner->isRecord())
5126       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5127                                 cast<CXXRecordDecl>(Record));
5128   }
5129 
5130   if (!Record->isUnion() && !Owner->isRecord()) {
5131     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5132       << getLangOpts().CPlusPlus;
5133     Invalid = true;
5134   }
5135 
5136   // C++ [dcl.dcl]p3:
5137   //   [If there are no declarators], and except for the declaration of an
5138   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5139   //   names into the program
5140   // C++ [class.mem]p2:
5141   //   each such member-declaration shall either declare at least one member
5142   //   name of the class or declare at least one unnamed bit-field
5143   //
5144   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5145   if (getLangOpts().CPlusPlus && Record->field_empty())
5146     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5147 
5148   // Mock up a declarator.
5149   Declarator Dc(DS, DeclaratorContext::MemberContext);
5150   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5151   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5152 
5153   // Create a declaration for this anonymous struct/union.
5154   NamedDecl *Anon = nullptr;
5155   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5156     Anon = FieldDecl::Create(
5157         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5158         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5159         /*BitWidth=*/nullptr, /*Mutable=*/false,
5160         /*InitStyle=*/ICIS_NoInit);
5161     Anon->setAccess(AS);
5162     ProcessDeclAttributes(S, Anon, Dc);
5163 
5164     if (getLangOpts().CPlusPlus)
5165       FieldCollector->Add(cast<FieldDecl>(Anon));
5166   } else {
5167     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5168     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5169     if (SCSpec == DeclSpec::SCS_mutable) {
5170       // mutable can only appear on non-static class members, so it's always
5171       // an error here
5172       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5173       Invalid = true;
5174       SC = SC_None;
5175     }
5176 
5177     assert(DS.getAttributes().empty() && "No attribute expected");
5178     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5179                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5180                            Context.getTypeDeclType(Record), TInfo, SC);
5181 
5182     // Default-initialize the implicit variable. This initialization will be
5183     // trivial in almost all cases, except if a union member has an in-class
5184     // initializer:
5185     //   union { int n = 0; };
5186     ActOnUninitializedDecl(Anon);
5187   }
5188   Anon->setImplicit();
5189 
5190   // Mark this as an anonymous struct/union type.
5191   Record->setAnonymousStructOrUnion(true);
5192 
5193   // Add the anonymous struct/union object to the current
5194   // context. We'll be referencing this object when we refer to one of
5195   // its members.
5196   Owner->addDecl(Anon);
5197 
5198   // Inject the members of the anonymous struct/union into the owning
5199   // context and into the identifier resolver chain for name lookup
5200   // purposes.
5201   SmallVector<NamedDecl*, 2> Chain;
5202   Chain.push_back(Anon);
5203 
5204   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5205     Invalid = true;
5206 
5207   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5208     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5209       MangleNumberingContext *MCtx;
5210       Decl *ManglingContextDecl;
5211       std::tie(MCtx, ManglingContextDecl) =
5212           getCurrentMangleNumberContext(NewVD->getDeclContext());
5213       if (MCtx) {
5214         Context.setManglingNumber(
5215             NewVD, MCtx->getManglingNumber(
5216                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5217         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5218       }
5219     }
5220   }
5221 
5222   if (Invalid)
5223     Anon->setInvalidDecl();
5224 
5225   return Anon;
5226 }
5227 
5228 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5229 /// Microsoft C anonymous structure.
5230 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5231 /// Example:
5232 ///
5233 /// struct A { int a; };
5234 /// struct B { struct A; int b; };
5235 ///
5236 /// void foo() {
5237 ///   B var;
5238 ///   var.a = 3;
5239 /// }
5240 ///
5241 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5242                                            RecordDecl *Record) {
5243   assert(Record && "expected a record!");
5244 
5245   // Mock up a declarator.
5246   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5247   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5248   assert(TInfo && "couldn't build declarator info for anonymous struct");
5249 
5250   auto *ParentDecl = cast<RecordDecl>(CurContext);
5251   QualType RecTy = Context.getTypeDeclType(Record);
5252 
5253   // Create a declaration for this anonymous struct.
5254   NamedDecl *Anon =
5255       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5256                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5257                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5258                         /*InitStyle=*/ICIS_NoInit);
5259   Anon->setImplicit();
5260 
5261   // Add the anonymous struct object to the current context.
5262   CurContext->addDecl(Anon);
5263 
5264   // Inject the members of the anonymous struct into the current
5265   // context and into the identifier resolver chain for name lookup
5266   // purposes.
5267   SmallVector<NamedDecl*, 2> Chain;
5268   Chain.push_back(Anon);
5269 
5270   RecordDecl *RecordDef = Record->getDefinition();
5271   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5272                                diag::err_field_incomplete_or_sizeless) ||
5273       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5274                                           AS_none, Chain)) {
5275     Anon->setInvalidDecl();
5276     ParentDecl->setInvalidDecl();
5277   }
5278 
5279   return Anon;
5280 }
5281 
5282 /// GetNameForDeclarator - Determine the full declaration name for the
5283 /// given Declarator.
5284 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5285   return GetNameFromUnqualifiedId(D.getName());
5286 }
5287 
5288 /// Retrieves the declaration name from a parsed unqualified-id.
5289 DeclarationNameInfo
5290 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5291   DeclarationNameInfo NameInfo;
5292   NameInfo.setLoc(Name.StartLocation);
5293 
5294   switch (Name.getKind()) {
5295 
5296   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5297   case UnqualifiedIdKind::IK_Identifier:
5298     NameInfo.setName(Name.Identifier);
5299     return NameInfo;
5300 
5301   case UnqualifiedIdKind::IK_DeductionGuideName: {
5302     // C++ [temp.deduct.guide]p3:
5303     //   The simple-template-id shall name a class template specialization.
5304     //   The template-name shall be the same identifier as the template-name
5305     //   of the simple-template-id.
5306     // These together intend to imply that the template-name shall name a
5307     // class template.
5308     // FIXME: template<typename T> struct X {};
5309     //        template<typename T> using Y = X<T>;
5310     //        Y(int) -> Y<int>;
5311     //   satisfies these rules but does not name a class template.
5312     TemplateName TN = Name.TemplateName.get().get();
5313     auto *Template = TN.getAsTemplateDecl();
5314     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5315       Diag(Name.StartLocation,
5316            diag::err_deduction_guide_name_not_class_template)
5317         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5318       if (Template)
5319         Diag(Template->getLocation(), diag::note_template_decl_here);
5320       return DeclarationNameInfo();
5321     }
5322 
5323     NameInfo.setName(
5324         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5325     return NameInfo;
5326   }
5327 
5328   case UnqualifiedIdKind::IK_OperatorFunctionId:
5329     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5330                                            Name.OperatorFunctionId.Operator));
5331     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5332       = Name.OperatorFunctionId.SymbolLocations[0];
5333     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5334       = Name.EndLocation.getRawEncoding();
5335     return NameInfo;
5336 
5337   case UnqualifiedIdKind::IK_LiteralOperatorId:
5338     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5339                                                            Name.Identifier));
5340     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5341     return NameInfo;
5342 
5343   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5344     TypeSourceInfo *TInfo;
5345     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5346     if (Ty.isNull())
5347       return DeclarationNameInfo();
5348     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5349                                                Context.getCanonicalType(Ty)));
5350     NameInfo.setNamedTypeInfo(TInfo);
5351     return NameInfo;
5352   }
5353 
5354   case UnqualifiedIdKind::IK_ConstructorName: {
5355     TypeSourceInfo *TInfo;
5356     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5357     if (Ty.isNull())
5358       return DeclarationNameInfo();
5359     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5360                                               Context.getCanonicalType(Ty)));
5361     NameInfo.setNamedTypeInfo(TInfo);
5362     return NameInfo;
5363   }
5364 
5365   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5366     // In well-formed code, we can only have a constructor
5367     // template-id that refers to the current context, so go there
5368     // to find the actual type being constructed.
5369     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5370     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5371       return DeclarationNameInfo();
5372 
5373     // Determine the type of the class being constructed.
5374     QualType CurClassType = Context.getTypeDeclType(CurClass);
5375 
5376     // FIXME: Check two things: that the template-id names the same type as
5377     // CurClassType, and that the template-id does not occur when the name
5378     // was qualified.
5379 
5380     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5381                                     Context.getCanonicalType(CurClassType)));
5382     // FIXME: should we retrieve TypeSourceInfo?
5383     NameInfo.setNamedTypeInfo(nullptr);
5384     return NameInfo;
5385   }
5386 
5387   case UnqualifiedIdKind::IK_DestructorName: {
5388     TypeSourceInfo *TInfo;
5389     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5390     if (Ty.isNull())
5391       return DeclarationNameInfo();
5392     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5393                                               Context.getCanonicalType(Ty)));
5394     NameInfo.setNamedTypeInfo(TInfo);
5395     return NameInfo;
5396   }
5397 
5398   case UnqualifiedIdKind::IK_TemplateId: {
5399     TemplateName TName = Name.TemplateId->Template.get();
5400     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5401     return Context.getNameForTemplate(TName, TNameLoc);
5402   }
5403 
5404   } // switch (Name.getKind())
5405 
5406   llvm_unreachable("Unknown name kind");
5407 }
5408 
5409 static QualType getCoreType(QualType Ty) {
5410   do {
5411     if (Ty->isPointerType() || Ty->isReferenceType())
5412       Ty = Ty->getPointeeType();
5413     else if (Ty->isArrayType())
5414       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5415     else
5416       return Ty.withoutLocalFastQualifiers();
5417   } while (true);
5418 }
5419 
5420 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5421 /// and Definition have "nearly" matching parameters. This heuristic is
5422 /// used to improve diagnostics in the case where an out-of-line function
5423 /// definition doesn't match any declaration within the class or namespace.
5424 /// Also sets Params to the list of indices to the parameters that differ
5425 /// between the declaration and the definition. If hasSimilarParameters
5426 /// returns true and Params is empty, then all of the parameters match.
5427 static bool hasSimilarParameters(ASTContext &Context,
5428                                      FunctionDecl *Declaration,
5429                                      FunctionDecl *Definition,
5430                                      SmallVectorImpl<unsigned> &Params) {
5431   Params.clear();
5432   if (Declaration->param_size() != Definition->param_size())
5433     return false;
5434   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5435     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5436     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5437 
5438     // The parameter types are identical
5439     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5440       continue;
5441 
5442     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5443     QualType DefParamBaseTy = getCoreType(DefParamTy);
5444     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5445     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5446 
5447     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5448         (DeclTyName && DeclTyName == DefTyName))
5449       Params.push_back(Idx);
5450     else  // The two parameters aren't even close
5451       return false;
5452   }
5453 
5454   return true;
5455 }
5456 
5457 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5458 /// declarator needs to be rebuilt in the current instantiation.
5459 /// Any bits of declarator which appear before the name are valid for
5460 /// consideration here.  That's specifically the type in the decl spec
5461 /// and the base type in any member-pointer chunks.
5462 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5463                                                     DeclarationName Name) {
5464   // The types we specifically need to rebuild are:
5465   //   - typenames, typeofs, and decltypes
5466   //   - types which will become injected class names
5467   // Of course, we also need to rebuild any type referencing such a
5468   // type.  It's safest to just say "dependent", but we call out a
5469   // few cases here.
5470 
5471   DeclSpec &DS = D.getMutableDeclSpec();
5472   switch (DS.getTypeSpecType()) {
5473   case DeclSpec::TST_typename:
5474   case DeclSpec::TST_typeofType:
5475   case DeclSpec::TST_underlyingType:
5476   case DeclSpec::TST_atomic: {
5477     // Grab the type from the parser.
5478     TypeSourceInfo *TSI = nullptr;
5479     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5480     if (T.isNull() || !T->isDependentType()) break;
5481 
5482     // Make sure there's a type source info.  This isn't really much
5483     // of a waste; most dependent types should have type source info
5484     // attached already.
5485     if (!TSI)
5486       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5487 
5488     // Rebuild the type in the current instantiation.
5489     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5490     if (!TSI) return true;
5491 
5492     // Store the new type back in the decl spec.
5493     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5494     DS.UpdateTypeRep(LocType);
5495     break;
5496   }
5497 
5498   case DeclSpec::TST_decltype:
5499   case DeclSpec::TST_typeofExpr: {
5500     Expr *E = DS.getRepAsExpr();
5501     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5502     if (Result.isInvalid()) return true;
5503     DS.UpdateExprRep(Result.get());
5504     break;
5505   }
5506 
5507   default:
5508     // Nothing to do for these decl specs.
5509     break;
5510   }
5511 
5512   // It doesn't matter what order we do this in.
5513   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5514     DeclaratorChunk &Chunk = D.getTypeObject(I);
5515 
5516     // The only type information in the declarator which can come
5517     // before the declaration name is the base type of a member
5518     // pointer.
5519     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5520       continue;
5521 
5522     // Rebuild the scope specifier in-place.
5523     CXXScopeSpec &SS = Chunk.Mem.Scope();
5524     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5525       return true;
5526   }
5527 
5528   return false;
5529 }
5530 
5531 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5532   D.setFunctionDefinitionKind(FDK_Declaration);
5533   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5534 
5535   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5536       Dcl && Dcl->getDeclContext()->isFileContext())
5537     Dcl->setTopLevelDeclInObjCContainer();
5538 
5539   if (getLangOpts().OpenCL)
5540     setCurrentOpenCLExtensionForDecl(Dcl);
5541 
5542   return Dcl;
5543 }
5544 
5545 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5546 ///   If T is the name of a class, then each of the following shall have a
5547 ///   name different from T:
5548 ///     - every static data member of class T;
5549 ///     - every member function of class T
5550 ///     - every member of class T that is itself a type;
5551 /// \returns true if the declaration name violates these rules.
5552 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5553                                    DeclarationNameInfo NameInfo) {
5554   DeclarationName Name = NameInfo.getName();
5555 
5556   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5557   while (Record && Record->isAnonymousStructOrUnion())
5558     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5559   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5560     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5561     return true;
5562   }
5563 
5564   return false;
5565 }
5566 
5567 /// Diagnose a declaration whose declarator-id has the given
5568 /// nested-name-specifier.
5569 ///
5570 /// \param SS The nested-name-specifier of the declarator-id.
5571 ///
5572 /// \param DC The declaration context to which the nested-name-specifier
5573 /// resolves.
5574 ///
5575 /// \param Name The name of the entity being declared.
5576 ///
5577 /// \param Loc The location of the name of the entity being declared.
5578 ///
5579 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5580 /// we're declaring an explicit / partial specialization / instantiation.
5581 ///
5582 /// \returns true if we cannot safely recover from this error, false otherwise.
5583 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5584                                         DeclarationName Name,
5585                                         SourceLocation Loc, bool IsTemplateId) {
5586   DeclContext *Cur = CurContext;
5587   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5588     Cur = Cur->getParent();
5589 
5590   // If the user provided a superfluous scope specifier that refers back to the
5591   // class in which the entity is already declared, diagnose and ignore it.
5592   //
5593   // class X {
5594   //   void X::f();
5595   // };
5596   //
5597   // Note, it was once ill-formed to give redundant qualification in all
5598   // contexts, but that rule was removed by DR482.
5599   if (Cur->Equals(DC)) {
5600     if (Cur->isRecord()) {
5601       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5602                                       : diag::err_member_extra_qualification)
5603         << Name << FixItHint::CreateRemoval(SS.getRange());
5604       SS.clear();
5605     } else {
5606       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5607     }
5608     return false;
5609   }
5610 
5611   // Check whether the qualifying scope encloses the scope of the original
5612   // declaration. For a template-id, we perform the checks in
5613   // CheckTemplateSpecializationScope.
5614   if (!Cur->Encloses(DC) && !IsTemplateId) {
5615     if (Cur->isRecord())
5616       Diag(Loc, diag::err_member_qualification)
5617         << Name << SS.getRange();
5618     else if (isa<TranslationUnitDecl>(DC))
5619       Diag(Loc, diag::err_invalid_declarator_global_scope)
5620         << Name << SS.getRange();
5621     else if (isa<FunctionDecl>(Cur))
5622       Diag(Loc, diag::err_invalid_declarator_in_function)
5623         << Name << SS.getRange();
5624     else if (isa<BlockDecl>(Cur))
5625       Diag(Loc, diag::err_invalid_declarator_in_block)
5626         << Name << SS.getRange();
5627     else
5628       Diag(Loc, diag::err_invalid_declarator_scope)
5629       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5630 
5631     return true;
5632   }
5633 
5634   if (Cur->isRecord()) {
5635     // Cannot qualify members within a class.
5636     Diag(Loc, diag::err_member_qualification)
5637       << Name << SS.getRange();
5638     SS.clear();
5639 
5640     // C++ constructors and destructors with incorrect scopes can break
5641     // our AST invariants by having the wrong underlying types. If
5642     // that's the case, then drop this declaration entirely.
5643     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5644          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5645         !Context.hasSameType(Name.getCXXNameType(),
5646                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5647       return true;
5648 
5649     return false;
5650   }
5651 
5652   // C++11 [dcl.meaning]p1:
5653   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5654   //   not begin with a decltype-specifer"
5655   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5656   while (SpecLoc.getPrefix())
5657     SpecLoc = SpecLoc.getPrefix();
5658   if (dyn_cast_or_null<DecltypeType>(
5659         SpecLoc.getNestedNameSpecifier()->getAsType()))
5660     Diag(Loc, diag::err_decltype_in_declarator)
5661       << SpecLoc.getTypeLoc().getSourceRange();
5662 
5663   return false;
5664 }
5665 
5666 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5667                                   MultiTemplateParamsArg TemplateParamLists) {
5668   // TODO: consider using NameInfo for diagnostic.
5669   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5670   DeclarationName Name = NameInfo.getName();
5671 
5672   // All of these full declarators require an identifier.  If it doesn't have
5673   // one, the ParsedFreeStandingDeclSpec action should be used.
5674   if (D.isDecompositionDeclarator()) {
5675     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5676   } else if (!Name) {
5677     if (!D.isInvalidType())  // Reject this if we think it is valid.
5678       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5679           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5680     return nullptr;
5681   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5682     return nullptr;
5683 
5684   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5685   // we find one that is.
5686   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5687          (S->getFlags() & Scope::TemplateParamScope) != 0)
5688     S = S->getParent();
5689 
5690   DeclContext *DC = CurContext;
5691   if (D.getCXXScopeSpec().isInvalid())
5692     D.setInvalidType();
5693   else if (D.getCXXScopeSpec().isSet()) {
5694     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5695                                         UPPC_DeclarationQualifier))
5696       return nullptr;
5697 
5698     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5699     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5700     if (!DC || isa<EnumDecl>(DC)) {
5701       // If we could not compute the declaration context, it's because the
5702       // declaration context is dependent but does not refer to a class,
5703       // class template, or class template partial specialization. Complain
5704       // and return early, to avoid the coming semantic disaster.
5705       Diag(D.getIdentifierLoc(),
5706            diag::err_template_qualified_declarator_no_match)
5707         << D.getCXXScopeSpec().getScopeRep()
5708         << D.getCXXScopeSpec().getRange();
5709       return nullptr;
5710     }
5711     bool IsDependentContext = DC->isDependentContext();
5712 
5713     if (!IsDependentContext &&
5714         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5715       return nullptr;
5716 
5717     // If a class is incomplete, do not parse entities inside it.
5718     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5719       Diag(D.getIdentifierLoc(),
5720            diag::err_member_def_undefined_record)
5721         << Name << DC << D.getCXXScopeSpec().getRange();
5722       return nullptr;
5723     }
5724     if (!D.getDeclSpec().isFriendSpecified()) {
5725       if (diagnoseQualifiedDeclaration(
5726               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5727               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5728         if (DC->isRecord())
5729           return nullptr;
5730 
5731         D.setInvalidType();
5732       }
5733     }
5734 
5735     // Check whether we need to rebuild the type of the given
5736     // declaration in the current instantiation.
5737     if (EnteringContext && IsDependentContext &&
5738         TemplateParamLists.size() != 0) {
5739       ContextRAII SavedContext(*this, DC);
5740       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5741         D.setInvalidType();
5742     }
5743   }
5744 
5745   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5746   QualType R = TInfo->getType();
5747 
5748   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5749                                       UPPC_DeclarationType))
5750     D.setInvalidType();
5751 
5752   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5753                         forRedeclarationInCurContext());
5754 
5755   // See if this is a redefinition of a variable in the same scope.
5756   if (!D.getCXXScopeSpec().isSet()) {
5757     bool IsLinkageLookup = false;
5758     bool CreateBuiltins = false;
5759 
5760     // If the declaration we're planning to build will be a function
5761     // or object with linkage, then look for another declaration with
5762     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5763     //
5764     // If the declaration we're planning to build will be declared with
5765     // external linkage in the translation unit, create any builtin with
5766     // the same name.
5767     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5768       /* Do nothing*/;
5769     else if (CurContext->isFunctionOrMethod() &&
5770              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5771               R->isFunctionType())) {
5772       IsLinkageLookup = true;
5773       CreateBuiltins =
5774           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5775     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5776                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5777       CreateBuiltins = true;
5778 
5779     if (IsLinkageLookup) {
5780       Previous.clear(LookupRedeclarationWithLinkage);
5781       Previous.setRedeclarationKind(ForExternalRedeclaration);
5782     }
5783 
5784     LookupName(Previous, S, CreateBuiltins);
5785   } else { // Something like "int foo::x;"
5786     LookupQualifiedName(Previous, DC);
5787 
5788     // C++ [dcl.meaning]p1:
5789     //   When the declarator-id is qualified, the declaration shall refer to a
5790     //  previously declared member of the class or namespace to which the
5791     //  qualifier refers (or, in the case of a namespace, of an element of the
5792     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5793     //  thereof; [...]
5794     //
5795     // Note that we already checked the context above, and that we do not have
5796     // enough information to make sure that Previous contains the declaration
5797     // we want to match. For example, given:
5798     //
5799     //   class X {
5800     //     void f();
5801     //     void f(float);
5802     //   };
5803     //
5804     //   void X::f(int) { } // ill-formed
5805     //
5806     // In this case, Previous will point to the overload set
5807     // containing the two f's declared in X, but neither of them
5808     // matches.
5809 
5810     // C++ [dcl.meaning]p1:
5811     //   [...] the member shall not merely have been introduced by a
5812     //   using-declaration in the scope of the class or namespace nominated by
5813     //   the nested-name-specifier of the declarator-id.
5814     RemoveUsingDecls(Previous);
5815   }
5816 
5817   if (Previous.isSingleResult() &&
5818       Previous.getFoundDecl()->isTemplateParameter()) {
5819     // Maybe we will complain about the shadowed template parameter.
5820     if (!D.isInvalidType())
5821       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5822                                       Previous.getFoundDecl());
5823 
5824     // Just pretend that we didn't see the previous declaration.
5825     Previous.clear();
5826   }
5827 
5828   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5829     // Forget that the previous declaration is the injected-class-name.
5830     Previous.clear();
5831 
5832   // In C++, the previous declaration we find might be a tag type
5833   // (class or enum). In this case, the new declaration will hide the
5834   // tag type. Note that this applies to functions, function templates, and
5835   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5836   if (Previous.isSingleTagDecl() &&
5837       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5838       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5839     Previous.clear();
5840 
5841   // Check that there are no default arguments other than in the parameters
5842   // of a function declaration (C++ only).
5843   if (getLangOpts().CPlusPlus)
5844     CheckExtraCXXDefaultArguments(D);
5845 
5846   NamedDecl *New;
5847 
5848   bool AddToScope = true;
5849   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5850     if (TemplateParamLists.size()) {
5851       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5852       return nullptr;
5853     }
5854 
5855     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5856   } else if (R->isFunctionType()) {
5857     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5858                                   TemplateParamLists,
5859                                   AddToScope);
5860   } else {
5861     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5862                                   AddToScope);
5863   }
5864 
5865   if (!New)
5866     return nullptr;
5867 
5868   // If this has an identifier and is not a function template specialization,
5869   // add it to the scope stack.
5870   if (New->getDeclName() && AddToScope)
5871     PushOnScopeChains(New, S);
5872 
5873   if (isInOpenMPDeclareTargetContext())
5874     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5875 
5876   return New;
5877 }
5878 
5879 /// Helper method to turn variable array types into constant array
5880 /// types in certain situations which would otherwise be errors (for
5881 /// GCC compatibility).
5882 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5883                                                     ASTContext &Context,
5884                                                     bool &SizeIsNegative,
5885                                                     llvm::APSInt &Oversized) {
5886   // This method tries to turn a variable array into a constant
5887   // array even when the size isn't an ICE.  This is necessary
5888   // for compatibility with code that depends on gcc's buggy
5889   // constant expression folding, like struct {char x[(int)(char*)2];}
5890   SizeIsNegative = false;
5891   Oversized = 0;
5892 
5893   if (T->isDependentType())
5894     return QualType();
5895 
5896   QualifierCollector Qs;
5897   const Type *Ty = Qs.strip(T);
5898 
5899   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5900     QualType Pointee = PTy->getPointeeType();
5901     QualType FixedType =
5902         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5903                                             Oversized);
5904     if (FixedType.isNull()) return FixedType;
5905     FixedType = Context.getPointerType(FixedType);
5906     return Qs.apply(Context, FixedType);
5907   }
5908   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5909     QualType Inner = PTy->getInnerType();
5910     QualType FixedType =
5911         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5912                                             Oversized);
5913     if (FixedType.isNull()) return FixedType;
5914     FixedType = Context.getParenType(FixedType);
5915     return Qs.apply(Context, FixedType);
5916   }
5917 
5918   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5919   if (!VLATy)
5920     return QualType();
5921   // FIXME: We should probably handle this case
5922   if (VLATy->getElementType()->isVariablyModifiedType())
5923     return QualType();
5924 
5925   Expr::EvalResult Result;
5926   if (!VLATy->getSizeExpr() ||
5927       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5928     return QualType();
5929 
5930   llvm::APSInt Res = Result.Val.getInt();
5931 
5932   // Check whether the array size is negative.
5933   if (Res.isSigned() && Res.isNegative()) {
5934     SizeIsNegative = true;
5935     return QualType();
5936   }
5937 
5938   // Check whether the array is too large to be addressed.
5939   unsigned ActiveSizeBits
5940     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5941                                               Res);
5942   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5943     Oversized = Res;
5944     return QualType();
5945   }
5946 
5947   return Context.getConstantArrayType(
5948       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5949 }
5950 
5951 static void
5952 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5953   SrcTL = SrcTL.getUnqualifiedLoc();
5954   DstTL = DstTL.getUnqualifiedLoc();
5955   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5956     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5957     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5958                                       DstPTL.getPointeeLoc());
5959     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5960     return;
5961   }
5962   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5963     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5964     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5965                                       DstPTL.getInnerLoc());
5966     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5967     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5968     return;
5969   }
5970   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5971   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5972   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5973   TypeLoc DstElemTL = DstATL.getElementLoc();
5974   DstElemTL.initializeFullCopy(SrcElemTL);
5975   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5976   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5977   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5978 }
5979 
5980 /// Helper method to turn variable array types into constant array
5981 /// types in certain situations which would otherwise be errors (for
5982 /// GCC compatibility).
5983 static TypeSourceInfo*
5984 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5985                                               ASTContext &Context,
5986                                               bool &SizeIsNegative,
5987                                               llvm::APSInt &Oversized) {
5988   QualType FixedTy
5989     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5990                                           SizeIsNegative, Oversized);
5991   if (FixedTy.isNull())
5992     return nullptr;
5993   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5994   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5995                                     FixedTInfo->getTypeLoc());
5996   return FixedTInfo;
5997 }
5998 
5999 /// Register the given locally-scoped extern "C" declaration so
6000 /// that it can be found later for redeclarations. We include any extern "C"
6001 /// declaration that is not visible in the translation unit here, not just
6002 /// function-scope declarations.
6003 void
6004 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6005   if (!getLangOpts().CPlusPlus &&
6006       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6007     // Don't need to track declarations in the TU in C.
6008     return;
6009 
6010   // Note that we have a locally-scoped external with this name.
6011   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6012 }
6013 
6014 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6015   // FIXME: We can have multiple results via __attribute__((overloadable)).
6016   auto Result = Context.getExternCContextDecl()->lookup(Name);
6017   return Result.empty() ? nullptr : *Result.begin();
6018 }
6019 
6020 /// Diagnose function specifiers on a declaration of an identifier that
6021 /// does not identify a function.
6022 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6023   // FIXME: We should probably indicate the identifier in question to avoid
6024   // confusion for constructs like "virtual int a(), b;"
6025   if (DS.isVirtualSpecified())
6026     Diag(DS.getVirtualSpecLoc(),
6027          diag::err_virtual_non_function);
6028 
6029   if (DS.hasExplicitSpecifier())
6030     Diag(DS.getExplicitSpecLoc(),
6031          diag::err_explicit_non_function);
6032 
6033   if (DS.isNoreturnSpecified())
6034     Diag(DS.getNoreturnSpecLoc(),
6035          diag::err_noreturn_non_function);
6036 }
6037 
6038 NamedDecl*
6039 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6040                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6041   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6042   if (D.getCXXScopeSpec().isSet()) {
6043     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6044       << D.getCXXScopeSpec().getRange();
6045     D.setInvalidType();
6046     // Pretend we didn't see the scope specifier.
6047     DC = CurContext;
6048     Previous.clear();
6049   }
6050 
6051   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6052 
6053   if (D.getDeclSpec().isInlineSpecified())
6054     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6055         << getLangOpts().CPlusPlus17;
6056   if (D.getDeclSpec().hasConstexprSpecifier())
6057     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6058         << 1 << D.getDeclSpec().getConstexprSpecifier();
6059 
6060   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6061     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6062       Diag(D.getName().StartLocation,
6063            diag::err_deduction_guide_invalid_specifier)
6064           << "typedef";
6065     else
6066       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6067           << D.getName().getSourceRange();
6068     return nullptr;
6069   }
6070 
6071   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6072   if (!NewTD) return nullptr;
6073 
6074   // Handle attributes prior to checking for duplicates in MergeVarDecl
6075   ProcessDeclAttributes(S, NewTD, D);
6076 
6077   CheckTypedefForVariablyModifiedType(S, NewTD);
6078 
6079   bool Redeclaration = D.isRedeclaration();
6080   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6081   D.setRedeclaration(Redeclaration);
6082   return ND;
6083 }
6084 
6085 void
6086 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6087   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6088   // then it shall have block scope.
6089   // Note that variably modified types must be fixed before merging the decl so
6090   // that redeclarations will match.
6091   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6092   QualType T = TInfo->getType();
6093   if (T->isVariablyModifiedType()) {
6094     setFunctionHasBranchProtectedScope();
6095 
6096     if (S->getFnParent() == nullptr) {
6097       bool SizeIsNegative;
6098       llvm::APSInt Oversized;
6099       TypeSourceInfo *FixedTInfo =
6100         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6101                                                       SizeIsNegative,
6102                                                       Oversized);
6103       if (FixedTInfo) {
6104         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6105         NewTD->setTypeSourceInfo(FixedTInfo);
6106       } else {
6107         if (SizeIsNegative)
6108           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6109         else if (T->isVariableArrayType())
6110           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6111         else if (Oversized.getBoolValue())
6112           Diag(NewTD->getLocation(), diag::err_array_too_large)
6113             << Oversized.toString(10);
6114         else
6115           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6116         NewTD->setInvalidDecl();
6117       }
6118     }
6119   }
6120 }
6121 
6122 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6123 /// declares a typedef-name, either using the 'typedef' type specifier or via
6124 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6125 NamedDecl*
6126 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6127                            LookupResult &Previous, bool &Redeclaration) {
6128 
6129   // Find the shadowed declaration before filtering for scope.
6130   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6131 
6132   // Merge the decl with the existing one if appropriate. If the decl is
6133   // in an outer scope, it isn't the same thing.
6134   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6135                        /*AllowInlineNamespace*/false);
6136   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6137   if (!Previous.empty()) {
6138     Redeclaration = true;
6139     MergeTypedefNameDecl(S, NewTD, Previous);
6140   } else {
6141     inferGslPointerAttribute(NewTD);
6142   }
6143 
6144   if (ShadowedDecl && !Redeclaration)
6145     CheckShadow(NewTD, ShadowedDecl, Previous);
6146 
6147   // If this is the C FILE type, notify the AST context.
6148   if (IdentifierInfo *II = NewTD->getIdentifier())
6149     if (!NewTD->isInvalidDecl() &&
6150         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6151       if (II->isStr("FILE"))
6152         Context.setFILEDecl(NewTD);
6153       else if (II->isStr("jmp_buf"))
6154         Context.setjmp_bufDecl(NewTD);
6155       else if (II->isStr("sigjmp_buf"))
6156         Context.setsigjmp_bufDecl(NewTD);
6157       else if (II->isStr("ucontext_t"))
6158         Context.setucontext_tDecl(NewTD);
6159     }
6160 
6161   return NewTD;
6162 }
6163 
6164 /// Determines whether the given declaration is an out-of-scope
6165 /// previous declaration.
6166 ///
6167 /// This routine should be invoked when name lookup has found a
6168 /// previous declaration (PrevDecl) that is not in the scope where a
6169 /// new declaration by the same name is being introduced. If the new
6170 /// declaration occurs in a local scope, previous declarations with
6171 /// linkage may still be considered previous declarations (C99
6172 /// 6.2.2p4-5, C++ [basic.link]p6).
6173 ///
6174 /// \param PrevDecl the previous declaration found by name
6175 /// lookup
6176 ///
6177 /// \param DC the context in which the new declaration is being
6178 /// declared.
6179 ///
6180 /// \returns true if PrevDecl is an out-of-scope previous declaration
6181 /// for a new delcaration with the same name.
6182 static bool
6183 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6184                                 ASTContext &Context) {
6185   if (!PrevDecl)
6186     return false;
6187 
6188   if (!PrevDecl->hasLinkage())
6189     return false;
6190 
6191   if (Context.getLangOpts().CPlusPlus) {
6192     // C++ [basic.link]p6:
6193     //   If there is a visible declaration of an entity with linkage
6194     //   having the same name and type, ignoring entities declared
6195     //   outside the innermost enclosing namespace scope, the block
6196     //   scope declaration declares that same entity and receives the
6197     //   linkage of the previous declaration.
6198     DeclContext *OuterContext = DC->getRedeclContext();
6199     if (!OuterContext->isFunctionOrMethod())
6200       // This rule only applies to block-scope declarations.
6201       return false;
6202 
6203     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6204     if (PrevOuterContext->isRecord())
6205       // We found a member function: ignore it.
6206       return false;
6207 
6208     // Find the innermost enclosing namespace for the new and
6209     // previous declarations.
6210     OuterContext = OuterContext->getEnclosingNamespaceContext();
6211     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6212 
6213     // The previous declaration is in a different namespace, so it
6214     // isn't the same function.
6215     if (!OuterContext->Equals(PrevOuterContext))
6216       return false;
6217   }
6218 
6219   return true;
6220 }
6221 
6222 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6223   CXXScopeSpec &SS = D.getCXXScopeSpec();
6224   if (!SS.isSet()) return;
6225   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6226 }
6227 
6228 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6229   QualType type = decl->getType();
6230   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6231   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6232     // Various kinds of declaration aren't allowed to be __autoreleasing.
6233     unsigned kind = -1U;
6234     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6235       if (var->hasAttr<BlocksAttr>())
6236         kind = 0; // __block
6237       else if (!var->hasLocalStorage())
6238         kind = 1; // global
6239     } else if (isa<ObjCIvarDecl>(decl)) {
6240       kind = 3; // ivar
6241     } else if (isa<FieldDecl>(decl)) {
6242       kind = 2; // field
6243     }
6244 
6245     if (kind != -1U) {
6246       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6247         << kind;
6248     }
6249   } else if (lifetime == Qualifiers::OCL_None) {
6250     // Try to infer lifetime.
6251     if (!type->isObjCLifetimeType())
6252       return false;
6253 
6254     lifetime = type->getObjCARCImplicitLifetime();
6255     type = Context.getLifetimeQualifiedType(type, lifetime);
6256     decl->setType(type);
6257   }
6258 
6259   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6260     // Thread-local variables cannot have lifetime.
6261     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6262         var->getTLSKind()) {
6263       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6264         << var->getType();
6265       return true;
6266     }
6267   }
6268 
6269   return false;
6270 }
6271 
6272 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6273   if (Decl->getType().hasAddressSpace())
6274     return;
6275   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6276     QualType Type = Var->getType();
6277     if (Type->isSamplerT() || Type->isVoidType())
6278       return;
6279     LangAS ImplAS = LangAS::opencl_private;
6280     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6281         Var->hasGlobalStorage())
6282       ImplAS = LangAS::opencl_global;
6283     // If the original type from a decayed type is an array type and that array
6284     // type has no address space yet, deduce it now.
6285     if (auto DT = dyn_cast<DecayedType>(Type)) {
6286       auto OrigTy = DT->getOriginalType();
6287       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6288         // Add the address space to the original array type and then propagate
6289         // that to the element type through `getAsArrayType`.
6290         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6291         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6292         // Re-generate the decayed type.
6293         Type = Context.getDecayedType(OrigTy);
6294       }
6295     }
6296     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6297     // Apply any qualifiers (including address space) from the array type to
6298     // the element type. This implements C99 6.7.3p8: "If the specification of
6299     // an array type includes any type qualifiers, the element type is so
6300     // qualified, not the array type."
6301     if (Type->isArrayType())
6302       Type = QualType(Context.getAsArrayType(Type), 0);
6303     Decl->setType(Type);
6304   }
6305 }
6306 
6307 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6308   // Ensure that an auto decl is deduced otherwise the checks below might cache
6309   // the wrong linkage.
6310   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6311 
6312   // 'weak' only applies to declarations with external linkage.
6313   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6314     if (!ND.isExternallyVisible()) {
6315       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6316       ND.dropAttr<WeakAttr>();
6317     }
6318   }
6319   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6320     if (ND.isExternallyVisible()) {
6321       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6322       ND.dropAttr<WeakRefAttr>();
6323       ND.dropAttr<AliasAttr>();
6324     }
6325   }
6326 
6327   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6328     if (VD->hasInit()) {
6329       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6330         assert(VD->isThisDeclarationADefinition() &&
6331                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6332         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6333         VD->dropAttr<AliasAttr>();
6334       }
6335     }
6336   }
6337 
6338   // 'selectany' only applies to externally visible variable declarations.
6339   // It does not apply to functions.
6340   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6341     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6342       S.Diag(Attr->getLocation(),
6343              diag::err_attribute_selectany_non_extern_data);
6344       ND.dropAttr<SelectAnyAttr>();
6345     }
6346   }
6347 
6348   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6349     auto *VD = dyn_cast<VarDecl>(&ND);
6350     bool IsAnonymousNS = false;
6351     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6352     if (VD) {
6353       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6354       while (NS && !IsAnonymousNS) {
6355         IsAnonymousNS = NS->isAnonymousNamespace();
6356         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6357       }
6358     }
6359     // dll attributes require external linkage. Static locals may have external
6360     // linkage but still cannot be explicitly imported or exported.
6361     // In Microsoft mode, a variable defined in anonymous namespace must have
6362     // external linkage in order to be exported.
6363     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6364     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6365         (!AnonNSInMicrosoftMode &&
6366          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6367       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6368         << &ND << Attr;
6369       ND.setInvalidDecl();
6370     }
6371   }
6372 
6373   // Virtual functions cannot be marked as 'notail'.
6374   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6375     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6376       if (MD->isVirtual()) {
6377         S.Diag(ND.getLocation(),
6378                diag::err_invalid_attribute_on_virtual_function)
6379             << Attr;
6380         ND.dropAttr<NotTailCalledAttr>();
6381       }
6382 
6383   // Check the attributes on the function type, if any.
6384   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6385     // Don't declare this variable in the second operand of the for-statement;
6386     // GCC miscompiles that by ending its lifetime before evaluating the
6387     // third operand. See gcc.gnu.org/PR86769.
6388     AttributedTypeLoc ATL;
6389     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6390          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6391          TL = ATL.getModifiedLoc()) {
6392       // The [[lifetimebound]] attribute can be applied to the implicit object
6393       // parameter of a non-static member function (other than a ctor or dtor)
6394       // by applying it to the function type.
6395       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6396         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6397         if (!MD || MD->isStatic()) {
6398           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6399               << !MD << A->getRange();
6400         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6401           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6402               << isa<CXXDestructorDecl>(MD) << A->getRange();
6403         }
6404       }
6405     }
6406   }
6407 }
6408 
6409 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6410                                            NamedDecl *NewDecl,
6411                                            bool IsSpecialization,
6412                                            bool IsDefinition) {
6413   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6414     return;
6415 
6416   bool IsTemplate = false;
6417   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6418     OldDecl = OldTD->getTemplatedDecl();
6419     IsTemplate = true;
6420     if (!IsSpecialization)
6421       IsDefinition = false;
6422   }
6423   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6424     NewDecl = NewTD->getTemplatedDecl();
6425     IsTemplate = true;
6426   }
6427 
6428   if (!OldDecl || !NewDecl)
6429     return;
6430 
6431   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6432   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6433   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6434   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6435 
6436   // dllimport and dllexport are inheritable attributes so we have to exclude
6437   // inherited attribute instances.
6438   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6439                     (NewExportAttr && !NewExportAttr->isInherited());
6440 
6441   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6442   // the only exception being explicit specializations.
6443   // Implicitly generated declarations are also excluded for now because there
6444   // is no other way to switch these to use dllimport or dllexport.
6445   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6446 
6447   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6448     // Allow with a warning for free functions and global variables.
6449     bool JustWarn = false;
6450     if (!OldDecl->isCXXClassMember()) {
6451       auto *VD = dyn_cast<VarDecl>(OldDecl);
6452       if (VD && !VD->getDescribedVarTemplate())
6453         JustWarn = true;
6454       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6455       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6456         JustWarn = true;
6457     }
6458 
6459     // We cannot change a declaration that's been used because IR has already
6460     // been emitted. Dllimported functions will still work though (modulo
6461     // address equality) as they can use the thunk.
6462     if (OldDecl->isUsed())
6463       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6464         JustWarn = false;
6465 
6466     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6467                                : diag::err_attribute_dll_redeclaration;
6468     S.Diag(NewDecl->getLocation(), DiagID)
6469         << NewDecl
6470         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6471     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6472     if (!JustWarn) {
6473       NewDecl->setInvalidDecl();
6474       return;
6475     }
6476   }
6477 
6478   // A redeclaration is not allowed to drop a dllimport attribute, the only
6479   // exceptions being inline function definitions (except for function
6480   // templates), local extern declarations, qualified friend declarations or
6481   // special MSVC extension: in the last case, the declaration is treated as if
6482   // it were marked dllexport.
6483   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6484   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6485   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6486     // Ignore static data because out-of-line definitions are diagnosed
6487     // separately.
6488     IsStaticDataMember = VD->isStaticDataMember();
6489     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6490                    VarDecl::DeclarationOnly;
6491   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6492     IsInline = FD->isInlined();
6493     IsQualifiedFriend = FD->getQualifier() &&
6494                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6495   }
6496 
6497   if (OldImportAttr && !HasNewAttr &&
6498       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6499       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6500     if (IsMicrosoft && IsDefinition) {
6501       S.Diag(NewDecl->getLocation(),
6502              diag::warn_redeclaration_without_import_attribute)
6503           << NewDecl;
6504       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6505       NewDecl->dropAttr<DLLImportAttr>();
6506       NewDecl->addAttr(
6507           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6508     } else {
6509       S.Diag(NewDecl->getLocation(),
6510              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6511           << NewDecl << OldImportAttr;
6512       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6513       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6514       OldDecl->dropAttr<DLLImportAttr>();
6515       NewDecl->dropAttr<DLLImportAttr>();
6516     }
6517   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6518     // In MinGW, seeing a function declared inline drops the dllimport
6519     // attribute.
6520     OldDecl->dropAttr<DLLImportAttr>();
6521     NewDecl->dropAttr<DLLImportAttr>();
6522     S.Diag(NewDecl->getLocation(),
6523            diag::warn_dllimport_dropped_from_inline_function)
6524         << NewDecl << OldImportAttr;
6525   }
6526 
6527   // A specialization of a class template member function is processed here
6528   // since it's a redeclaration. If the parent class is dllexport, the
6529   // specialization inherits that attribute. This doesn't happen automatically
6530   // since the parent class isn't instantiated until later.
6531   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6532     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6533         !NewImportAttr && !NewExportAttr) {
6534       if (const DLLExportAttr *ParentExportAttr =
6535               MD->getParent()->getAttr<DLLExportAttr>()) {
6536         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6537         NewAttr->setInherited(true);
6538         NewDecl->addAttr(NewAttr);
6539       }
6540     }
6541   }
6542 }
6543 
6544 /// Given that we are within the definition of the given function,
6545 /// will that definition behave like C99's 'inline', where the
6546 /// definition is discarded except for optimization purposes?
6547 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6548   // Try to avoid calling GetGVALinkageForFunction.
6549 
6550   // All cases of this require the 'inline' keyword.
6551   if (!FD->isInlined()) return false;
6552 
6553   // This is only possible in C++ with the gnu_inline attribute.
6554   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6555     return false;
6556 
6557   // Okay, go ahead and call the relatively-more-expensive function.
6558   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6559 }
6560 
6561 /// Determine whether a variable is extern "C" prior to attaching
6562 /// an initializer. We can't just call isExternC() here, because that
6563 /// will also compute and cache whether the declaration is externally
6564 /// visible, which might change when we attach the initializer.
6565 ///
6566 /// This can only be used if the declaration is known to not be a
6567 /// redeclaration of an internal linkage declaration.
6568 ///
6569 /// For instance:
6570 ///
6571 ///   auto x = []{};
6572 ///
6573 /// Attaching the initializer here makes this declaration not externally
6574 /// visible, because its type has internal linkage.
6575 ///
6576 /// FIXME: This is a hack.
6577 template<typename T>
6578 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6579   if (S.getLangOpts().CPlusPlus) {
6580     // In C++, the overloadable attribute negates the effects of extern "C".
6581     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6582       return false;
6583 
6584     // So do CUDA's host/device attributes.
6585     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6586                                  D->template hasAttr<CUDAHostAttr>()))
6587       return false;
6588   }
6589   return D->isExternC();
6590 }
6591 
6592 static bool shouldConsiderLinkage(const VarDecl *VD) {
6593   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6594   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6595       isa<OMPDeclareMapperDecl>(DC))
6596     return VD->hasExternalStorage();
6597   if (DC->isFileContext())
6598     return true;
6599   if (DC->isRecord())
6600     return false;
6601   if (isa<RequiresExprBodyDecl>(DC))
6602     return false;
6603   llvm_unreachable("Unexpected context");
6604 }
6605 
6606 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6607   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6608   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6609       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6610     return true;
6611   if (DC->isRecord())
6612     return false;
6613   llvm_unreachable("Unexpected context");
6614 }
6615 
6616 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6617                           ParsedAttr::Kind Kind) {
6618   // Check decl attributes on the DeclSpec.
6619   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6620     return true;
6621 
6622   // Walk the declarator structure, checking decl attributes that were in a type
6623   // position to the decl itself.
6624   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6625     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6626       return true;
6627   }
6628 
6629   // Finally, check attributes on the decl itself.
6630   return PD.getAttributes().hasAttribute(Kind);
6631 }
6632 
6633 /// Adjust the \c DeclContext for a function or variable that might be a
6634 /// function-local external declaration.
6635 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6636   if (!DC->isFunctionOrMethod())
6637     return false;
6638 
6639   // If this is a local extern function or variable declared within a function
6640   // template, don't add it into the enclosing namespace scope until it is
6641   // instantiated; it might have a dependent type right now.
6642   if (DC->isDependentContext())
6643     return true;
6644 
6645   // C++11 [basic.link]p7:
6646   //   When a block scope declaration of an entity with linkage is not found to
6647   //   refer to some other declaration, then that entity is a member of the
6648   //   innermost enclosing namespace.
6649   //
6650   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6651   // semantically-enclosing namespace, not a lexically-enclosing one.
6652   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6653     DC = DC->getParent();
6654   return true;
6655 }
6656 
6657 /// Returns true if given declaration has external C language linkage.
6658 static bool isDeclExternC(const Decl *D) {
6659   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6660     return FD->isExternC();
6661   if (const auto *VD = dyn_cast<VarDecl>(D))
6662     return VD->isExternC();
6663 
6664   llvm_unreachable("Unknown type of decl!");
6665 }
6666 /// Returns true if there hasn't been any invalid type diagnosed.
6667 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6668                                 DeclContext *DC, QualType R) {
6669   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6670   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6671   // argument.
6672   if (R->isImageType() || R->isPipeType()) {
6673     Se.Diag(D.getIdentifierLoc(),
6674             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6675         << R;
6676     D.setInvalidType();
6677     return false;
6678   }
6679 
6680   // OpenCL v1.2 s6.9.r:
6681   // The event type cannot be used to declare a program scope variable.
6682   // OpenCL v2.0 s6.9.q:
6683   // The clk_event_t and reserve_id_t types cannot be declared in program
6684   // scope.
6685   if (NULL == S->getParent()) {
6686     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6687       Se.Diag(D.getIdentifierLoc(),
6688               diag::err_invalid_type_for_program_scope_var)
6689           << R;
6690       D.setInvalidType();
6691       return false;
6692     }
6693   }
6694 
6695   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6696   QualType NR = R;
6697   while (NR->isPointerType()) {
6698     if (NR->isFunctionPointerType()) {
6699       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6700       D.setInvalidType();
6701       return false;
6702     }
6703     NR = NR->getPointeeType();
6704   }
6705 
6706   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6707     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6708     // half array type (unless the cl_khr_fp16 extension is enabled).
6709     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6710       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6711       D.setInvalidType();
6712       return false;
6713     }
6714   }
6715 
6716   // OpenCL v1.2 s6.9.r:
6717   // The event type cannot be used with the __local, __constant and __global
6718   // address space qualifiers.
6719   if (R->isEventT()) {
6720     if (R.getAddressSpace() != LangAS::opencl_private) {
6721       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6722       D.setInvalidType();
6723       return false;
6724     }
6725   }
6726 
6727   // C++ for OpenCL does not allow the thread_local storage qualifier.
6728   // OpenCL C does not support thread_local either, and
6729   // also reject all other thread storage class specifiers.
6730   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6731   if (TSC != TSCS_unspecified) {
6732     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6733     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6734             diag::err_opencl_unknown_type_specifier)
6735         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6736         << DeclSpec::getSpecifierName(TSC) << 1;
6737     D.setInvalidType();
6738     return false;
6739   }
6740 
6741   if (R->isSamplerT()) {
6742     // OpenCL v1.2 s6.9.b p4:
6743     // The sampler type cannot be used with the __local and __global address
6744     // space qualifiers.
6745     if (R.getAddressSpace() == LangAS::opencl_local ||
6746         R.getAddressSpace() == LangAS::opencl_global) {
6747       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6748       D.setInvalidType();
6749     }
6750 
6751     // OpenCL v1.2 s6.12.14.1:
6752     // A global sampler must be declared with either the constant address
6753     // space qualifier or with the const qualifier.
6754     if (DC->isTranslationUnit() &&
6755         !(R.getAddressSpace() == LangAS::opencl_constant ||
6756           R.isConstQualified())) {
6757       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6758       D.setInvalidType();
6759     }
6760     if (D.isInvalidType())
6761       return false;
6762   }
6763   return true;
6764 }
6765 
6766 NamedDecl *Sema::ActOnVariableDeclarator(
6767     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6768     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6769     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6770   QualType R = TInfo->getType();
6771   DeclarationName Name = GetNameForDeclarator(D).getName();
6772 
6773   IdentifierInfo *II = Name.getAsIdentifierInfo();
6774 
6775   if (D.isDecompositionDeclarator()) {
6776     // Take the name of the first declarator as our name for diagnostic
6777     // purposes.
6778     auto &Decomp = D.getDecompositionDeclarator();
6779     if (!Decomp.bindings().empty()) {
6780       II = Decomp.bindings()[0].Name;
6781       Name = II;
6782     }
6783   } else if (!II) {
6784     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6785     return nullptr;
6786   }
6787 
6788 
6789   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6790   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6791 
6792   // dllimport globals without explicit storage class are treated as extern. We
6793   // have to change the storage class this early to get the right DeclContext.
6794   if (SC == SC_None && !DC->isRecord() &&
6795       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6796       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6797     SC = SC_Extern;
6798 
6799   DeclContext *OriginalDC = DC;
6800   bool IsLocalExternDecl = SC == SC_Extern &&
6801                            adjustContextForLocalExternDecl(DC);
6802 
6803   if (SCSpec == DeclSpec::SCS_mutable) {
6804     // mutable can only appear on non-static class members, so it's always
6805     // an error here
6806     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6807     D.setInvalidType();
6808     SC = SC_None;
6809   }
6810 
6811   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6812       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6813                               D.getDeclSpec().getStorageClassSpecLoc())) {
6814     // In C++11, the 'register' storage class specifier is deprecated.
6815     // Suppress the warning in system macros, it's used in macros in some
6816     // popular C system headers, such as in glibc's htonl() macro.
6817     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6818          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6819                                    : diag::warn_deprecated_register)
6820       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6821   }
6822 
6823   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6824 
6825   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6826     // C99 6.9p2: The storage-class specifiers auto and register shall not
6827     // appear in the declaration specifiers in an external declaration.
6828     // Global Register+Asm is a GNU extension we support.
6829     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6830       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6831       D.setInvalidType();
6832     }
6833   }
6834 
6835   bool IsMemberSpecialization = false;
6836   bool IsVariableTemplateSpecialization = false;
6837   bool IsPartialSpecialization = false;
6838   bool IsVariableTemplate = false;
6839   VarDecl *NewVD = nullptr;
6840   VarTemplateDecl *NewTemplate = nullptr;
6841   TemplateParameterList *TemplateParams = nullptr;
6842   if (!getLangOpts().CPlusPlus) {
6843     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6844                             II, R, TInfo, SC);
6845 
6846     if (R->getContainedDeducedType())
6847       ParsingInitForAutoVars.insert(NewVD);
6848 
6849     if (D.isInvalidType())
6850       NewVD->setInvalidDecl();
6851 
6852     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6853         NewVD->hasLocalStorage())
6854       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6855                             NTCUC_AutoVar, NTCUK_Destruct);
6856   } else {
6857     bool Invalid = false;
6858 
6859     if (DC->isRecord() && !CurContext->isRecord()) {
6860       // This is an out-of-line definition of a static data member.
6861       switch (SC) {
6862       case SC_None:
6863         break;
6864       case SC_Static:
6865         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6866              diag::err_static_out_of_line)
6867           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6868         break;
6869       case SC_Auto:
6870       case SC_Register:
6871       case SC_Extern:
6872         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6873         // to names of variables declared in a block or to function parameters.
6874         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6875         // of class members
6876 
6877         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6878              diag::err_storage_class_for_static_member)
6879           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6880         break;
6881       case SC_PrivateExtern:
6882         llvm_unreachable("C storage class in c++!");
6883       }
6884     }
6885 
6886     if (SC == SC_Static && CurContext->isRecord()) {
6887       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6888         // C++ [class.static.data]p2:
6889         //   A static data member shall not be a direct member of an unnamed
6890         //   or local class
6891         // FIXME: or of a (possibly indirectly) nested class thereof.
6892         if (RD->isLocalClass()) {
6893           Diag(D.getIdentifierLoc(),
6894                diag::err_static_data_member_not_allowed_in_local_class)
6895             << Name << RD->getDeclName() << RD->getTagKind();
6896         } else if (!RD->getDeclName()) {
6897           Diag(D.getIdentifierLoc(),
6898                diag::err_static_data_member_not_allowed_in_anon_struct)
6899             << Name << RD->getTagKind();
6900           Invalid = true;
6901         } else if (RD->isUnion()) {
6902           // C++98 [class.union]p1: If a union contains a static data member,
6903           // the program is ill-formed. C++11 drops this restriction.
6904           Diag(D.getIdentifierLoc(),
6905                getLangOpts().CPlusPlus11
6906                  ? diag::warn_cxx98_compat_static_data_member_in_union
6907                  : diag::ext_static_data_member_in_union) << Name;
6908         }
6909       }
6910     }
6911 
6912     // Match up the template parameter lists with the scope specifier, then
6913     // determine whether we have a template or a template specialization.
6914     bool InvalidScope = false;
6915     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6916         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6917         D.getCXXScopeSpec(),
6918         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6919             ? D.getName().TemplateId
6920             : nullptr,
6921         TemplateParamLists,
6922         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6923     Invalid |= InvalidScope;
6924 
6925     if (TemplateParams) {
6926       if (!TemplateParams->size() &&
6927           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6928         // There is an extraneous 'template<>' for this variable. Complain
6929         // about it, but allow the declaration of the variable.
6930         Diag(TemplateParams->getTemplateLoc(),
6931              diag::err_template_variable_noparams)
6932           << II
6933           << SourceRange(TemplateParams->getTemplateLoc(),
6934                          TemplateParams->getRAngleLoc());
6935         TemplateParams = nullptr;
6936       } else {
6937         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6938           // This is an explicit specialization or a partial specialization.
6939           // FIXME: Check that we can declare a specialization here.
6940           IsVariableTemplateSpecialization = true;
6941           IsPartialSpecialization = TemplateParams->size() > 0;
6942         } else { // if (TemplateParams->size() > 0)
6943           // This is a template declaration.
6944           IsVariableTemplate = true;
6945 
6946           // Check that we can declare a template here.
6947           if (CheckTemplateDeclScope(S, TemplateParams))
6948             return nullptr;
6949 
6950           // Only C++1y supports variable templates (N3651).
6951           Diag(D.getIdentifierLoc(),
6952                getLangOpts().CPlusPlus14
6953                    ? diag::warn_cxx11_compat_variable_template
6954                    : diag::ext_variable_template);
6955         }
6956       }
6957     } else {
6958       assert((Invalid ||
6959               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6960              "should have a 'template<>' for this decl");
6961     }
6962 
6963     if (IsVariableTemplateSpecialization) {
6964       SourceLocation TemplateKWLoc =
6965           TemplateParamLists.size() > 0
6966               ? TemplateParamLists[0]->getTemplateLoc()
6967               : SourceLocation();
6968       DeclResult Res = ActOnVarTemplateSpecialization(
6969           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6970           IsPartialSpecialization);
6971       if (Res.isInvalid())
6972         return nullptr;
6973       NewVD = cast<VarDecl>(Res.get());
6974       AddToScope = false;
6975     } else if (D.isDecompositionDeclarator()) {
6976       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6977                                         D.getIdentifierLoc(), R, TInfo, SC,
6978                                         Bindings);
6979     } else
6980       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6981                               D.getIdentifierLoc(), II, R, TInfo, SC);
6982 
6983     // If this is supposed to be a variable template, create it as such.
6984     if (IsVariableTemplate) {
6985       NewTemplate =
6986           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6987                                   TemplateParams, NewVD);
6988       NewVD->setDescribedVarTemplate(NewTemplate);
6989     }
6990 
6991     // If this decl has an auto type in need of deduction, make a note of the
6992     // Decl so we can diagnose uses of it in its own initializer.
6993     if (R->getContainedDeducedType())
6994       ParsingInitForAutoVars.insert(NewVD);
6995 
6996     if (D.isInvalidType() || Invalid) {
6997       NewVD->setInvalidDecl();
6998       if (NewTemplate)
6999         NewTemplate->setInvalidDecl();
7000     }
7001 
7002     SetNestedNameSpecifier(*this, NewVD, D);
7003 
7004     // If we have any template parameter lists that don't directly belong to
7005     // the variable (matching the scope specifier), store them.
7006     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7007     if (TemplateParamLists.size() > VDTemplateParamLists)
7008       NewVD->setTemplateParameterListsInfo(
7009           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7010   }
7011 
7012   if (D.getDeclSpec().isInlineSpecified()) {
7013     if (!getLangOpts().CPlusPlus) {
7014       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7015           << 0;
7016     } else if (CurContext->isFunctionOrMethod()) {
7017       // 'inline' is not allowed on block scope variable declaration.
7018       Diag(D.getDeclSpec().getInlineSpecLoc(),
7019            diag::err_inline_declaration_block_scope) << Name
7020         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7021     } else {
7022       Diag(D.getDeclSpec().getInlineSpecLoc(),
7023            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7024                                      : diag::ext_inline_variable);
7025       NewVD->setInlineSpecified();
7026     }
7027   }
7028 
7029   // Set the lexical context. If the declarator has a C++ scope specifier, the
7030   // lexical context will be different from the semantic context.
7031   NewVD->setLexicalDeclContext(CurContext);
7032   if (NewTemplate)
7033     NewTemplate->setLexicalDeclContext(CurContext);
7034 
7035   if (IsLocalExternDecl) {
7036     if (D.isDecompositionDeclarator())
7037       for (auto *B : Bindings)
7038         B->setLocalExternDecl();
7039     else
7040       NewVD->setLocalExternDecl();
7041   }
7042 
7043   bool EmitTLSUnsupportedError = false;
7044   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7045     // C++11 [dcl.stc]p4:
7046     //   When thread_local is applied to a variable of block scope the
7047     //   storage-class-specifier static is implied if it does not appear
7048     //   explicitly.
7049     // Core issue: 'static' is not implied if the variable is declared
7050     //   'extern'.
7051     if (NewVD->hasLocalStorage() &&
7052         (SCSpec != DeclSpec::SCS_unspecified ||
7053          TSCS != DeclSpec::TSCS_thread_local ||
7054          !DC->isFunctionOrMethod()))
7055       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7056            diag::err_thread_non_global)
7057         << DeclSpec::getSpecifierName(TSCS);
7058     else if (!Context.getTargetInfo().isTLSSupported()) {
7059       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7060         // Postpone error emission until we've collected attributes required to
7061         // figure out whether it's a host or device variable and whether the
7062         // error should be ignored.
7063         EmitTLSUnsupportedError = true;
7064         // We still need to mark the variable as TLS so it shows up in AST with
7065         // proper storage class for other tools to use even if we're not going
7066         // to emit any code for it.
7067         NewVD->setTSCSpec(TSCS);
7068       } else
7069         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7070              diag::err_thread_unsupported);
7071     } else
7072       NewVD->setTSCSpec(TSCS);
7073   }
7074 
7075   switch (D.getDeclSpec().getConstexprSpecifier()) {
7076   case CSK_unspecified:
7077     break;
7078 
7079   case CSK_consteval:
7080     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7081         diag::err_constexpr_wrong_decl_kind)
7082       << D.getDeclSpec().getConstexprSpecifier();
7083     LLVM_FALLTHROUGH;
7084 
7085   case CSK_constexpr:
7086     NewVD->setConstexpr(true);
7087     // C++1z [dcl.spec.constexpr]p1:
7088     //   A static data member declared with the constexpr specifier is
7089     //   implicitly an inline variable.
7090     if (NewVD->isStaticDataMember() &&
7091         (getLangOpts().CPlusPlus17 ||
7092          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7093       NewVD->setImplicitlyInline();
7094     break;
7095 
7096   case CSK_constinit:
7097     if (!NewVD->hasGlobalStorage())
7098       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7099            diag::err_constinit_local_variable);
7100     else
7101       NewVD->addAttr(ConstInitAttr::Create(
7102           Context, D.getDeclSpec().getConstexprSpecLoc(),
7103           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7104     break;
7105   }
7106 
7107   // C99 6.7.4p3
7108   //   An inline definition of a function with external linkage shall
7109   //   not contain a definition of a modifiable object with static or
7110   //   thread storage duration...
7111   // We only apply this when the function is required to be defined
7112   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7113   // that a local variable with thread storage duration still has to
7114   // be marked 'static'.  Also note that it's possible to get these
7115   // semantics in C++ using __attribute__((gnu_inline)).
7116   if (SC == SC_Static && S->getFnParent() != nullptr &&
7117       !NewVD->getType().isConstQualified()) {
7118     FunctionDecl *CurFD = getCurFunctionDecl();
7119     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7120       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7121            diag::warn_static_local_in_extern_inline);
7122       MaybeSuggestAddingStaticToDecl(CurFD);
7123     }
7124   }
7125 
7126   if (D.getDeclSpec().isModulePrivateSpecified()) {
7127     if (IsVariableTemplateSpecialization)
7128       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7129           << (IsPartialSpecialization ? 1 : 0)
7130           << FixItHint::CreateRemoval(
7131                  D.getDeclSpec().getModulePrivateSpecLoc());
7132     else if (IsMemberSpecialization)
7133       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7134         << 2
7135         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7136     else if (NewVD->hasLocalStorage())
7137       Diag(NewVD->getLocation(), diag::err_module_private_local)
7138         << 0 << NewVD->getDeclName()
7139         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7140         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7141     else {
7142       NewVD->setModulePrivate();
7143       if (NewTemplate)
7144         NewTemplate->setModulePrivate();
7145       for (auto *B : Bindings)
7146         B->setModulePrivate();
7147     }
7148   }
7149 
7150   if (getLangOpts().OpenCL) {
7151 
7152     deduceOpenCLAddressSpace(NewVD);
7153 
7154     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7155   }
7156 
7157   // Handle attributes prior to checking for duplicates in MergeVarDecl
7158   ProcessDeclAttributes(S, NewVD, D);
7159 
7160   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7161     if (EmitTLSUnsupportedError &&
7162         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7163          (getLangOpts().OpenMPIsDevice &&
7164           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7165       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7166            diag::err_thread_unsupported);
7167     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7168     // storage [duration]."
7169     if (SC == SC_None && S->getFnParent() != nullptr &&
7170         (NewVD->hasAttr<CUDASharedAttr>() ||
7171          NewVD->hasAttr<CUDAConstantAttr>())) {
7172       NewVD->setStorageClass(SC_Static);
7173     }
7174   }
7175 
7176   // Ensure that dllimport globals without explicit storage class are treated as
7177   // extern. The storage class is set above using parsed attributes. Now we can
7178   // check the VarDecl itself.
7179   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7180          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7181          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7182 
7183   // In auto-retain/release, infer strong retension for variables of
7184   // retainable type.
7185   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7186     NewVD->setInvalidDecl();
7187 
7188   // Handle GNU asm-label extension (encoded as an attribute).
7189   if (Expr *E = (Expr*)D.getAsmLabel()) {
7190     // The parser guarantees this is a string.
7191     StringLiteral *SE = cast<StringLiteral>(E);
7192     StringRef Label = SE->getString();
7193     if (S->getFnParent() != nullptr) {
7194       switch (SC) {
7195       case SC_None:
7196       case SC_Auto:
7197         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7198         break;
7199       case SC_Register:
7200         // Local Named register
7201         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7202             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7203           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7204         break;
7205       case SC_Static:
7206       case SC_Extern:
7207       case SC_PrivateExtern:
7208         break;
7209       }
7210     } else if (SC == SC_Register) {
7211       // Global Named register
7212       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7213         const auto &TI = Context.getTargetInfo();
7214         bool HasSizeMismatch;
7215 
7216         if (!TI.isValidGCCRegisterName(Label))
7217           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7218         else if (!TI.validateGlobalRegisterVariable(Label,
7219                                                     Context.getTypeSize(R),
7220                                                     HasSizeMismatch))
7221           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7222         else if (HasSizeMismatch)
7223           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7224       }
7225 
7226       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7227         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7228         NewVD->setInvalidDecl(true);
7229       }
7230     }
7231 
7232     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7233                                         /*IsLiteralLabel=*/true,
7234                                         SE->getStrTokenLoc(0)));
7235   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7236     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7237       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7238     if (I != ExtnameUndeclaredIdentifiers.end()) {
7239       if (isDeclExternC(NewVD)) {
7240         NewVD->addAttr(I->second);
7241         ExtnameUndeclaredIdentifiers.erase(I);
7242       } else
7243         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7244             << /*Variable*/1 << NewVD;
7245     }
7246   }
7247 
7248   // Find the shadowed declaration before filtering for scope.
7249   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7250                                 ? getShadowedDeclaration(NewVD, Previous)
7251                                 : nullptr;
7252 
7253   // Don't consider existing declarations that are in a different
7254   // scope and are out-of-semantic-context declarations (if the new
7255   // declaration has linkage).
7256   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7257                        D.getCXXScopeSpec().isNotEmpty() ||
7258                        IsMemberSpecialization ||
7259                        IsVariableTemplateSpecialization);
7260 
7261   // Check whether the previous declaration is in the same block scope. This
7262   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7263   if (getLangOpts().CPlusPlus &&
7264       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7265     NewVD->setPreviousDeclInSameBlockScope(
7266         Previous.isSingleResult() && !Previous.isShadowed() &&
7267         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7268 
7269   if (!getLangOpts().CPlusPlus) {
7270     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7271   } else {
7272     // If this is an explicit specialization of a static data member, check it.
7273     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7274         CheckMemberSpecialization(NewVD, Previous))
7275       NewVD->setInvalidDecl();
7276 
7277     // Merge the decl with the existing one if appropriate.
7278     if (!Previous.empty()) {
7279       if (Previous.isSingleResult() &&
7280           isa<FieldDecl>(Previous.getFoundDecl()) &&
7281           D.getCXXScopeSpec().isSet()) {
7282         // The user tried to define a non-static data member
7283         // out-of-line (C++ [dcl.meaning]p1).
7284         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7285           << D.getCXXScopeSpec().getRange();
7286         Previous.clear();
7287         NewVD->setInvalidDecl();
7288       }
7289     } else if (D.getCXXScopeSpec().isSet()) {
7290       // No previous declaration in the qualifying scope.
7291       Diag(D.getIdentifierLoc(), diag::err_no_member)
7292         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7293         << D.getCXXScopeSpec().getRange();
7294       NewVD->setInvalidDecl();
7295     }
7296 
7297     if (!IsVariableTemplateSpecialization)
7298       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7299 
7300     if (NewTemplate) {
7301       VarTemplateDecl *PrevVarTemplate =
7302           NewVD->getPreviousDecl()
7303               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7304               : nullptr;
7305 
7306       // Check the template parameter list of this declaration, possibly
7307       // merging in the template parameter list from the previous variable
7308       // template declaration.
7309       if (CheckTemplateParameterList(
7310               TemplateParams,
7311               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7312                               : nullptr,
7313               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7314                DC->isDependentContext())
7315                   ? TPC_ClassTemplateMember
7316                   : TPC_VarTemplate))
7317         NewVD->setInvalidDecl();
7318 
7319       // If we are providing an explicit specialization of a static variable
7320       // template, make a note of that.
7321       if (PrevVarTemplate &&
7322           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7323         PrevVarTemplate->setMemberSpecialization();
7324     }
7325   }
7326 
7327   // Diagnose shadowed variables iff this isn't a redeclaration.
7328   if (ShadowedDecl && !D.isRedeclaration())
7329     CheckShadow(NewVD, ShadowedDecl, Previous);
7330 
7331   ProcessPragmaWeak(S, NewVD);
7332 
7333   // If this is the first declaration of an extern C variable, update
7334   // the map of such variables.
7335   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7336       isIncompleteDeclExternC(*this, NewVD))
7337     RegisterLocallyScopedExternCDecl(NewVD, S);
7338 
7339   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7340     MangleNumberingContext *MCtx;
7341     Decl *ManglingContextDecl;
7342     std::tie(MCtx, ManglingContextDecl) =
7343         getCurrentMangleNumberContext(NewVD->getDeclContext());
7344     if (MCtx) {
7345       Context.setManglingNumber(
7346           NewVD, MCtx->getManglingNumber(
7347                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7348       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7349     }
7350   }
7351 
7352   // Special handling of variable named 'main'.
7353   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7354       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7355       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7356 
7357     // C++ [basic.start.main]p3
7358     // A program that declares a variable main at global scope is ill-formed.
7359     if (getLangOpts().CPlusPlus)
7360       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7361 
7362     // In C, and external-linkage variable named main results in undefined
7363     // behavior.
7364     else if (NewVD->hasExternalFormalLinkage())
7365       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7366   }
7367 
7368   if (D.isRedeclaration() && !Previous.empty()) {
7369     NamedDecl *Prev = Previous.getRepresentativeDecl();
7370     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7371                                    D.isFunctionDefinition());
7372   }
7373 
7374   if (NewTemplate) {
7375     if (NewVD->isInvalidDecl())
7376       NewTemplate->setInvalidDecl();
7377     ActOnDocumentableDecl(NewTemplate);
7378     return NewTemplate;
7379   }
7380 
7381   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7382     CompleteMemberSpecialization(NewVD, Previous);
7383 
7384   return NewVD;
7385 }
7386 
7387 /// Enum describing the %select options in diag::warn_decl_shadow.
7388 enum ShadowedDeclKind {
7389   SDK_Local,
7390   SDK_Global,
7391   SDK_StaticMember,
7392   SDK_Field,
7393   SDK_Typedef,
7394   SDK_Using
7395 };
7396 
7397 /// Determine what kind of declaration we're shadowing.
7398 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7399                                                 const DeclContext *OldDC) {
7400   if (isa<TypeAliasDecl>(ShadowedDecl))
7401     return SDK_Using;
7402   else if (isa<TypedefDecl>(ShadowedDecl))
7403     return SDK_Typedef;
7404   else if (isa<RecordDecl>(OldDC))
7405     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7406 
7407   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7408 }
7409 
7410 /// Return the location of the capture if the given lambda captures the given
7411 /// variable \p VD, or an invalid source location otherwise.
7412 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7413                                          const VarDecl *VD) {
7414   for (const Capture &Capture : LSI->Captures) {
7415     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7416       return Capture.getLocation();
7417   }
7418   return SourceLocation();
7419 }
7420 
7421 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7422                                      const LookupResult &R) {
7423   // Only diagnose if we're shadowing an unambiguous field or variable.
7424   if (R.getResultKind() != LookupResult::Found)
7425     return false;
7426 
7427   // Return false if warning is ignored.
7428   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7429 }
7430 
7431 /// Return the declaration shadowed by the given variable \p D, or null
7432 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7433 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7434                                         const LookupResult &R) {
7435   if (!shouldWarnIfShadowedDecl(Diags, R))
7436     return nullptr;
7437 
7438   // Don't diagnose declarations at file scope.
7439   if (D->hasGlobalStorage())
7440     return nullptr;
7441 
7442   NamedDecl *ShadowedDecl = R.getFoundDecl();
7443   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7444              ? ShadowedDecl
7445              : nullptr;
7446 }
7447 
7448 /// Return the declaration shadowed by the given typedef \p D, or null
7449 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7450 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7451                                         const LookupResult &R) {
7452   // Don't warn if typedef declaration is part of a class
7453   if (D->getDeclContext()->isRecord())
7454     return nullptr;
7455 
7456   if (!shouldWarnIfShadowedDecl(Diags, R))
7457     return nullptr;
7458 
7459   NamedDecl *ShadowedDecl = R.getFoundDecl();
7460   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7461 }
7462 
7463 /// Diagnose variable or built-in function shadowing.  Implements
7464 /// -Wshadow.
7465 ///
7466 /// This method is called whenever a VarDecl is added to a "useful"
7467 /// scope.
7468 ///
7469 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7470 /// \param R the lookup of the name
7471 ///
7472 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7473                        const LookupResult &R) {
7474   DeclContext *NewDC = D->getDeclContext();
7475 
7476   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7477     // Fields are not shadowed by variables in C++ static methods.
7478     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7479       if (MD->isStatic())
7480         return;
7481 
7482     // Fields shadowed by constructor parameters are a special case. Usually
7483     // the constructor initializes the field with the parameter.
7484     if (isa<CXXConstructorDecl>(NewDC))
7485       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7486         // Remember that this was shadowed so we can either warn about its
7487         // modification or its existence depending on warning settings.
7488         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7489         return;
7490       }
7491   }
7492 
7493   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7494     if (shadowedVar->isExternC()) {
7495       // For shadowing external vars, make sure that we point to the global
7496       // declaration, not a locally scoped extern declaration.
7497       for (auto I : shadowedVar->redecls())
7498         if (I->isFileVarDecl()) {
7499           ShadowedDecl = I;
7500           break;
7501         }
7502     }
7503 
7504   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7505 
7506   unsigned WarningDiag = diag::warn_decl_shadow;
7507   SourceLocation CaptureLoc;
7508   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7509       isa<CXXMethodDecl>(NewDC)) {
7510     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7511       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7512         if (RD->getLambdaCaptureDefault() == LCD_None) {
7513           // Try to avoid warnings for lambdas with an explicit capture list.
7514           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7515           // Warn only when the lambda captures the shadowed decl explicitly.
7516           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7517           if (CaptureLoc.isInvalid())
7518             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7519         } else {
7520           // Remember that this was shadowed so we can avoid the warning if the
7521           // shadowed decl isn't captured and the warning settings allow it.
7522           cast<LambdaScopeInfo>(getCurFunction())
7523               ->ShadowingDecls.push_back(
7524                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7525           return;
7526         }
7527       }
7528 
7529       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7530         // A variable can't shadow a local variable in an enclosing scope, if
7531         // they are separated by a non-capturing declaration context.
7532         for (DeclContext *ParentDC = NewDC;
7533              ParentDC && !ParentDC->Equals(OldDC);
7534              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7535           // Only block literals, captured statements, and lambda expressions
7536           // can capture; other scopes don't.
7537           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7538               !isLambdaCallOperator(ParentDC)) {
7539             return;
7540           }
7541         }
7542       }
7543     }
7544   }
7545 
7546   // Only warn about certain kinds of shadowing for class members.
7547   if (NewDC && NewDC->isRecord()) {
7548     // In particular, don't warn about shadowing non-class members.
7549     if (!OldDC->isRecord())
7550       return;
7551 
7552     // TODO: should we warn about static data members shadowing
7553     // static data members from base classes?
7554 
7555     // TODO: don't diagnose for inaccessible shadowed members.
7556     // This is hard to do perfectly because we might friend the
7557     // shadowing context, but that's just a false negative.
7558   }
7559 
7560 
7561   DeclarationName Name = R.getLookupName();
7562 
7563   // Emit warning and note.
7564   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7565     return;
7566   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7567   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7568   if (!CaptureLoc.isInvalid())
7569     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7570         << Name << /*explicitly*/ 1;
7571   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7572 }
7573 
7574 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7575 /// when these variables are captured by the lambda.
7576 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7577   for (const auto &Shadow : LSI->ShadowingDecls) {
7578     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7579     // Try to avoid the warning when the shadowed decl isn't captured.
7580     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7581     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7582     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7583                                        ? diag::warn_decl_shadow_uncaptured_local
7584                                        : diag::warn_decl_shadow)
7585         << Shadow.VD->getDeclName()
7586         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7587     if (!CaptureLoc.isInvalid())
7588       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7589           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7590     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7591   }
7592 }
7593 
7594 /// Check -Wshadow without the advantage of a previous lookup.
7595 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7596   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7597     return;
7598 
7599   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7600                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7601   LookupName(R, S);
7602   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7603     CheckShadow(D, ShadowedDecl, R);
7604 }
7605 
7606 /// Check if 'E', which is an expression that is about to be modified, refers
7607 /// to a constructor parameter that shadows a field.
7608 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7609   // Quickly ignore expressions that can't be shadowing ctor parameters.
7610   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7611     return;
7612   E = E->IgnoreParenImpCasts();
7613   auto *DRE = dyn_cast<DeclRefExpr>(E);
7614   if (!DRE)
7615     return;
7616   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7617   auto I = ShadowingDecls.find(D);
7618   if (I == ShadowingDecls.end())
7619     return;
7620   const NamedDecl *ShadowedDecl = I->second;
7621   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7622   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7623   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7624   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7625 
7626   // Avoid issuing multiple warnings about the same decl.
7627   ShadowingDecls.erase(I);
7628 }
7629 
7630 /// Check for conflict between this global or extern "C" declaration and
7631 /// previous global or extern "C" declarations. This is only used in C++.
7632 template<typename T>
7633 static bool checkGlobalOrExternCConflict(
7634     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7635   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7636   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7637 
7638   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7639     // The common case: this global doesn't conflict with any extern "C"
7640     // declaration.
7641     return false;
7642   }
7643 
7644   if (Prev) {
7645     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7646       // Both the old and new declarations have C language linkage. This is a
7647       // redeclaration.
7648       Previous.clear();
7649       Previous.addDecl(Prev);
7650       return true;
7651     }
7652 
7653     // This is a global, non-extern "C" declaration, and there is a previous
7654     // non-global extern "C" declaration. Diagnose if this is a variable
7655     // declaration.
7656     if (!isa<VarDecl>(ND))
7657       return false;
7658   } else {
7659     // The declaration is extern "C". Check for any declaration in the
7660     // translation unit which might conflict.
7661     if (IsGlobal) {
7662       // We have already performed the lookup into the translation unit.
7663       IsGlobal = false;
7664       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7665            I != E; ++I) {
7666         if (isa<VarDecl>(*I)) {
7667           Prev = *I;
7668           break;
7669         }
7670       }
7671     } else {
7672       DeclContext::lookup_result R =
7673           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7674       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7675            I != E; ++I) {
7676         if (isa<VarDecl>(*I)) {
7677           Prev = *I;
7678           break;
7679         }
7680         // FIXME: If we have any other entity with this name in global scope,
7681         // the declaration is ill-formed, but that is a defect: it breaks the
7682         // 'stat' hack, for instance. Only variables can have mangled name
7683         // clashes with extern "C" declarations, so only they deserve a
7684         // diagnostic.
7685       }
7686     }
7687 
7688     if (!Prev)
7689       return false;
7690   }
7691 
7692   // Use the first declaration's location to ensure we point at something which
7693   // is lexically inside an extern "C" linkage-spec.
7694   assert(Prev && "should have found a previous declaration to diagnose");
7695   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7696     Prev = FD->getFirstDecl();
7697   else
7698     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7699 
7700   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7701     << IsGlobal << ND;
7702   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7703     << IsGlobal;
7704   return false;
7705 }
7706 
7707 /// Apply special rules for handling extern "C" declarations. Returns \c true
7708 /// if we have found that this is a redeclaration of some prior entity.
7709 ///
7710 /// Per C++ [dcl.link]p6:
7711 ///   Two declarations [for a function or variable] with C language linkage
7712 ///   with the same name that appear in different scopes refer to the same
7713 ///   [entity]. An entity with C language linkage shall not be declared with
7714 ///   the same name as an entity in global scope.
7715 template<typename T>
7716 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7717                                                   LookupResult &Previous) {
7718   if (!S.getLangOpts().CPlusPlus) {
7719     // In C, when declaring a global variable, look for a corresponding 'extern'
7720     // variable declared in function scope. We don't need this in C++, because
7721     // we find local extern decls in the surrounding file-scope DeclContext.
7722     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7723       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7724         Previous.clear();
7725         Previous.addDecl(Prev);
7726         return true;
7727       }
7728     }
7729     return false;
7730   }
7731 
7732   // A declaration in the translation unit can conflict with an extern "C"
7733   // declaration.
7734   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7735     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7736 
7737   // An extern "C" declaration can conflict with a declaration in the
7738   // translation unit or can be a redeclaration of an extern "C" declaration
7739   // in another scope.
7740   if (isIncompleteDeclExternC(S,ND))
7741     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7742 
7743   // Neither global nor extern "C": nothing to do.
7744   return false;
7745 }
7746 
7747 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7748   // If the decl is already known invalid, don't check it.
7749   if (NewVD->isInvalidDecl())
7750     return;
7751 
7752   QualType T = NewVD->getType();
7753 
7754   // Defer checking an 'auto' type until its initializer is attached.
7755   if (T->isUndeducedType())
7756     return;
7757 
7758   if (NewVD->hasAttrs())
7759     CheckAlignasUnderalignment(NewVD);
7760 
7761   if (T->isObjCObjectType()) {
7762     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7763       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7764     T = Context.getObjCObjectPointerType(T);
7765     NewVD->setType(T);
7766   }
7767 
7768   // Emit an error if an address space was applied to decl with local storage.
7769   // This includes arrays of objects with address space qualifiers, but not
7770   // automatic variables that point to other address spaces.
7771   // ISO/IEC TR 18037 S5.1.2
7772   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7773       T.getAddressSpace() != LangAS::Default) {
7774     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7775     NewVD->setInvalidDecl();
7776     return;
7777   }
7778 
7779   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7780   // scope.
7781   if (getLangOpts().OpenCLVersion == 120 &&
7782       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7783       NewVD->isStaticLocal()) {
7784     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7785     NewVD->setInvalidDecl();
7786     return;
7787   }
7788 
7789   if (getLangOpts().OpenCL) {
7790     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7791     if (NewVD->hasAttr<BlocksAttr>()) {
7792       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7793       return;
7794     }
7795 
7796     if (T->isBlockPointerType()) {
7797       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7798       // can't use 'extern' storage class.
7799       if (!T.isConstQualified()) {
7800         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7801             << 0 /*const*/;
7802         NewVD->setInvalidDecl();
7803         return;
7804       }
7805       if (NewVD->hasExternalStorage()) {
7806         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7807         NewVD->setInvalidDecl();
7808         return;
7809       }
7810     }
7811     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7812     // __constant address space.
7813     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7814     // variables inside a function can also be declared in the global
7815     // address space.
7816     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7817     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7818     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7819         NewVD->hasExternalStorage()) {
7820       if (!T->isSamplerT() &&
7821           !(T.getAddressSpace() == LangAS::opencl_constant ||
7822             (T.getAddressSpace() == LangAS::opencl_global &&
7823              (getLangOpts().OpenCLVersion == 200 ||
7824               getLangOpts().OpenCLCPlusPlus)))) {
7825         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7826         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7827           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7828               << Scope << "global or constant";
7829         else
7830           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7831               << Scope << "constant";
7832         NewVD->setInvalidDecl();
7833         return;
7834       }
7835     } else {
7836       if (T.getAddressSpace() == LangAS::opencl_global) {
7837         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7838             << 1 /*is any function*/ << "global";
7839         NewVD->setInvalidDecl();
7840         return;
7841       }
7842       if (T.getAddressSpace() == LangAS::opencl_constant ||
7843           T.getAddressSpace() == LangAS::opencl_local) {
7844         FunctionDecl *FD = getCurFunctionDecl();
7845         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7846         // in functions.
7847         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7848           if (T.getAddressSpace() == LangAS::opencl_constant)
7849             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7850                 << 0 /*non-kernel only*/ << "constant";
7851           else
7852             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7853                 << 0 /*non-kernel only*/ << "local";
7854           NewVD->setInvalidDecl();
7855           return;
7856         }
7857         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7858         // in the outermost scope of a kernel function.
7859         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7860           if (!getCurScope()->isFunctionScope()) {
7861             if (T.getAddressSpace() == LangAS::opencl_constant)
7862               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7863                   << "constant";
7864             else
7865               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7866                   << "local";
7867             NewVD->setInvalidDecl();
7868             return;
7869           }
7870         }
7871       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7872                  // If we are parsing a template we didn't deduce an addr
7873                  // space yet.
7874                  T.getAddressSpace() != LangAS::Default) {
7875         // Do not allow other address spaces on automatic variable.
7876         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7877         NewVD->setInvalidDecl();
7878         return;
7879       }
7880     }
7881   }
7882 
7883   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7884       && !NewVD->hasAttr<BlocksAttr>()) {
7885     if (getLangOpts().getGC() != LangOptions::NonGC)
7886       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7887     else {
7888       assert(!getLangOpts().ObjCAutoRefCount);
7889       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7890     }
7891   }
7892 
7893   bool isVM = T->isVariablyModifiedType();
7894   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7895       NewVD->hasAttr<BlocksAttr>())
7896     setFunctionHasBranchProtectedScope();
7897 
7898   if ((isVM && NewVD->hasLinkage()) ||
7899       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7900     bool SizeIsNegative;
7901     llvm::APSInt Oversized;
7902     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7903         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7904     QualType FixedT;
7905     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7906       FixedT = FixedTInfo->getType();
7907     else if (FixedTInfo) {
7908       // Type and type-as-written are canonically different. We need to fix up
7909       // both types separately.
7910       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7911                                                    Oversized);
7912     }
7913     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7914       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7915       // FIXME: This won't give the correct result for
7916       // int a[10][n];
7917       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7918 
7919       if (NewVD->isFileVarDecl())
7920         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7921         << SizeRange;
7922       else if (NewVD->isStaticLocal())
7923         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7924         << SizeRange;
7925       else
7926         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7927         << SizeRange;
7928       NewVD->setInvalidDecl();
7929       return;
7930     }
7931 
7932     if (!FixedTInfo) {
7933       if (NewVD->isFileVarDecl())
7934         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7935       else
7936         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7937       NewVD->setInvalidDecl();
7938       return;
7939     }
7940 
7941     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7942     NewVD->setType(FixedT);
7943     NewVD->setTypeSourceInfo(FixedTInfo);
7944   }
7945 
7946   if (T->isVoidType()) {
7947     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7948     //                    of objects and functions.
7949     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7950       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7951         << T;
7952       NewVD->setInvalidDecl();
7953       return;
7954     }
7955   }
7956 
7957   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7958     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7959     NewVD->setInvalidDecl();
7960     return;
7961   }
7962 
7963   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
7964     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
7965     NewVD->setInvalidDecl();
7966     return;
7967   }
7968 
7969   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7970     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7971     NewVD->setInvalidDecl();
7972     return;
7973   }
7974 
7975   if (NewVD->isConstexpr() && !T->isDependentType() &&
7976       RequireLiteralType(NewVD->getLocation(), T,
7977                          diag::err_constexpr_var_non_literal)) {
7978     NewVD->setInvalidDecl();
7979     return;
7980   }
7981 }
7982 
7983 /// Perform semantic checking on a newly-created variable
7984 /// declaration.
7985 ///
7986 /// This routine performs all of the type-checking required for a
7987 /// variable declaration once it has been built. It is used both to
7988 /// check variables after they have been parsed and their declarators
7989 /// have been translated into a declaration, and to check variables
7990 /// that have been instantiated from a template.
7991 ///
7992 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7993 ///
7994 /// Returns true if the variable declaration is a redeclaration.
7995 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7996   CheckVariableDeclarationType(NewVD);
7997 
7998   // If the decl is already known invalid, don't check it.
7999   if (NewVD->isInvalidDecl())
8000     return false;
8001 
8002   // If we did not find anything by this name, look for a non-visible
8003   // extern "C" declaration with the same name.
8004   if (Previous.empty() &&
8005       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8006     Previous.setShadowed();
8007 
8008   if (!Previous.empty()) {
8009     MergeVarDecl(NewVD, Previous);
8010     return true;
8011   }
8012   return false;
8013 }
8014 
8015 namespace {
8016 struct FindOverriddenMethod {
8017   Sema *S;
8018   CXXMethodDecl *Method;
8019 
8020   /// Member lookup function that determines whether a given C++
8021   /// method overrides a method in a base class, to be used with
8022   /// CXXRecordDecl::lookupInBases().
8023   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8024     RecordDecl *BaseRecord =
8025         Specifier->getType()->castAs<RecordType>()->getDecl();
8026 
8027     DeclarationName Name = Method->getDeclName();
8028 
8029     // FIXME: Do we care about other names here too?
8030     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8031       // We really want to find the base class destructor here.
8032       QualType T = S->Context.getTypeDeclType(BaseRecord);
8033       CanQualType CT = S->Context.getCanonicalType(T);
8034 
8035       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8036     }
8037 
8038     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8039          Path.Decls = Path.Decls.slice(1)) {
8040       NamedDecl *D = Path.Decls.front();
8041       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8042         if (MD->isVirtual() &&
8043             !S->IsOverload(
8044                 Method, MD, /*UseMemberUsingDeclRules=*/false,
8045                 /*ConsiderCudaAttrs=*/true,
8046                 // C++2a [class.virtual]p2 does not consider requires clauses
8047                 // when overriding.
8048                 /*ConsiderRequiresClauses=*/false))
8049           return true;
8050       }
8051     }
8052 
8053     return false;
8054   }
8055 };
8056 } // end anonymous namespace
8057 
8058 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8059 /// and if so, check that it's a valid override and remember it.
8060 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8061   // Look for methods in base classes that this method might override.
8062   CXXBasePaths Paths;
8063   FindOverriddenMethod FOM;
8064   FOM.Method = MD;
8065   FOM.S = this;
8066   bool AddedAny = false;
8067   if (DC->lookupInBases(FOM, Paths)) {
8068     for (auto *I : Paths.found_decls()) {
8069       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8070         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8071         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8072             !CheckOverridingFunctionAttributes(MD, OldMD) &&
8073             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8074             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8075           AddedAny = true;
8076         }
8077       }
8078     }
8079   }
8080 
8081   return AddedAny;
8082 }
8083 
8084 namespace {
8085   // Struct for holding all of the extra arguments needed by
8086   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8087   struct ActOnFDArgs {
8088     Scope *S;
8089     Declarator &D;
8090     MultiTemplateParamsArg TemplateParamLists;
8091     bool AddToScope;
8092   };
8093 } // end anonymous namespace
8094 
8095 namespace {
8096 
8097 // Callback to only accept typo corrections that have a non-zero edit distance.
8098 // Also only accept corrections that have the same parent decl.
8099 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8100  public:
8101   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8102                             CXXRecordDecl *Parent)
8103       : Context(Context), OriginalFD(TypoFD),
8104         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8105 
8106   bool ValidateCandidate(const TypoCorrection &candidate) override {
8107     if (candidate.getEditDistance() == 0)
8108       return false;
8109 
8110     SmallVector<unsigned, 1> MismatchedParams;
8111     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8112                                           CDeclEnd = candidate.end();
8113          CDecl != CDeclEnd; ++CDecl) {
8114       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8115 
8116       if (FD && !FD->hasBody() &&
8117           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8118         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8119           CXXRecordDecl *Parent = MD->getParent();
8120           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8121             return true;
8122         } else if (!ExpectedParent) {
8123           return true;
8124         }
8125       }
8126     }
8127 
8128     return false;
8129   }
8130 
8131   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8132     return std::make_unique<DifferentNameValidatorCCC>(*this);
8133   }
8134 
8135  private:
8136   ASTContext &Context;
8137   FunctionDecl *OriginalFD;
8138   CXXRecordDecl *ExpectedParent;
8139 };
8140 
8141 } // end anonymous namespace
8142 
8143 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8144   TypoCorrectedFunctionDefinitions.insert(F);
8145 }
8146 
8147 /// Generate diagnostics for an invalid function redeclaration.
8148 ///
8149 /// This routine handles generating the diagnostic messages for an invalid
8150 /// function redeclaration, including finding possible similar declarations
8151 /// or performing typo correction if there are no previous declarations with
8152 /// the same name.
8153 ///
8154 /// Returns a NamedDecl iff typo correction was performed and substituting in
8155 /// the new declaration name does not cause new errors.
8156 static NamedDecl *DiagnoseInvalidRedeclaration(
8157     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8158     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8159   DeclarationName Name = NewFD->getDeclName();
8160   DeclContext *NewDC = NewFD->getDeclContext();
8161   SmallVector<unsigned, 1> MismatchedParams;
8162   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8163   TypoCorrection Correction;
8164   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8165   unsigned DiagMsg =
8166     IsLocalFriend ? diag::err_no_matching_local_friend :
8167     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8168     diag::err_member_decl_does_not_match;
8169   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8170                     IsLocalFriend ? Sema::LookupLocalFriendName
8171                                   : Sema::LookupOrdinaryName,
8172                     Sema::ForVisibleRedeclaration);
8173 
8174   NewFD->setInvalidDecl();
8175   if (IsLocalFriend)
8176     SemaRef.LookupName(Prev, S);
8177   else
8178     SemaRef.LookupQualifiedName(Prev, NewDC);
8179   assert(!Prev.isAmbiguous() &&
8180          "Cannot have an ambiguity in previous-declaration lookup");
8181   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8182   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8183                                 MD ? MD->getParent() : nullptr);
8184   if (!Prev.empty()) {
8185     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8186          Func != FuncEnd; ++Func) {
8187       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8188       if (FD &&
8189           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8190         // Add 1 to the index so that 0 can mean the mismatch didn't
8191         // involve a parameter
8192         unsigned ParamNum =
8193             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8194         NearMatches.push_back(std::make_pair(FD, ParamNum));
8195       }
8196     }
8197   // If the qualified name lookup yielded nothing, try typo correction
8198   } else if ((Correction = SemaRef.CorrectTypo(
8199                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8200                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8201                   IsLocalFriend ? nullptr : NewDC))) {
8202     // Set up everything for the call to ActOnFunctionDeclarator
8203     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8204                               ExtraArgs.D.getIdentifierLoc());
8205     Previous.clear();
8206     Previous.setLookupName(Correction.getCorrection());
8207     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8208                                     CDeclEnd = Correction.end();
8209          CDecl != CDeclEnd; ++CDecl) {
8210       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8211       if (FD && !FD->hasBody() &&
8212           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8213         Previous.addDecl(FD);
8214       }
8215     }
8216     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8217 
8218     NamedDecl *Result;
8219     // Retry building the function declaration with the new previous
8220     // declarations, and with errors suppressed.
8221     {
8222       // Trap errors.
8223       Sema::SFINAETrap Trap(SemaRef);
8224 
8225       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8226       // pieces need to verify the typo-corrected C++ declaration and hopefully
8227       // eliminate the need for the parameter pack ExtraArgs.
8228       Result = SemaRef.ActOnFunctionDeclarator(
8229           ExtraArgs.S, ExtraArgs.D,
8230           Correction.getCorrectionDecl()->getDeclContext(),
8231           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8232           ExtraArgs.AddToScope);
8233 
8234       if (Trap.hasErrorOccurred())
8235         Result = nullptr;
8236     }
8237 
8238     if (Result) {
8239       // Determine which correction we picked.
8240       Decl *Canonical = Result->getCanonicalDecl();
8241       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8242            I != E; ++I)
8243         if ((*I)->getCanonicalDecl() == Canonical)
8244           Correction.setCorrectionDecl(*I);
8245 
8246       // Let Sema know about the correction.
8247       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8248       SemaRef.diagnoseTypo(
8249           Correction,
8250           SemaRef.PDiag(IsLocalFriend
8251                           ? diag::err_no_matching_local_friend_suggest
8252                           : diag::err_member_decl_does_not_match_suggest)
8253             << Name << NewDC << IsDefinition);
8254       return Result;
8255     }
8256 
8257     // Pretend the typo correction never occurred
8258     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8259                               ExtraArgs.D.getIdentifierLoc());
8260     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8261     Previous.clear();
8262     Previous.setLookupName(Name);
8263   }
8264 
8265   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8266       << Name << NewDC << IsDefinition << NewFD->getLocation();
8267 
8268   bool NewFDisConst = false;
8269   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8270     NewFDisConst = NewMD->isConst();
8271 
8272   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8273        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8274        NearMatch != NearMatchEnd; ++NearMatch) {
8275     FunctionDecl *FD = NearMatch->first;
8276     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8277     bool FDisConst = MD && MD->isConst();
8278     bool IsMember = MD || !IsLocalFriend;
8279 
8280     // FIXME: These notes are poorly worded for the local friend case.
8281     if (unsigned Idx = NearMatch->second) {
8282       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8283       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8284       if (Loc.isInvalid()) Loc = FD->getLocation();
8285       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8286                                  : diag::note_local_decl_close_param_match)
8287         << Idx << FDParam->getType()
8288         << NewFD->getParamDecl(Idx - 1)->getType();
8289     } else if (FDisConst != NewFDisConst) {
8290       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8291           << NewFDisConst << FD->getSourceRange().getEnd();
8292     } else
8293       SemaRef.Diag(FD->getLocation(),
8294                    IsMember ? diag::note_member_def_close_match
8295                             : diag::note_local_decl_close_match);
8296   }
8297   return nullptr;
8298 }
8299 
8300 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8301   switch (D.getDeclSpec().getStorageClassSpec()) {
8302   default: llvm_unreachable("Unknown storage class!");
8303   case DeclSpec::SCS_auto:
8304   case DeclSpec::SCS_register:
8305   case DeclSpec::SCS_mutable:
8306     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8307                  diag::err_typecheck_sclass_func);
8308     D.getMutableDeclSpec().ClearStorageClassSpecs();
8309     D.setInvalidType();
8310     break;
8311   case DeclSpec::SCS_unspecified: break;
8312   case DeclSpec::SCS_extern:
8313     if (D.getDeclSpec().isExternInLinkageSpec())
8314       return SC_None;
8315     return SC_Extern;
8316   case DeclSpec::SCS_static: {
8317     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8318       // C99 6.7.1p5:
8319       //   The declaration of an identifier for a function that has
8320       //   block scope shall have no explicit storage-class specifier
8321       //   other than extern
8322       // See also (C++ [dcl.stc]p4).
8323       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8324                    diag::err_static_block_func);
8325       break;
8326     } else
8327       return SC_Static;
8328   }
8329   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8330   }
8331 
8332   // No explicit storage class has already been returned
8333   return SC_None;
8334 }
8335 
8336 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8337                                            DeclContext *DC, QualType &R,
8338                                            TypeSourceInfo *TInfo,
8339                                            StorageClass SC,
8340                                            bool &IsVirtualOkay) {
8341   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8342   DeclarationName Name = NameInfo.getName();
8343 
8344   FunctionDecl *NewFD = nullptr;
8345   bool isInline = D.getDeclSpec().isInlineSpecified();
8346 
8347   if (!SemaRef.getLangOpts().CPlusPlus) {
8348     // Determine whether the function was written with a
8349     // prototype. This true when:
8350     //   - there is a prototype in the declarator, or
8351     //   - the type R of the function is some kind of typedef or other non-
8352     //     attributed reference to a type name (which eventually refers to a
8353     //     function type).
8354     bool HasPrototype =
8355       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8356       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8357 
8358     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8359                                  R, TInfo, SC, isInline, HasPrototype,
8360                                  CSK_unspecified,
8361                                  /*TrailingRequiresClause=*/nullptr);
8362     if (D.isInvalidType())
8363       NewFD->setInvalidDecl();
8364 
8365     return NewFD;
8366   }
8367 
8368   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8369 
8370   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8371   if (ConstexprKind == CSK_constinit) {
8372     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8373                  diag::err_constexpr_wrong_decl_kind)
8374         << ConstexprKind;
8375     ConstexprKind = CSK_unspecified;
8376     D.getMutableDeclSpec().ClearConstexprSpec();
8377   }
8378   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8379 
8380   // Check that the return type is not an abstract class type.
8381   // For record types, this is done by the AbstractClassUsageDiagnoser once
8382   // the class has been completely parsed.
8383   if (!DC->isRecord() &&
8384       SemaRef.RequireNonAbstractType(
8385           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8386           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8387     D.setInvalidType();
8388 
8389   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8390     // This is a C++ constructor declaration.
8391     assert(DC->isRecord() &&
8392            "Constructors can only be declared in a member context");
8393 
8394     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8395     return CXXConstructorDecl::Create(
8396         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8397         TInfo, ExplicitSpecifier, isInline,
8398         /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8399         TrailingRequiresClause);
8400 
8401   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8402     // This is a C++ destructor declaration.
8403     if (DC->isRecord()) {
8404       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8405       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8406       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8407           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8408           isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8409           TrailingRequiresClause);
8410 
8411       // If the destructor needs an implicit exception specification, set it
8412       // now. FIXME: It'd be nice to be able to create the right type to start
8413       // with, but the type needs to reference the destructor declaration.
8414       if (SemaRef.getLangOpts().CPlusPlus11)
8415         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8416 
8417       IsVirtualOkay = true;
8418       return NewDD;
8419 
8420     } else {
8421       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8422       D.setInvalidType();
8423 
8424       // Create a FunctionDecl to satisfy the function definition parsing
8425       // code path.
8426       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8427                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8428                                   isInline,
8429                                   /*hasPrototype=*/true, ConstexprKind,
8430                                   TrailingRequiresClause);
8431     }
8432 
8433   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8434     if (!DC->isRecord()) {
8435       SemaRef.Diag(D.getIdentifierLoc(),
8436            diag::err_conv_function_not_member);
8437       return nullptr;
8438     }
8439 
8440     SemaRef.CheckConversionDeclarator(D, R, SC);
8441     if (D.isInvalidType())
8442       return nullptr;
8443 
8444     IsVirtualOkay = true;
8445     return CXXConversionDecl::Create(
8446         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8447         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8448         TrailingRequiresClause);
8449 
8450   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8451     if (TrailingRequiresClause)
8452       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8453                    diag::err_trailing_requires_clause_on_deduction_guide)
8454           << TrailingRequiresClause->getSourceRange();
8455     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8456 
8457     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8458                                          ExplicitSpecifier, NameInfo, R, TInfo,
8459                                          D.getEndLoc());
8460   } else if (DC->isRecord()) {
8461     // If the name of the function is the same as the name of the record,
8462     // then this must be an invalid constructor that has a return type.
8463     // (The parser checks for a return type and makes the declarator a
8464     // constructor if it has no return type).
8465     if (Name.getAsIdentifierInfo() &&
8466         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8467       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8468         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8469         << SourceRange(D.getIdentifierLoc());
8470       return nullptr;
8471     }
8472 
8473     // This is a C++ method declaration.
8474     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8475         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8476         TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8477         TrailingRequiresClause);
8478     IsVirtualOkay = !Ret->isStatic();
8479     return Ret;
8480   } else {
8481     bool isFriend =
8482         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8483     if (!isFriend && SemaRef.CurContext->isRecord())
8484       return nullptr;
8485 
8486     // Determine whether the function was written with a
8487     // prototype. This true when:
8488     //   - we're in C++ (where every function has a prototype),
8489     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8490                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8491                                 ConstexprKind, TrailingRequiresClause);
8492   }
8493 }
8494 
8495 enum OpenCLParamType {
8496   ValidKernelParam,
8497   PtrPtrKernelParam,
8498   PtrKernelParam,
8499   InvalidAddrSpacePtrKernelParam,
8500   InvalidKernelParam,
8501   RecordKernelParam
8502 };
8503 
8504 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8505   // Size dependent types are just typedefs to normal integer types
8506   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8507   // integers other than by their names.
8508   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8509 
8510   // Remove typedefs one by one until we reach a typedef
8511   // for a size dependent type.
8512   QualType DesugaredTy = Ty;
8513   do {
8514     ArrayRef<StringRef> Names(SizeTypeNames);
8515     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8516     if (Names.end() != Match)
8517       return true;
8518 
8519     Ty = DesugaredTy;
8520     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8521   } while (DesugaredTy != Ty);
8522 
8523   return false;
8524 }
8525 
8526 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8527   if (PT->isPointerType()) {
8528     QualType PointeeType = PT->getPointeeType();
8529     if (PointeeType->isPointerType())
8530       return PtrPtrKernelParam;
8531     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8532         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8533         PointeeType.getAddressSpace() == LangAS::Default)
8534       return InvalidAddrSpacePtrKernelParam;
8535     return PtrKernelParam;
8536   }
8537 
8538   // OpenCL v1.2 s6.9.k:
8539   // Arguments to kernel functions in a program cannot be declared with the
8540   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8541   // uintptr_t or a struct and/or union that contain fields declared to be one
8542   // of these built-in scalar types.
8543   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8544     return InvalidKernelParam;
8545 
8546   if (PT->isImageType())
8547     return PtrKernelParam;
8548 
8549   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8550     return InvalidKernelParam;
8551 
8552   // OpenCL extension spec v1.2 s9.5:
8553   // This extension adds support for half scalar and vector types as built-in
8554   // types that can be used for arithmetic operations, conversions etc.
8555   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8556     return InvalidKernelParam;
8557 
8558   if (PT->isRecordType())
8559     return RecordKernelParam;
8560 
8561   // Look into an array argument to check if it has a forbidden type.
8562   if (PT->isArrayType()) {
8563     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8564     // Call ourself to check an underlying type of an array. Since the
8565     // getPointeeOrArrayElementType returns an innermost type which is not an
8566     // array, this recursive call only happens once.
8567     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8568   }
8569 
8570   return ValidKernelParam;
8571 }
8572 
8573 static void checkIsValidOpenCLKernelParameter(
8574   Sema &S,
8575   Declarator &D,
8576   ParmVarDecl *Param,
8577   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8578   QualType PT = Param->getType();
8579 
8580   // Cache the valid types we encounter to avoid rechecking structs that are
8581   // used again
8582   if (ValidTypes.count(PT.getTypePtr()))
8583     return;
8584 
8585   switch (getOpenCLKernelParameterType(S, PT)) {
8586   case PtrPtrKernelParam:
8587     // OpenCL v1.2 s6.9.a:
8588     // A kernel function argument cannot be declared as a
8589     // pointer to a pointer type.
8590     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8591     D.setInvalidType();
8592     return;
8593 
8594   case InvalidAddrSpacePtrKernelParam:
8595     // OpenCL v1.0 s6.5:
8596     // __kernel function arguments declared to be a pointer of a type can point
8597     // to one of the following address spaces only : __global, __local or
8598     // __constant.
8599     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8600     D.setInvalidType();
8601     return;
8602 
8603     // OpenCL v1.2 s6.9.k:
8604     // Arguments to kernel functions in a program cannot be declared with the
8605     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8606     // uintptr_t or a struct and/or union that contain fields declared to be
8607     // one of these built-in scalar types.
8608 
8609   case InvalidKernelParam:
8610     // OpenCL v1.2 s6.8 n:
8611     // A kernel function argument cannot be declared
8612     // of event_t type.
8613     // Do not diagnose half type since it is diagnosed as invalid argument
8614     // type for any function elsewhere.
8615     if (!PT->isHalfType()) {
8616       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8617 
8618       // Explain what typedefs are involved.
8619       const TypedefType *Typedef = nullptr;
8620       while ((Typedef = PT->getAs<TypedefType>())) {
8621         SourceLocation Loc = Typedef->getDecl()->getLocation();
8622         // SourceLocation may be invalid for a built-in type.
8623         if (Loc.isValid())
8624           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8625         PT = Typedef->desugar();
8626       }
8627     }
8628 
8629     D.setInvalidType();
8630     return;
8631 
8632   case PtrKernelParam:
8633   case ValidKernelParam:
8634     ValidTypes.insert(PT.getTypePtr());
8635     return;
8636 
8637   case RecordKernelParam:
8638     break;
8639   }
8640 
8641   // Track nested structs we will inspect
8642   SmallVector<const Decl *, 4> VisitStack;
8643 
8644   // Track where we are in the nested structs. Items will migrate from
8645   // VisitStack to HistoryStack as we do the DFS for bad field.
8646   SmallVector<const FieldDecl *, 4> HistoryStack;
8647   HistoryStack.push_back(nullptr);
8648 
8649   // At this point we already handled everything except of a RecordType or
8650   // an ArrayType of a RecordType.
8651   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8652   const RecordType *RecTy =
8653       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8654   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8655 
8656   VisitStack.push_back(RecTy->getDecl());
8657   assert(VisitStack.back() && "First decl null?");
8658 
8659   do {
8660     const Decl *Next = VisitStack.pop_back_val();
8661     if (!Next) {
8662       assert(!HistoryStack.empty());
8663       // Found a marker, we have gone up a level
8664       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8665         ValidTypes.insert(Hist->getType().getTypePtr());
8666 
8667       continue;
8668     }
8669 
8670     // Adds everything except the original parameter declaration (which is not a
8671     // field itself) to the history stack.
8672     const RecordDecl *RD;
8673     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8674       HistoryStack.push_back(Field);
8675 
8676       QualType FieldTy = Field->getType();
8677       // Other field types (known to be valid or invalid) are handled while we
8678       // walk around RecordDecl::fields().
8679       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8680              "Unexpected type.");
8681       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8682 
8683       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8684     } else {
8685       RD = cast<RecordDecl>(Next);
8686     }
8687 
8688     // Add a null marker so we know when we've gone back up a level
8689     VisitStack.push_back(nullptr);
8690 
8691     for (const auto *FD : RD->fields()) {
8692       QualType QT = FD->getType();
8693 
8694       if (ValidTypes.count(QT.getTypePtr()))
8695         continue;
8696 
8697       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8698       if (ParamType == ValidKernelParam)
8699         continue;
8700 
8701       if (ParamType == RecordKernelParam) {
8702         VisitStack.push_back(FD);
8703         continue;
8704       }
8705 
8706       // OpenCL v1.2 s6.9.p:
8707       // Arguments to kernel functions that are declared to be a struct or union
8708       // do not allow OpenCL objects to be passed as elements of the struct or
8709       // union.
8710       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8711           ParamType == InvalidAddrSpacePtrKernelParam) {
8712         S.Diag(Param->getLocation(),
8713                diag::err_record_with_pointers_kernel_param)
8714           << PT->isUnionType()
8715           << PT;
8716       } else {
8717         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8718       }
8719 
8720       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8721           << OrigRecDecl->getDeclName();
8722 
8723       // We have an error, now let's go back up through history and show where
8724       // the offending field came from
8725       for (ArrayRef<const FieldDecl *>::const_iterator
8726                I = HistoryStack.begin() + 1,
8727                E = HistoryStack.end();
8728            I != E; ++I) {
8729         const FieldDecl *OuterField = *I;
8730         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8731           << OuterField->getType();
8732       }
8733 
8734       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8735         << QT->isPointerType()
8736         << QT;
8737       D.setInvalidType();
8738       return;
8739     }
8740   } while (!VisitStack.empty());
8741 }
8742 
8743 /// Find the DeclContext in which a tag is implicitly declared if we see an
8744 /// elaborated type specifier in the specified context, and lookup finds
8745 /// nothing.
8746 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8747   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8748     DC = DC->getParent();
8749   return DC;
8750 }
8751 
8752 /// Find the Scope in which a tag is implicitly declared if we see an
8753 /// elaborated type specifier in the specified context, and lookup finds
8754 /// nothing.
8755 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8756   while (S->isClassScope() ||
8757          (LangOpts.CPlusPlus &&
8758           S->isFunctionPrototypeScope()) ||
8759          ((S->getFlags() & Scope::DeclScope) == 0) ||
8760          (S->getEntity() && S->getEntity()->isTransparentContext()))
8761     S = S->getParent();
8762   return S;
8763 }
8764 
8765 NamedDecl*
8766 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8767                               TypeSourceInfo *TInfo, LookupResult &Previous,
8768                               MultiTemplateParamsArg TemplateParamListsRef,
8769                               bool &AddToScope) {
8770   QualType R = TInfo->getType();
8771 
8772   assert(R->isFunctionType());
8773   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8774     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8775 
8776   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8777   for (TemplateParameterList *TPL : TemplateParamListsRef)
8778     TemplateParamLists.push_back(TPL);
8779   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8780     if (!TemplateParamLists.empty() &&
8781         Invented->getDepth() == TemplateParamLists.back()->getDepth())
8782       TemplateParamLists.back() = Invented;
8783     else
8784       TemplateParamLists.push_back(Invented);
8785   }
8786 
8787   // TODO: consider using NameInfo for diagnostic.
8788   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8789   DeclarationName Name = NameInfo.getName();
8790   StorageClass SC = getFunctionStorageClass(*this, D);
8791 
8792   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8793     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8794          diag::err_invalid_thread)
8795       << DeclSpec::getSpecifierName(TSCS);
8796 
8797   if (D.isFirstDeclarationOfMember())
8798     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8799                            D.getIdentifierLoc());
8800 
8801   bool isFriend = false;
8802   FunctionTemplateDecl *FunctionTemplate = nullptr;
8803   bool isMemberSpecialization = false;
8804   bool isFunctionTemplateSpecialization = false;
8805 
8806   bool isDependentClassScopeExplicitSpecialization = false;
8807   bool HasExplicitTemplateArgs = false;
8808   TemplateArgumentListInfo TemplateArgs;
8809 
8810   bool isVirtualOkay = false;
8811 
8812   DeclContext *OriginalDC = DC;
8813   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8814 
8815   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8816                                               isVirtualOkay);
8817   if (!NewFD) return nullptr;
8818 
8819   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8820     NewFD->setTopLevelDeclInObjCContainer();
8821 
8822   // Set the lexical context. If this is a function-scope declaration, or has a
8823   // C++ scope specifier, or is the object of a friend declaration, the lexical
8824   // context will be different from the semantic context.
8825   NewFD->setLexicalDeclContext(CurContext);
8826 
8827   if (IsLocalExternDecl)
8828     NewFD->setLocalExternDecl();
8829 
8830   if (getLangOpts().CPlusPlus) {
8831     bool isInline = D.getDeclSpec().isInlineSpecified();
8832     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8833     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8834     isFriend = D.getDeclSpec().isFriendSpecified();
8835     if (isFriend && !isInline && D.isFunctionDefinition()) {
8836       // C++ [class.friend]p5
8837       //   A function can be defined in a friend declaration of a
8838       //   class . . . . Such a function is implicitly inline.
8839       NewFD->setImplicitlyInline();
8840     }
8841 
8842     // If this is a method defined in an __interface, and is not a constructor
8843     // or an overloaded operator, then set the pure flag (isVirtual will already
8844     // return true).
8845     if (const CXXRecordDecl *Parent =
8846           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8847       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8848         NewFD->setPure(true);
8849 
8850       // C++ [class.union]p2
8851       //   A union can have member functions, but not virtual functions.
8852       if (isVirtual && Parent->isUnion())
8853         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8854     }
8855 
8856     SetNestedNameSpecifier(*this, NewFD, D);
8857     isMemberSpecialization = false;
8858     isFunctionTemplateSpecialization = false;
8859     if (D.isInvalidType())
8860       NewFD->setInvalidDecl();
8861 
8862     // Match up the template parameter lists with the scope specifier, then
8863     // determine whether we have a template or a template specialization.
8864     bool Invalid = false;
8865     TemplateParameterList *TemplateParams =
8866         MatchTemplateParametersToScopeSpecifier(
8867             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8868             D.getCXXScopeSpec(),
8869             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8870                 ? D.getName().TemplateId
8871                 : nullptr,
8872             TemplateParamLists, isFriend, isMemberSpecialization,
8873             Invalid);
8874     if (TemplateParams) {
8875       if (TemplateParams->size() > 0) {
8876         // This is a function template
8877 
8878         // Check that we can declare a template here.
8879         if (CheckTemplateDeclScope(S, TemplateParams))
8880           NewFD->setInvalidDecl();
8881 
8882         // A destructor cannot be a template.
8883         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8884           Diag(NewFD->getLocation(), diag::err_destructor_template);
8885           NewFD->setInvalidDecl();
8886         }
8887 
8888         // If we're adding a template to a dependent context, we may need to
8889         // rebuilding some of the types used within the template parameter list,
8890         // now that we know what the current instantiation is.
8891         if (DC->isDependentContext()) {
8892           ContextRAII SavedContext(*this, DC);
8893           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8894             Invalid = true;
8895         }
8896 
8897         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8898                                                         NewFD->getLocation(),
8899                                                         Name, TemplateParams,
8900                                                         NewFD);
8901         FunctionTemplate->setLexicalDeclContext(CurContext);
8902         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8903 
8904         // For source fidelity, store the other template param lists.
8905         if (TemplateParamLists.size() > 1) {
8906           NewFD->setTemplateParameterListsInfo(Context,
8907               ArrayRef<TemplateParameterList *>(TemplateParamLists)
8908                   .drop_back(1));
8909         }
8910       } else {
8911         // This is a function template specialization.
8912         isFunctionTemplateSpecialization = true;
8913         // For source fidelity, store all the template param lists.
8914         if (TemplateParamLists.size() > 0)
8915           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8916 
8917         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8918         if (isFriend) {
8919           // We want to remove the "template<>", found here.
8920           SourceRange RemoveRange = TemplateParams->getSourceRange();
8921 
8922           // If we remove the template<> and the name is not a
8923           // template-id, we're actually silently creating a problem:
8924           // the friend declaration will refer to an untemplated decl,
8925           // and clearly the user wants a template specialization.  So
8926           // we need to insert '<>' after the name.
8927           SourceLocation InsertLoc;
8928           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8929             InsertLoc = D.getName().getSourceRange().getEnd();
8930             InsertLoc = getLocForEndOfToken(InsertLoc);
8931           }
8932 
8933           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8934             << Name << RemoveRange
8935             << FixItHint::CreateRemoval(RemoveRange)
8936             << FixItHint::CreateInsertion(InsertLoc, "<>");
8937         }
8938       }
8939     } else {
8940       // All template param lists were matched against the scope specifier:
8941       // this is NOT (an explicit specialization of) a template.
8942       if (TemplateParamLists.size() > 0)
8943         // For source fidelity, store all the template param lists.
8944         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8945     }
8946 
8947     if (Invalid) {
8948       NewFD->setInvalidDecl();
8949       if (FunctionTemplate)
8950         FunctionTemplate->setInvalidDecl();
8951     }
8952 
8953     // C++ [dcl.fct.spec]p5:
8954     //   The virtual specifier shall only be used in declarations of
8955     //   nonstatic class member functions that appear within a
8956     //   member-specification of a class declaration; see 10.3.
8957     //
8958     if (isVirtual && !NewFD->isInvalidDecl()) {
8959       if (!isVirtualOkay) {
8960         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8961              diag::err_virtual_non_function);
8962       } else if (!CurContext->isRecord()) {
8963         // 'virtual' was specified outside of the class.
8964         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8965              diag::err_virtual_out_of_class)
8966           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8967       } else if (NewFD->getDescribedFunctionTemplate()) {
8968         // C++ [temp.mem]p3:
8969         //  A member function template shall not be virtual.
8970         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8971              diag::err_virtual_member_function_template)
8972           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8973       } else {
8974         // Okay: Add virtual to the method.
8975         NewFD->setVirtualAsWritten(true);
8976       }
8977 
8978       if (getLangOpts().CPlusPlus14 &&
8979           NewFD->getReturnType()->isUndeducedType())
8980         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8981     }
8982 
8983     if (getLangOpts().CPlusPlus14 &&
8984         (NewFD->isDependentContext() ||
8985          (isFriend && CurContext->isDependentContext())) &&
8986         NewFD->getReturnType()->isUndeducedType()) {
8987       // If the function template is referenced directly (for instance, as a
8988       // member of the current instantiation), pretend it has a dependent type.
8989       // This is not really justified by the standard, but is the only sane
8990       // thing to do.
8991       // FIXME: For a friend function, we have not marked the function as being
8992       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8993       const FunctionProtoType *FPT =
8994           NewFD->getType()->castAs<FunctionProtoType>();
8995       QualType Result =
8996           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8997       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8998                                              FPT->getExtProtoInfo()));
8999     }
9000 
9001     // C++ [dcl.fct.spec]p3:
9002     //  The inline specifier shall not appear on a block scope function
9003     //  declaration.
9004     if (isInline && !NewFD->isInvalidDecl()) {
9005       if (CurContext->isFunctionOrMethod()) {
9006         // 'inline' is not allowed on block scope function declaration.
9007         Diag(D.getDeclSpec().getInlineSpecLoc(),
9008              diag::err_inline_declaration_block_scope) << Name
9009           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9010       }
9011     }
9012 
9013     // C++ [dcl.fct.spec]p6:
9014     //  The explicit specifier shall be used only in the declaration of a
9015     //  constructor or conversion function within its class definition;
9016     //  see 12.3.1 and 12.3.2.
9017     if (hasExplicit && !NewFD->isInvalidDecl() &&
9018         !isa<CXXDeductionGuideDecl>(NewFD)) {
9019       if (!CurContext->isRecord()) {
9020         // 'explicit' was specified outside of the class.
9021         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9022              diag::err_explicit_out_of_class)
9023             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9024       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9025                  !isa<CXXConversionDecl>(NewFD)) {
9026         // 'explicit' was specified on a function that wasn't a constructor
9027         // or conversion function.
9028         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9029              diag::err_explicit_non_ctor_or_conv_function)
9030             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9031       }
9032     }
9033 
9034     if (ConstexprSpecKind ConstexprKind =
9035             D.getDeclSpec().getConstexprSpecifier()) {
9036       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9037       // are implicitly inline.
9038       NewFD->setImplicitlyInline();
9039 
9040       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9041       // be either constructors or to return a literal type. Therefore,
9042       // destructors cannot be declared constexpr.
9043       if (isa<CXXDestructorDecl>(NewFD) &&
9044           (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9045         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9046             << ConstexprKind;
9047         NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9048       }
9049       // C++20 [dcl.constexpr]p2: An allocation function, or a
9050       // deallocation function shall not be declared with the consteval
9051       // specifier.
9052       if (ConstexprKind == CSK_consteval &&
9053           (NewFD->getOverloadedOperator() == OO_New ||
9054            NewFD->getOverloadedOperator() == OO_Array_New ||
9055            NewFD->getOverloadedOperator() == OO_Delete ||
9056            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9057         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9058              diag::err_invalid_consteval_decl_kind)
9059             << NewFD;
9060         NewFD->setConstexprKind(CSK_constexpr);
9061       }
9062     }
9063 
9064     // If __module_private__ was specified, mark the function accordingly.
9065     if (D.getDeclSpec().isModulePrivateSpecified()) {
9066       if (isFunctionTemplateSpecialization) {
9067         SourceLocation ModulePrivateLoc
9068           = D.getDeclSpec().getModulePrivateSpecLoc();
9069         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9070           << 0
9071           << FixItHint::CreateRemoval(ModulePrivateLoc);
9072       } else {
9073         NewFD->setModulePrivate();
9074         if (FunctionTemplate)
9075           FunctionTemplate->setModulePrivate();
9076       }
9077     }
9078 
9079     if (isFriend) {
9080       if (FunctionTemplate) {
9081         FunctionTemplate->setObjectOfFriendDecl();
9082         FunctionTemplate->setAccess(AS_public);
9083       }
9084       NewFD->setObjectOfFriendDecl();
9085       NewFD->setAccess(AS_public);
9086     }
9087 
9088     // If a function is defined as defaulted or deleted, mark it as such now.
9089     // We'll do the relevant checks on defaulted / deleted functions later.
9090     switch (D.getFunctionDefinitionKind()) {
9091       case FDK_Declaration:
9092       case FDK_Definition:
9093         break;
9094 
9095       case FDK_Defaulted:
9096         NewFD->setDefaulted();
9097         break;
9098 
9099       case FDK_Deleted:
9100         NewFD->setDeletedAsWritten();
9101         break;
9102     }
9103 
9104     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9105         D.isFunctionDefinition()) {
9106       // C++ [class.mfct]p2:
9107       //   A member function may be defined (8.4) in its class definition, in
9108       //   which case it is an inline member function (7.1.2)
9109       NewFD->setImplicitlyInline();
9110     }
9111 
9112     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9113         !CurContext->isRecord()) {
9114       // C++ [class.static]p1:
9115       //   A data or function member of a class may be declared static
9116       //   in a class definition, in which case it is a static member of
9117       //   the class.
9118 
9119       // Complain about the 'static' specifier if it's on an out-of-line
9120       // member function definition.
9121 
9122       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9123       // member function template declaration and class member template
9124       // declaration (MSVC versions before 2015), warn about this.
9125       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9126            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9127              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9128            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9129            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9130         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9131     }
9132 
9133     // C++11 [except.spec]p15:
9134     //   A deallocation function with no exception-specification is treated
9135     //   as if it were specified with noexcept(true).
9136     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9137     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9138          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9139         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9140       NewFD->setType(Context.getFunctionType(
9141           FPT->getReturnType(), FPT->getParamTypes(),
9142           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9143   }
9144 
9145   // Filter out previous declarations that don't match the scope.
9146   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9147                        D.getCXXScopeSpec().isNotEmpty() ||
9148                        isMemberSpecialization ||
9149                        isFunctionTemplateSpecialization);
9150 
9151   // Handle GNU asm-label extension (encoded as an attribute).
9152   if (Expr *E = (Expr*) D.getAsmLabel()) {
9153     // The parser guarantees this is a string.
9154     StringLiteral *SE = cast<StringLiteral>(E);
9155     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9156                                         /*IsLiteralLabel=*/true,
9157                                         SE->getStrTokenLoc(0)));
9158   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9159     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9160       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9161     if (I != ExtnameUndeclaredIdentifiers.end()) {
9162       if (isDeclExternC(NewFD)) {
9163         NewFD->addAttr(I->second);
9164         ExtnameUndeclaredIdentifiers.erase(I);
9165       } else
9166         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9167             << /*Variable*/0 << NewFD;
9168     }
9169   }
9170 
9171   // Copy the parameter declarations from the declarator D to the function
9172   // declaration NewFD, if they are available.  First scavenge them into Params.
9173   SmallVector<ParmVarDecl*, 16> Params;
9174   unsigned FTIIdx;
9175   if (D.isFunctionDeclarator(FTIIdx)) {
9176     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9177 
9178     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9179     // function that takes no arguments, not a function that takes a
9180     // single void argument.
9181     // We let through "const void" here because Sema::GetTypeForDeclarator
9182     // already checks for that case.
9183     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9184       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9185         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9186         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9187         Param->setDeclContext(NewFD);
9188         Params.push_back(Param);
9189 
9190         if (Param->isInvalidDecl())
9191           NewFD->setInvalidDecl();
9192       }
9193     }
9194 
9195     if (!getLangOpts().CPlusPlus) {
9196       // In C, find all the tag declarations from the prototype and move them
9197       // into the function DeclContext. Remove them from the surrounding tag
9198       // injection context of the function, which is typically but not always
9199       // the TU.
9200       DeclContext *PrototypeTagContext =
9201           getTagInjectionContext(NewFD->getLexicalDeclContext());
9202       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9203         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9204 
9205         // We don't want to reparent enumerators. Look at their parent enum
9206         // instead.
9207         if (!TD) {
9208           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9209             TD = cast<EnumDecl>(ECD->getDeclContext());
9210         }
9211         if (!TD)
9212           continue;
9213         DeclContext *TagDC = TD->getLexicalDeclContext();
9214         if (!TagDC->containsDecl(TD))
9215           continue;
9216         TagDC->removeDecl(TD);
9217         TD->setDeclContext(NewFD);
9218         NewFD->addDecl(TD);
9219 
9220         // Preserve the lexical DeclContext if it is not the surrounding tag
9221         // injection context of the FD. In this example, the semantic context of
9222         // E will be f and the lexical context will be S, while both the
9223         // semantic and lexical contexts of S will be f:
9224         //   void f(struct S { enum E { a } f; } s);
9225         if (TagDC != PrototypeTagContext)
9226           TD->setLexicalDeclContext(TagDC);
9227       }
9228     }
9229   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9230     // When we're declaring a function with a typedef, typeof, etc as in the
9231     // following example, we'll need to synthesize (unnamed)
9232     // parameters for use in the declaration.
9233     //
9234     // @code
9235     // typedef void fn(int);
9236     // fn f;
9237     // @endcode
9238 
9239     // Synthesize a parameter for each argument type.
9240     for (const auto &AI : FT->param_types()) {
9241       ParmVarDecl *Param =
9242           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9243       Param->setScopeInfo(0, Params.size());
9244       Params.push_back(Param);
9245     }
9246   } else {
9247     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9248            "Should not need args for typedef of non-prototype fn");
9249   }
9250 
9251   // Finally, we know we have the right number of parameters, install them.
9252   NewFD->setParams(Params);
9253 
9254   if (D.getDeclSpec().isNoreturnSpecified())
9255     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9256                                            D.getDeclSpec().getNoreturnSpecLoc(),
9257                                            AttributeCommonInfo::AS_Keyword));
9258 
9259   // Functions returning a variably modified type violate C99 6.7.5.2p2
9260   // because all functions have linkage.
9261   if (!NewFD->isInvalidDecl() &&
9262       NewFD->getReturnType()->isVariablyModifiedType()) {
9263     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9264     NewFD->setInvalidDecl();
9265   }
9266 
9267   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9268   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9269       !NewFD->hasAttr<SectionAttr>())
9270     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9271         Context, PragmaClangTextSection.SectionName,
9272         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9273 
9274   // Apply an implicit SectionAttr if #pragma code_seg is active.
9275   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9276       !NewFD->hasAttr<SectionAttr>()) {
9277     NewFD->addAttr(SectionAttr::CreateImplicit(
9278         Context, CodeSegStack.CurrentValue->getString(),
9279         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9280         SectionAttr::Declspec_allocate));
9281     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9282                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9283                          ASTContext::PSF_Read,
9284                      NewFD))
9285       NewFD->dropAttr<SectionAttr>();
9286   }
9287 
9288   // Apply an implicit CodeSegAttr from class declspec or
9289   // apply an implicit SectionAttr from #pragma code_seg if active.
9290   if (!NewFD->hasAttr<CodeSegAttr>()) {
9291     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9292                                                                  D.isFunctionDefinition())) {
9293       NewFD->addAttr(SAttr);
9294     }
9295   }
9296 
9297   // Handle attributes.
9298   ProcessDeclAttributes(S, NewFD, D);
9299 
9300   if (getLangOpts().OpenCL) {
9301     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9302     // type declaration will generate a compilation error.
9303     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9304     if (AddressSpace != LangAS::Default) {
9305       Diag(NewFD->getLocation(),
9306            diag::err_opencl_return_value_with_address_space);
9307       NewFD->setInvalidDecl();
9308     }
9309   }
9310 
9311   if (!getLangOpts().CPlusPlus) {
9312     // Perform semantic checking on the function declaration.
9313     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9314       CheckMain(NewFD, D.getDeclSpec());
9315 
9316     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9317       CheckMSVCRTEntryPoint(NewFD);
9318 
9319     if (!NewFD->isInvalidDecl())
9320       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9321                                                   isMemberSpecialization));
9322     else if (!Previous.empty())
9323       // Recover gracefully from an invalid redeclaration.
9324       D.setRedeclaration(true);
9325     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9326             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9327            "previous declaration set still overloaded");
9328 
9329     // Diagnose no-prototype function declarations with calling conventions that
9330     // don't support variadic calls. Only do this in C and do it after merging
9331     // possibly prototyped redeclarations.
9332     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9333     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9334       CallingConv CC = FT->getExtInfo().getCC();
9335       if (!supportsVariadicCall(CC)) {
9336         // Windows system headers sometimes accidentally use stdcall without
9337         // (void) parameters, so we relax this to a warning.
9338         int DiagID =
9339             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9340         Diag(NewFD->getLocation(), DiagID)
9341             << FunctionType::getNameForCallConv(CC);
9342       }
9343     }
9344 
9345    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9346        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9347      checkNonTrivialCUnion(NewFD->getReturnType(),
9348                            NewFD->getReturnTypeSourceRange().getBegin(),
9349                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9350   } else {
9351     // C++11 [replacement.functions]p3:
9352     //  The program's definitions shall not be specified as inline.
9353     //
9354     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9355     //
9356     // Suppress the diagnostic if the function is __attribute__((used)), since
9357     // that forces an external definition to be emitted.
9358     if (D.getDeclSpec().isInlineSpecified() &&
9359         NewFD->isReplaceableGlobalAllocationFunction() &&
9360         !NewFD->hasAttr<UsedAttr>())
9361       Diag(D.getDeclSpec().getInlineSpecLoc(),
9362            diag::ext_operator_new_delete_declared_inline)
9363         << NewFD->getDeclName();
9364 
9365     // If the declarator is a template-id, translate the parser's template
9366     // argument list into our AST format.
9367     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9368       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9369       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9370       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9371       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9372                                          TemplateId->NumArgs);
9373       translateTemplateArguments(TemplateArgsPtr,
9374                                  TemplateArgs);
9375 
9376       HasExplicitTemplateArgs = true;
9377 
9378       if (NewFD->isInvalidDecl()) {
9379         HasExplicitTemplateArgs = false;
9380       } else if (FunctionTemplate) {
9381         // Function template with explicit template arguments.
9382         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9383           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9384 
9385         HasExplicitTemplateArgs = false;
9386       } else {
9387         assert((isFunctionTemplateSpecialization ||
9388                 D.getDeclSpec().isFriendSpecified()) &&
9389                "should have a 'template<>' for this decl");
9390         // "friend void foo<>(int);" is an implicit specialization decl.
9391         isFunctionTemplateSpecialization = true;
9392       }
9393     } else if (isFriend && isFunctionTemplateSpecialization) {
9394       // This combination is only possible in a recovery case;  the user
9395       // wrote something like:
9396       //   template <> friend void foo(int);
9397       // which we're recovering from as if the user had written:
9398       //   friend void foo<>(int);
9399       // Go ahead and fake up a template id.
9400       HasExplicitTemplateArgs = true;
9401       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9402       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9403     }
9404 
9405     // We do not add HD attributes to specializations here because
9406     // they may have different constexpr-ness compared to their
9407     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9408     // may end up with different effective targets. Instead, a
9409     // specialization inherits its target attributes from its template
9410     // in the CheckFunctionTemplateSpecialization() call below.
9411     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9412       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9413 
9414     // If it's a friend (and only if it's a friend), it's possible
9415     // that either the specialized function type or the specialized
9416     // template is dependent, and therefore matching will fail.  In
9417     // this case, don't check the specialization yet.
9418     bool InstantiationDependent = false;
9419     if (isFunctionTemplateSpecialization && isFriend &&
9420         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9421          TemplateSpecializationType::anyDependentTemplateArguments(
9422             TemplateArgs,
9423             InstantiationDependent))) {
9424       assert(HasExplicitTemplateArgs &&
9425              "friend function specialization without template args");
9426       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9427                                                        Previous))
9428         NewFD->setInvalidDecl();
9429     } else if (isFunctionTemplateSpecialization) {
9430       if (CurContext->isDependentContext() && CurContext->isRecord()
9431           && !isFriend) {
9432         isDependentClassScopeExplicitSpecialization = true;
9433       } else if (!NewFD->isInvalidDecl() &&
9434                  CheckFunctionTemplateSpecialization(
9435                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9436                      Previous))
9437         NewFD->setInvalidDecl();
9438 
9439       // C++ [dcl.stc]p1:
9440       //   A storage-class-specifier shall not be specified in an explicit
9441       //   specialization (14.7.3)
9442       FunctionTemplateSpecializationInfo *Info =
9443           NewFD->getTemplateSpecializationInfo();
9444       if (Info && SC != SC_None) {
9445         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9446           Diag(NewFD->getLocation(),
9447                diag::err_explicit_specialization_inconsistent_storage_class)
9448             << SC
9449             << FixItHint::CreateRemoval(
9450                                       D.getDeclSpec().getStorageClassSpecLoc());
9451 
9452         else
9453           Diag(NewFD->getLocation(),
9454                diag::ext_explicit_specialization_storage_class)
9455             << FixItHint::CreateRemoval(
9456                                       D.getDeclSpec().getStorageClassSpecLoc());
9457       }
9458     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9459       if (CheckMemberSpecialization(NewFD, Previous))
9460           NewFD->setInvalidDecl();
9461     }
9462 
9463     // Perform semantic checking on the function declaration.
9464     if (!isDependentClassScopeExplicitSpecialization) {
9465       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9466         CheckMain(NewFD, D.getDeclSpec());
9467 
9468       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9469         CheckMSVCRTEntryPoint(NewFD);
9470 
9471       if (!NewFD->isInvalidDecl())
9472         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9473                                                     isMemberSpecialization));
9474       else if (!Previous.empty())
9475         // Recover gracefully from an invalid redeclaration.
9476         D.setRedeclaration(true);
9477     }
9478 
9479     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9480             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9481            "previous declaration set still overloaded");
9482 
9483     NamedDecl *PrincipalDecl = (FunctionTemplate
9484                                 ? cast<NamedDecl>(FunctionTemplate)
9485                                 : NewFD);
9486 
9487     if (isFriend && NewFD->getPreviousDecl()) {
9488       AccessSpecifier Access = AS_public;
9489       if (!NewFD->isInvalidDecl())
9490         Access = NewFD->getPreviousDecl()->getAccess();
9491 
9492       NewFD->setAccess(Access);
9493       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9494     }
9495 
9496     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9497         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9498       PrincipalDecl->setNonMemberOperator();
9499 
9500     // If we have a function template, check the template parameter
9501     // list. This will check and merge default template arguments.
9502     if (FunctionTemplate) {
9503       FunctionTemplateDecl *PrevTemplate =
9504                                      FunctionTemplate->getPreviousDecl();
9505       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9506                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9507                                     : nullptr,
9508                             D.getDeclSpec().isFriendSpecified()
9509                               ? (D.isFunctionDefinition()
9510                                    ? TPC_FriendFunctionTemplateDefinition
9511                                    : TPC_FriendFunctionTemplate)
9512                               : (D.getCXXScopeSpec().isSet() &&
9513                                  DC && DC->isRecord() &&
9514                                  DC->isDependentContext())
9515                                   ? TPC_ClassTemplateMember
9516                                   : TPC_FunctionTemplate);
9517     }
9518 
9519     if (NewFD->isInvalidDecl()) {
9520       // Ignore all the rest of this.
9521     } else if (!D.isRedeclaration()) {
9522       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9523                                        AddToScope };
9524       // Fake up an access specifier if it's supposed to be a class member.
9525       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9526         NewFD->setAccess(AS_public);
9527 
9528       // Qualified decls generally require a previous declaration.
9529       if (D.getCXXScopeSpec().isSet()) {
9530         // ...with the major exception of templated-scope or
9531         // dependent-scope friend declarations.
9532 
9533         // TODO: we currently also suppress this check in dependent
9534         // contexts because (1) the parameter depth will be off when
9535         // matching friend templates and (2) we might actually be
9536         // selecting a friend based on a dependent factor.  But there
9537         // are situations where these conditions don't apply and we
9538         // can actually do this check immediately.
9539         //
9540         // Unless the scope is dependent, it's always an error if qualified
9541         // redeclaration lookup found nothing at all. Diagnose that now;
9542         // nothing will diagnose that error later.
9543         if (isFriend &&
9544             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9545              (!Previous.empty() && CurContext->isDependentContext()))) {
9546           // ignore these
9547         } else {
9548           // The user tried to provide an out-of-line definition for a
9549           // function that is a member of a class or namespace, but there
9550           // was no such member function declared (C++ [class.mfct]p2,
9551           // C++ [namespace.memdef]p2). For example:
9552           //
9553           // class X {
9554           //   void f() const;
9555           // };
9556           //
9557           // void X::f() { } // ill-formed
9558           //
9559           // Complain about this problem, and attempt to suggest close
9560           // matches (e.g., those that differ only in cv-qualifiers and
9561           // whether the parameter types are references).
9562 
9563           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9564                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9565             AddToScope = ExtraArgs.AddToScope;
9566             return Result;
9567           }
9568         }
9569 
9570         // Unqualified local friend declarations are required to resolve
9571         // to something.
9572       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9573         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9574                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9575           AddToScope = ExtraArgs.AddToScope;
9576           return Result;
9577         }
9578       }
9579     } else if (!D.isFunctionDefinition() &&
9580                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9581                !isFriend && !isFunctionTemplateSpecialization &&
9582                !isMemberSpecialization) {
9583       // An out-of-line member function declaration must also be a
9584       // definition (C++ [class.mfct]p2).
9585       // Note that this is not the case for explicit specializations of
9586       // function templates or member functions of class templates, per
9587       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9588       // extension for compatibility with old SWIG code which likes to
9589       // generate them.
9590       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9591         << D.getCXXScopeSpec().getRange();
9592     }
9593   }
9594 
9595   ProcessPragmaWeak(S, NewFD);
9596   checkAttributesAfterMerging(*this, *NewFD);
9597 
9598   AddKnownFunctionAttributes(NewFD);
9599 
9600   if (NewFD->hasAttr<OverloadableAttr>() &&
9601       !NewFD->getType()->getAs<FunctionProtoType>()) {
9602     Diag(NewFD->getLocation(),
9603          diag::err_attribute_overloadable_no_prototype)
9604       << NewFD;
9605 
9606     // Turn this into a variadic function with no parameters.
9607     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9608     FunctionProtoType::ExtProtoInfo EPI(
9609         Context.getDefaultCallingConvention(true, false));
9610     EPI.Variadic = true;
9611     EPI.ExtInfo = FT->getExtInfo();
9612 
9613     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9614     NewFD->setType(R);
9615   }
9616 
9617   // If there's a #pragma GCC visibility in scope, and this isn't a class
9618   // member, set the visibility of this function.
9619   if (!DC->isRecord() && NewFD->isExternallyVisible())
9620     AddPushedVisibilityAttribute(NewFD);
9621 
9622   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9623   // marking the function.
9624   AddCFAuditedAttribute(NewFD);
9625 
9626   // If this is a function definition, check if we have to apply optnone due to
9627   // a pragma.
9628   if(D.isFunctionDefinition())
9629     AddRangeBasedOptnone(NewFD);
9630 
9631   // If this is the first declaration of an extern C variable, update
9632   // the map of such variables.
9633   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9634       isIncompleteDeclExternC(*this, NewFD))
9635     RegisterLocallyScopedExternCDecl(NewFD, S);
9636 
9637   // Set this FunctionDecl's range up to the right paren.
9638   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9639 
9640   if (D.isRedeclaration() && !Previous.empty()) {
9641     NamedDecl *Prev = Previous.getRepresentativeDecl();
9642     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9643                                    isMemberSpecialization ||
9644                                        isFunctionTemplateSpecialization,
9645                                    D.isFunctionDefinition());
9646   }
9647 
9648   if (getLangOpts().CUDA) {
9649     IdentifierInfo *II = NewFD->getIdentifier();
9650     if (II && II->isStr(getCudaConfigureFuncName()) &&
9651         !NewFD->isInvalidDecl() &&
9652         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9653       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9654         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9655             << getCudaConfigureFuncName();
9656       Context.setcudaConfigureCallDecl(NewFD);
9657     }
9658 
9659     // Variadic functions, other than a *declaration* of printf, are not allowed
9660     // in device-side CUDA code, unless someone passed
9661     // -fcuda-allow-variadic-functions.
9662     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9663         (NewFD->hasAttr<CUDADeviceAttr>() ||
9664          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9665         !(II && II->isStr("printf") && NewFD->isExternC() &&
9666           !D.isFunctionDefinition())) {
9667       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9668     }
9669   }
9670 
9671   MarkUnusedFileScopedDecl(NewFD);
9672 
9673 
9674 
9675   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9676     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9677     if ((getLangOpts().OpenCLVersion >= 120)
9678         && (SC == SC_Static)) {
9679       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9680       D.setInvalidType();
9681     }
9682 
9683     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9684     if (!NewFD->getReturnType()->isVoidType()) {
9685       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9686       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9687           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9688                                 : FixItHint());
9689       D.setInvalidType();
9690     }
9691 
9692     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9693     for (auto Param : NewFD->parameters())
9694       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9695 
9696     if (getLangOpts().OpenCLCPlusPlus) {
9697       if (DC->isRecord()) {
9698         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9699         D.setInvalidType();
9700       }
9701       if (FunctionTemplate) {
9702         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9703         D.setInvalidType();
9704       }
9705     }
9706   }
9707 
9708   if (getLangOpts().CPlusPlus) {
9709     if (FunctionTemplate) {
9710       if (NewFD->isInvalidDecl())
9711         FunctionTemplate->setInvalidDecl();
9712       return FunctionTemplate;
9713     }
9714 
9715     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9716       CompleteMemberSpecialization(NewFD, Previous);
9717   }
9718 
9719   for (const ParmVarDecl *Param : NewFD->parameters()) {
9720     QualType PT = Param->getType();
9721 
9722     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9723     // types.
9724     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9725       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9726         QualType ElemTy = PipeTy->getElementType();
9727           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9728             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9729             D.setInvalidType();
9730           }
9731       }
9732     }
9733   }
9734 
9735   // Here we have an function template explicit specialization at class scope.
9736   // The actual specialization will be postponed to template instatiation
9737   // time via the ClassScopeFunctionSpecializationDecl node.
9738   if (isDependentClassScopeExplicitSpecialization) {
9739     ClassScopeFunctionSpecializationDecl *NewSpec =
9740                          ClassScopeFunctionSpecializationDecl::Create(
9741                                 Context, CurContext, NewFD->getLocation(),
9742                                 cast<CXXMethodDecl>(NewFD),
9743                                 HasExplicitTemplateArgs, TemplateArgs);
9744     CurContext->addDecl(NewSpec);
9745     AddToScope = false;
9746   }
9747 
9748   // Diagnose availability attributes. Availability cannot be used on functions
9749   // that are run during load/unload.
9750   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9751     if (NewFD->hasAttr<ConstructorAttr>()) {
9752       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9753           << 1;
9754       NewFD->dropAttr<AvailabilityAttr>();
9755     }
9756     if (NewFD->hasAttr<DestructorAttr>()) {
9757       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9758           << 2;
9759       NewFD->dropAttr<AvailabilityAttr>();
9760     }
9761   }
9762 
9763   // Diagnose no_builtin attribute on function declaration that are not a
9764   // definition.
9765   // FIXME: We should really be doing this in
9766   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9767   // the FunctionDecl and at this point of the code
9768   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9769   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9770   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9771     switch (D.getFunctionDefinitionKind()) {
9772     case FDK_Defaulted:
9773     case FDK_Deleted:
9774       Diag(NBA->getLocation(),
9775            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9776           << NBA->getSpelling();
9777       break;
9778     case FDK_Declaration:
9779       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9780           << NBA->getSpelling();
9781       break;
9782     case FDK_Definition:
9783       break;
9784     }
9785 
9786   return NewFD;
9787 }
9788 
9789 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9790 /// when __declspec(code_seg) "is applied to a class, all member functions of
9791 /// the class and nested classes -- this includes compiler-generated special
9792 /// member functions -- are put in the specified segment."
9793 /// The actual behavior is a little more complicated. The Microsoft compiler
9794 /// won't check outer classes if there is an active value from #pragma code_seg.
9795 /// The CodeSeg is always applied from the direct parent but only from outer
9796 /// classes when the #pragma code_seg stack is empty. See:
9797 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9798 /// available since MS has removed the page.
9799 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9800   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9801   if (!Method)
9802     return nullptr;
9803   const CXXRecordDecl *Parent = Method->getParent();
9804   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9805     Attr *NewAttr = SAttr->clone(S.getASTContext());
9806     NewAttr->setImplicit(true);
9807     return NewAttr;
9808   }
9809 
9810   // The Microsoft compiler won't check outer classes for the CodeSeg
9811   // when the #pragma code_seg stack is active.
9812   if (S.CodeSegStack.CurrentValue)
9813    return nullptr;
9814 
9815   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9816     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9817       Attr *NewAttr = SAttr->clone(S.getASTContext());
9818       NewAttr->setImplicit(true);
9819       return NewAttr;
9820     }
9821   }
9822   return nullptr;
9823 }
9824 
9825 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9826 /// containing class. Otherwise it will return implicit SectionAttr if the
9827 /// function is a definition and there is an active value on CodeSegStack
9828 /// (from the current #pragma code-seg value).
9829 ///
9830 /// \param FD Function being declared.
9831 /// \param IsDefinition Whether it is a definition or just a declarartion.
9832 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9833 ///          nullptr if no attribute should be added.
9834 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9835                                                        bool IsDefinition) {
9836   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9837     return A;
9838   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9839       CodeSegStack.CurrentValue)
9840     return SectionAttr::CreateImplicit(
9841         getASTContext(), CodeSegStack.CurrentValue->getString(),
9842         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9843         SectionAttr::Declspec_allocate);
9844   return nullptr;
9845 }
9846 
9847 /// Determines if we can perform a correct type check for \p D as a
9848 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9849 /// best-effort check.
9850 ///
9851 /// \param NewD The new declaration.
9852 /// \param OldD The old declaration.
9853 /// \param NewT The portion of the type of the new declaration to check.
9854 /// \param OldT The portion of the type of the old declaration to check.
9855 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9856                                           QualType NewT, QualType OldT) {
9857   if (!NewD->getLexicalDeclContext()->isDependentContext())
9858     return true;
9859 
9860   // For dependently-typed local extern declarations and friends, we can't
9861   // perform a correct type check in general until instantiation:
9862   //
9863   //   int f();
9864   //   template<typename T> void g() { T f(); }
9865   //
9866   // (valid if g() is only instantiated with T = int).
9867   if (NewT->isDependentType() &&
9868       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9869     return false;
9870 
9871   // Similarly, if the previous declaration was a dependent local extern
9872   // declaration, we don't really know its type yet.
9873   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9874     return false;
9875 
9876   return true;
9877 }
9878 
9879 /// Checks if the new declaration declared in dependent context must be
9880 /// put in the same redeclaration chain as the specified declaration.
9881 ///
9882 /// \param D Declaration that is checked.
9883 /// \param PrevDecl Previous declaration found with proper lookup method for the
9884 ///                 same declaration name.
9885 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9886 ///          belongs to.
9887 ///
9888 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9889   if (!D->getLexicalDeclContext()->isDependentContext())
9890     return true;
9891 
9892   // Don't chain dependent friend function definitions until instantiation, to
9893   // permit cases like
9894   //
9895   //   void func();
9896   //   template<typename T> class C1 { friend void func() {} };
9897   //   template<typename T> class C2 { friend void func() {} };
9898   //
9899   // ... which is valid if only one of C1 and C2 is ever instantiated.
9900   //
9901   // FIXME: This need only apply to function definitions. For now, we proxy
9902   // this by checking for a file-scope function. We do not want this to apply
9903   // to friend declarations nominating member functions, because that gets in
9904   // the way of access checks.
9905   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9906     return false;
9907 
9908   auto *VD = dyn_cast<ValueDecl>(D);
9909   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9910   return !VD || !PrevVD ||
9911          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9912                                         PrevVD->getType());
9913 }
9914 
9915 /// Check the target attribute of the function for MultiVersion
9916 /// validity.
9917 ///
9918 /// Returns true if there was an error, false otherwise.
9919 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9920   const auto *TA = FD->getAttr<TargetAttr>();
9921   assert(TA && "MultiVersion Candidate requires a target attribute");
9922   ParsedTargetAttr ParseInfo = TA->parse();
9923   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9924   enum ErrType { Feature = 0, Architecture = 1 };
9925 
9926   if (!ParseInfo.Architecture.empty() &&
9927       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9928     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9929         << Architecture << ParseInfo.Architecture;
9930     return true;
9931   }
9932 
9933   for (const auto &Feat : ParseInfo.Features) {
9934     auto BareFeat = StringRef{Feat}.substr(1);
9935     if (Feat[0] == '-') {
9936       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9937           << Feature << ("no-" + BareFeat).str();
9938       return true;
9939     }
9940 
9941     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9942         !TargetInfo.isValidFeatureName(BareFeat)) {
9943       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9944           << Feature << BareFeat;
9945       return true;
9946     }
9947   }
9948   return false;
9949 }
9950 
9951 // Provide a white-list of attributes that are allowed to be combined with
9952 // multiversion functions.
9953 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
9954                                            MultiVersionKind MVType) {
9955   switch (Kind) {
9956   default:
9957     return false;
9958   case attr::Used:
9959     return MVType == MultiVersionKind::Target;
9960   }
9961 }
9962 
9963 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9964                                          MultiVersionKind MVType) {
9965   for (const Attr *A : FD->attrs()) {
9966     switch (A->getKind()) {
9967     case attr::CPUDispatch:
9968     case attr::CPUSpecific:
9969       if (MVType != MultiVersionKind::CPUDispatch &&
9970           MVType != MultiVersionKind::CPUSpecific)
9971         return true;
9972       break;
9973     case attr::Target:
9974       if (MVType != MultiVersionKind::Target)
9975         return true;
9976       break;
9977     default:
9978       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
9979         return true;
9980       break;
9981     }
9982   }
9983   return false;
9984 }
9985 
9986 bool Sema::areMultiversionVariantFunctionsCompatible(
9987     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9988     const PartialDiagnostic &NoProtoDiagID,
9989     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9990     const PartialDiagnosticAt &NoSupportDiagIDAt,
9991     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9992     bool ConstexprSupported, bool CLinkageMayDiffer) {
9993   enum DoesntSupport {
9994     FuncTemplates = 0,
9995     VirtFuncs = 1,
9996     DeducedReturn = 2,
9997     Constructors = 3,
9998     Destructors = 4,
9999     DeletedFuncs = 5,
10000     DefaultedFuncs = 6,
10001     ConstexprFuncs = 7,
10002     ConstevalFuncs = 8,
10003   };
10004   enum Different {
10005     CallingConv = 0,
10006     ReturnType = 1,
10007     ConstexprSpec = 2,
10008     InlineSpec = 3,
10009     StorageClass = 4,
10010     Linkage = 5,
10011   };
10012 
10013   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10014       !OldFD->getType()->getAs<FunctionProtoType>()) {
10015     Diag(OldFD->getLocation(), NoProtoDiagID);
10016     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10017     return true;
10018   }
10019 
10020   if (NoProtoDiagID.getDiagID() != 0 &&
10021       !NewFD->getType()->getAs<FunctionProtoType>())
10022     return Diag(NewFD->getLocation(), NoProtoDiagID);
10023 
10024   if (!TemplatesSupported &&
10025       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10026     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10027            << FuncTemplates;
10028 
10029   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10030     if (NewCXXFD->isVirtual())
10031       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10032              << VirtFuncs;
10033 
10034     if (isa<CXXConstructorDecl>(NewCXXFD))
10035       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10036              << Constructors;
10037 
10038     if (isa<CXXDestructorDecl>(NewCXXFD))
10039       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10040              << Destructors;
10041   }
10042 
10043   if (NewFD->isDeleted())
10044     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10045            << DeletedFuncs;
10046 
10047   if (NewFD->isDefaulted())
10048     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10049            << DefaultedFuncs;
10050 
10051   if (!ConstexprSupported && NewFD->isConstexpr())
10052     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10053            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10054 
10055   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10056   const auto *NewType = cast<FunctionType>(NewQType);
10057   QualType NewReturnType = NewType->getReturnType();
10058 
10059   if (NewReturnType->isUndeducedType())
10060     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10061            << DeducedReturn;
10062 
10063   // Ensure the return type is identical.
10064   if (OldFD) {
10065     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10066     const auto *OldType = cast<FunctionType>(OldQType);
10067     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10068     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10069 
10070     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10071       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10072 
10073     QualType OldReturnType = OldType->getReturnType();
10074 
10075     if (OldReturnType != NewReturnType)
10076       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10077 
10078     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10079       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10080 
10081     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10082       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10083 
10084     if (OldFD->getStorageClass() != NewFD->getStorageClass())
10085       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10086 
10087     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10088       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10089 
10090     if (CheckEquivalentExceptionSpec(
10091             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10092             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10093       return true;
10094   }
10095   return false;
10096 }
10097 
10098 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10099                                              const FunctionDecl *NewFD,
10100                                              bool CausesMV,
10101                                              MultiVersionKind MVType) {
10102   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10103     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10104     if (OldFD)
10105       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10106     return true;
10107   }
10108 
10109   bool IsCPUSpecificCPUDispatchMVType =
10110       MVType == MultiVersionKind::CPUDispatch ||
10111       MVType == MultiVersionKind::CPUSpecific;
10112 
10113   // For now, disallow all other attributes.  These should be opt-in, but
10114   // an analysis of all of them is a future FIXME.
10115   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
10116     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
10117         << IsCPUSpecificCPUDispatchMVType;
10118     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10119     return true;
10120   }
10121 
10122   if (HasNonMultiVersionAttributes(NewFD, MVType))
10123     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
10124            << IsCPUSpecificCPUDispatchMVType;
10125 
10126   // Only allow transition to MultiVersion if it hasn't been used.
10127   if (OldFD && CausesMV && OldFD->isUsed(false))
10128     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10129 
10130   return S.areMultiversionVariantFunctionsCompatible(
10131       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10132       PartialDiagnosticAt(NewFD->getLocation(),
10133                           S.PDiag(diag::note_multiversioning_caused_here)),
10134       PartialDiagnosticAt(NewFD->getLocation(),
10135                           S.PDiag(diag::err_multiversion_doesnt_support)
10136                               << IsCPUSpecificCPUDispatchMVType),
10137       PartialDiagnosticAt(NewFD->getLocation(),
10138                           S.PDiag(diag::err_multiversion_diff)),
10139       /*TemplatesSupported=*/false,
10140       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10141       /*CLinkageMayDiffer=*/false);
10142 }
10143 
10144 /// Check the validity of a multiversion function declaration that is the
10145 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10146 ///
10147 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10148 ///
10149 /// Returns true if there was an error, false otherwise.
10150 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10151                                            MultiVersionKind MVType,
10152                                            const TargetAttr *TA) {
10153   assert(MVType != MultiVersionKind::None &&
10154          "Function lacks multiversion attribute");
10155 
10156   // Target only causes MV if it is default, otherwise this is a normal
10157   // function.
10158   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10159     return false;
10160 
10161   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10162     FD->setInvalidDecl();
10163     return true;
10164   }
10165 
10166   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10167     FD->setInvalidDecl();
10168     return true;
10169   }
10170 
10171   FD->setIsMultiVersion();
10172   return false;
10173 }
10174 
10175 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10176   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10177     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10178       return true;
10179   }
10180 
10181   return false;
10182 }
10183 
10184 static bool CheckTargetCausesMultiVersioning(
10185     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10186     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10187     LookupResult &Previous) {
10188   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10189   ParsedTargetAttr NewParsed = NewTA->parse();
10190   // Sort order doesn't matter, it just needs to be consistent.
10191   llvm::sort(NewParsed.Features);
10192 
10193   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10194   // to change, this is a simple redeclaration.
10195   if (!NewTA->isDefaultVersion() &&
10196       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10197     return false;
10198 
10199   // Otherwise, this decl causes MultiVersioning.
10200   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10201     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10202     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10203     NewFD->setInvalidDecl();
10204     return true;
10205   }
10206 
10207   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10208                                        MultiVersionKind::Target)) {
10209     NewFD->setInvalidDecl();
10210     return true;
10211   }
10212 
10213   if (CheckMultiVersionValue(S, NewFD)) {
10214     NewFD->setInvalidDecl();
10215     return true;
10216   }
10217 
10218   // If this is 'default', permit the forward declaration.
10219   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10220     Redeclaration = true;
10221     OldDecl = OldFD;
10222     OldFD->setIsMultiVersion();
10223     NewFD->setIsMultiVersion();
10224     return false;
10225   }
10226 
10227   if (CheckMultiVersionValue(S, OldFD)) {
10228     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10229     NewFD->setInvalidDecl();
10230     return true;
10231   }
10232 
10233   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10234 
10235   if (OldParsed == NewParsed) {
10236     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10237     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10238     NewFD->setInvalidDecl();
10239     return true;
10240   }
10241 
10242   for (const auto *FD : OldFD->redecls()) {
10243     const auto *CurTA = FD->getAttr<TargetAttr>();
10244     // We allow forward declarations before ANY multiversioning attributes, but
10245     // nothing after the fact.
10246     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10247         (!CurTA || CurTA->isInherited())) {
10248       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10249           << 0;
10250       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10251       NewFD->setInvalidDecl();
10252       return true;
10253     }
10254   }
10255 
10256   OldFD->setIsMultiVersion();
10257   NewFD->setIsMultiVersion();
10258   Redeclaration = false;
10259   MergeTypeWithPrevious = false;
10260   OldDecl = nullptr;
10261   Previous.clear();
10262   return false;
10263 }
10264 
10265 /// Check the validity of a new function declaration being added to an existing
10266 /// multiversioned declaration collection.
10267 static bool CheckMultiVersionAdditionalDecl(
10268     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10269     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10270     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10271     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10272     LookupResult &Previous) {
10273 
10274   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10275   // Disallow mixing of multiversioning types.
10276   if ((OldMVType == MultiVersionKind::Target &&
10277        NewMVType != MultiVersionKind::Target) ||
10278       (NewMVType == MultiVersionKind::Target &&
10279        OldMVType != MultiVersionKind::Target)) {
10280     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10281     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10282     NewFD->setInvalidDecl();
10283     return true;
10284   }
10285 
10286   ParsedTargetAttr NewParsed;
10287   if (NewTA) {
10288     NewParsed = NewTA->parse();
10289     llvm::sort(NewParsed.Features);
10290   }
10291 
10292   bool UseMemberUsingDeclRules =
10293       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10294 
10295   // Next, check ALL non-overloads to see if this is a redeclaration of a
10296   // previous member of the MultiVersion set.
10297   for (NamedDecl *ND : Previous) {
10298     FunctionDecl *CurFD = ND->getAsFunction();
10299     if (!CurFD)
10300       continue;
10301     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10302       continue;
10303 
10304     if (NewMVType == MultiVersionKind::Target) {
10305       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10306       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10307         NewFD->setIsMultiVersion();
10308         Redeclaration = true;
10309         OldDecl = ND;
10310         return false;
10311       }
10312 
10313       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10314       if (CurParsed == NewParsed) {
10315         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10316         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10317         NewFD->setInvalidDecl();
10318         return true;
10319       }
10320     } else {
10321       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10322       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10323       // Handle CPUDispatch/CPUSpecific versions.
10324       // Only 1 CPUDispatch function is allowed, this will make it go through
10325       // the redeclaration errors.
10326       if (NewMVType == MultiVersionKind::CPUDispatch &&
10327           CurFD->hasAttr<CPUDispatchAttr>()) {
10328         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10329             std::equal(
10330                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10331                 NewCPUDisp->cpus_begin(),
10332                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10333                   return Cur->getName() == New->getName();
10334                 })) {
10335           NewFD->setIsMultiVersion();
10336           Redeclaration = true;
10337           OldDecl = ND;
10338           return false;
10339         }
10340 
10341         // If the declarations don't match, this is an error condition.
10342         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10343         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10344         NewFD->setInvalidDecl();
10345         return true;
10346       }
10347       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10348 
10349         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10350             std::equal(
10351                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10352                 NewCPUSpec->cpus_begin(),
10353                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10354                   return Cur->getName() == New->getName();
10355                 })) {
10356           NewFD->setIsMultiVersion();
10357           Redeclaration = true;
10358           OldDecl = ND;
10359           return false;
10360         }
10361 
10362         // Only 1 version of CPUSpecific is allowed for each CPU.
10363         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10364           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10365             if (CurII == NewII) {
10366               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10367                   << NewII;
10368               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10369               NewFD->setInvalidDecl();
10370               return true;
10371             }
10372           }
10373         }
10374       }
10375       // If the two decls aren't the same MVType, there is no possible error
10376       // condition.
10377     }
10378   }
10379 
10380   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10381   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10382   // handled in the attribute adding step.
10383   if (NewMVType == MultiVersionKind::Target &&
10384       CheckMultiVersionValue(S, NewFD)) {
10385     NewFD->setInvalidDecl();
10386     return true;
10387   }
10388 
10389   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10390                                        !OldFD->isMultiVersion(), NewMVType)) {
10391     NewFD->setInvalidDecl();
10392     return true;
10393   }
10394 
10395   // Permit forward declarations in the case where these two are compatible.
10396   if (!OldFD->isMultiVersion()) {
10397     OldFD->setIsMultiVersion();
10398     NewFD->setIsMultiVersion();
10399     Redeclaration = true;
10400     OldDecl = OldFD;
10401     return false;
10402   }
10403 
10404   NewFD->setIsMultiVersion();
10405   Redeclaration = false;
10406   MergeTypeWithPrevious = false;
10407   OldDecl = nullptr;
10408   Previous.clear();
10409   return false;
10410 }
10411 
10412 
10413 /// Check the validity of a mulitversion function declaration.
10414 /// Also sets the multiversion'ness' of the function itself.
10415 ///
10416 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10417 ///
10418 /// Returns true if there was an error, false otherwise.
10419 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10420                                       bool &Redeclaration, NamedDecl *&OldDecl,
10421                                       bool &MergeTypeWithPrevious,
10422                                       LookupResult &Previous) {
10423   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10424   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10425   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10426 
10427   // Mixing Multiversioning types is prohibited.
10428   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10429       (NewCPUDisp && NewCPUSpec)) {
10430     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10431     NewFD->setInvalidDecl();
10432     return true;
10433   }
10434 
10435   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10436 
10437   // Main isn't allowed to become a multiversion function, however it IS
10438   // permitted to have 'main' be marked with the 'target' optimization hint.
10439   if (NewFD->isMain()) {
10440     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10441         MVType == MultiVersionKind::CPUDispatch ||
10442         MVType == MultiVersionKind::CPUSpecific) {
10443       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10444       NewFD->setInvalidDecl();
10445       return true;
10446     }
10447     return false;
10448   }
10449 
10450   if (!OldDecl || !OldDecl->getAsFunction() ||
10451       OldDecl->getDeclContext()->getRedeclContext() !=
10452           NewFD->getDeclContext()->getRedeclContext()) {
10453     // If there's no previous declaration, AND this isn't attempting to cause
10454     // multiversioning, this isn't an error condition.
10455     if (MVType == MultiVersionKind::None)
10456       return false;
10457     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10458   }
10459 
10460   FunctionDecl *OldFD = OldDecl->getAsFunction();
10461 
10462   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10463     return false;
10464 
10465   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10466     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10467         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10468     NewFD->setInvalidDecl();
10469     return true;
10470   }
10471 
10472   // Handle the target potentially causes multiversioning case.
10473   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10474     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10475                                             Redeclaration, OldDecl,
10476                                             MergeTypeWithPrevious, Previous);
10477 
10478   // At this point, we have a multiversion function decl (in OldFD) AND an
10479   // appropriate attribute in the current function decl.  Resolve that these are
10480   // still compatible with previous declarations.
10481   return CheckMultiVersionAdditionalDecl(
10482       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10483       OldDecl, MergeTypeWithPrevious, Previous);
10484 }
10485 
10486 /// Perform semantic checking of a new function declaration.
10487 ///
10488 /// Performs semantic analysis of the new function declaration
10489 /// NewFD. This routine performs all semantic checking that does not
10490 /// require the actual declarator involved in the declaration, and is
10491 /// used both for the declaration of functions as they are parsed
10492 /// (called via ActOnDeclarator) and for the declaration of functions
10493 /// that have been instantiated via C++ template instantiation (called
10494 /// via InstantiateDecl).
10495 ///
10496 /// \param IsMemberSpecialization whether this new function declaration is
10497 /// a member specialization (that replaces any definition provided by the
10498 /// previous declaration).
10499 ///
10500 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10501 ///
10502 /// \returns true if the function declaration is a redeclaration.
10503 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10504                                     LookupResult &Previous,
10505                                     bool IsMemberSpecialization) {
10506   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10507          "Variably modified return types are not handled here");
10508 
10509   // Determine whether the type of this function should be merged with
10510   // a previous visible declaration. This never happens for functions in C++,
10511   // and always happens in C if the previous declaration was visible.
10512   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10513                                !Previous.isShadowed();
10514 
10515   bool Redeclaration = false;
10516   NamedDecl *OldDecl = nullptr;
10517   bool MayNeedOverloadableChecks = false;
10518 
10519   // Merge or overload the declaration with an existing declaration of
10520   // the same name, if appropriate.
10521   if (!Previous.empty()) {
10522     // Determine whether NewFD is an overload of PrevDecl or
10523     // a declaration that requires merging. If it's an overload,
10524     // there's no more work to do here; we'll just add the new
10525     // function to the scope.
10526     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10527       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10528       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10529         Redeclaration = true;
10530         OldDecl = Candidate;
10531       }
10532     } else {
10533       MayNeedOverloadableChecks = true;
10534       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10535                             /*NewIsUsingDecl*/ false)) {
10536       case Ovl_Match:
10537         Redeclaration = true;
10538         break;
10539 
10540       case Ovl_NonFunction:
10541         Redeclaration = true;
10542         break;
10543 
10544       case Ovl_Overload:
10545         Redeclaration = false;
10546         break;
10547       }
10548     }
10549   }
10550 
10551   // Check for a previous extern "C" declaration with this name.
10552   if (!Redeclaration &&
10553       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10554     if (!Previous.empty()) {
10555       // This is an extern "C" declaration with the same name as a previous
10556       // declaration, and thus redeclares that entity...
10557       Redeclaration = true;
10558       OldDecl = Previous.getFoundDecl();
10559       MergeTypeWithPrevious = false;
10560 
10561       // ... except in the presence of __attribute__((overloadable)).
10562       if (OldDecl->hasAttr<OverloadableAttr>() ||
10563           NewFD->hasAttr<OverloadableAttr>()) {
10564         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10565           MayNeedOverloadableChecks = true;
10566           Redeclaration = false;
10567           OldDecl = nullptr;
10568         }
10569       }
10570     }
10571   }
10572 
10573   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10574                                 MergeTypeWithPrevious, Previous))
10575     return Redeclaration;
10576 
10577   // C++11 [dcl.constexpr]p8:
10578   //   A constexpr specifier for a non-static member function that is not
10579   //   a constructor declares that member function to be const.
10580   //
10581   // This needs to be delayed until we know whether this is an out-of-line
10582   // definition of a static member function.
10583   //
10584   // This rule is not present in C++1y, so we produce a backwards
10585   // compatibility warning whenever it happens in C++11.
10586   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10587   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10588       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10589       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10590     CXXMethodDecl *OldMD = nullptr;
10591     if (OldDecl)
10592       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10593     if (!OldMD || !OldMD->isStatic()) {
10594       const FunctionProtoType *FPT =
10595         MD->getType()->castAs<FunctionProtoType>();
10596       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10597       EPI.TypeQuals.addConst();
10598       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10599                                           FPT->getParamTypes(), EPI));
10600 
10601       // Warn that we did this, if we're not performing template instantiation.
10602       // In that case, we'll have warned already when the template was defined.
10603       if (!inTemplateInstantiation()) {
10604         SourceLocation AddConstLoc;
10605         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10606                 .IgnoreParens().getAs<FunctionTypeLoc>())
10607           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10608 
10609         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10610           << FixItHint::CreateInsertion(AddConstLoc, " const");
10611       }
10612     }
10613   }
10614 
10615   if (Redeclaration) {
10616     // NewFD and OldDecl represent declarations that need to be
10617     // merged.
10618     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10619       NewFD->setInvalidDecl();
10620       return Redeclaration;
10621     }
10622 
10623     Previous.clear();
10624     Previous.addDecl(OldDecl);
10625 
10626     if (FunctionTemplateDecl *OldTemplateDecl =
10627             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10628       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10629       FunctionTemplateDecl *NewTemplateDecl
10630         = NewFD->getDescribedFunctionTemplate();
10631       assert(NewTemplateDecl && "Template/non-template mismatch");
10632 
10633       // The call to MergeFunctionDecl above may have created some state in
10634       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10635       // can add it as a redeclaration.
10636       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10637 
10638       NewFD->setPreviousDeclaration(OldFD);
10639       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10640       if (NewFD->isCXXClassMember()) {
10641         NewFD->setAccess(OldTemplateDecl->getAccess());
10642         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10643       }
10644 
10645       // If this is an explicit specialization of a member that is a function
10646       // template, mark it as a member specialization.
10647       if (IsMemberSpecialization &&
10648           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10649         NewTemplateDecl->setMemberSpecialization();
10650         assert(OldTemplateDecl->isMemberSpecialization());
10651         // Explicit specializations of a member template do not inherit deleted
10652         // status from the parent member template that they are specializing.
10653         if (OldFD->isDeleted()) {
10654           // FIXME: This assert will not hold in the presence of modules.
10655           assert(OldFD->getCanonicalDecl() == OldFD);
10656           // FIXME: We need an update record for this AST mutation.
10657           OldFD->setDeletedAsWritten(false);
10658         }
10659       }
10660 
10661     } else {
10662       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10663         auto *OldFD = cast<FunctionDecl>(OldDecl);
10664         // This needs to happen first so that 'inline' propagates.
10665         NewFD->setPreviousDeclaration(OldFD);
10666         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10667         if (NewFD->isCXXClassMember())
10668           NewFD->setAccess(OldFD->getAccess());
10669       }
10670     }
10671   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10672              !NewFD->getAttr<OverloadableAttr>()) {
10673     assert((Previous.empty() ||
10674             llvm::any_of(Previous,
10675                          [](const NamedDecl *ND) {
10676                            return ND->hasAttr<OverloadableAttr>();
10677                          })) &&
10678            "Non-redecls shouldn't happen without overloadable present");
10679 
10680     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10681       const auto *FD = dyn_cast<FunctionDecl>(ND);
10682       return FD && !FD->hasAttr<OverloadableAttr>();
10683     });
10684 
10685     if (OtherUnmarkedIter != Previous.end()) {
10686       Diag(NewFD->getLocation(),
10687            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10688       Diag((*OtherUnmarkedIter)->getLocation(),
10689            diag::note_attribute_overloadable_prev_overload)
10690           << false;
10691 
10692       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10693     }
10694   }
10695 
10696   // Semantic checking for this function declaration (in isolation).
10697 
10698   if (getLangOpts().CPlusPlus) {
10699     // C++-specific checks.
10700     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10701       CheckConstructor(Constructor);
10702     } else if (CXXDestructorDecl *Destructor =
10703                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10704       CXXRecordDecl *Record = Destructor->getParent();
10705       QualType ClassType = Context.getTypeDeclType(Record);
10706 
10707       // FIXME: Shouldn't we be able to perform this check even when the class
10708       // type is dependent? Both gcc and edg can handle that.
10709       if (!ClassType->isDependentType()) {
10710         DeclarationName Name
10711           = Context.DeclarationNames.getCXXDestructorName(
10712                                         Context.getCanonicalType(ClassType));
10713         if (NewFD->getDeclName() != Name) {
10714           Diag(NewFD->getLocation(), diag::err_destructor_name);
10715           NewFD->setInvalidDecl();
10716           return Redeclaration;
10717         }
10718       }
10719     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10720       if (auto *TD = Guide->getDescribedFunctionTemplate())
10721         CheckDeductionGuideTemplate(TD);
10722 
10723       // A deduction guide is not on the list of entities that can be
10724       // explicitly specialized.
10725       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10726         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10727             << /*explicit specialization*/ 1;
10728     }
10729 
10730     // Find any virtual functions that this function overrides.
10731     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10732       if (!Method->isFunctionTemplateSpecialization() &&
10733           !Method->getDescribedFunctionTemplate() &&
10734           Method->isCanonicalDecl()) {
10735         AddOverriddenMethods(Method->getParent(), Method);
10736       }
10737       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10738         // C++2a [class.virtual]p6
10739         // A virtual method shall not have a requires-clause.
10740         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10741              diag::err_constrained_virtual_method);
10742 
10743       if (Method->isStatic())
10744         checkThisInStaticMemberFunctionType(Method);
10745     }
10746 
10747     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10748       ActOnConversionDeclarator(Conversion);
10749 
10750     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10751     if (NewFD->isOverloadedOperator() &&
10752         CheckOverloadedOperatorDeclaration(NewFD)) {
10753       NewFD->setInvalidDecl();
10754       return Redeclaration;
10755     }
10756 
10757     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10758     if (NewFD->getLiteralIdentifier() &&
10759         CheckLiteralOperatorDeclaration(NewFD)) {
10760       NewFD->setInvalidDecl();
10761       return Redeclaration;
10762     }
10763 
10764     // In C++, check default arguments now that we have merged decls. Unless
10765     // the lexical context is the class, because in this case this is done
10766     // during delayed parsing anyway.
10767     if (!CurContext->isRecord())
10768       CheckCXXDefaultArguments(NewFD);
10769 
10770     // If this function declares a builtin function, check the type of this
10771     // declaration against the expected type for the builtin.
10772     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10773       ASTContext::GetBuiltinTypeError Error;
10774       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10775       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10776       // If the type of the builtin differs only in its exception
10777       // specification, that's OK.
10778       // FIXME: If the types do differ in this way, it would be better to
10779       // retain the 'noexcept' form of the type.
10780       if (!T.isNull() &&
10781           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10782                                                             NewFD->getType()))
10783         // The type of this function differs from the type of the builtin,
10784         // so forget about the builtin entirely.
10785         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10786     }
10787 
10788     // If this function is declared as being extern "C", then check to see if
10789     // the function returns a UDT (class, struct, or union type) that is not C
10790     // compatible, and if it does, warn the user.
10791     // But, issue any diagnostic on the first declaration only.
10792     if (Previous.empty() && NewFD->isExternC()) {
10793       QualType R = NewFD->getReturnType();
10794       if (R->isIncompleteType() && !R->isVoidType())
10795         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10796             << NewFD << R;
10797       else if (!R.isPODType(Context) && !R->isVoidType() &&
10798                !R->isObjCObjectPointerType())
10799         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10800     }
10801 
10802     // C++1z [dcl.fct]p6:
10803     //   [...] whether the function has a non-throwing exception-specification
10804     //   [is] part of the function type
10805     //
10806     // This results in an ABI break between C++14 and C++17 for functions whose
10807     // declared type includes an exception-specification in a parameter or
10808     // return type. (Exception specifications on the function itself are OK in
10809     // most cases, and exception specifications are not permitted in most other
10810     // contexts where they could make it into a mangling.)
10811     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10812       auto HasNoexcept = [&](QualType T) -> bool {
10813         // Strip off declarator chunks that could be between us and a function
10814         // type. We don't need to look far, exception specifications are very
10815         // restricted prior to C++17.
10816         if (auto *RT = T->getAs<ReferenceType>())
10817           T = RT->getPointeeType();
10818         else if (T->isAnyPointerType())
10819           T = T->getPointeeType();
10820         else if (auto *MPT = T->getAs<MemberPointerType>())
10821           T = MPT->getPointeeType();
10822         if (auto *FPT = T->getAs<FunctionProtoType>())
10823           if (FPT->isNothrow())
10824             return true;
10825         return false;
10826       };
10827 
10828       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10829       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10830       for (QualType T : FPT->param_types())
10831         AnyNoexcept |= HasNoexcept(T);
10832       if (AnyNoexcept)
10833         Diag(NewFD->getLocation(),
10834              diag::warn_cxx17_compat_exception_spec_in_signature)
10835             << NewFD;
10836     }
10837 
10838     if (!Redeclaration && LangOpts.CUDA)
10839       checkCUDATargetOverload(NewFD, Previous);
10840   }
10841   return Redeclaration;
10842 }
10843 
10844 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10845   // C++11 [basic.start.main]p3:
10846   //   A program that [...] declares main to be inline, static or
10847   //   constexpr is ill-formed.
10848   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10849   //   appear in a declaration of main.
10850   // static main is not an error under C99, but we should warn about it.
10851   // We accept _Noreturn main as an extension.
10852   if (FD->getStorageClass() == SC_Static)
10853     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10854          ? diag::err_static_main : diag::warn_static_main)
10855       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10856   if (FD->isInlineSpecified())
10857     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10858       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10859   if (DS.isNoreturnSpecified()) {
10860     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10861     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10862     Diag(NoreturnLoc, diag::ext_noreturn_main);
10863     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10864       << FixItHint::CreateRemoval(NoreturnRange);
10865   }
10866   if (FD->isConstexpr()) {
10867     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10868         << FD->isConsteval()
10869         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10870     FD->setConstexprKind(CSK_unspecified);
10871   }
10872 
10873   if (getLangOpts().OpenCL) {
10874     Diag(FD->getLocation(), diag::err_opencl_no_main)
10875         << FD->hasAttr<OpenCLKernelAttr>();
10876     FD->setInvalidDecl();
10877     return;
10878   }
10879 
10880   QualType T = FD->getType();
10881   assert(T->isFunctionType() && "function decl is not of function type");
10882   const FunctionType* FT = T->castAs<FunctionType>();
10883 
10884   // Set default calling convention for main()
10885   if (FT->getCallConv() != CC_C) {
10886     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10887     FD->setType(QualType(FT, 0));
10888     T = Context.getCanonicalType(FD->getType());
10889   }
10890 
10891   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10892     // In C with GNU extensions we allow main() to have non-integer return
10893     // type, but we should warn about the extension, and we disable the
10894     // implicit-return-zero rule.
10895 
10896     // GCC in C mode accepts qualified 'int'.
10897     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10898       FD->setHasImplicitReturnZero(true);
10899     else {
10900       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10901       SourceRange RTRange = FD->getReturnTypeSourceRange();
10902       if (RTRange.isValid())
10903         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10904             << FixItHint::CreateReplacement(RTRange, "int");
10905     }
10906   } else {
10907     // In C and C++, main magically returns 0 if you fall off the end;
10908     // set the flag which tells us that.
10909     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10910 
10911     // All the standards say that main() should return 'int'.
10912     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10913       FD->setHasImplicitReturnZero(true);
10914     else {
10915       // Otherwise, this is just a flat-out error.
10916       SourceRange RTRange = FD->getReturnTypeSourceRange();
10917       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10918           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10919                                 : FixItHint());
10920       FD->setInvalidDecl(true);
10921     }
10922   }
10923 
10924   // Treat protoless main() as nullary.
10925   if (isa<FunctionNoProtoType>(FT)) return;
10926 
10927   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10928   unsigned nparams = FTP->getNumParams();
10929   assert(FD->getNumParams() == nparams);
10930 
10931   bool HasExtraParameters = (nparams > 3);
10932 
10933   if (FTP->isVariadic()) {
10934     Diag(FD->getLocation(), diag::ext_variadic_main);
10935     // FIXME: if we had information about the location of the ellipsis, we
10936     // could add a FixIt hint to remove it as a parameter.
10937   }
10938 
10939   // Darwin passes an undocumented fourth argument of type char**.  If
10940   // other platforms start sprouting these, the logic below will start
10941   // getting shifty.
10942   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10943     HasExtraParameters = false;
10944 
10945   if (HasExtraParameters) {
10946     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10947     FD->setInvalidDecl(true);
10948     nparams = 3;
10949   }
10950 
10951   // FIXME: a lot of the following diagnostics would be improved
10952   // if we had some location information about types.
10953 
10954   QualType CharPP =
10955     Context.getPointerType(Context.getPointerType(Context.CharTy));
10956   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10957 
10958   for (unsigned i = 0; i < nparams; ++i) {
10959     QualType AT = FTP->getParamType(i);
10960 
10961     bool mismatch = true;
10962 
10963     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10964       mismatch = false;
10965     else if (Expected[i] == CharPP) {
10966       // As an extension, the following forms are okay:
10967       //   char const **
10968       //   char const * const *
10969       //   char * const *
10970 
10971       QualifierCollector qs;
10972       const PointerType* PT;
10973       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10974           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10975           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10976                               Context.CharTy)) {
10977         qs.removeConst();
10978         mismatch = !qs.empty();
10979       }
10980     }
10981 
10982     if (mismatch) {
10983       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10984       // TODO: suggest replacing given type with expected type
10985       FD->setInvalidDecl(true);
10986     }
10987   }
10988 
10989   if (nparams == 1 && !FD->isInvalidDecl()) {
10990     Diag(FD->getLocation(), diag::warn_main_one_arg);
10991   }
10992 
10993   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10994     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10995     FD->setInvalidDecl();
10996   }
10997 }
10998 
10999 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11000   QualType T = FD->getType();
11001   assert(T->isFunctionType() && "function decl is not of function type");
11002   const FunctionType *FT = T->castAs<FunctionType>();
11003 
11004   // Set an implicit return of 'zero' if the function can return some integral,
11005   // enumeration, pointer or nullptr type.
11006   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11007       FT->getReturnType()->isAnyPointerType() ||
11008       FT->getReturnType()->isNullPtrType())
11009     // DllMain is exempt because a return value of zero means it failed.
11010     if (FD->getName() != "DllMain")
11011       FD->setHasImplicitReturnZero(true);
11012 
11013   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11014     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11015     FD->setInvalidDecl();
11016   }
11017 }
11018 
11019 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11020   // FIXME: Need strict checking.  In C89, we need to check for
11021   // any assignment, increment, decrement, function-calls, or
11022   // commas outside of a sizeof.  In C99, it's the same list,
11023   // except that the aforementioned are allowed in unevaluated
11024   // expressions.  Everything else falls under the
11025   // "may accept other forms of constant expressions" exception.
11026   // (We never end up here for C++, so the constant expression
11027   // rules there don't matter.)
11028   const Expr *Culprit;
11029   if (Init->isConstantInitializer(Context, false, &Culprit))
11030     return false;
11031   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11032     << Culprit->getSourceRange();
11033   return true;
11034 }
11035 
11036 namespace {
11037   // Visits an initialization expression to see if OrigDecl is evaluated in
11038   // its own initialization and throws a warning if it does.
11039   class SelfReferenceChecker
11040       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11041     Sema &S;
11042     Decl *OrigDecl;
11043     bool isRecordType;
11044     bool isPODType;
11045     bool isReferenceType;
11046 
11047     bool isInitList;
11048     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11049 
11050   public:
11051     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11052 
11053     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11054                                                     S(S), OrigDecl(OrigDecl) {
11055       isPODType = false;
11056       isRecordType = false;
11057       isReferenceType = false;
11058       isInitList = false;
11059       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11060         isPODType = VD->getType().isPODType(S.Context);
11061         isRecordType = VD->getType()->isRecordType();
11062         isReferenceType = VD->getType()->isReferenceType();
11063       }
11064     }
11065 
11066     // For most expressions, just call the visitor.  For initializer lists,
11067     // track the index of the field being initialized since fields are
11068     // initialized in order allowing use of previously initialized fields.
11069     void CheckExpr(Expr *E) {
11070       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11071       if (!InitList) {
11072         Visit(E);
11073         return;
11074       }
11075 
11076       // Track and increment the index here.
11077       isInitList = true;
11078       InitFieldIndex.push_back(0);
11079       for (auto Child : InitList->children()) {
11080         CheckExpr(cast<Expr>(Child));
11081         ++InitFieldIndex.back();
11082       }
11083       InitFieldIndex.pop_back();
11084     }
11085 
11086     // Returns true if MemberExpr is checked and no further checking is needed.
11087     // Returns false if additional checking is required.
11088     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11089       llvm::SmallVector<FieldDecl*, 4> Fields;
11090       Expr *Base = E;
11091       bool ReferenceField = false;
11092 
11093       // Get the field members used.
11094       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11095         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11096         if (!FD)
11097           return false;
11098         Fields.push_back(FD);
11099         if (FD->getType()->isReferenceType())
11100           ReferenceField = true;
11101         Base = ME->getBase()->IgnoreParenImpCasts();
11102       }
11103 
11104       // Keep checking only if the base Decl is the same.
11105       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11106       if (!DRE || DRE->getDecl() != OrigDecl)
11107         return false;
11108 
11109       // A reference field can be bound to an unininitialized field.
11110       if (CheckReference && !ReferenceField)
11111         return true;
11112 
11113       // Convert FieldDecls to their index number.
11114       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11115       for (const FieldDecl *I : llvm::reverse(Fields))
11116         UsedFieldIndex.push_back(I->getFieldIndex());
11117 
11118       // See if a warning is needed by checking the first difference in index
11119       // numbers.  If field being used has index less than the field being
11120       // initialized, then the use is safe.
11121       for (auto UsedIter = UsedFieldIndex.begin(),
11122                 UsedEnd = UsedFieldIndex.end(),
11123                 OrigIter = InitFieldIndex.begin(),
11124                 OrigEnd = InitFieldIndex.end();
11125            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11126         if (*UsedIter < *OrigIter)
11127           return true;
11128         if (*UsedIter > *OrigIter)
11129           break;
11130       }
11131 
11132       // TODO: Add a different warning which will print the field names.
11133       HandleDeclRefExpr(DRE);
11134       return true;
11135     }
11136 
11137     // For most expressions, the cast is directly above the DeclRefExpr.
11138     // For conditional operators, the cast can be outside the conditional
11139     // operator if both expressions are DeclRefExpr's.
11140     void HandleValue(Expr *E) {
11141       E = E->IgnoreParens();
11142       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11143         HandleDeclRefExpr(DRE);
11144         return;
11145       }
11146 
11147       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11148         Visit(CO->getCond());
11149         HandleValue(CO->getTrueExpr());
11150         HandleValue(CO->getFalseExpr());
11151         return;
11152       }
11153 
11154       if (BinaryConditionalOperator *BCO =
11155               dyn_cast<BinaryConditionalOperator>(E)) {
11156         Visit(BCO->getCond());
11157         HandleValue(BCO->getFalseExpr());
11158         return;
11159       }
11160 
11161       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11162         HandleValue(OVE->getSourceExpr());
11163         return;
11164       }
11165 
11166       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11167         if (BO->getOpcode() == BO_Comma) {
11168           Visit(BO->getLHS());
11169           HandleValue(BO->getRHS());
11170           return;
11171         }
11172       }
11173 
11174       if (isa<MemberExpr>(E)) {
11175         if (isInitList) {
11176           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11177                                       false /*CheckReference*/))
11178             return;
11179         }
11180 
11181         Expr *Base = E->IgnoreParenImpCasts();
11182         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11183           // Check for static member variables and don't warn on them.
11184           if (!isa<FieldDecl>(ME->getMemberDecl()))
11185             return;
11186           Base = ME->getBase()->IgnoreParenImpCasts();
11187         }
11188         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11189           HandleDeclRefExpr(DRE);
11190         return;
11191       }
11192 
11193       Visit(E);
11194     }
11195 
11196     // Reference types not handled in HandleValue are handled here since all
11197     // uses of references are bad, not just r-value uses.
11198     void VisitDeclRefExpr(DeclRefExpr *E) {
11199       if (isReferenceType)
11200         HandleDeclRefExpr(E);
11201     }
11202 
11203     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11204       if (E->getCastKind() == CK_LValueToRValue) {
11205         HandleValue(E->getSubExpr());
11206         return;
11207       }
11208 
11209       Inherited::VisitImplicitCastExpr(E);
11210     }
11211 
11212     void VisitMemberExpr(MemberExpr *E) {
11213       if (isInitList) {
11214         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11215           return;
11216       }
11217 
11218       // Don't warn on arrays since they can be treated as pointers.
11219       if (E->getType()->canDecayToPointerType()) return;
11220 
11221       // Warn when a non-static method call is followed by non-static member
11222       // field accesses, which is followed by a DeclRefExpr.
11223       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11224       bool Warn = (MD && !MD->isStatic());
11225       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11226       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11227         if (!isa<FieldDecl>(ME->getMemberDecl()))
11228           Warn = false;
11229         Base = ME->getBase()->IgnoreParenImpCasts();
11230       }
11231 
11232       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11233         if (Warn)
11234           HandleDeclRefExpr(DRE);
11235         return;
11236       }
11237 
11238       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11239       // Visit that expression.
11240       Visit(Base);
11241     }
11242 
11243     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11244       Expr *Callee = E->getCallee();
11245 
11246       if (isa<UnresolvedLookupExpr>(Callee))
11247         return Inherited::VisitCXXOperatorCallExpr(E);
11248 
11249       Visit(Callee);
11250       for (auto Arg: E->arguments())
11251         HandleValue(Arg->IgnoreParenImpCasts());
11252     }
11253 
11254     void VisitUnaryOperator(UnaryOperator *E) {
11255       // For POD record types, addresses of its own members are well-defined.
11256       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11257           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11258         if (!isPODType)
11259           HandleValue(E->getSubExpr());
11260         return;
11261       }
11262 
11263       if (E->isIncrementDecrementOp()) {
11264         HandleValue(E->getSubExpr());
11265         return;
11266       }
11267 
11268       Inherited::VisitUnaryOperator(E);
11269     }
11270 
11271     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11272 
11273     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11274       if (E->getConstructor()->isCopyConstructor()) {
11275         Expr *ArgExpr = E->getArg(0);
11276         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11277           if (ILE->getNumInits() == 1)
11278             ArgExpr = ILE->getInit(0);
11279         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11280           if (ICE->getCastKind() == CK_NoOp)
11281             ArgExpr = ICE->getSubExpr();
11282         HandleValue(ArgExpr);
11283         return;
11284       }
11285       Inherited::VisitCXXConstructExpr(E);
11286     }
11287 
11288     void VisitCallExpr(CallExpr *E) {
11289       // Treat std::move as a use.
11290       if (E->isCallToStdMove()) {
11291         HandleValue(E->getArg(0));
11292         return;
11293       }
11294 
11295       Inherited::VisitCallExpr(E);
11296     }
11297 
11298     void VisitBinaryOperator(BinaryOperator *E) {
11299       if (E->isCompoundAssignmentOp()) {
11300         HandleValue(E->getLHS());
11301         Visit(E->getRHS());
11302         return;
11303       }
11304 
11305       Inherited::VisitBinaryOperator(E);
11306     }
11307 
11308     // A custom visitor for BinaryConditionalOperator is needed because the
11309     // regular visitor would check the condition and true expression separately
11310     // but both point to the same place giving duplicate diagnostics.
11311     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11312       Visit(E->getCond());
11313       Visit(E->getFalseExpr());
11314     }
11315 
11316     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11317       Decl* ReferenceDecl = DRE->getDecl();
11318       if (OrigDecl != ReferenceDecl) return;
11319       unsigned diag;
11320       if (isReferenceType) {
11321         diag = diag::warn_uninit_self_reference_in_reference_init;
11322       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11323         diag = diag::warn_static_self_reference_in_init;
11324       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11325                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11326                  DRE->getDecl()->getType()->isRecordType()) {
11327         diag = diag::warn_uninit_self_reference_in_init;
11328       } else {
11329         // Local variables will be handled by the CFG analysis.
11330         return;
11331       }
11332 
11333       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11334                             S.PDiag(diag)
11335                                 << DRE->getDecl() << OrigDecl->getLocation()
11336                                 << DRE->getSourceRange());
11337     }
11338   };
11339 
11340   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11341   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11342                                  bool DirectInit) {
11343     // Parameters arguments are occassionially constructed with itself,
11344     // for instance, in recursive functions.  Skip them.
11345     if (isa<ParmVarDecl>(OrigDecl))
11346       return;
11347 
11348     E = E->IgnoreParens();
11349 
11350     // Skip checking T a = a where T is not a record or reference type.
11351     // Doing so is a way to silence uninitialized warnings.
11352     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11353       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11354         if (ICE->getCastKind() == CK_LValueToRValue)
11355           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11356             if (DRE->getDecl() == OrigDecl)
11357               return;
11358 
11359     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11360   }
11361 } // end anonymous namespace
11362 
11363 namespace {
11364   // Simple wrapper to add the name of a variable or (if no variable is
11365   // available) a DeclarationName into a diagnostic.
11366   struct VarDeclOrName {
11367     VarDecl *VDecl;
11368     DeclarationName Name;
11369 
11370     friend const Sema::SemaDiagnosticBuilder &
11371     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11372       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11373     }
11374   };
11375 } // end anonymous namespace
11376 
11377 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11378                                             DeclarationName Name, QualType Type,
11379                                             TypeSourceInfo *TSI,
11380                                             SourceRange Range, bool DirectInit,
11381                                             Expr *Init) {
11382   bool IsInitCapture = !VDecl;
11383   assert((!VDecl || !VDecl->isInitCapture()) &&
11384          "init captures are expected to be deduced prior to initialization");
11385 
11386   VarDeclOrName VN{VDecl, Name};
11387 
11388   DeducedType *Deduced = Type->getContainedDeducedType();
11389   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11390 
11391   // C++11 [dcl.spec.auto]p3
11392   if (!Init) {
11393     assert(VDecl && "no init for init capture deduction?");
11394 
11395     // Except for class argument deduction, and then for an initializing
11396     // declaration only, i.e. no static at class scope or extern.
11397     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11398         VDecl->hasExternalStorage() ||
11399         VDecl->isStaticDataMember()) {
11400       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11401         << VDecl->getDeclName() << Type;
11402       return QualType();
11403     }
11404   }
11405 
11406   ArrayRef<Expr*> DeduceInits;
11407   if (Init)
11408     DeduceInits = Init;
11409 
11410   if (DirectInit) {
11411     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11412       DeduceInits = PL->exprs();
11413   }
11414 
11415   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11416     assert(VDecl && "non-auto type for init capture deduction?");
11417     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11418     InitializationKind Kind = InitializationKind::CreateForInit(
11419         VDecl->getLocation(), DirectInit, Init);
11420     // FIXME: Initialization should not be taking a mutable list of inits.
11421     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11422     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11423                                                        InitsCopy);
11424   }
11425 
11426   if (DirectInit) {
11427     if (auto *IL = dyn_cast<InitListExpr>(Init))
11428       DeduceInits = IL->inits();
11429   }
11430 
11431   // Deduction only works if we have exactly one source expression.
11432   if (DeduceInits.empty()) {
11433     // It isn't possible to write this directly, but it is possible to
11434     // end up in this situation with "auto x(some_pack...);"
11435     Diag(Init->getBeginLoc(), IsInitCapture
11436                                   ? diag::err_init_capture_no_expression
11437                                   : diag::err_auto_var_init_no_expression)
11438         << VN << Type << Range;
11439     return QualType();
11440   }
11441 
11442   if (DeduceInits.size() > 1) {
11443     Diag(DeduceInits[1]->getBeginLoc(),
11444          IsInitCapture ? diag::err_init_capture_multiple_expressions
11445                        : diag::err_auto_var_init_multiple_expressions)
11446         << VN << Type << Range;
11447     return QualType();
11448   }
11449 
11450   Expr *DeduceInit = DeduceInits[0];
11451   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11452     Diag(Init->getBeginLoc(), IsInitCapture
11453                                   ? diag::err_init_capture_paren_braces
11454                                   : diag::err_auto_var_init_paren_braces)
11455         << isa<InitListExpr>(Init) << VN << Type << Range;
11456     return QualType();
11457   }
11458 
11459   // Expressions default to 'id' when we're in a debugger.
11460   bool DefaultedAnyToId = false;
11461   if (getLangOpts().DebuggerCastResultToId &&
11462       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11463     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11464     if (Result.isInvalid()) {
11465       return QualType();
11466     }
11467     Init = Result.get();
11468     DefaultedAnyToId = true;
11469   }
11470 
11471   // C++ [dcl.decomp]p1:
11472   //   If the assignment-expression [...] has array type A and no ref-qualifier
11473   //   is present, e has type cv A
11474   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11475       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11476       DeduceInit->getType()->isConstantArrayType())
11477     return Context.getQualifiedType(DeduceInit->getType(),
11478                                     Type.getQualifiers());
11479 
11480   QualType DeducedType;
11481   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11482     if (!IsInitCapture)
11483       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11484     else if (isa<InitListExpr>(Init))
11485       Diag(Range.getBegin(),
11486            diag::err_init_capture_deduction_failure_from_init_list)
11487           << VN
11488           << (DeduceInit->getType().isNull() ? TSI->getType()
11489                                              : DeduceInit->getType())
11490           << DeduceInit->getSourceRange();
11491     else
11492       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11493           << VN << TSI->getType()
11494           << (DeduceInit->getType().isNull() ? TSI->getType()
11495                                              : DeduceInit->getType())
11496           << DeduceInit->getSourceRange();
11497   }
11498 
11499   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11500   // 'id' instead of a specific object type prevents most of our usual
11501   // checks.
11502   // We only want to warn outside of template instantiations, though:
11503   // inside a template, the 'id' could have come from a parameter.
11504   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11505       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11506     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11507     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11508   }
11509 
11510   return DeducedType;
11511 }
11512 
11513 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11514                                          Expr *Init) {
11515   assert(!Init || !Init->containsErrors());
11516   QualType DeducedType = deduceVarTypeFromInitializer(
11517       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11518       VDecl->getSourceRange(), DirectInit, Init);
11519   if (DeducedType.isNull()) {
11520     VDecl->setInvalidDecl();
11521     return true;
11522   }
11523 
11524   VDecl->setType(DeducedType);
11525   assert(VDecl->isLinkageValid());
11526 
11527   // In ARC, infer lifetime.
11528   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11529     VDecl->setInvalidDecl();
11530 
11531   if (getLangOpts().OpenCL)
11532     deduceOpenCLAddressSpace(VDecl);
11533 
11534   // If this is a redeclaration, check that the type we just deduced matches
11535   // the previously declared type.
11536   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11537     // We never need to merge the type, because we cannot form an incomplete
11538     // array of auto, nor deduce such a type.
11539     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11540   }
11541 
11542   // Check the deduced type is valid for a variable declaration.
11543   CheckVariableDeclarationType(VDecl);
11544   return VDecl->isInvalidDecl();
11545 }
11546 
11547 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11548                                               SourceLocation Loc) {
11549   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11550     Init = EWC->getSubExpr();
11551 
11552   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11553     Init = CE->getSubExpr();
11554 
11555   QualType InitType = Init->getType();
11556   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11557           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11558          "shouldn't be called if type doesn't have a non-trivial C struct");
11559   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11560     for (auto I : ILE->inits()) {
11561       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11562           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11563         continue;
11564       SourceLocation SL = I->getExprLoc();
11565       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11566     }
11567     return;
11568   }
11569 
11570   if (isa<ImplicitValueInitExpr>(Init)) {
11571     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11572       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11573                             NTCUK_Init);
11574   } else {
11575     // Assume all other explicit initializers involving copying some existing
11576     // object.
11577     // TODO: ignore any explicit initializers where we can guarantee
11578     // copy-elision.
11579     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11580       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11581   }
11582 }
11583 
11584 namespace {
11585 
11586 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11587   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11588   // in the source code or implicitly by the compiler if it is in a union
11589   // defined in a system header and has non-trivial ObjC ownership
11590   // qualifications. We don't want those fields to participate in determining
11591   // whether the containing union is non-trivial.
11592   return FD->hasAttr<UnavailableAttr>();
11593 }
11594 
11595 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11596     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11597                                     void> {
11598   using Super =
11599       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11600                                     void>;
11601 
11602   DiagNonTrivalCUnionDefaultInitializeVisitor(
11603       QualType OrigTy, SourceLocation OrigLoc,
11604       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11605       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11606 
11607   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11608                      const FieldDecl *FD, bool InNonTrivialUnion) {
11609     if (const auto *AT = S.Context.getAsArrayType(QT))
11610       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11611                                      InNonTrivialUnion);
11612     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11613   }
11614 
11615   void visitARCStrong(QualType QT, const FieldDecl *FD,
11616                       bool InNonTrivialUnion) {
11617     if (InNonTrivialUnion)
11618       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11619           << 1 << 0 << QT << FD->getName();
11620   }
11621 
11622   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11623     if (InNonTrivialUnion)
11624       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11625           << 1 << 0 << QT << FD->getName();
11626   }
11627 
11628   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11629     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11630     if (RD->isUnion()) {
11631       if (OrigLoc.isValid()) {
11632         bool IsUnion = false;
11633         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11634           IsUnion = OrigRD->isUnion();
11635         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11636             << 0 << OrigTy << IsUnion << UseContext;
11637         // Reset OrigLoc so that this diagnostic is emitted only once.
11638         OrigLoc = SourceLocation();
11639       }
11640       InNonTrivialUnion = true;
11641     }
11642 
11643     if (InNonTrivialUnion)
11644       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11645           << 0 << 0 << QT.getUnqualifiedType() << "";
11646 
11647     for (const FieldDecl *FD : RD->fields())
11648       if (!shouldIgnoreForRecordTriviality(FD))
11649         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11650   }
11651 
11652   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11653 
11654   // The non-trivial C union type or the struct/union type that contains a
11655   // non-trivial C union.
11656   QualType OrigTy;
11657   SourceLocation OrigLoc;
11658   Sema::NonTrivialCUnionContext UseContext;
11659   Sema &S;
11660 };
11661 
11662 struct DiagNonTrivalCUnionDestructedTypeVisitor
11663     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11664   using Super =
11665       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11666 
11667   DiagNonTrivalCUnionDestructedTypeVisitor(
11668       QualType OrigTy, SourceLocation OrigLoc,
11669       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11670       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11671 
11672   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11673                      const FieldDecl *FD, bool InNonTrivialUnion) {
11674     if (const auto *AT = S.Context.getAsArrayType(QT))
11675       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11676                                      InNonTrivialUnion);
11677     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11678   }
11679 
11680   void visitARCStrong(QualType QT, const FieldDecl *FD,
11681                       bool InNonTrivialUnion) {
11682     if (InNonTrivialUnion)
11683       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11684           << 1 << 1 << QT << FD->getName();
11685   }
11686 
11687   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11688     if (InNonTrivialUnion)
11689       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11690           << 1 << 1 << QT << FD->getName();
11691   }
11692 
11693   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11694     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11695     if (RD->isUnion()) {
11696       if (OrigLoc.isValid()) {
11697         bool IsUnion = false;
11698         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11699           IsUnion = OrigRD->isUnion();
11700         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11701             << 1 << OrigTy << IsUnion << UseContext;
11702         // Reset OrigLoc so that this diagnostic is emitted only once.
11703         OrigLoc = SourceLocation();
11704       }
11705       InNonTrivialUnion = true;
11706     }
11707 
11708     if (InNonTrivialUnion)
11709       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11710           << 0 << 1 << QT.getUnqualifiedType() << "";
11711 
11712     for (const FieldDecl *FD : RD->fields())
11713       if (!shouldIgnoreForRecordTriviality(FD))
11714         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11715   }
11716 
11717   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11718   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11719                           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 DiagNonTrivalCUnionCopyVisitor
11730     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11731   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11732 
11733   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11734                                  Sema::NonTrivialCUnionContext UseContext,
11735                                  Sema &S)
11736       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11737 
11738   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11739                      const FieldDecl *FD, bool InNonTrivialUnion) {
11740     if (const auto *AT = S.Context.getAsArrayType(QT))
11741       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11742                                      InNonTrivialUnion);
11743     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11744   }
11745 
11746   void visitARCStrong(QualType QT, const FieldDecl *FD,
11747                       bool InNonTrivialUnion) {
11748     if (InNonTrivialUnion)
11749       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11750           << 1 << 2 << QT << FD->getName();
11751   }
11752 
11753   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11754     if (InNonTrivialUnion)
11755       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11756           << 1 << 2 << QT << FD->getName();
11757   }
11758 
11759   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11760     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11761     if (RD->isUnion()) {
11762       if (OrigLoc.isValid()) {
11763         bool IsUnion = false;
11764         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11765           IsUnion = OrigRD->isUnion();
11766         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11767             << 2 << OrigTy << IsUnion << UseContext;
11768         // Reset OrigLoc so that this diagnostic is emitted only once.
11769         OrigLoc = SourceLocation();
11770       }
11771       InNonTrivialUnion = true;
11772     }
11773 
11774     if (InNonTrivialUnion)
11775       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11776           << 0 << 2 << QT.getUnqualifiedType() << "";
11777 
11778     for (const FieldDecl *FD : RD->fields())
11779       if (!shouldIgnoreForRecordTriviality(FD))
11780         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11781   }
11782 
11783   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11784                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11785   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11786   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11787                             bool InNonTrivialUnion) {}
11788 
11789   // The non-trivial C union type or the struct/union type that contains a
11790   // non-trivial C union.
11791   QualType OrigTy;
11792   SourceLocation OrigLoc;
11793   Sema::NonTrivialCUnionContext UseContext;
11794   Sema &S;
11795 };
11796 
11797 } // namespace
11798 
11799 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11800                                  NonTrivialCUnionContext UseContext,
11801                                  unsigned NonTrivialKind) {
11802   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11803           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11804           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11805          "shouldn't be called if type doesn't have a non-trivial C union");
11806 
11807   if ((NonTrivialKind & NTCUK_Init) &&
11808       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11809     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11810         .visit(QT, nullptr, false);
11811   if ((NonTrivialKind & NTCUK_Destruct) &&
11812       QT.hasNonTrivialToPrimitiveDestructCUnion())
11813     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11814         .visit(QT, nullptr, false);
11815   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11816     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11817         .visit(QT, nullptr, false);
11818 }
11819 
11820 /// AddInitializerToDecl - Adds the initializer Init to the
11821 /// declaration dcl. If DirectInit is true, this is C++ direct
11822 /// initialization rather than copy initialization.
11823 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11824   // If there is no declaration, there was an error parsing it.  Just ignore
11825   // the initializer.
11826   if (!RealDecl || RealDecl->isInvalidDecl()) {
11827     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11828     return;
11829   }
11830 
11831   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11832     // Pure-specifiers are handled in ActOnPureSpecifier.
11833     Diag(Method->getLocation(), diag::err_member_function_initialization)
11834       << Method->getDeclName() << Init->getSourceRange();
11835     Method->setInvalidDecl();
11836     return;
11837   }
11838 
11839   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11840   if (!VDecl) {
11841     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11842     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11843     RealDecl->setInvalidDecl();
11844     return;
11845   }
11846 
11847   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11848   if (VDecl->getType()->isUndeducedType()) {
11849     // Attempt typo correction early so that the type of the init expression can
11850     // be deduced based on the chosen correction if the original init contains a
11851     // TypoExpr.
11852     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11853     if (!Res.isUsable()) {
11854       // There are unresolved typos in Init, just drop them.
11855       // FIXME: improve the recovery strategy to preserve the Init.
11856       RealDecl->setInvalidDecl();
11857       return;
11858     }
11859     if (Res.get()->containsErrors()) {
11860       // Invalidate the decl as we don't know the type for recovery-expr yet.
11861       RealDecl->setInvalidDecl();
11862       VDecl->setInit(Res.get());
11863       return;
11864     }
11865     Init = Res.get();
11866 
11867     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11868       return;
11869   }
11870 
11871   // dllimport cannot be used on variable definitions.
11872   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11873     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11874     VDecl->setInvalidDecl();
11875     return;
11876   }
11877 
11878   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11879     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11880     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11881     VDecl->setInvalidDecl();
11882     return;
11883   }
11884 
11885   if (!VDecl->getType()->isDependentType()) {
11886     // A definition must end up with a complete type, which means it must be
11887     // complete with the restriction that an array type might be completed by
11888     // the initializer; note that later code assumes this restriction.
11889     QualType BaseDeclType = VDecl->getType();
11890     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11891       BaseDeclType = Array->getElementType();
11892     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11893                             diag::err_typecheck_decl_incomplete_type)) {
11894       RealDecl->setInvalidDecl();
11895       return;
11896     }
11897 
11898     // The variable can not have an abstract class type.
11899     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11900                                diag::err_abstract_type_in_decl,
11901                                AbstractVariableType))
11902       VDecl->setInvalidDecl();
11903   }
11904 
11905   // If adding the initializer will turn this declaration into a definition,
11906   // and we already have a definition for this variable, diagnose or otherwise
11907   // handle the situation.
11908   VarDecl *Def;
11909   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11910       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11911       !VDecl->isThisDeclarationADemotedDefinition() &&
11912       checkVarDeclRedefinition(Def, VDecl))
11913     return;
11914 
11915   if (getLangOpts().CPlusPlus) {
11916     // C++ [class.static.data]p4
11917     //   If a static data member is of const integral or const
11918     //   enumeration type, its declaration in the class definition can
11919     //   specify a constant-initializer which shall be an integral
11920     //   constant expression (5.19). In that case, the member can appear
11921     //   in integral constant expressions. The member shall still be
11922     //   defined in a namespace scope if it is used in the program and the
11923     //   namespace scope definition shall not contain an initializer.
11924     //
11925     // We already performed a redefinition check above, but for static
11926     // data members we also need to check whether there was an in-class
11927     // declaration with an initializer.
11928     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11929       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11930           << VDecl->getDeclName();
11931       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11932            diag::note_previous_initializer)
11933           << 0;
11934       return;
11935     }
11936 
11937     if (VDecl->hasLocalStorage())
11938       setFunctionHasBranchProtectedScope();
11939 
11940     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11941       VDecl->setInvalidDecl();
11942       return;
11943     }
11944   }
11945 
11946   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11947   // a kernel function cannot be initialized."
11948   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11949     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11950     VDecl->setInvalidDecl();
11951     return;
11952   }
11953 
11954   // The LoaderUninitialized attribute acts as a definition (of undef).
11955   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
11956     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
11957     VDecl->setInvalidDecl();
11958     return;
11959   }
11960 
11961   // Get the decls type and save a reference for later, since
11962   // CheckInitializerTypes may change it.
11963   QualType DclT = VDecl->getType(), SavT = DclT;
11964 
11965   // Expressions default to 'id' when we're in a debugger
11966   // and we are assigning it to a variable of Objective-C pointer type.
11967   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11968       Init->getType() == Context.UnknownAnyTy) {
11969     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11970     if (Result.isInvalid()) {
11971       VDecl->setInvalidDecl();
11972       return;
11973     }
11974     Init = Result.get();
11975   }
11976 
11977   // Perform the initialization.
11978   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11979   if (!VDecl->isInvalidDecl()) {
11980     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11981     InitializationKind Kind = InitializationKind::CreateForInit(
11982         VDecl->getLocation(), DirectInit, Init);
11983 
11984     MultiExprArg Args = Init;
11985     if (CXXDirectInit)
11986       Args = MultiExprArg(CXXDirectInit->getExprs(),
11987                           CXXDirectInit->getNumExprs());
11988 
11989     // Try to correct any TypoExprs in the initialization arguments.
11990     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11991       ExprResult Res = CorrectDelayedTyposInExpr(
11992           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11993             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11994             return Init.Failed() ? ExprError() : E;
11995           });
11996       if (Res.isInvalid()) {
11997         VDecl->setInvalidDecl();
11998       } else if (Res.get() != Args[Idx]) {
11999         Args[Idx] = Res.get();
12000       }
12001     }
12002     if (VDecl->isInvalidDecl())
12003       return;
12004 
12005     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12006                                    /*TopLevelOfInitList=*/false,
12007                                    /*TreatUnavailableAsInvalid=*/false);
12008     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12009     if (Result.isInvalid()) {
12010       // If the provied initializer fails to initialize the var decl,
12011       // we attach a recovery expr for better recovery.
12012       auto RecoveryExpr =
12013           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12014       if (RecoveryExpr.get())
12015         VDecl->setInit(RecoveryExpr.get());
12016       return;
12017     }
12018 
12019     Init = Result.getAs<Expr>();
12020   }
12021 
12022   // Check for self-references within variable initializers.
12023   // Variables declared within a function/method body (except for references)
12024   // are handled by a dataflow analysis.
12025   // This is undefined behavior in C++, but valid in C.
12026   if (getLangOpts().CPlusPlus) {
12027     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12028         VDecl->getType()->isReferenceType()) {
12029       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12030     }
12031   }
12032 
12033   // If the type changed, it means we had an incomplete type that was
12034   // completed by the initializer. For example:
12035   //   int ary[] = { 1, 3, 5 };
12036   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12037   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12038     VDecl->setType(DclT);
12039 
12040   if (!VDecl->isInvalidDecl()) {
12041     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12042 
12043     if (VDecl->hasAttr<BlocksAttr>())
12044       checkRetainCycles(VDecl, Init);
12045 
12046     // It is safe to assign a weak reference into a strong variable.
12047     // Although this code can still have problems:
12048     //   id x = self.weakProp;
12049     //   id y = self.weakProp;
12050     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12051     // paths through the function. This should be revisited if
12052     // -Wrepeated-use-of-weak is made flow-sensitive.
12053     if (FunctionScopeInfo *FSI = getCurFunction())
12054       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12055            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12056           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12057                            Init->getBeginLoc()))
12058         FSI->markSafeWeakUse(Init);
12059   }
12060 
12061   // The initialization is usually a full-expression.
12062   //
12063   // FIXME: If this is a braced initialization of an aggregate, it is not
12064   // an expression, and each individual field initializer is a separate
12065   // full-expression. For instance, in:
12066   //
12067   //   struct Temp { ~Temp(); };
12068   //   struct S { S(Temp); };
12069   //   struct T { S a, b; } t = { Temp(), Temp() }
12070   //
12071   // we should destroy the first Temp before constructing the second.
12072   ExprResult Result =
12073       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12074                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12075   if (Result.isInvalid()) {
12076     VDecl->setInvalidDecl();
12077     return;
12078   }
12079   Init = Result.get();
12080 
12081   // Attach the initializer to the decl.
12082   VDecl->setInit(Init);
12083 
12084   if (VDecl->isLocalVarDecl()) {
12085     // Don't check the initializer if the declaration is malformed.
12086     if (VDecl->isInvalidDecl()) {
12087       // do nothing
12088 
12089     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12090     // This is true even in C++ for OpenCL.
12091     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12092       CheckForConstantInitializer(Init, DclT);
12093 
12094     // Otherwise, C++ does not restrict the initializer.
12095     } else if (getLangOpts().CPlusPlus) {
12096       // do nothing
12097 
12098     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12099     // static storage duration shall be constant expressions or string literals.
12100     } else if (VDecl->getStorageClass() == SC_Static) {
12101       CheckForConstantInitializer(Init, DclT);
12102 
12103     // C89 is stricter than C99 for aggregate initializers.
12104     // C89 6.5.7p3: All the expressions [...] in an initializer list
12105     // for an object that has aggregate or union type shall be
12106     // constant expressions.
12107     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12108                isa<InitListExpr>(Init)) {
12109       const Expr *Culprit;
12110       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12111         Diag(Culprit->getExprLoc(),
12112              diag::ext_aggregate_init_not_constant)
12113           << Culprit->getSourceRange();
12114       }
12115     }
12116 
12117     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12118       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12119         if (VDecl->hasLocalStorage())
12120           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12121   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12122              VDecl->getLexicalDeclContext()->isRecord()) {
12123     // This is an in-class initialization for a static data member, e.g.,
12124     //
12125     // struct S {
12126     //   static const int value = 17;
12127     // };
12128 
12129     // C++ [class.mem]p4:
12130     //   A member-declarator can contain a constant-initializer only
12131     //   if it declares a static member (9.4) of const integral or
12132     //   const enumeration type, see 9.4.2.
12133     //
12134     // C++11 [class.static.data]p3:
12135     //   If a non-volatile non-inline const static data member is of integral
12136     //   or enumeration type, its declaration in the class definition can
12137     //   specify a brace-or-equal-initializer in which every initializer-clause
12138     //   that is an assignment-expression is a constant expression. A static
12139     //   data member of literal type can be declared in the class definition
12140     //   with the constexpr specifier; if so, its declaration shall specify a
12141     //   brace-or-equal-initializer in which every initializer-clause that is
12142     //   an assignment-expression is a constant expression.
12143 
12144     // Do nothing on dependent types.
12145     if (DclT->isDependentType()) {
12146 
12147     // Allow any 'static constexpr' members, whether or not they are of literal
12148     // type. We separately check that every constexpr variable is of literal
12149     // type.
12150     } else if (VDecl->isConstexpr()) {
12151 
12152     // Require constness.
12153     } else if (!DclT.isConstQualified()) {
12154       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12155         << Init->getSourceRange();
12156       VDecl->setInvalidDecl();
12157 
12158     // We allow integer constant expressions in all cases.
12159     } else if (DclT->isIntegralOrEnumerationType()) {
12160       // Check whether the expression is a constant expression.
12161       SourceLocation Loc;
12162       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12163         // In C++11, a non-constexpr const static data member with an
12164         // in-class initializer cannot be volatile.
12165         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12166       else if (Init->isValueDependent())
12167         ; // Nothing to check.
12168       else if (Init->isIntegerConstantExpr(Context, &Loc))
12169         ; // Ok, it's an ICE!
12170       else if (Init->getType()->isScopedEnumeralType() &&
12171                Init->isCXX11ConstantExpr(Context))
12172         ; // Ok, it is a scoped-enum constant expression.
12173       else if (Init->isEvaluatable(Context)) {
12174         // If we can constant fold the initializer through heroics, accept it,
12175         // but report this as a use of an extension for -pedantic.
12176         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12177           << Init->getSourceRange();
12178       } else {
12179         // Otherwise, this is some crazy unknown case.  Report the issue at the
12180         // location provided by the isIntegerConstantExpr failed check.
12181         Diag(Loc, diag::err_in_class_initializer_non_constant)
12182           << Init->getSourceRange();
12183         VDecl->setInvalidDecl();
12184       }
12185 
12186     // We allow foldable floating-point constants as an extension.
12187     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12188       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12189       // it anyway and provide a fixit to add the 'constexpr'.
12190       if (getLangOpts().CPlusPlus11) {
12191         Diag(VDecl->getLocation(),
12192              diag::ext_in_class_initializer_float_type_cxx11)
12193             << DclT << Init->getSourceRange();
12194         Diag(VDecl->getBeginLoc(),
12195              diag::note_in_class_initializer_float_type_cxx11)
12196             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12197       } else {
12198         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12199           << DclT << Init->getSourceRange();
12200 
12201         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12202           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12203             << Init->getSourceRange();
12204           VDecl->setInvalidDecl();
12205         }
12206       }
12207 
12208     // Suggest adding 'constexpr' in C++11 for literal types.
12209     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12210       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12211           << DclT << Init->getSourceRange()
12212           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12213       VDecl->setConstexpr(true);
12214 
12215     } else {
12216       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12217         << DclT << Init->getSourceRange();
12218       VDecl->setInvalidDecl();
12219     }
12220   } else if (VDecl->isFileVarDecl()) {
12221     // In C, extern is typically used to avoid tentative definitions when
12222     // declaring variables in headers, but adding an intializer makes it a
12223     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12224     // In C++, extern is often used to give implictly static const variables
12225     // external linkage, so don't warn in that case. If selectany is present,
12226     // this might be header code intended for C and C++ inclusion, so apply the
12227     // C++ rules.
12228     if (VDecl->getStorageClass() == SC_Extern &&
12229         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12230          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12231         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12232         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12233       Diag(VDecl->getLocation(), diag::warn_extern_init);
12234 
12235     // In Microsoft C++ mode, a const variable defined in namespace scope has
12236     // external linkage by default if the variable is declared with
12237     // __declspec(dllexport).
12238     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12239         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12240         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12241       VDecl->setStorageClass(SC_Extern);
12242 
12243     // C99 6.7.8p4. All file scoped initializers need to be constant.
12244     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12245       CheckForConstantInitializer(Init, DclT);
12246   }
12247 
12248   QualType InitType = Init->getType();
12249   if (!InitType.isNull() &&
12250       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12251        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12252     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12253 
12254   // We will represent direct-initialization similarly to copy-initialization:
12255   //    int x(1);  -as-> int x = 1;
12256   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12257   //
12258   // Clients that want to distinguish between the two forms, can check for
12259   // direct initializer using VarDecl::getInitStyle().
12260   // A major benefit is that clients that don't particularly care about which
12261   // exactly form was it (like the CodeGen) can handle both cases without
12262   // special case code.
12263 
12264   // C++ 8.5p11:
12265   // The form of initialization (using parentheses or '=') is generally
12266   // insignificant, but does matter when the entity being initialized has a
12267   // class type.
12268   if (CXXDirectInit) {
12269     assert(DirectInit && "Call-style initializer must be direct init.");
12270     VDecl->setInitStyle(VarDecl::CallInit);
12271   } else if (DirectInit) {
12272     // This must be list-initialization. No other way is direct-initialization.
12273     VDecl->setInitStyle(VarDecl::ListInit);
12274   }
12275 
12276   if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12277     DeclsToCheckForDeferredDiags.push_back(VDecl);
12278   CheckCompleteVariableDeclaration(VDecl);
12279 }
12280 
12281 /// ActOnInitializerError - Given that there was an error parsing an
12282 /// initializer for the given declaration, try to return to some form
12283 /// of sanity.
12284 void Sema::ActOnInitializerError(Decl *D) {
12285   // Our main concern here is re-establishing invariants like "a
12286   // variable's type is either dependent or complete".
12287   if (!D || D->isInvalidDecl()) return;
12288 
12289   VarDecl *VD = dyn_cast<VarDecl>(D);
12290   if (!VD) return;
12291 
12292   // Bindings are not usable if we can't make sense of the initializer.
12293   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12294     for (auto *BD : DD->bindings())
12295       BD->setInvalidDecl();
12296 
12297   // Auto types are meaningless if we can't make sense of the initializer.
12298   if (ParsingInitForAutoVars.count(D)) {
12299     D->setInvalidDecl();
12300     return;
12301   }
12302 
12303   QualType Ty = VD->getType();
12304   if (Ty->isDependentType()) return;
12305 
12306   // Require a complete type.
12307   if (RequireCompleteType(VD->getLocation(),
12308                           Context.getBaseElementType(Ty),
12309                           diag::err_typecheck_decl_incomplete_type)) {
12310     VD->setInvalidDecl();
12311     return;
12312   }
12313 
12314   // Require a non-abstract type.
12315   if (RequireNonAbstractType(VD->getLocation(), Ty,
12316                              diag::err_abstract_type_in_decl,
12317                              AbstractVariableType)) {
12318     VD->setInvalidDecl();
12319     return;
12320   }
12321 
12322   // Don't bother complaining about constructors or destructors,
12323   // though.
12324 }
12325 
12326 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12327   // If there is no declaration, there was an error parsing it. Just ignore it.
12328   if (!RealDecl)
12329     return;
12330 
12331   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12332     QualType Type = Var->getType();
12333 
12334     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12335     if (isa<DecompositionDecl>(RealDecl)) {
12336       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12337       Var->setInvalidDecl();
12338       return;
12339     }
12340 
12341     if (Type->isUndeducedType() &&
12342         DeduceVariableDeclarationType(Var, false, nullptr))
12343       return;
12344 
12345     // C++11 [class.static.data]p3: A static data member can be declared with
12346     // the constexpr specifier; if so, its declaration shall specify
12347     // a brace-or-equal-initializer.
12348     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12349     // the definition of a variable [...] or the declaration of a static data
12350     // member.
12351     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12352         !Var->isThisDeclarationADemotedDefinition()) {
12353       if (Var->isStaticDataMember()) {
12354         // C++1z removes the relevant rule; the in-class declaration is always
12355         // a definition there.
12356         if (!getLangOpts().CPlusPlus17 &&
12357             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12358           Diag(Var->getLocation(),
12359                diag::err_constexpr_static_mem_var_requires_init)
12360             << Var->getDeclName();
12361           Var->setInvalidDecl();
12362           return;
12363         }
12364       } else {
12365         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12366         Var->setInvalidDecl();
12367         return;
12368       }
12369     }
12370 
12371     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12372     // be initialized.
12373     if (!Var->isInvalidDecl() &&
12374         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12375         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12376       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12377       Var->setInvalidDecl();
12378       return;
12379     }
12380 
12381     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12382       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12383         if (!RD->hasTrivialDefaultConstructor()) {
12384           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12385           Var->setInvalidDecl();
12386           return;
12387         }
12388       }
12389       if (Var->getStorageClass() == SC_Extern) {
12390         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12391             << Var;
12392         Var->setInvalidDecl();
12393         return;
12394       }
12395     }
12396 
12397     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12398     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12399         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12400       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12401                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12402 
12403 
12404     switch (DefKind) {
12405     case VarDecl::Definition:
12406       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12407         break;
12408 
12409       // We have an out-of-line definition of a static data member
12410       // that has an in-class initializer, so we type-check this like
12411       // a declaration.
12412       //
12413       LLVM_FALLTHROUGH;
12414 
12415     case VarDecl::DeclarationOnly:
12416       // It's only a declaration.
12417 
12418       // Block scope. C99 6.7p7: If an identifier for an object is
12419       // declared with no linkage (C99 6.2.2p6), the type for the
12420       // object shall be complete.
12421       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12422           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12423           RequireCompleteType(Var->getLocation(), Type,
12424                               diag::err_typecheck_decl_incomplete_type))
12425         Var->setInvalidDecl();
12426 
12427       // Make sure that the type is not abstract.
12428       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12429           RequireNonAbstractType(Var->getLocation(), Type,
12430                                  diag::err_abstract_type_in_decl,
12431                                  AbstractVariableType))
12432         Var->setInvalidDecl();
12433       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12434           Var->getStorageClass() == SC_PrivateExtern) {
12435         Diag(Var->getLocation(), diag::warn_private_extern);
12436         Diag(Var->getLocation(), diag::note_private_extern);
12437       }
12438 
12439       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12440           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12441         ExternalDeclarations.push_back(Var);
12442 
12443       return;
12444 
12445     case VarDecl::TentativeDefinition:
12446       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12447       // object that has file scope without an initializer, and without a
12448       // storage-class specifier or with the storage-class specifier "static",
12449       // constitutes a tentative definition. Note: A tentative definition with
12450       // external linkage is valid (C99 6.2.2p5).
12451       if (!Var->isInvalidDecl()) {
12452         if (const IncompleteArrayType *ArrayT
12453                                     = Context.getAsIncompleteArrayType(Type)) {
12454           if (RequireCompleteSizedType(
12455                   Var->getLocation(), ArrayT->getElementType(),
12456                   diag::err_array_incomplete_or_sizeless_type))
12457             Var->setInvalidDecl();
12458         } else if (Var->getStorageClass() == SC_Static) {
12459           // C99 6.9.2p3: If the declaration of an identifier for an object is
12460           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12461           // declared type shall not be an incomplete type.
12462           // NOTE: code such as the following
12463           //     static struct s;
12464           //     struct s { int a; };
12465           // is accepted by gcc. Hence here we issue a warning instead of
12466           // an error and we do not invalidate the static declaration.
12467           // NOTE: to avoid multiple warnings, only check the first declaration.
12468           if (Var->isFirstDecl())
12469             RequireCompleteType(Var->getLocation(), Type,
12470                                 diag::ext_typecheck_decl_incomplete_type);
12471         }
12472       }
12473 
12474       // Record the tentative definition; we're done.
12475       if (!Var->isInvalidDecl())
12476         TentativeDefinitions.push_back(Var);
12477       return;
12478     }
12479 
12480     // Provide a specific diagnostic for uninitialized variable
12481     // definitions with incomplete array type.
12482     if (Type->isIncompleteArrayType()) {
12483       Diag(Var->getLocation(),
12484            diag::err_typecheck_incomplete_array_needs_initializer);
12485       Var->setInvalidDecl();
12486       return;
12487     }
12488 
12489     // Provide a specific diagnostic for uninitialized variable
12490     // definitions with reference type.
12491     if (Type->isReferenceType()) {
12492       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12493         << Var->getDeclName()
12494         << SourceRange(Var->getLocation(), Var->getLocation());
12495       Var->setInvalidDecl();
12496       return;
12497     }
12498 
12499     // Do not attempt to type-check the default initializer for a
12500     // variable with dependent type.
12501     if (Type->isDependentType())
12502       return;
12503 
12504     if (Var->isInvalidDecl())
12505       return;
12506 
12507     if (!Var->hasAttr<AliasAttr>()) {
12508       if (RequireCompleteType(Var->getLocation(),
12509                               Context.getBaseElementType(Type),
12510                               diag::err_typecheck_decl_incomplete_type)) {
12511         Var->setInvalidDecl();
12512         return;
12513       }
12514     } else {
12515       return;
12516     }
12517 
12518     // The variable can not have an abstract class type.
12519     if (RequireNonAbstractType(Var->getLocation(), Type,
12520                                diag::err_abstract_type_in_decl,
12521                                AbstractVariableType)) {
12522       Var->setInvalidDecl();
12523       return;
12524     }
12525 
12526     // Check for jumps past the implicit initializer.  C++0x
12527     // clarifies that this applies to a "variable with automatic
12528     // storage duration", not a "local variable".
12529     // C++11 [stmt.dcl]p3
12530     //   A program that jumps from a point where a variable with automatic
12531     //   storage duration is not in scope to a point where it is in scope is
12532     //   ill-formed unless the variable has scalar type, class type with a
12533     //   trivial default constructor and a trivial destructor, a cv-qualified
12534     //   version of one of these types, or an array of one of the preceding
12535     //   types and is declared without an initializer.
12536     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12537       if (const RecordType *Record
12538             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12539         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12540         // Mark the function (if we're in one) for further checking even if the
12541         // looser rules of C++11 do not require such checks, so that we can
12542         // diagnose incompatibilities with C++98.
12543         if (!CXXRecord->isPOD())
12544           setFunctionHasBranchProtectedScope();
12545       }
12546     }
12547     // In OpenCL, we can't initialize objects in the __local address space,
12548     // even implicitly, so don't synthesize an implicit initializer.
12549     if (getLangOpts().OpenCL &&
12550         Var->getType().getAddressSpace() == LangAS::opencl_local)
12551       return;
12552     // C++03 [dcl.init]p9:
12553     //   If no initializer is specified for an object, and the
12554     //   object is of (possibly cv-qualified) non-POD class type (or
12555     //   array thereof), the object shall be default-initialized; if
12556     //   the object is of const-qualified type, the underlying class
12557     //   type shall have a user-declared default
12558     //   constructor. Otherwise, if no initializer is specified for
12559     //   a non- static object, the object and its subobjects, if
12560     //   any, have an indeterminate initial value); if the object
12561     //   or any of its subobjects are of const-qualified type, the
12562     //   program is ill-formed.
12563     // C++0x [dcl.init]p11:
12564     //   If no initializer is specified for an object, the object is
12565     //   default-initialized; [...].
12566     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12567     InitializationKind Kind
12568       = InitializationKind::CreateDefault(Var->getLocation());
12569 
12570     InitializationSequence InitSeq(*this, Entity, Kind, None);
12571     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12572 
12573     if (Init.get()) {
12574       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12575       // This is important for template substitution.
12576       Var->setInitStyle(VarDecl::CallInit);
12577     } else if (Init.isInvalid()) {
12578       // If default-init fails, attach a recovery-expr initializer to track
12579       // that initialization was attempted and failed.
12580       auto RecoveryExpr =
12581           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12582       if (RecoveryExpr.get())
12583         Var->setInit(RecoveryExpr.get());
12584     }
12585 
12586     CheckCompleteVariableDeclaration(Var);
12587   }
12588 }
12589 
12590 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12591   // If there is no declaration, there was an error parsing it. Ignore it.
12592   if (!D)
12593     return;
12594 
12595   VarDecl *VD = dyn_cast<VarDecl>(D);
12596   if (!VD) {
12597     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12598     D->setInvalidDecl();
12599     return;
12600   }
12601 
12602   VD->setCXXForRangeDecl(true);
12603 
12604   // for-range-declaration cannot be given a storage class specifier.
12605   int Error = -1;
12606   switch (VD->getStorageClass()) {
12607   case SC_None:
12608     break;
12609   case SC_Extern:
12610     Error = 0;
12611     break;
12612   case SC_Static:
12613     Error = 1;
12614     break;
12615   case SC_PrivateExtern:
12616     Error = 2;
12617     break;
12618   case SC_Auto:
12619     Error = 3;
12620     break;
12621   case SC_Register:
12622     Error = 4;
12623     break;
12624   }
12625   if (Error != -1) {
12626     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12627       << VD->getDeclName() << Error;
12628     D->setInvalidDecl();
12629   }
12630 }
12631 
12632 StmtResult
12633 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12634                                  IdentifierInfo *Ident,
12635                                  ParsedAttributes &Attrs,
12636                                  SourceLocation AttrEnd) {
12637   // C++1y [stmt.iter]p1:
12638   //   A range-based for statement of the form
12639   //      for ( for-range-identifier : for-range-initializer ) statement
12640   //   is equivalent to
12641   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12642   DeclSpec DS(Attrs.getPool().getFactory());
12643 
12644   const char *PrevSpec;
12645   unsigned DiagID;
12646   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12647                      getPrintingPolicy());
12648 
12649   Declarator D(DS, DeclaratorContext::ForContext);
12650   D.SetIdentifier(Ident, IdentLoc);
12651   D.takeAttributes(Attrs, AttrEnd);
12652 
12653   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12654                 IdentLoc);
12655   Decl *Var = ActOnDeclarator(S, D);
12656   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12657   FinalizeDeclaration(Var);
12658   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12659                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12660 }
12661 
12662 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12663   if (var->isInvalidDecl()) return;
12664 
12665   if (getLangOpts().OpenCL) {
12666     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12667     // initialiser
12668     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12669         !var->hasInit()) {
12670       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12671           << 1 /*Init*/;
12672       var->setInvalidDecl();
12673       return;
12674     }
12675   }
12676 
12677   // In Objective-C, don't allow jumps past the implicit initialization of a
12678   // local retaining variable.
12679   if (getLangOpts().ObjC &&
12680       var->hasLocalStorage()) {
12681     switch (var->getType().getObjCLifetime()) {
12682     case Qualifiers::OCL_None:
12683     case Qualifiers::OCL_ExplicitNone:
12684     case Qualifiers::OCL_Autoreleasing:
12685       break;
12686 
12687     case Qualifiers::OCL_Weak:
12688     case Qualifiers::OCL_Strong:
12689       setFunctionHasBranchProtectedScope();
12690       break;
12691     }
12692   }
12693 
12694   if (var->hasLocalStorage() &&
12695       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12696     setFunctionHasBranchProtectedScope();
12697 
12698   // Warn about externally-visible variables being defined without a
12699   // prior declaration.  We only want to do this for global
12700   // declarations, but we also specifically need to avoid doing it for
12701   // class members because the linkage of an anonymous class can
12702   // change if it's later given a typedef name.
12703   if (var->isThisDeclarationADefinition() &&
12704       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12705       var->isExternallyVisible() && var->hasLinkage() &&
12706       !var->isInline() && !var->getDescribedVarTemplate() &&
12707       !isa<VarTemplatePartialSpecializationDecl>(var) &&
12708       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12709       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12710                                   var->getLocation())) {
12711     // Find a previous declaration that's not a definition.
12712     VarDecl *prev = var->getPreviousDecl();
12713     while (prev && prev->isThisDeclarationADefinition())
12714       prev = prev->getPreviousDecl();
12715 
12716     if (!prev) {
12717       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12718       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12719           << /* variable */ 0;
12720     }
12721   }
12722 
12723   // Cache the result of checking for constant initialization.
12724   Optional<bool> CacheHasConstInit;
12725   const Expr *CacheCulprit = nullptr;
12726   auto checkConstInit = [&]() mutable {
12727     if (!CacheHasConstInit)
12728       CacheHasConstInit = var->getInit()->isConstantInitializer(
12729             Context, var->getType()->isReferenceType(), &CacheCulprit);
12730     return *CacheHasConstInit;
12731   };
12732 
12733   if (var->getTLSKind() == VarDecl::TLS_Static) {
12734     if (var->getType().isDestructedType()) {
12735       // GNU C++98 edits for __thread, [basic.start.term]p3:
12736       //   The type of an object with thread storage duration shall not
12737       //   have a non-trivial destructor.
12738       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12739       if (getLangOpts().CPlusPlus11)
12740         Diag(var->getLocation(), diag::note_use_thread_local);
12741     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12742       if (!checkConstInit()) {
12743         // GNU C++98 edits for __thread, [basic.start.init]p4:
12744         //   An object of thread storage duration shall not require dynamic
12745         //   initialization.
12746         // FIXME: Need strict checking here.
12747         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12748           << CacheCulprit->getSourceRange();
12749         if (getLangOpts().CPlusPlus11)
12750           Diag(var->getLocation(), diag::note_use_thread_local);
12751       }
12752     }
12753   }
12754 
12755   // Apply section attributes and pragmas to global variables.
12756   bool GlobalStorage = var->hasGlobalStorage();
12757   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12758       !inTemplateInstantiation()) {
12759     PragmaStack<StringLiteral *> *Stack = nullptr;
12760     int SectionFlags = ASTContext::PSF_Read;
12761     if (var->getType().isConstQualified())
12762       Stack = &ConstSegStack;
12763     else if (!var->getInit()) {
12764       Stack = &BSSSegStack;
12765       SectionFlags |= ASTContext::PSF_Write;
12766     } else {
12767       Stack = &DataSegStack;
12768       SectionFlags |= ASTContext::PSF_Write;
12769     }
12770     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12771       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12772         SectionFlags |= ASTContext::PSF_Implicit;
12773       UnifySection(SA->getName(), SectionFlags, var);
12774     } else if (Stack->CurrentValue) {
12775       SectionFlags |= ASTContext::PSF_Implicit;
12776       auto SectionName = Stack->CurrentValue->getString();
12777       var->addAttr(SectionAttr::CreateImplicit(
12778           Context, SectionName, Stack->CurrentPragmaLocation,
12779           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12780       if (UnifySection(SectionName, SectionFlags, var))
12781         var->dropAttr<SectionAttr>();
12782     }
12783 
12784     // Apply the init_seg attribute if this has an initializer.  If the
12785     // initializer turns out to not be dynamic, we'll end up ignoring this
12786     // attribute.
12787     if (CurInitSeg && var->getInit())
12788       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12789                                                CurInitSegLoc,
12790                                                AttributeCommonInfo::AS_Pragma));
12791   }
12792 
12793   // All the following checks are C++ only.
12794   if (!getLangOpts().CPlusPlus) {
12795       // If this variable must be emitted, add it as an initializer for the
12796       // current module.
12797      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12798        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12799      return;
12800   }
12801 
12802   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12803     CheckCompleteDecompositionDeclaration(DD);
12804 
12805   QualType type = var->getType();
12806   if (type->isDependentType()) return;
12807 
12808   if (var->hasAttr<BlocksAttr>())
12809     getCurFunction()->addByrefBlockVar(var);
12810 
12811   Expr *Init = var->getInit();
12812   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12813   QualType baseType = Context.getBaseElementType(type);
12814 
12815   if (Init && !Init->isValueDependent()) {
12816     if (var->isConstexpr()) {
12817       SmallVector<PartialDiagnosticAt, 8> Notes;
12818       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12819         SourceLocation DiagLoc = var->getLocation();
12820         // If the note doesn't add any useful information other than a source
12821         // location, fold it into the primary diagnostic.
12822         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12823               diag::note_invalid_subexpr_in_const_expr) {
12824           DiagLoc = Notes[0].first;
12825           Notes.clear();
12826         }
12827         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12828           << var << Init->getSourceRange();
12829         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12830           Diag(Notes[I].first, Notes[I].second);
12831       }
12832     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12833       // Check whether the initializer of a const variable of integral or
12834       // enumeration type is an ICE now, since we can't tell whether it was
12835       // initialized by a constant expression if we check later.
12836       var->checkInitIsICE();
12837     }
12838 
12839     // Don't emit further diagnostics about constexpr globals since they
12840     // were just diagnosed.
12841     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12842       // FIXME: Need strict checking in C++03 here.
12843       bool DiagErr = getLangOpts().CPlusPlus11
12844           ? !var->checkInitIsICE() : !checkConstInit();
12845       if (DiagErr) {
12846         auto *Attr = var->getAttr<ConstInitAttr>();
12847         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12848           << Init->getSourceRange();
12849         Diag(Attr->getLocation(),
12850              diag::note_declared_required_constant_init_here)
12851             << Attr->getRange() << Attr->isConstinit();
12852         if (getLangOpts().CPlusPlus11) {
12853           APValue Value;
12854           SmallVector<PartialDiagnosticAt, 8> Notes;
12855           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12856           for (auto &it : Notes)
12857             Diag(it.first, it.second);
12858         } else {
12859           Diag(CacheCulprit->getExprLoc(),
12860                diag::note_invalid_subexpr_in_const_expr)
12861               << CacheCulprit->getSourceRange();
12862         }
12863       }
12864     }
12865     else if (!var->isConstexpr() && IsGlobal &&
12866              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12867                                     var->getLocation())) {
12868       // Warn about globals which don't have a constant initializer.  Don't
12869       // warn about globals with a non-trivial destructor because we already
12870       // warned about them.
12871       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12872       if (!(RD && !RD->hasTrivialDestructor())) {
12873         if (!checkConstInit())
12874           Diag(var->getLocation(), diag::warn_global_constructor)
12875             << Init->getSourceRange();
12876       }
12877     }
12878   }
12879 
12880   // Require the destructor.
12881   if (const RecordType *recordType = baseType->getAs<RecordType>())
12882     FinalizeVarWithDestructor(var, recordType);
12883 
12884   // If this variable must be emitted, add it as an initializer for the current
12885   // module.
12886   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12887     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12888 }
12889 
12890 /// Determines if a variable's alignment is dependent.
12891 static bool hasDependentAlignment(VarDecl *VD) {
12892   if (VD->getType()->isDependentType())
12893     return true;
12894   for (auto *I : VD->specific_attrs<AlignedAttr>())
12895     if (I->isAlignmentDependent())
12896       return true;
12897   return false;
12898 }
12899 
12900 /// Check if VD needs to be dllexport/dllimport due to being in a
12901 /// dllexport/import function.
12902 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12903   assert(VD->isStaticLocal());
12904 
12905   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12906 
12907   // Find outermost function when VD is in lambda function.
12908   while (FD && !getDLLAttr(FD) &&
12909          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12910          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12911     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12912   }
12913 
12914   if (!FD)
12915     return;
12916 
12917   // Static locals inherit dll attributes from their function.
12918   if (Attr *A = getDLLAttr(FD)) {
12919     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12920     NewAttr->setInherited(true);
12921     VD->addAttr(NewAttr);
12922   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12923     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12924     NewAttr->setInherited(true);
12925     VD->addAttr(NewAttr);
12926 
12927     // Export this function to enforce exporting this static variable even
12928     // if it is not used in this compilation unit.
12929     if (!FD->hasAttr<DLLExportAttr>())
12930       FD->addAttr(NewAttr);
12931 
12932   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12933     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12934     NewAttr->setInherited(true);
12935     VD->addAttr(NewAttr);
12936   }
12937 }
12938 
12939 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12940 /// any semantic actions necessary after any initializer has been attached.
12941 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12942   // Note that we are no longer parsing the initializer for this declaration.
12943   ParsingInitForAutoVars.erase(ThisDecl);
12944 
12945   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12946   if (!VD)
12947     return;
12948 
12949   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12950   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12951       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12952     if (PragmaClangBSSSection.Valid)
12953       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12954           Context, PragmaClangBSSSection.SectionName,
12955           PragmaClangBSSSection.PragmaLocation,
12956           AttributeCommonInfo::AS_Pragma));
12957     if (PragmaClangDataSection.Valid)
12958       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12959           Context, PragmaClangDataSection.SectionName,
12960           PragmaClangDataSection.PragmaLocation,
12961           AttributeCommonInfo::AS_Pragma));
12962     if (PragmaClangRodataSection.Valid)
12963       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12964           Context, PragmaClangRodataSection.SectionName,
12965           PragmaClangRodataSection.PragmaLocation,
12966           AttributeCommonInfo::AS_Pragma));
12967     if (PragmaClangRelroSection.Valid)
12968       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12969           Context, PragmaClangRelroSection.SectionName,
12970           PragmaClangRelroSection.PragmaLocation,
12971           AttributeCommonInfo::AS_Pragma));
12972   }
12973 
12974   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12975     for (auto *BD : DD->bindings()) {
12976       FinalizeDeclaration(BD);
12977     }
12978   }
12979 
12980   checkAttributesAfterMerging(*this, *VD);
12981 
12982   // Perform TLS alignment check here after attributes attached to the variable
12983   // which may affect the alignment have been processed. Only perform the check
12984   // if the target has a maximum TLS alignment (zero means no constraints).
12985   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12986     // Protect the check so that it's not performed on dependent types and
12987     // dependent alignments (we can't determine the alignment in that case).
12988     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12989         !VD->isInvalidDecl()) {
12990       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12991       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12992         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12993           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12994           << (unsigned)MaxAlignChars.getQuantity();
12995       }
12996     }
12997   }
12998 
12999   if (VD->isStaticLocal()) {
13000     CheckStaticLocalForDllExport(VD);
13001 
13002     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13003       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13004       // function, only __shared__ variables or variables without any device
13005       // memory qualifiers may be declared with static storage class.
13006       // Note: It is unclear how a function-scope non-const static variable
13007       // without device memory qualifier is implemented, therefore only static
13008       // const variable without device memory qualifier is allowed.
13009       [&]() {
13010         if (!getLangOpts().CUDA)
13011           return;
13012         if (VD->hasAttr<CUDASharedAttr>())
13013           return;
13014         if (VD->getType().isConstQualified() &&
13015             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13016           return;
13017         if (CUDADiagIfDeviceCode(VD->getLocation(),
13018                                  diag::err_device_static_local_var)
13019             << CurrentCUDATarget())
13020           VD->setInvalidDecl();
13021       }();
13022     }
13023   }
13024 
13025   // Perform check for initializers of device-side global variables.
13026   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13027   // 7.5). We must also apply the same checks to all __shared__
13028   // variables whether they are local or not. CUDA also allows
13029   // constant initializers for __constant__ and __device__ variables.
13030   if (getLangOpts().CUDA)
13031     checkAllowedCUDAInitializer(VD);
13032 
13033   // Grab the dllimport or dllexport attribute off of the VarDecl.
13034   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13035 
13036   // Imported static data members cannot be defined out-of-line.
13037   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13038     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13039         VD->isThisDeclarationADefinition()) {
13040       // We allow definitions of dllimport class template static data members
13041       // with a warning.
13042       CXXRecordDecl *Context =
13043         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13044       bool IsClassTemplateMember =
13045           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13046           Context->getDescribedClassTemplate();
13047 
13048       Diag(VD->getLocation(),
13049            IsClassTemplateMember
13050                ? diag::warn_attribute_dllimport_static_field_definition
13051                : diag::err_attribute_dllimport_static_field_definition);
13052       Diag(IA->getLocation(), diag::note_attribute);
13053       if (!IsClassTemplateMember)
13054         VD->setInvalidDecl();
13055     }
13056   }
13057 
13058   // dllimport/dllexport variables cannot be thread local, their TLS index
13059   // isn't exported with the variable.
13060   if (DLLAttr && VD->getTLSKind()) {
13061     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13062     if (F && getDLLAttr(F)) {
13063       assert(VD->isStaticLocal());
13064       // But if this is a static local in a dlimport/dllexport function, the
13065       // function will never be inlined, which means the var would never be
13066       // imported, so having it marked import/export is safe.
13067     } else {
13068       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13069                                                                     << DLLAttr;
13070       VD->setInvalidDecl();
13071     }
13072   }
13073 
13074   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13075     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13076       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13077       VD->dropAttr<UsedAttr>();
13078     }
13079   }
13080 
13081   const DeclContext *DC = VD->getDeclContext();
13082   // If there's a #pragma GCC visibility in scope, and this isn't a class
13083   // member, set the visibility of this variable.
13084   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13085     AddPushedVisibilityAttribute(VD);
13086 
13087   // FIXME: Warn on unused var template partial specializations.
13088   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13089     MarkUnusedFileScopedDecl(VD);
13090 
13091   // Now we have parsed the initializer and can update the table of magic
13092   // tag values.
13093   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13094       !VD->getType()->isIntegralOrEnumerationType())
13095     return;
13096 
13097   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13098     const Expr *MagicValueExpr = VD->getInit();
13099     if (!MagicValueExpr) {
13100       continue;
13101     }
13102     llvm::APSInt MagicValueInt;
13103     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
13104       Diag(I->getRange().getBegin(),
13105            diag::err_type_tag_for_datatype_not_ice)
13106         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13107       continue;
13108     }
13109     if (MagicValueInt.getActiveBits() > 64) {
13110       Diag(I->getRange().getBegin(),
13111            diag::err_type_tag_for_datatype_too_large)
13112         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13113       continue;
13114     }
13115     uint64_t MagicValue = MagicValueInt.getZExtValue();
13116     RegisterTypeTagForDatatype(I->getArgumentKind(),
13117                                MagicValue,
13118                                I->getMatchingCType(),
13119                                I->getLayoutCompatible(),
13120                                I->getMustBeNull());
13121   }
13122 }
13123 
13124 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13125   auto *VD = dyn_cast<VarDecl>(DD);
13126   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13127 }
13128 
13129 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13130                                                    ArrayRef<Decl *> Group) {
13131   SmallVector<Decl*, 8> Decls;
13132 
13133   if (DS.isTypeSpecOwned())
13134     Decls.push_back(DS.getRepAsDecl());
13135 
13136   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13137   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13138   bool DiagnosedMultipleDecomps = false;
13139   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13140   bool DiagnosedNonDeducedAuto = false;
13141 
13142   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13143     if (Decl *D = Group[i]) {
13144       // For declarators, there are some additional syntactic-ish checks we need
13145       // to perform.
13146       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13147         if (!FirstDeclaratorInGroup)
13148           FirstDeclaratorInGroup = DD;
13149         if (!FirstDecompDeclaratorInGroup)
13150           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13151         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13152             !hasDeducedAuto(DD))
13153           FirstNonDeducedAutoInGroup = DD;
13154 
13155         if (FirstDeclaratorInGroup != DD) {
13156           // A decomposition declaration cannot be combined with any other
13157           // declaration in the same group.
13158           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13159             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13160                  diag::err_decomp_decl_not_alone)
13161                 << FirstDeclaratorInGroup->getSourceRange()
13162                 << DD->getSourceRange();
13163             DiagnosedMultipleDecomps = true;
13164           }
13165 
13166           // A declarator that uses 'auto' in any way other than to declare a
13167           // variable with a deduced type cannot be combined with any other
13168           // declarator in the same group.
13169           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13170             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13171                  diag::err_auto_non_deduced_not_alone)
13172                 << FirstNonDeducedAutoInGroup->getType()
13173                        ->hasAutoForTrailingReturnType()
13174                 << FirstDeclaratorInGroup->getSourceRange()
13175                 << DD->getSourceRange();
13176             DiagnosedNonDeducedAuto = true;
13177           }
13178         }
13179       }
13180 
13181       Decls.push_back(D);
13182     }
13183   }
13184 
13185   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13186     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13187       handleTagNumbering(Tag, S);
13188       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13189           getLangOpts().CPlusPlus)
13190         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13191     }
13192   }
13193 
13194   return BuildDeclaratorGroup(Decls);
13195 }
13196 
13197 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13198 /// group, performing any necessary semantic checking.
13199 Sema::DeclGroupPtrTy
13200 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13201   // C++14 [dcl.spec.auto]p7: (DR1347)
13202   //   If the type that replaces the placeholder type is not the same in each
13203   //   deduction, the program is ill-formed.
13204   if (Group.size() > 1) {
13205     QualType Deduced;
13206     VarDecl *DeducedDecl = nullptr;
13207     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13208       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13209       if (!D || D->isInvalidDecl())
13210         break;
13211       DeducedType *DT = D->getType()->getContainedDeducedType();
13212       if (!DT || DT->getDeducedType().isNull())
13213         continue;
13214       if (Deduced.isNull()) {
13215         Deduced = DT->getDeducedType();
13216         DeducedDecl = D;
13217       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13218         auto *AT = dyn_cast<AutoType>(DT);
13219         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13220                         diag::err_auto_different_deductions)
13221                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13222                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13223                    << D->getDeclName();
13224         if (DeducedDecl->hasInit())
13225           Dia << DeducedDecl->getInit()->getSourceRange();
13226         if (D->getInit())
13227           Dia << D->getInit()->getSourceRange();
13228         D->setInvalidDecl();
13229         break;
13230       }
13231     }
13232   }
13233 
13234   ActOnDocumentableDecls(Group);
13235 
13236   return DeclGroupPtrTy::make(
13237       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13238 }
13239 
13240 void Sema::ActOnDocumentableDecl(Decl *D) {
13241   ActOnDocumentableDecls(D);
13242 }
13243 
13244 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13245   // Don't parse the comment if Doxygen diagnostics are ignored.
13246   if (Group.empty() || !Group[0])
13247     return;
13248 
13249   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13250                       Group[0]->getLocation()) &&
13251       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13252                       Group[0]->getLocation()))
13253     return;
13254 
13255   if (Group.size() >= 2) {
13256     // This is a decl group.  Normally it will contain only declarations
13257     // produced from declarator list.  But in case we have any definitions or
13258     // additional declaration references:
13259     //   'typedef struct S {} S;'
13260     //   'typedef struct S *S;'
13261     //   'struct S *pS;'
13262     // FinalizeDeclaratorGroup adds these as separate declarations.
13263     Decl *MaybeTagDecl = Group[0];
13264     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13265       Group = Group.slice(1);
13266     }
13267   }
13268 
13269   // FIMXE: We assume every Decl in the group is in the same file.
13270   // This is false when preprocessor constructs the group from decls in
13271   // different files (e. g. macros or #include).
13272   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13273 }
13274 
13275 /// Common checks for a parameter-declaration that should apply to both function
13276 /// parameters and non-type template parameters.
13277 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13278   // Check that there are no default arguments inside the type of this
13279   // parameter.
13280   if (getLangOpts().CPlusPlus)
13281     CheckExtraCXXDefaultArguments(D);
13282 
13283   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13284   if (D.getCXXScopeSpec().isSet()) {
13285     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13286       << D.getCXXScopeSpec().getRange();
13287   }
13288 
13289   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13290   // simple identifier except [...irrelevant cases...].
13291   switch (D.getName().getKind()) {
13292   case UnqualifiedIdKind::IK_Identifier:
13293     break;
13294 
13295   case UnqualifiedIdKind::IK_OperatorFunctionId:
13296   case UnqualifiedIdKind::IK_ConversionFunctionId:
13297   case UnqualifiedIdKind::IK_LiteralOperatorId:
13298   case UnqualifiedIdKind::IK_ConstructorName:
13299   case UnqualifiedIdKind::IK_DestructorName:
13300   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13301   case UnqualifiedIdKind::IK_DeductionGuideName:
13302     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13303       << GetNameForDeclarator(D).getName();
13304     break;
13305 
13306   case UnqualifiedIdKind::IK_TemplateId:
13307   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13308     // GetNameForDeclarator would not produce a useful name in this case.
13309     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13310     break;
13311   }
13312 }
13313 
13314 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13315 /// to introduce parameters into function prototype scope.
13316 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13317   const DeclSpec &DS = D.getDeclSpec();
13318 
13319   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13320 
13321   // C++03 [dcl.stc]p2 also permits 'auto'.
13322   StorageClass SC = SC_None;
13323   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13324     SC = SC_Register;
13325     // In C++11, the 'register' storage class specifier is deprecated.
13326     // In C++17, it is not allowed, but we tolerate it as an extension.
13327     if (getLangOpts().CPlusPlus11) {
13328       Diag(DS.getStorageClassSpecLoc(),
13329            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13330                                      : diag::warn_deprecated_register)
13331         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13332     }
13333   } else if (getLangOpts().CPlusPlus &&
13334              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13335     SC = SC_Auto;
13336   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13337     Diag(DS.getStorageClassSpecLoc(),
13338          diag::err_invalid_storage_class_in_func_decl);
13339     D.getMutableDeclSpec().ClearStorageClassSpecs();
13340   }
13341 
13342   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13343     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13344       << DeclSpec::getSpecifierName(TSCS);
13345   if (DS.isInlineSpecified())
13346     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13347         << getLangOpts().CPlusPlus17;
13348   if (DS.hasConstexprSpecifier())
13349     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13350         << 0 << D.getDeclSpec().getConstexprSpecifier();
13351 
13352   DiagnoseFunctionSpecifiers(DS);
13353 
13354   CheckFunctionOrTemplateParamDeclarator(S, D);
13355 
13356   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13357   QualType parmDeclType = TInfo->getType();
13358 
13359   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13360   IdentifierInfo *II = D.getIdentifier();
13361   if (II) {
13362     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13363                    ForVisibleRedeclaration);
13364     LookupName(R, S);
13365     if (R.isSingleResult()) {
13366       NamedDecl *PrevDecl = R.getFoundDecl();
13367       if (PrevDecl->isTemplateParameter()) {
13368         // Maybe we will complain about the shadowed template parameter.
13369         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13370         // Just pretend that we didn't see the previous declaration.
13371         PrevDecl = nullptr;
13372       } else if (S->isDeclScope(PrevDecl)) {
13373         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13374         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13375 
13376         // Recover by removing the name
13377         II = nullptr;
13378         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13379         D.setInvalidType(true);
13380       }
13381     }
13382   }
13383 
13384   // Temporarily put parameter variables in the translation unit, not
13385   // the enclosing context.  This prevents them from accidentally
13386   // looking like class members in C++.
13387   ParmVarDecl *New =
13388       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13389                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13390 
13391   if (D.isInvalidType())
13392     New->setInvalidDecl();
13393 
13394   assert(S->isFunctionPrototypeScope());
13395   assert(S->getFunctionPrototypeDepth() >= 1);
13396   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13397                     S->getNextFunctionPrototypeIndex());
13398 
13399   // Add the parameter declaration into this scope.
13400   S->AddDecl(New);
13401   if (II)
13402     IdResolver.AddDecl(New);
13403 
13404   ProcessDeclAttributes(S, New, D);
13405 
13406   if (D.getDeclSpec().isModulePrivateSpecified())
13407     Diag(New->getLocation(), diag::err_module_private_local)
13408       << 1 << New->getDeclName()
13409       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13410       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13411 
13412   if (New->hasAttr<BlocksAttr>()) {
13413     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13414   }
13415 
13416   if (getLangOpts().OpenCL)
13417     deduceOpenCLAddressSpace(New);
13418 
13419   return New;
13420 }
13421 
13422 /// Synthesizes a variable for a parameter arising from a
13423 /// typedef.
13424 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13425                                               SourceLocation Loc,
13426                                               QualType T) {
13427   /* FIXME: setting StartLoc == Loc.
13428      Would it be worth to modify callers so as to provide proper source
13429      location for the unnamed parameters, embedding the parameter's type? */
13430   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13431                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13432                                            SC_None, nullptr);
13433   Param->setImplicit();
13434   return Param;
13435 }
13436 
13437 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13438   // Don't diagnose unused-parameter errors in template instantiations; we
13439   // will already have done so in the template itself.
13440   if (inTemplateInstantiation())
13441     return;
13442 
13443   for (const ParmVarDecl *Parameter : Parameters) {
13444     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13445         !Parameter->hasAttr<UnusedAttr>()) {
13446       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13447         << Parameter->getDeclName();
13448     }
13449   }
13450 }
13451 
13452 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13453     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13454   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13455     return;
13456 
13457   // Warn if the return value is pass-by-value and larger than the specified
13458   // threshold.
13459   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13460     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13461     if (Size > LangOpts.NumLargeByValueCopy)
13462       Diag(D->getLocation(), diag::warn_return_value_size)
13463           << D->getDeclName() << Size;
13464   }
13465 
13466   // Warn if any parameter is pass-by-value and larger than the specified
13467   // threshold.
13468   for (const ParmVarDecl *Parameter : Parameters) {
13469     QualType T = Parameter->getType();
13470     if (T->isDependentType() || !T.isPODType(Context))
13471       continue;
13472     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13473     if (Size > LangOpts.NumLargeByValueCopy)
13474       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13475           << Parameter->getDeclName() << Size;
13476   }
13477 }
13478 
13479 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13480                                   SourceLocation NameLoc, IdentifierInfo *Name,
13481                                   QualType T, TypeSourceInfo *TSInfo,
13482                                   StorageClass SC) {
13483   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13484   if (getLangOpts().ObjCAutoRefCount &&
13485       T.getObjCLifetime() == Qualifiers::OCL_None &&
13486       T->isObjCLifetimeType()) {
13487 
13488     Qualifiers::ObjCLifetime lifetime;
13489 
13490     // Special cases for arrays:
13491     //   - if it's const, use __unsafe_unretained
13492     //   - otherwise, it's an error
13493     if (T->isArrayType()) {
13494       if (!T.isConstQualified()) {
13495         if (DelayedDiagnostics.shouldDelayDiagnostics())
13496           DelayedDiagnostics.add(
13497               sema::DelayedDiagnostic::makeForbiddenType(
13498               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13499         else
13500           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13501               << TSInfo->getTypeLoc().getSourceRange();
13502       }
13503       lifetime = Qualifiers::OCL_ExplicitNone;
13504     } else {
13505       lifetime = T->getObjCARCImplicitLifetime();
13506     }
13507     T = Context.getLifetimeQualifiedType(T, lifetime);
13508   }
13509 
13510   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13511                                          Context.getAdjustedParameterType(T),
13512                                          TSInfo, SC, nullptr);
13513 
13514   // Make a note if we created a new pack in the scope of a lambda, so that
13515   // we know that references to that pack must also be expanded within the
13516   // lambda scope.
13517   if (New->isParameterPack())
13518     if (auto *LSI = getEnclosingLambda())
13519       LSI->LocalPacks.push_back(New);
13520 
13521   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13522       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13523     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13524                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13525 
13526   // Parameters can not be abstract class types.
13527   // For record types, this is done by the AbstractClassUsageDiagnoser once
13528   // the class has been completely parsed.
13529   if (!CurContext->isRecord() &&
13530       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13531                              AbstractParamType))
13532     New->setInvalidDecl();
13533 
13534   // Parameter declarators cannot be interface types. All ObjC objects are
13535   // passed by reference.
13536   if (T->isObjCObjectType()) {
13537     SourceLocation TypeEndLoc =
13538         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13539     Diag(NameLoc,
13540          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13541       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13542     T = Context.getObjCObjectPointerType(T);
13543     New->setType(T);
13544   }
13545 
13546   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13547   // duration shall not be qualified by an address-space qualifier."
13548   // Since all parameters have automatic store duration, they can not have
13549   // an address space.
13550   if (T.getAddressSpace() != LangAS::Default &&
13551       // OpenCL allows function arguments declared to be an array of a type
13552       // to be qualified with an address space.
13553       !(getLangOpts().OpenCL &&
13554         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13555     Diag(NameLoc, diag::err_arg_with_address_space);
13556     New->setInvalidDecl();
13557   }
13558 
13559   return New;
13560 }
13561 
13562 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13563                                            SourceLocation LocAfterDecls) {
13564   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13565 
13566   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13567   // for a K&R function.
13568   if (!FTI.hasPrototype) {
13569     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13570       --i;
13571       if (FTI.Params[i].Param == nullptr) {
13572         SmallString<256> Code;
13573         llvm::raw_svector_ostream(Code)
13574             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13575         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13576             << FTI.Params[i].Ident
13577             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13578 
13579         // Implicitly declare the argument as type 'int' for lack of a better
13580         // type.
13581         AttributeFactory attrs;
13582         DeclSpec DS(attrs);
13583         const char* PrevSpec; // unused
13584         unsigned DiagID; // unused
13585         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13586                            DiagID, Context.getPrintingPolicy());
13587         // Use the identifier location for the type source range.
13588         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13589         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13590         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13591         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13592         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13593       }
13594     }
13595   }
13596 }
13597 
13598 Decl *
13599 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13600                               MultiTemplateParamsArg TemplateParameterLists,
13601                               SkipBodyInfo *SkipBody) {
13602   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13603   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13604   Scope *ParentScope = FnBodyScope->getParent();
13605 
13606   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13607   // we define a non-templated function definition, we will create a declaration
13608   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13609   // The base function declaration will have the equivalent of an `omp declare
13610   // variant` annotation which specifies the mangled definition as a
13611   // specialization function under the OpenMP context defined as part of the
13612   // `omp begin declare variant`.
13613   FunctionDecl *BaseFD = nullptr;
13614   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() &&
13615       TemplateParameterLists.empty())
13616     BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13617         ParentScope, D);
13618 
13619   D.setFunctionDefinitionKind(FDK_Definition);
13620   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13621   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13622 
13623   if (BaseFD)
13624     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
13625         cast<FunctionDecl>(Dcl), BaseFD);
13626 
13627   return Dcl;
13628 }
13629 
13630 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13631   Consumer.HandleInlineFunctionDefinition(D);
13632 }
13633 
13634 static bool
13635 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13636                                 const FunctionDecl *&PossiblePrototype) {
13637   // Don't warn about invalid declarations.
13638   if (FD->isInvalidDecl())
13639     return false;
13640 
13641   // Or declarations that aren't global.
13642   if (!FD->isGlobal())
13643     return false;
13644 
13645   // Don't warn about C++ member functions.
13646   if (isa<CXXMethodDecl>(FD))
13647     return false;
13648 
13649   // Don't warn about 'main'.
13650   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13651     if (IdentifierInfo *II = FD->getIdentifier())
13652       if (II->isStr("main"))
13653         return false;
13654 
13655   // Don't warn about inline functions.
13656   if (FD->isInlined())
13657     return false;
13658 
13659   // Don't warn about function templates.
13660   if (FD->getDescribedFunctionTemplate())
13661     return false;
13662 
13663   // Don't warn about function template specializations.
13664   if (FD->isFunctionTemplateSpecialization())
13665     return false;
13666 
13667   // Don't warn for OpenCL kernels.
13668   if (FD->hasAttr<OpenCLKernelAttr>())
13669     return false;
13670 
13671   // Don't warn on explicitly deleted functions.
13672   if (FD->isDeleted())
13673     return false;
13674 
13675   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13676        Prev; Prev = Prev->getPreviousDecl()) {
13677     // Ignore any declarations that occur in function or method
13678     // scope, because they aren't visible from the header.
13679     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13680       continue;
13681 
13682     PossiblePrototype = Prev;
13683     return Prev->getType()->isFunctionNoProtoType();
13684   }
13685 
13686   return true;
13687 }
13688 
13689 void
13690 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13691                                    const FunctionDecl *EffectiveDefinition,
13692                                    SkipBodyInfo *SkipBody) {
13693   const FunctionDecl *Definition = EffectiveDefinition;
13694   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13695     // If this is a friend function defined in a class template, it does not
13696     // have a body until it is used, nevertheless it is a definition, see
13697     // [temp.inst]p2:
13698     //
13699     // ... for the purpose of determining whether an instantiated redeclaration
13700     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13701     // corresponds to a definition in the template is considered to be a
13702     // definition.
13703     //
13704     // The following code must produce redefinition error:
13705     //
13706     //     template<typename T> struct C20 { friend void func_20() {} };
13707     //     C20<int> c20i;
13708     //     void func_20() {}
13709     //
13710     for (auto I : FD->redecls()) {
13711       if (I != FD && !I->isInvalidDecl() &&
13712           I->getFriendObjectKind() != Decl::FOK_None) {
13713         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13714           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13715             // A merged copy of the same function, instantiated as a member of
13716             // the same class, is OK.
13717             if (declaresSameEntity(OrigFD, Original) &&
13718                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13719                                    cast<Decl>(FD->getLexicalDeclContext())))
13720               continue;
13721           }
13722 
13723           if (Original->isThisDeclarationADefinition()) {
13724             Definition = I;
13725             break;
13726           }
13727         }
13728       }
13729     }
13730   }
13731 
13732   if (!Definition)
13733     // Similar to friend functions a friend function template may be a
13734     // definition and do not have a body if it is instantiated in a class
13735     // template.
13736     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13737       for (auto I : FTD->redecls()) {
13738         auto D = cast<FunctionTemplateDecl>(I);
13739         if (D != FTD) {
13740           assert(!D->isThisDeclarationADefinition() &&
13741                  "More than one definition in redeclaration chain");
13742           if (D->getFriendObjectKind() != Decl::FOK_None)
13743             if (FunctionTemplateDecl *FT =
13744                                        D->getInstantiatedFromMemberTemplate()) {
13745               if (FT->isThisDeclarationADefinition()) {
13746                 Definition = D->getTemplatedDecl();
13747                 break;
13748               }
13749             }
13750         }
13751       }
13752     }
13753 
13754   if (!Definition)
13755     return;
13756 
13757   if (canRedefineFunction(Definition, getLangOpts()))
13758     return;
13759 
13760   // Don't emit an error when this is redefinition of a typo-corrected
13761   // definition.
13762   if (TypoCorrectedFunctionDefinitions.count(Definition))
13763     return;
13764 
13765   // If we don't have a visible definition of the function, and it's inline or
13766   // a template, skip the new definition.
13767   if (SkipBody && !hasVisibleDefinition(Definition) &&
13768       (Definition->getFormalLinkage() == InternalLinkage ||
13769        Definition->isInlined() ||
13770        Definition->getDescribedFunctionTemplate() ||
13771        Definition->getNumTemplateParameterLists())) {
13772     SkipBody->ShouldSkip = true;
13773     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13774     if (auto *TD = Definition->getDescribedFunctionTemplate())
13775       makeMergedDefinitionVisible(TD);
13776     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13777     return;
13778   }
13779 
13780   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13781       Definition->getStorageClass() == SC_Extern)
13782     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13783         << FD->getDeclName() << getLangOpts().CPlusPlus;
13784   else
13785     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13786 
13787   Diag(Definition->getLocation(), diag::note_previous_definition);
13788   FD->setInvalidDecl();
13789 }
13790 
13791 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13792                                    Sema &S) {
13793   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13794 
13795   LambdaScopeInfo *LSI = S.PushLambdaScope();
13796   LSI->CallOperator = CallOperator;
13797   LSI->Lambda = LambdaClass;
13798   LSI->ReturnType = CallOperator->getReturnType();
13799   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13800 
13801   if (LCD == LCD_None)
13802     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13803   else if (LCD == LCD_ByCopy)
13804     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13805   else if (LCD == LCD_ByRef)
13806     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13807   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13808 
13809   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13810   LSI->Mutable = !CallOperator->isConst();
13811 
13812   // Add the captures to the LSI so they can be noted as already
13813   // captured within tryCaptureVar.
13814   auto I = LambdaClass->field_begin();
13815   for (const auto &C : LambdaClass->captures()) {
13816     if (C.capturesVariable()) {
13817       VarDecl *VD = C.getCapturedVar();
13818       if (VD->isInitCapture())
13819         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13820       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13821       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13822           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13823           /*EllipsisLoc*/C.isPackExpansion()
13824                          ? C.getEllipsisLoc() : SourceLocation(),
13825           I->getType(), /*Invalid*/false);
13826 
13827     } else if (C.capturesThis()) {
13828       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13829                           C.getCaptureKind() == LCK_StarThis);
13830     } else {
13831       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13832                              I->getType());
13833     }
13834     ++I;
13835   }
13836 }
13837 
13838 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13839                                     SkipBodyInfo *SkipBody) {
13840   if (!D) {
13841     // Parsing the function declaration failed in some way. Push on a fake scope
13842     // anyway so we can try to parse the function body.
13843     PushFunctionScope();
13844     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13845     return D;
13846   }
13847 
13848   FunctionDecl *FD = nullptr;
13849 
13850   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13851     FD = FunTmpl->getTemplatedDecl();
13852   else
13853     FD = cast<FunctionDecl>(D);
13854 
13855   // Do not push if it is a lambda because one is already pushed when building
13856   // the lambda in ActOnStartOfLambdaDefinition().
13857   if (!isLambdaCallOperator(FD))
13858     PushExpressionEvaluationContext(
13859         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
13860                           : ExprEvalContexts.back().Context);
13861 
13862   // Check for defining attributes before the check for redefinition.
13863   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13864     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13865     FD->dropAttr<AliasAttr>();
13866     FD->setInvalidDecl();
13867   }
13868   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13869     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13870     FD->dropAttr<IFuncAttr>();
13871     FD->setInvalidDecl();
13872   }
13873 
13874   // See if this is a redefinition. If 'will have body' is already set, then
13875   // these checks were already performed when it was set.
13876   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13877     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13878 
13879     // If we're skipping the body, we're done. Don't enter the scope.
13880     if (SkipBody && SkipBody->ShouldSkip)
13881       return D;
13882   }
13883 
13884   // Mark this function as "will have a body eventually".  This lets users to
13885   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13886   // this function.
13887   FD->setWillHaveBody();
13888 
13889   // If we are instantiating a generic lambda call operator, push
13890   // a LambdaScopeInfo onto the function stack.  But use the information
13891   // that's already been calculated (ActOnLambdaExpr) to prime the current
13892   // LambdaScopeInfo.
13893   // When the template operator is being specialized, the LambdaScopeInfo,
13894   // has to be properly restored so that tryCaptureVariable doesn't try
13895   // and capture any new variables. In addition when calculating potential
13896   // captures during transformation of nested lambdas, it is necessary to
13897   // have the LSI properly restored.
13898   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13899     assert(inTemplateInstantiation() &&
13900            "There should be an active template instantiation on the stack "
13901            "when instantiating a generic lambda!");
13902     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13903   } else {
13904     // Enter a new function scope
13905     PushFunctionScope();
13906   }
13907 
13908   // Builtin functions cannot be defined.
13909   if (unsigned BuiltinID = FD->getBuiltinID()) {
13910     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13911         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13912       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13913       FD->setInvalidDecl();
13914     }
13915   }
13916 
13917   // The return type of a function definition must be complete
13918   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13919   QualType ResultType = FD->getReturnType();
13920   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13921       !FD->isInvalidDecl() &&
13922       RequireCompleteType(FD->getLocation(), ResultType,
13923                           diag::err_func_def_incomplete_result))
13924     FD->setInvalidDecl();
13925 
13926   if (FnBodyScope)
13927     PushDeclContext(FnBodyScope, FD);
13928 
13929   // Check the validity of our function parameters
13930   CheckParmsForFunctionDef(FD->parameters(),
13931                            /*CheckParameterNames=*/true);
13932 
13933   // Add non-parameter declarations already in the function to the current
13934   // scope.
13935   if (FnBodyScope) {
13936     for (Decl *NPD : FD->decls()) {
13937       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13938       if (!NonParmDecl)
13939         continue;
13940       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13941              "parameters should not be in newly created FD yet");
13942 
13943       // If the decl has a name, make it accessible in the current scope.
13944       if (NonParmDecl->getDeclName())
13945         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13946 
13947       // Similarly, dive into enums and fish their constants out, making them
13948       // accessible in this scope.
13949       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13950         for (auto *EI : ED->enumerators())
13951           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13952       }
13953     }
13954   }
13955 
13956   // Introduce our parameters into the function scope
13957   for (auto Param : FD->parameters()) {
13958     Param->setOwningFunction(FD);
13959 
13960     // If this has an identifier, add it to the scope stack.
13961     if (Param->getIdentifier() && FnBodyScope) {
13962       CheckShadow(FnBodyScope, Param);
13963 
13964       PushOnScopeChains(Param, FnBodyScope);
13965     }
13966   }
13967 
13968   // Ensure that the function's exception specification is instantiated.
13969   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13970     ResolveExceptionSpec(D->getLocation(), FPT);
13971 
13972   // dllimport cannot be applied to non-inline function definitions.
13973   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13974       !FD->isTemplateInstantiation()) {
13975     assert(!FD->hasAttr<DLLExportAttr>());
13976     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13977     FD->setInvalidDecl();
13978     return D;
13979   }
13980   // We want to attach documentation to original Decl (which might be
13981   // a function template).
13982   ActOnDocumentableDecl(D);
13983   if (getCurLexicalContext()->isObjCContainer() &&
13984       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13985       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13986     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13987 
13988   return D;
13989 }
13990 
13991 /// Given the set of return statements within a function body,
13992 /// compute the variables that are subject to the named return value
13993 /// optimization.
13994 ///
13995 /// Each of the variables that is subject to the named return value
13996 /// optimization will be marked as NRVO variables in the AST, and any
13997 /// return statement that has a marked NRVO variable as its NRVO candidate can
13998 /// use the named return value optimization.
13999 ///
14000 /// This function applies a very simplistic algorithm for NRVO: if every return
14001 /// statement in the scope of a variable has the same NRVO candidate, that
14002 /// candidate is an NRVO variable.
14003 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14004   ReturnStmt **Returns = Scope->Returns.data();
14005 
14006   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14007     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14008       if (!NRVOCandidate->isNRVOVariable())
14009         Returns[I]->setNRVOCandidate(nullptr);
14010     }
14011   }
14012 }
14013 
14014 bool Sema::canDelayFunctionBody(const Declarator &D) {
14015   // We can't delay parsing the body of a constexpr function template (yet).
14016   if (D.getDeclSpec().hasConstexprSpecifier())
14017     return false;
14018 
14019   // We can't delay parsing the body of a function template with a deduced
14020   // return type (yet).
14021   if (D.getDeclSpec().hasAutoTypeSpec()) {
14022     // If the placeholder introduces a non-deduced trailing return type,
14023     // we can still delay parsing it.
14024     if (D.getNumTypeObjects()) {
14025       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14026       if (Outer.Kind == DeclaratorChunk::Function &&
14027           Outer.Fun.hasTrailingReturnType()) {
14028         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14029         return Ty.isNull() || !Ty->isUndeducedType();
14030       }
14031     }
14032     return false;
14033   }
14034 
14035   return true;
14036 }
14037 
14038 bool Sema::canSkipFunctionBody(Decl *D) {
14039   // We cannot skip the body of a function (or function template) which is
14040   // constexpr, since we may need to evaluate its body in order to parse the
14041   // rest of the file.
14042   // We cannot skip the body of a function with an undeduced return type,
14043   // because any callers of that function need to know the type.
14044   if (const FunctionDecl *FD = D->getAsFunction()) {
14045     if (FD->isConstexpr())
14046       return false;
14047     // We can't simply call Type::isUndeducedType here, because inside template
14048     // auto can be deduced to a dependent type, which is not considered
14049     // "undeduced".
14050     if (FD->getReturnType()->getContainedDeducedType())
14051       return false;
14052   }
14053   return Consumer.shouldSkipFunctionBody(D);
14054 }
14055 
14056 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14057   if (!Decl)
14058     return nullptr;
14059   if (FunctionDecl *FD = Decl->getAsFunction())
14060     FD->setHasSkippedBody();
14061   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14062     MD->setHasSkippedBody();
14063   return Decl;
14064 }
14065 
14066 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14067   return ActOnFinishFunctionBody(D, BodyArg, false);
14068 }
14069 
14070 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14071 /// body.
14072 class ExitFunctionBodyRAII {
14073 public:
14074   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14075   ~ExitFunctionBodyRAII() {
14076     if (!IsLambda)
14077       S.PopExpressionEvaluationContext();
14078   }
14079 
14080 private:
14081   Sema &S;
14082   bool IsLambda = false;
14083 };
14084 
14085 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14086   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14087 
14088   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14089     if (EscapeInfo.count(BD))
14090       return EscapeInfo[BD];
14091 
14092     bool R = false;
14093     const BlockDecl *CurBD = BD;
14094 
14095     do {
14096       R = !CurBD->doesNotEscape();
14097       if (R)
14098         break;
14099       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14100     } while (CurBD);
14101 
14102     return EscapeInfo[BD] = R;
14103   };
14104 
14105   // If the location where 'self' is implicitly retained is inside a escaping
14106   // block, emit a diagnostic.
14107   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14108        S.ImplicitlyRetainedSelfLocs)
14109     if (IsOrNestedInEscapingBlock(P.second))
14110       S.Diag(P.first, diag::warn_implicitly_retains_self)
14111           << FixItHint::CreateInsertion(P.first, "self->");
14112 }
14113 
14114 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14115                                     bool IsInstantiation) {
14116   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14117 
14118   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14119   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14120 
14121   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14122     CheckCompletedCoroutineBody(FD, Body);
14123 
14124   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14125   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14126   // meant to pop the context added in ActOnStartOfFunctionDef().
14127   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14128 
14129   if (FD) {
14130     FD->setBody(Body);
14131     FD->setWillHaveBody(false);
14132 
14133     if (getLangOpts().CPlusPlus14) {
14134       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14135           FD->getReturnType()->isUndeducedType()) {
14136         // If the function has a deduced result type but contains no 'return'
14137         // statements, the result type as written must be exactly 'auto', and
14138         // the deduced result type is 'void'.
14139         if (!FD->getReturnType()->getAs<AutoType>()) {
14140           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14141               << FD->getReturnType();
14142           FD->setInvalidDecl();
14143         } else {
14144           // Substitute 'void' for the 'auto' in the type.
14145           TypeLoc ResultType = getReturnTypeLoc(FD);
14146           Context.adjustDeducedFunctionResultType(
14147               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14148         }
14149       }
14150     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14151       // In C++11, we don't use 'auto' deduction rules for lambda call
14152       // operators because we don't support return type deduction.
14153       auto *LSI = getCurLambda();
14154       if (LSI->HasImplicitReturnType) {
14155         deduceClosureReturnType(*LSI);
14156 
14157         // C++11 [expr.prim.lambda]p4:
14158         //   [...] if there are no return statements in the compound-statement
14159         //   [the deduced type is] the type void
14160         QualType RetType =
14161             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14162 
14163         // Update the return type to the deduced type.
14164         const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14165         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14166                                             Proto->getExtProtoInfo()));
14167       }
14168     }
14169 
14170     // If the function implicitly returns zero (like 'main') or is naked,
14171     // don't complain about missing return statements.
14172     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14173       WP.disableCheckFallThrough();
14174 
14175     // MSVC permits the use of pure specifier (=0) on function definition,
14176     // defined at class scope, warn about this non-standard construct.
14177     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14178       Diag(FD->getLocation(), diag::ext_pure_function_definition);
14179 
14180     if (!FD->isInvalidDecl()) {
14181       // Don't diagnose unused parameters of defaulted or deleted functions.
14182       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14183         DiagnoseUnusedParameters(FD->parameters());
14184       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14185                                              FD->getReturnType(), FD);
14186 
14187       // If this is a structor, we need a vtable.
14188       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14189         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14190       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14191         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14192 
14193       // Try to apply the named return value optimization. We have to check
14194       // if we can do this here because lambdas keep return statements around
14195       // to deduce an implicit return type.
14196       if (FD->getReturnType()->isRecordType() &&
14197           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14198         computeNRVO(Body, getCurFunction());
14199     }
14200 
14201     // GNU warning -Wmissing-prototypes:
14202     //   Warn if a global function is defined without a previous
14203     //   prototype declaration. This warning is issued even if the
14204     //   definition itself provides a prototype. The aim is to detect
14205     //   global functions that fail to be declared in header files.
14206     const FunctionDecl *PossiblePrototype = nullptr;
14207     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14208       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14209 
14210       if (PossiblePrototype) {
14211         // We found a declaration that is not a prototype,
14212         // but that could be a zero-parameter prototype
14213         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14214           TypeLoc TL = TI->getTypeLoc();
14215           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14216             Diag(PossiblePrototype->getLocation(),
14217                  diag::note_declaration_not_a_prototype)
14218                 << (FD->getNumParams() != 0)
14219                 << (FD->getNumParams() == 0
14220                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14221                         : FixItHint{});
14222         }
14223       } else {
14224         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14225             << /* function */ 1
14226             << (FD->getStorageClass() == SC_None
14227                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
14228                                                  "static ")
14229                     : FixItHint{});
14230       }
14231 
14232       // GNU warning -Wstrict-prototypes
14233       //   Warn if K&R function is defined without a previous declaration.
14234       //   This warning is issued only if the definition itself does not provide
14235       //   a prototype. Only K&R definitions do not provide a prototype.
14236       if (!FD->hasWrittenPrototype()) {
14237         TypeSourceInfo *TI = FD->getTypeSourceInfo();
14238         TypeLoc TL = TI->getTypeLoc();
14239         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14240         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14241       }
14242     }
14243 
14244     // Warn on CPUDispatch with an actual body.
14245     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14246       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14247         if (!CmpndBody->body_empty())
14248           Diag(CmpndBody->body_front()->getBeginLoc(),
14249                diag::warn_dispatch_body_ignored);
14250 
14251     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14252       const CXXMethodDecl *KeyFunction;
14253       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14254           MD->isVirtual() &&
14255           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14256           MD == KeyFunction->getCanonicalDecl()) {
14257         // Update the key-function state if necessary for this ABI.
14258         if (FD->isInlined() &&
14259             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14260           Context.setNonKeyFunction(MD);
14261 
14262           // If the newly-chosen key function is already defined, then we
14263           // need to mark the vtable as used retroactively.
14264           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14265           const FunctionDecl *Definition;
14266           if (KeyFunction && KeyFunction->isDefined(Definition))
14267             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14268         } else {
14269           // We just defined they key function; mark the vtable as used.
14270           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14271         }
14272       }
14273     }
14274 
14275     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14276            "Function parsing confused");
14277   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14278     assert(MD == getCurMethodDecl() && "Method parsing confused");
14279     MD->setBody(Body);
14280     if (!MD->isInvalidDecl()) {
14281       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14282                                              MD->getReturnType(), MD);
14283 
14284       if (Body)
14285         computeNRVO(Body, getCurFunction());
14286     }
14287     if (getCurFunction()->ObjCShouldCallSuper) {
14288       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14289           << MD->getSelector().getAsString();
14290       getCurFunction()->ObjCShouldCallSuper = false;
14291     }
14292     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14293       const ObjCMethodDecl *InitMethod = nullptr;
14294       bool isDesignated =
14295           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14296       assert(isDesignated && InitMethod);
14297       (void)isDesignated;
14298 
14299       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14300         auto IFace = MD->getClassInterface();
14301         if (!IFace)
14302           return false;
14303         auto SuperD = IFace->getSuperClass();
14304         if (!SuperD)
14305           return false;
14306         return SuperD->getIdentifier() ==
14307             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14308       };
14309       // Don't issue this warning for unavailable inits or direct subclasses
14310       // of NSObject.
14311       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14312         Diag(MD->getLocation(),
14313              diag::warn_objc_designated_init_missing_super_call);
14314         Diag(InitMethod->getLocation(),
14315              diag::note_objc_designated_init_marked_here);
14316       }
14317       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14318     }
14319     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14320       // Don't issue this warning for unavaialable inits.
14321       if (!MD->isUnavailable())
14322         Diag(MD->getLocation(),
14323              diag::warn_objc_secondary_init_missing_init_call);
14324       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14325     }
14326 
14327     diagnoseImplicitlyRetainedSelf(*this);
14328   } else {
14329     // Parsing the function declaration failed in some way. Pop the fake scope
14330     // we pushed on.
14331     PopFunctionScopeInfo(ActivePolicy, dcl);
14332     return nullptr;
14333   }
14334 
14335   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14336     DiagnoseUnguardedAvailabilityViolations(dcl);
14337 
14338   assert(!getCurFunction()->ObjCShouldCallSuper &&
14339          "This should only be set for ObjC methods, which should have been "
14340          "handled in the block above.");
14341 
14342   // Verify and clean out per-function state.
14343   if (Body && (!FD || !FD->isDefaulted())) {
14344     // C++ constructors that have function-try-blocks can't have return
14345     // statements in the handlers of that block. (C++ [except.handle]p14)
14346     // Verify this.
14347     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14348       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14349 
14350     // Verify that gotos and switch cases don't jump into scopes illegally.
14351     if (getCurFunction()->NeedsScopeChecking() &&
14352         !PP.isCodeCompletionEnabled())
14353       DiagnoseInvalidJumps(Body);
14354 
14355     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14356       if (!Destructor->getParent()->isDependentType())
14357         CheckDestructor(Destructor);
14358 
14359       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14360                                              Destructor->getParent());
14361     }
14362 
14363     // If any errors have occurred, clear out any temporaries that may have
14364     // been leftover. This ensures that these temporaries won't be picked up for
14365     // deletion in some later function.
14366     if (getDiagnostics().hasErrorOccurred() ||
14367         getDiagnostics().getSuppressAllDiagnostics()) {
14368       DiscardCleanupsInEvaluationContext();
14369     }
14370     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14371         !isa<FunctionTemplateDecl>(dcl)) {
14372       // Since the body is valid, issue any analysis-based warnings that are
14373       // enabled.
14374       ActivePolicy = &WP;
14375     }
14376 
14377     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14378         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14379       FD->setInvalidDecl();
14380 
14381     if (FD && FD->hasAttr<NakedAttr>()) {
14382       for (const Stmt *S : Body->children()) {
14383         // Allow local register variables without initializer as they don't
14384         // require prologue.
14385         bool RegisterVariables = false;
14386         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14387           for (const auto *Decl : DS->decls()) {
14388             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14389               RegisterVariables =
14390                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14391               if (!RegisterVariables)
14392                 break;
14393             }
14394           }
14395         }
14396         if (RegisterVariables)
14397           continue;
14398         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14399           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14400           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14401           FD->setInvalidDecl();
14402           break;
14403         }
14404       }
14405     }
14406 
14407     assert(ExprCleanupObjects.size() ==
14408                ExprEvalContexts.back().NumCleanupObjects &&
14409            "Leftover temporaries in function");
14410     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14411     assert(MaybeODRUseExprs.empty() &&
14412            "Leftover expressions for odr-use checking");
14413   }
14414 
14415   if (!IsInstantiation)
14416     PopDeclContext();
14417 
14418   PopFunctionScopeInfo(ActivePolicy, dcl);
14419   // If any errors have occurred, clear out any temporaries that may have
14420   // been leftover. This ensures that these temporaries won't be picked up for
14421   // deletion in some later function.
14422   if (getDiagnostics().hasErrorOccurred()) {
14423     DiscardCleanupsInEvaluationContext();
14424   }
14425 
14426   if (LangOpts.OpenMP || LangOpts.CUDA) {
14427     auto ES = getEmissionStatus(FD);
14428     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14429         ES == Sema::FunctionEmissionStatus::Unknown)
14430       DeclsToCheckForDeferredDiags.push_back(FD);
14431   }
14432 
14433   return dcl;
14434 }
14435 
14436 /// When we finish delayed parsing of an attribute, we must attach it to the
14437 /// relevant Decl.
14438 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14439                                        ParsedAttributes &Attrs) {
14440   // Always attach attributes to the underlying decl.
14441   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14442     D = TD->getTemplatedDecl();
14443   ProcessDeclAttributeList(S, D, Attrs);
14444 
14445   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14446     if (Method->isStatic())
14447       checkThisInStaticMemberFunctionAttributes(Method);
14448 }
14449 
14450 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14451 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14452 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14453                                           IdentifierInfo &II, Scope *S) {
14454   // Find the scope in which the identifier is injected and the corresponding
14455   // DeclContext.
14456   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14457   // In that case, we inject the declaration into the translation unit scope
14458   // instead.
14459   Scope *BlockScope = S;
14460   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14461     BlockScope = BlockScope->getParent();
14462 
14463   Scope *ContextScope = BlockScope;
14464   while (!ContextScope->getEntity())
14465     ContextScope = ContextScope->getParent();
14466   ContextRAII SavedContext(*this, ContextScope->getEntity());
14467 
14468   // Before we produce a declaration for an implicitly defined
14469   // function, see whether there was a locally-scoped declaration of
14470   // this name as a function or variable. If so, use that
14471   // (non-visible) declaration, and complain about it.
14472   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14473   if (ExternCPrev) {
14474     // We still need to inject the function into the enclosing block scope so
14475     // that later (non-call) uses can see it.
14476     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14477 
14478     // C89 footnote 38:
14479     //   If in fact it is not defined as having type "function returning int",
14480     //   the behavior is undefined.
14481     if (!isa<FunctionDecl>(ExternCPrev) ||
14482         !Context.typesAreCompatible(
14483             cast<FunctionDecl>(ExternCPrev)->getType(),
14484             Context.getFunctionNoProtoType(Context.IntTy))) {
14485       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14486           << ExternCPrev << !getLangOpts().C99;
14487       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14488       return ExternCPrev;
14489     }
14490   }
14491 
14492   // Extension in C99.  Legal in C90, but warn about it.
14493   unsigned diag_id;
14494   if (II.getName().startswith("__builtin_"))
14495     diag_id = diag::warn_builtin_unknown;
14496   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14497   else if (getLangOpts().OpenCL)
14498     diag_id = diag::err_opencl_implicit_function_decl;
14499   else if (getLangOpts().C99)
14500     diag_id = diag::ext_implicit_function_decl;
14501   else
14502     diag_id = diag::warn_implicit_function_decl;
14503   Diag(Loc, diag_id) << &II;
14504 
14505   // If we found a prior declaration of this function, don't bother building
14506   // another one. We've already pushed that one into scope, so there's nothing
14507   // more to do.
14508   if (ExternCPrev)
14509     return ExternCPrev;
14510 
14511   // Because typo correction is expensive, only do it if the implicit
14512   // function declaration is going to be treated as an error.
14513   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14514     TypoCorrection Corrected;
14515     DeclFilterCCC<FunctionDecl> CCC{};
14516     if (S && (Corrected =
14517                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14518                               S, nullptr, CCC, CTK_NonError)))
14519       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14520                    /*ErrorRecovery*/false);
14521   }
14522 
14523   // Set a Declarator for the implicit definition: int foo();
14524   const char *Dummy;
14525   AttributeFactory attrFactory;
14526   DeclSpec DS(attrFactory);
14527   unsigned DiagID;
14528   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14529                                   Context.getPrintingPolicy());
14530   (void)Error; // Silence warning.
14531   assert(!Error && "Error setting up implicit decl!");
14532   SourceLocation NoLoc;
14533   Declarator D(DS, DeclaratorContext::BlockContext);
14534   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14535                                              /*IsAmbiguous=*/false,
14536                                              /*LParenLoc=*/NoLoc,
14537                                              /*Params=*/nullptr,
14538                                              /*NumParams=*/0,
14539                                              /*EllipsisLoc=*/NoLoc,
14540                                              /*RParenLoc=*/NoLoc,
14541                                              /*RefQualifierIsLvalueRef=*/true,
14542                                              /*RefQualifierLoc=*/NoLoc,
14543                                              /*MutableLoc=*/NoLoc, EST_None,
14544                                              /*ESpecRange=*/SourceRange(),
14545                                              /*Exceptions=*/nullptr,
14546                                              /*ExceptionRanges=*/nullptr,
14547                                              /*NumExceptions=*/0,
14548                                              /*NoexceptExpr=*/nullptr,
14549                                              /*ExceptionSpecTokens=*/nullptr,
14550                                              /*DeclsInPrototype=*/None, Loc,
14551                                              Loc, D),
14552                 std::move(DS.getAttributes()), SourceLocation());
14553   D.SetIdentifier(&II, Loc);
14554 
14555   // Insert this function into the enclosing block scope.
14556   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14557   FD->setImplicit();
14558 
14559   AddKnownFunctionAttributes(FD);
14560 
14561   return FD;
14562 }
14563 
14564 /// If this function is a C++ replaceable global allocation function
14565 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14566 /// adds any function attributes that we know a priori based on the standard.
14567 ///
14568 /// We need to check for duplicate attributes both here and where user-written
14569 /// attributes are applied to declarations.
14570 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14571     FunctionDecl *FD) {
14572   if (FD->isInvalidDecl())
14573     return;
14574 
14575   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14576       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14577     return;
14578 
14579   Optional<unsigned> AlignmentParam;
14580   bool IsNothrow = false;
14581   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14582     return;
14583 
14584   // C++2a [basic.stc.dynamic.allocation]p4:
14585   //   An allocation function that has a non-throwing exception specification
14586   //   indicates failure by returning a null pointer value. Any other allocation
14587   //   function never returns a null pointer value and indicates failure only by
14588   //   throwing an exception [...]
14589   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14590     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14591 
14592   // C++2a [basic.stc.dynamic.allocation]p2:
14593   //   An allocation function attempts to allocate the requested amount of
14594   //   storage. [...] If the request succeeds, the value returned by a
14595   //   replaceable allocation function is a [...] pointer value p0 different
14596   //   from any previously returned value p1 [...]
14597   //
14598   // However, this particular information is being added in codegen,
14599   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14600 
14601   // C++2a [basic.stc.dynamic.allocation]p2:
14602   //   An allocation function attempts to allocate the requested amount of
14603   //   storage. If it is successful, it returns the address of the start of a
14604   //   block of storage whose length in bytes is at least as large as the
14605   //   requested size.
14606   if (!FD->hasAttr<AllocSizeAttr>()) {
14607     FD->addAttr(AllocSizeAttr::CreateImplicit(
14608         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14609         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14610   }
14611 
14612   // C++2a [basic.stc.dynamic.allocation]p3:
14613   //   For an allocation function [...], the pointer returned on a successful
14614   //   call shall represent the address of storage that is aligned as follows:
14615   //   (3.1) If the allocation function takes an argument of type
14616   //         std​::​align_­val_­t, the storage will have the alignment
14617   //         specified by the value of this argument.
14618   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14619     FD->addAttr(AllocAlignAttr::CreateImplicit(
14620         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14621   }
14622 
14623   // FIXME:
14624   // C++2a [basic.stc.dynamic.allocation]p3:
14625   //   For an allocation function [...], the pointer returned on a successful
14626   //   call shall represent the address of storage that is aligned as follows:
14627   //   (3.2) Otherwise, if the allocation function is named operator new[],
14628   //         the storage is aligned for any object that does not have
14629   //         new-extended alignment ([basic.align]) and is no larger than the
14630   //         requested size.
14631   //   (3.3) Otherwise, the storage is aligned for any object that does not
14632   //         have new-extended alignment and is of the requested size.
14633 }
14634 
14635 /// Adds any function attributes that we know a priori based on
14636 /// the declaration of this function.
14637 ///
14638 /// These attributes can apply both to implicitly-declared builtins
14639 /// (like __builtin___printf_chk) or to library-declared functions
14640 /// like NSLog or printf.
14641 ///
14642 /// We need to check for duplicate attributes both here and where user-written
14643 /// attributes are applied to declarations.
14644 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14645   if (FD->isInvalidDecl())
14646     return;
14647 
14648   // If this is a built-in function, map its builtin attributes to
14649   // actual attributes.
14650   if (unsigned BuiltinID = FD->getBuiltinID()) {
14651     // Handle printf-formatting attributes.
14652     unsigned FormatIdx;
14653     bool HasVAListArg;
14654     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14655       if (!FD->hasAttr<FormatAttr>()) {
14656         const char *fmt = "printf";
14657         unsigned int NumParams = FD->getNumParams();
14658         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14659             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14660           fmt = "NSString";
14661         FD->addAttr(FormatAttr::CreateImplicit(Context,
14662                                                &Context.Idents.get(fmt),
14663                                                FormatIdx+1,
14664                                                HasVAListArg ? 0 : FormatIdx+2,
14665                                                FD->getLocation()));
14666       }
14667     }
14668     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14669                                              HasVAListArg)) {
14670      if (!FD->hasAttr<FormatAttr>())
14671        FD->addAttr(FormatAttr::CreateImplicit(Context,
14672                                               &Context.Idents.get("scanf"),
14673                                               FormatIdx+1,
14674                                               HasVAListArg ? 0 : FormatIdx+2,
14675                                               FD->getLocation()));
14676     }
14677 
14678     // Handle automatically recognized callbacks.
14679     SmallVector<int, 4> Encoding;
14680     if (!FD->hasAttr<CallbackAttr>() &&
14681         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14682       FD->addAttr(CallbackAttr::CreateImplicit(
14683           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14684 
14685     // Mark const if we don't care about errno and that is the only thing
14686     // preventing the function from being const. This allows IRgen to use LLVM
14687     // intrinsics for such functions.
14688     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14689         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14690       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14691 
14692     // We make "fma" on some platforms const because we know it does not set
14693     // errno in those environments even though it could set errno based on the
14694     // C standard.
14695     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14696     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14697         !FD->hasAttr<ConstAttr>()) {
14698       switch (BuiltinID) {
14699       case Builtin::BI__builtin_fma:
14700       case Builtin::BI__builtin_fmaf:
14701       case Builtin::BI__builtin_fmal:
14702       case Builtin::BIfma:
14703       case Builtin::BIfmaf:
14704       case Builtin::BIfmal:
14705         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14706         break;
14707       default:
14708         break;
14709       }
14710     }
14711 
14712     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14713         !FD->hasAttr<ReturnsTwiceAttr>())
14714       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14715                                          FD->getLocation()));
14716     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14717       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14718     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14719       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14720     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14721       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14722     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14723         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14724       // Add the appropriate attribute, depending on the CUDA compilation mode
14725       // and which target the builtin belongs to. For example, during host
14726       // compilation, aux builtins are __device__, while the rest are __host__.
14727       if (getLangOpts().CUDAIsDevice !=
14728           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14729         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14730       else
14731         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14732     }
14733   }
14734 
14735   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14736 
14737   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14738   // throw, add an implicit nothrow attribute to any extern "C" function we come
14739   // across.
14740   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14741       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14742     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14743     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14744       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14745   }
14746 
14747   IdentifierInfo *Name = FD->getIdentifier();
14748   if (!Name)
14749     return;
14750   if ((!getLangOpts().CPlusPlus &&
14751        FD->getDeclContext()->isTranslationUnit()) ||
14752       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14753        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14754        LinkageSpecDecl::lang_c)) {
14755     // Okay: this could be a libc/libm/Objective-C function we know
14756     // about.
14757   } else
14758     return;
14759 
14760   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14761     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14762     // target-specific builtins, perhaps?
14763     if (!FD->hasAttr<FormatAttr>())
14764       FD->addAttr(FormatAttr::CreateImplicit(Context,
14765                                              &Context.Idents.get("printf"), 2,
14766                                              Name->isStr("vasprintf") ? 0 : 3,
14767                                              FD->getLocation()));
14768   }
14769 
14770   if (Name->isStr("__CFStringMakeConstantString")) {
14771     // We already have a __builtin___CFStringMakeConstantString,
14772     // but builds that use -fno-constant-cfstrings don't go through that.
14773     if (!FD->hasAttr<FormatArgAttr>())
14774       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14775                                                 FD->getLocation()));
14776   }
14777 }
14778 
14779 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14780                                     TypeSourceInfo *TInfo) {
14781   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14782   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14783 
14784   if (!TInfo) {
14785     assert(D.isInvalidType() && "no declarator info for valid type");
14786     TInfo = Context.getTrivialTypeSourceInfo(T);
14787   }
14788 
14789   // Scope manipulation handled by caller.
14790   TypedefDecl *NewTD =
14791       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14792                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14793 
14794   // Bail out immediately if we have an invalid declaration.
14795   if (D.isInvalidType()) {
14796     NewTD->setInvalidDecl();
14797     return NewTD;
14798   }
14799 
14800   if (D.getDeclSpec().isModulePrivateSpecified()) {
14801     if (CurContext->isFunctionOrMethod())
14802       Diag(NewTD->getLocation(), diag::err_module_private_local)
14803         << 2 << NewTD->getDeclName()
14804         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14805         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14806     else
14807       NewTD->setModulePrivate();
14808   }
14809 
14810   // C++ [dcl.typedef]p8:
14811   //   If the typedef declaration defines an unnamed class (or
14812   //   enum), the first typedef-name declared by the declaration
14813   //   to be that class type (or enum type) is used to denote the
14814   //   class type (or enum type) for linkage purposes only.
14815   // We need to check whether the type was declared in the declaration.
14816   switch (D.getDeclSpec().getTypeSpecType()) {
14817   case TST_enum:
14818   case TST_struct:
14819   case TST_interface:
14820   case TST_union:
14821   case TST_class: {
14822     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14823     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14824     break;
14825   }
14826 
14827   default:
14828     break;
14829   }
14830 
14831   return NewTD;
14832 }
14833 
14834 /// Check that this is a valid underlying type for an enum declaration.
14835 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14836   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14837   QualType T = TI->getType();
14838 
14839   if (T->isDependentType())
14840     return false;
14841 
14842   // This doesn't use 'isIntegralType' despite the error message mentioning
14843   // integral type because isIntegralType would also allow enum types in C.
14844   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14845     if (BT->isInteger())
14846       return false;
14847 
14848   if (T->isExtIntType())
14849     return false;
14850 
14851   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14852 }
14853 
14854 /// Check whether this is a valid redeclaration of a previous enumeration.
14855 /// \return true if the redeclaration was invalid.
14856 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14857                                   QualType EnumUnderlyingTy, bool IsFixed,
14858                                   const EnumDecl *Prev) {
14859   if (IsScoped != Prev->isScoped()) {
14860     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14861       << Prev->isScoped();
14862     Diag(Prev->getLocation(), diag::note_previous_declaration);
14863     return true;
14864   }
14865 
14866   if (IsFixed && Prev->isFixed()) {
14867     if (!EnumUnderlyingTy->isDependentType() &&
14868         !Prev->getIntegerType()->isDependentType() &&
14869         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14870                                         Prev->getIntegerType())) {
14871       // TODO: Highlight the underlying type of the redeclaration.
14872       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14873         << EnumUnderlyingTy << Prev->getIntegerType();
14874       Diag(Prev->getLocation(), diag::note_previous_declaration)
14875           << Prev->getIntegerTypeRange();
14876       return true;
14877     }
14878   } else if (IsFixed != Prev->isFixed()) {
14879     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14880       << Prev->isFixed();
14881     Diag(Prev->getLocation(), diag::note_previous_declaration);
14882     return true;
14883   }
14884 
14885   return false;
14886 }
14887 
14888 /// Get diagnostic %select index for tag kind for
14889 /// redeclaration diagnostic message.
14890 /// WARNING: Indexes apply to particular diagnostics only!
14891 ///
14892 /// \returns diagnostic %select index.
14893 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14894   switch (Tag) {
14895   case TTK_Struct: return 0;
14896   case TTK_Interface: return 1;
14897   case TTK_Class:  return 2;
14898   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14899   }
14900 }
14901 
14902 /// Determine if tag kind is a class-key compatible with
14903 /// class for redeclaration (class, struct, or __interface).
14904 ///
14905 /// \returns true iff the tag kind is compatible.
14906 static bool isClassCompatTagKind(TagTypeKind Tag)
14907 {
14908   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14909 }
14910 
14911 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14912                                              TagTypeKind TTK) {
14913   if (isa<TypedefDecl>(PrevDecl))
14914     return NTK_Typedef;
14915   else if (isa<TypeAliasDecl>(PrevDecl))
14916     return NTK_TypeAlias;
14917   else if (isa<ClassTemplateDecl>(PrevDecl))
14918     return NTK_Template;
14919   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14920     return NTK_TypeAliasTemplate;
14921   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14922     return NTK_TemplateTemplateArgument;
14923   switch (TTK) {
14924   case TTK_Struct:
14925   case TTK_Interface:
14926   case TTK_Class:
14927     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14928   case TTK_Union:
14929     return NTK_NonUnion;
14930   case TTK_Enum:
14931     return NTK_NonEnum;
14932   }
14933   llvm_unreachable("invalid TTK");
14934 }
14935 
14936 /// Determine whether a tag with a given kind is acceptable
14937 /// as a redeclaration of the given tag declaration.
14938 ///
14939 /// \returns true if the new tag kind is acceptable, false otherwise.
14940 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14941                                         TagTypeKind NewTag, bool isDefinition,
14942                                         SourceLocation NewTagLoc,
14943                                         const IdentifierInfo *Name) {
14944   // C++ [dcl.type.elab]p3:
14945   //   The class-key or enum keyword present in the
14946   //   elaborated-type-specifier shall agree in kind with the
14947   //   declaration to which the name in the elaborated-type-specifier
14948   //   refers. This rule also applies to the form of
14949   //   elaborated-type-specifier that declares a class-name or
14950   //   friend class since it can be construed as referring to the
14951   //   definition of the class. Thus, in any
14952   //   elaborated-type-specifier, the enum keyword shall be used to
14953   //   refer to an enumeration (7.2), the union class-key shall be
14954   //   used to refer to a union (clause 9), and either the class or
14955   //   struct class-key shall be used to refer to a class (clause 9)
14956   //   declared using the class or struct class-key.
14957   TagTypeKind OldTag = Previous->getTagKind();
14958   if (OldTag != NewTag &&
14959       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14960     return false;
14961 
14962   // Tags are compatible, but we might still want to warn on mismatched tags.
14963   // Non-class tags can't be mismatched at this point.
14964   if (!isClassCompatTagKind(NewTag))
14965     return true;
14966 
14967   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14968   // by our warning analysis. We don't want to warn about mismatches with (eg)
14969   // declarations in system headers that are designed to be specialized, but if
14970   // a user asks us to warn, we should warn if their code contains mismatched
14971   // declarations.
14972   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14973     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14974                                       Loc);
14975   };
14976   if (IsIgnoredLoc(NewTagLoc))
14977     return true;
14978 
14979   auto IsIgnored = [&](const TagDecl *Tag) {
14980     return IsIgnoredLoc(Tag->getLocation());
14981   };
14982   while (IsIgnored(Previous)) {
14983     Previous = Previous->getPreviousDecl();
14984     if (!Previous)
14985       return true;
14986     OldTag = Previous->getTagKind();
14987   }
14988 
14989   bool isTemplate = false;
14990   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14991     isTemplate = Record->getDescribedClassTemplate();
14992 
14993   if (inTemplateInstantiation()) {
14994     if (OldTag != NewTag) {
14995       // In a template instantiation, do not offer fix-its for tag mismatches
14996       // since they usually mess up the template instead of fixing the problem.
14997       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14998         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14999         << getRedeclDiagFromTagKind(OldTag);
15000       // FIXME: Note previous location?
15001     }
15002     return true;
15003   }
15004 
15005   if (isDefinition) {
15006     // On definitions, check all previous tags and issue a fix-it for each
15007     // one that doesn't match the current tag.
15008     if (Previous->getDefinition()) {
15009       // Don't suggest fix-its for redefinitions.
15010       return true;
15011     }
15012 
15013     bool previousMismatch = false;
15014     for (const TagDecl *I : Previous->redecls()) {
15015       if (I->getTagKind() != NewTag) {
15016         // Ignore previous declarations for which the warning was disabled.
15017         if (IsIgnored(I))
15018           continue;
15019 
15020         if (!previousMismatch) {
15021           previousMismatch = true;
15022           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15023             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15024             << getRedeclDiagFromTagKind(I->getTagKind());
15025         }
15026         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15027           << getRedeclDiagFromTagKind(NewTag)
15028           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15029                TypeWithKeyword::getTagTypeKindName(NewTag));
15030       }
15031     }
15032     return true;
15033   }
15034 
15035   // Identify the prevailing tag kind: this is the kind of the definition (if
15036   // there is a non-ignored definition), or otherwise the kind of the prior
15037   // (non-ignored) declaration.
15038   const TagDecl *PrevDef = Previous->getDefinition();
15039   if (PrevDef && IsIgnored(PrevDef))
15040     PrevDef = nullptr;
15041   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15042   if (Redecl->getTagKind() != NewTag) {
15043     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15044       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15045       << getRedeclDiagFromTagKind(OldTag);
15046     Diag(Redecl->getLocation(), diag::note_previous_use);
15047 
15048     // If there is a previous definition, suggest a fix-it.
15049     if (PrevDef) {
15050       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15051         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15052         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15053              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15054     }
15055   }
15056 
15057   return true;
15058 }
15059 
15060 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15061 /// from an outer enclosing namespace or file scope inside a friend declaration.
15062 /// This should provide the commented out code in the following snippet:
15063 ///   namespace N {
15064 ///     struct X;
15065 ///     namespace M {
15066 ///       struct Y { friend struct /*N::*/ X; };
15067 ///     }
15068 ///   }
15069 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15070                                          SourceLocation NameLoc) {
15071   // While the decl is in a namespace, do repeated lookup of that name and see
15072   // if we get the same namespace back.  If we do not, continue until
15073   // translation unit scope, at which point we have a fully qualified NNS.
15074   SmallVector<IdentifierInfo *, 4> Namespaces;
15075   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15076   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15077     // This tag should be declared in a namespace, which can only be enclosed by
15078     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15079     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15080     if (!Namespace || Namespace->isAnonymousNamespace())
15081       return FixItHint();
15082     IdentifierInfo *II = Namespace->getIdentifier();
15083     Namespaces.push_back(II);
15084     NamedDecl *Lookup = SemaRef.LookupSingleName(
15085         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15086     if (Lookup == Namespace)
15087       break;
15088   }
15089 
15090   // Once we have all the namespaces, reverse them to go outermost first, and
15091   // build an NNS.
15092   SmallString<64> Insertion;
15093   llvm::raw_svector_ostream OS(Insertion);
15094   if (DC->isTranslationUnit())
15095     OS << "::";
15096   std::reverse(Namespaces.begin(), Namespaces.end());
15097   for (auto *II : Namespaces)
15098     OS << II->getName() << "::";
15099   return FixItHint::CreateInsertion(NameLoc, Insertion);
15100 }
15101 
15102 /// Determine whether a tag originally declared in context \p OldDC can
15103 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15104 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15105 /// using-declaration).
15106 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15107                                          DeclContext *NewDC) {
15108   OldDC = OldDC->getRedeclContext();
15109   NewDC = NewDC->getRedeclContext();
15110 
15111   if (OldDC->Equals(NewDC))
15112     return true;
15113 
15114   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15115   // encloses the other).
15116   if (S.getLangOpts().MSVCCompat &&
15117       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15118     return true;
15119 
15120   return false;
15121 }
15122 
15123 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15124 /// former case, Name will be non-null.  In the later case, Name will be null.
15125 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15126 /// reference/declaration/definition of a tag.
15127 ///
15128 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15129 /// trailing-type-specifier) other than one in an alias-declaration.
15130 ///
15131 /// \param SkipBody If non-null, will be set to indicate if the caller should
15132 /// skip the definition of this tag and treat it as if it were a declaration.
15133 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15134                      SourceLocation KWLoc, CXXScopeSpec &SS,
15135                      IdentifierInfo *Name, SourceLocation NameLoc,
15136                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15137                      SourceLocation ModulePrivateLoc,
15138                      MultiTemplateParamsArg TemplateParameterLists,
15139                      bool &OwnedDecl, bool &IsDependent,
15140                      SourceLocation ScopedEnumKWLoc,
15141                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15142                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15143                      SkipBodyInfo *SkipBody) {
15144   // If this is not a definition, it must have a name.
15145   IdentifierInfo *OrigName = Name;
15146   assert((Name != nullptr || TUK == TUK_Definition) &&
15147          "Nameless record must be a definition!");
15148   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15149 
15150   OwnedDecl = false;
15151   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15152   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15153 
15154   // FIXME: Check member specializations more carefully.
15155   bool isMemberSpecialization = false;
15156   bool Invalid = false;
15157 
15158   // We only need to do this matching if we have template parameters
15159   // or a scope specifier, which also conveniently avoids this work
15160   // for non-C++ cases.
15161   if (TemplateParameterLists.size() > 0 ||
15162       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15163     if (TemplateParameterList *TemplateParams =
15164             MatchTemplateParametersToScopeSpecifier(
15165                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15166                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15167       if (Kind == TTK_Enum) {
15168         Diag(KWLoc, diag::err_enum_template);
15169         return nullptr;
15170       }
15171 
15172       if (TemplateParams->size() > 0) {
15173         // This is a declaration or definition of a class template (which may
15174         // be a member of another template).
15175 
15176         if (Invalid)
15177           return nullptr;
15178 
15179         OwnedDecl = false;
15180         DeclResult Result = CheckClassTemplate(
15181             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15182             AS, ModulePrivateLoc,
15183             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15184             TemplateParameterLists.data(), SkipBody);
15185         return Result.get();
15186       } else {
15187         // The "template<>" header is extraneous.
15188         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15189           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15190         isMemberSpecialization = true;
15191       }
15192     }
15193   }
15194 
15195   // Figure out the underlying type if this a enum declaration. We need to do
15196   // this early, because it's needed to detect if this is an incompatible
15197   // redeclaration.
15198   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15199   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15200 
15201   if (Kind == TTK_Enum) {
15202     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15203       // No underlying type explicitly specified, or we failed to parse the
15204       // type, default to int.
15205       EnumUnderlying = Context.IntTy.getTypePtr();
15206     } else if (UnderlyingType.get()) {
15207       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15208       // integral type; any cv-qualification is ignored.
15209       TypeSourceInfo *TI = nullptr;
15210       GetTypeFromParser(UnderlyingType.get(), &TI);
15211       EnumUnderlying = TI;
15212 
15213       if (CheckEnumUnderlyingType(TI))
15214         // Recover by falling back to int.
15215         EnumUnderlying = Context.IntTy.getTypePtr();
15216 
15217       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15218                                           UPPC_FixedUnderlyingType))
15219         EnumUnderlying = Context.IntTy.getTypePtr();
15220 
15221     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15222       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15223       // of 'int'. However, if this is an unfixed forward declaration, don't set
15224       // the underlying type unless the user enables -fms-compatibility. This
15225       // makes unfixed forward declared enums incomplete and is more conforming.
15226       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15227         EnumUnderlying = Context.IntTy.getTypePtr();
15228     }
15229   }
15230 
15231   DeclContext *SearchDC = CurContext;
15232   DeclContext *DC = CurContext;
15233   bool isStdBadAlloc = false;
15234   bool isStdAlignValT = false;
15235 
15236   RedeclarationKind Redecl = forRedeclarationInCurContext();
15237   if (TUK == TUK_Friend || TUK == TUK_Reference)
15238     Redecl = NotForRedeclaration;
15239 
15240   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15241   /// implemented asks for structural equivalence checking, the returned decl
15242   /// here is passed back to the parser, allowing the tag body to be parsed.
15243   auto createTagFromNewDecl = [&]() -> TagDecl * {
15244     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15245     // If there is an identifier, use the location of the identifier as the
15246     // location of the decl, otherwise use the location of the struct/union
15247     // keyword.
15248     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15249     TagDecl *New = nullptr;
15250 
15251     if (Kind == TTK_Enum) {
15252       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15253                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15254       // If this is an undefined enum, bail.
15255       if (TUK != TUK_Definition && !Invalid)
15256         return nullptr;
15257       if (EnumUnderlying) {
15258         EnumDecl *ED = cast<EnumDecl>(New);
15259         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15260           ED->setIntegerTypeSourceInfo(TI);
15261         else
15262           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15263         ED->setPromotionType(ED->getIntegerType());
15264       }
15265     } else { // struct/union
15266       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15267                                nullptr);
15268     }
15269 
15270     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15271       // Add alignment attributes if necessary; these attributes are checked
15272       // when the ASTContext lays out the structure.
15273       //
15274       // It is important for implementing the correct semantics that this
15275       // happen here (in ActOnTag). The #pragma pack stack is
15276       // maintained as a result of parser callbacks which can occur at
15277       // many points during the parsing of a struct declaration (because
15278       // the #pragma tokens are effectively skipped over during the
15279       // parsing of the struct).
15280       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15281         AddAlignmentAttributesForRecord(RD);
15282         AddMsStructLayoutForRecord(RD);
15283       }
15284     }
15285     New->setLexicalDeclContext(CurContext);
15286     return New;
15287   };
15288 
15289   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15290   if (Name && SS.isNotEmpty()) {
15291     // We have a nested-name tag ('struct foo::bar').
15292 
15293     // Check for invalid 'foo::'.
15294     if (SS.isInvalid()) {
15295       Name = nullptr;
15296       goto CreateNewDecl;
15297     }
15298 
15299     // If this is a friend or a reference to a class in a dependent
15300     // context, don't try to make a decl for it.
15301     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15302       DC = computeDeclContext(SS, false);
15303       if (!DC) {
15304         IsDependent = true;
15305         return nullptr;
15306       }
15307     } else {
15308       DC = computeDeclContext(SS, true);
15309       if (!DC) {
15310         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15311           << SS.getRange();
15312         return nullptr;
15313       }
15314     }
15315 
15316     if (RequireCompleteDeclContext(SS, DC))
15317       return nullptr;
15318 
15319     SearchDC = DC;
15320     // Look-up name inside 'foo::'.
15321     LookupQualifiedName(Previous, DC);
15322 
15323     if (Previous.isAmbiguous())
15324       return nullptr;
15325 
15326     if (Previous.empty()) {
15327       // Name lookup did not find anything. However, if the
15328       // nested-name-specifier refers to the current instantiation,
15329       // and that current instantiation has any dependent base
15330       // classes, we might find something at instantiation time: treat
15331       // this as a dependent elaborated-type-specifier.
15332       // But this only makes any sense for reference-like lookups.
15333       if (Previous.wasNotFoundInCurrentInstantiation() &&
15334           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15335         IsDependent = true;
15336         return nullptr;
15337       }
15338 
15339       // A tag 'foo::bar' must already exist.
15340       Diag(NameLoc, diag::err_not_tag_in_scope)
15341         << Kind << Name << DC << SS.getRange();
15342       Name = nullptr;
15343       Invalid = true;
15344       goto CreateNewDecl;
15345     }
15346   } else if (Name) {
15347     // C++14 [class.mem]p14:
15348     //   If T is the name of a class, then each of the following shall have a
15349     //   name different from T:
15350     //    -- every member of class T that is itself a type
15351     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15352         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15353       return nullptr;
15354 
15355     // If this is a named struct, check to see if there was a previous forward
15356     // declaration or definition.
15357     // FIXME: We're looking into outer scopes here, even when we
15358     // shouldn't be. Doing so can result in ambiguities that we
15359     // shouldn't be diagnosing.
15360     LookupName(Previous, S);
15361 
15362     // When declaring or defining a tag, ignore ambiguities introduced
15363     // by types using'ed into this scope.
15364     if (Previous.isAmbiguous() &&
15365         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15366       LookupResult::Filter F = Previous.makeFilter();
15367       while (F.hasNext()) {
15368         NamedDecl *ND = F.next();
15369         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15370                 SearchDC->getRedeclContext()))
15371           F.erase();
15372       }
15373       F.done();
15374     }
15375 
15376     // C++11 [namespace.memdef]p3:
15377     //   If the name in a friend declaration is neither qualified nor
15378     //   a template-id and the declaration is a function or an
15379     //   elaborated-type-specifier, the lookup to determine whether
15380     //   the entity has been previously declared shall not consider
15381     //   any scopes outside the innermost enclosing namespace.
15382     //
15383     // MSVC doesn't implement the above rule for types, so a friend tag
15384     // declaration may be a redeclaration of a type declared in an enclosing
15385     // scope.  They do implement this rule for friend functions.
15386     //
15387     // Does it matter that this should be by scope instead of by
15388     // semantic context?
15389     if (!Previous.empty() && TUK == TUK_Friend) {
15390       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15391       LookupResult::Filter F = Previous.makeFilter();
15392       bool FriendSawTagOutsideEnclosingNamespace = false;
15393       while (F.hasNext()) {
15394         NamedDecl *ND = F.next();
15395         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15396         if (DC->isFileContext() &&
15397             !EnclosingNS->Encloses(ND->getDeclContext())) {
15398           if (getLangOpts().MSVCCompat)
15399             FriendSawTagOutsideEnclosingNamespace = true;
15400           else
15401             F.erase();
15402         }
15403       }
15404       F.done();
15405 
15406       // Diagnose this MSVC extension in the easy case where lookup would have
15407       // unambiguously found something outside the enclosing namespace.
15408       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15409         NamedDecl *ND = Previous.getFoundDecl();
15410         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15411             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15412       }
15413     }
15414 
15415     // Note:  there used to be some attempt at recovery here.
15416     if (Previous.isAmbiguous())
15417       return nullptr;
15418 
15419     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15420       // FIXME: This makes sure that we ignore the contexts associated
15421       // with C structs, unions, and enums when looking for a matching
15422       // tag declaration or definition. See the similar lookup tweak
15423       // in Sema::LookupName; is there a better way to deal with this?
15424       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15425         SearchDC = SearchDC->getParent();
15426     }
15427   }
15428 
15429   if (Previous.isSingleResult() &&
15430       Previous.getFoundDecl()->isTemplateParameter()) {
15431     // Maybe we will complain about the shadowed template parameter.
15432     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15433     // Just pretend that we didn't see the previous declaration.
15434     Previous.clear();
15435   }
15436 
15437   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15438       DC->Equals(getStdNamespace())) {
15439     if (Name->isStr("bad_alloc")) {
15440       // This is a declaration of or a reference to "std::bad_alloc".
15441       isStdBadAlloc = true;
15442 
15443       // If std::bad_alloc has been implicitly declared (but made invisible to
15444       // name lookup), fill in this implicit declaration as the previous
15445       // declaration, so that the declarations get chained appropriately.
15446       if (Previous.empty() && StdBadAlloc)
15447         Previous.addDecl(getStdBadAlloc());
15448     } else if (Name->isStr("align_val_t")) {
15449       isStdAlignValT = true;
15450       if (Previous.empty() && StdAlignValT)
15451         Previous.addDecl(getStdAlignValT());
15452     }
15453   }
15454 
15455   // If we didn't find a previous declaration, and this is a reference
15456   // (or friend reference), move to the correct scope.  In C++, we
15457   // also need to do a redeclaration lookup there, just in case
15458   // there's a shadow friend decl.
15459   if (Name && Previous.empty() &&
15460       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15461     if (Invalid) goto CreateNewDecl;
15462     assert(SS.isEmpty());
15463 
15464     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15465       // C++ [basic.scope.pdecl]p5:
15466       //   -- for an elaborated-type-specifier of the form
15467       //
15468       //          class-key identifier
15469       //
15470       //      if the elaborated-type-specifier is used in the
15471       //      decl-specifier-seq or parameter-declaration-clause of a
15472       //      function defined in namespace scope, the identifier is
15473       //      declared as a class-name in the namespace that contains
15474       //      the declaration; otherwise, except as a friend
15475       //      declaration, the identifier is declared in the smallest
15476       //      non-class, non-function-prototype scope that contains the
15477       //      declaration.
15478       //
15479       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15480       // C structs and unions.
15481       //
15482       // It is an error in C++ to declare (rather than define) an enum
15483       // type, including via an elaborated type specifier.  We'll
15484       // diagnose that later; for now, declare the enum in the same
15485       // scope as we would have picked for any other tag type.
15486       //
15487       // GNU C also supports this behavior as part of its incomplete
15488       // enum types extension, while GNU C++ does not.
15489       //
15490       // Find the context where we'll be declaring the tag.
15491       // FIXME: We would like to maintain the current DeclContext as the
15492       // lexical context,
15493       SearchDC = getTagInjectionContext(SearchDC);
15494 
15495       // Find the scope where we'll be declaring the tag.
15496       S = getTagInjectionScope(S, getLangOpts());
15497     } else {
15498       assert(TUK == TUK_Friend);
15499       // C++ [namespace.memdef]p3:
15500       //   If a friend declaration in a non-local class first declares a
15501       //   class or function, the friend class or function is a member of
15502       //   the innermost enclosing namespace.
15503       SearchDC = SearchDC->getEnclosingNamespaceContext();
15504     }
15505 
15506     // In C++, we need to do a redeclaration lookup to properly
15507     // diagnose some problems.
15508     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15509     // hidden declaration so that we don't get ambiguity errors when using a
15510     // type declared by an elaborated-type-specifier.  In C that is not correct
15511     // and we should instead merge compatible types found by lookup.
15512     if (getLangOpts().CPlusPlus) {
15513       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15514       LookupQualifiedName(Previous, SearchDC);
15515     } else {
15516       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15517       LookupName(Previous, S);
15518     }
15519   }
15520 
15521   // If we have a known previous declaration to use, then use it.
15522   if (Previous.empty() && SkipBody && SkipBody->Previous)
15523     Previous.addDecl(SkipBody->Previous);
15524 
15525   if (!Previous.empty()) {
15526     NamedDecl *PrevDecl = Previous.getFoundDecl();
15527     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15528 
15529     // It's okay to have a tag decl in the same scope as a typedef
15530     // which hides a tag decl in the same scope.  Finding this
15531     // insanity with a redeclaration lookup can only actually happen
15532     // in C++.
15533     //
15534     // This is also okay for elaborated-type-specifiers, which is
15535     // technically forbidden by the current standard but which is
15536     // okay according to the likely resolution of an open issue;
15537     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15538     if (getLangOpts().CPlusPlus) {
15539       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15540         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15541           TagDecl *Tag = TT->getDecl();
15542           if (Tag->getDeclName() == Name &&
15543               Tag->getDeclContext()->getRedeclContext()
15544                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15545             PrevDecl = Tag;
15546             Previous.clear();
15547             Previous.addDecl(Tag);
15548             Previous.resolveKind();
15549           }
15550         }
15551       }
15552     }
15553 
15554     // If this is a redeclaration of a using shadow declaration, it must
15555     // declare a tag in the same context. In MSVC mode, we allow a
15556     // redefinition if either context is within the other.
15557     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15558       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15559       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15560           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15561           !(OldTag && isAcceptableTagRedeclContext(
15562                           *this, OldTag->getDeclContext(), SearchDC))) {
15563         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15564         Diag(Shadow->getTargetDecl()->getLocation(),
15565              diag::note_using_decl_target);
15566         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15567             << 0;
15568         // Recover by ignoring the old declaration.
15569         Previous.clear();
15570         goto CreateNewDecl;
15571       }
15572     }
15573 
15574     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15575       // If this is a use of a previous tag, or if the tag is already declared
15576       // in the same scope (so that the definition/declaration completes or
15577       // rementions the tag), reuse the decl.
15578       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15579           isDeclInScope(DirectPrevDecl, SearchDC, S,
15580                         SS.isNotEmpty() || isMemberSpecialization)) {
15581         // Make sure that this wasn't declared as an enum and now used as a
15582         // struct or something similar.
15583         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15584                                           TUK == TUK_Definition, KWLoc,
15585                                           Name)) {
15586           bool SafeToContinue
15587             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15588                Kind != TTK_Enum);
15589           if (SafeToContinue)
15590             Diag(KWLoc, diag::err_use_with_wrong_tag)
15591               << Name
15592               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15593                                               PrevTagDecl->getKindName());
15594           else
15595             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15596           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15597 
15598           if (SafeToContinue)
15599             Kind = PrevTagDecl->getTagKind();
15600           else {
15601             // Recover by making this an anonymous redefinition.
15602             Name = nullptr;
15603             Previous.clear();
15604             Invalid = true;
15605           }
15606         }
15607 
15608         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15609           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15610           if (TUK == TUK_Reference || TUK == TUK_Friend)
15611             return PrevTagDecl;
15612 
15613           QualType EnumUnderlyingTy;
15614           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15615             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15616           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15617             EnumUnderlyingTy = QualType(T, 0);
15618 
15619           // All conflicts with previous declarations are recovered by
15620           // returning the previous declaration, unless this is a definition,
15621           // in which case we want the caller to bail out.
15622           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15623                                      ScopedEnum, EnumUnderlyingTy,
15624                                      IsFixed, PrevEnum))
15625             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15626         }
15627 
15628         // C++11 [class.mem]p1:
15629         //   A member shall not be declared twice in the member-specification,
15630         //   except that a nested class or member class template can be declared
15631         //   and then later defined.
15632         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15633             S->isDeclScope(PrevDecl)) {
15634           Diag(NameLoc, diag::ext_member_redeclared);
15635           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15636         }
15637 
15638         if (!Invalid) {
15639           // If this is a use, just return the declaration we found, unless
15640           // we have attributes.
15641           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15642             if (!Attrs.empty()) {
15643               // FIXME: Diagnose these attributes. For now, we create a new
15644               // declaration to hold them.
15645             } else if (TUK == TUK_Reference &&
15646                        (PrevTagDecl->getFriendObjectKind() ==
15647                             Decl::FOK_Undeclared ||
15648                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15649                        SS.isEmpty()) {
15650               // This declaration is a reference to an existing entity, but
15651               // has different visibility from that entity: it either makes
15652               // a friend visible or it makes a type visible in a new module.
15653               // In either case, create a new declaration. We only do this if
15654               // the declaration would have meant the same thing if no prior
15655               // declaration were found, that is, if it was found in the same
15656               // scope where we would have injected a declaration.
15657               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15658                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15659                 return PrevTagDecl;
15660               // This is in the injected scope, create a new declaration in
15661               // that scope.
15662               S = getTagInjectionScope(S, getLangOpts());
15663             } else {
15664               return PrevTagDecl;
15665             }
15666           }
15667 
15668           // Diagnose attempts to redefine a tag.
15669           if (TUK == TUK_Definition) {
15670             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15671               // If we're defining a specialization and the previous definition
15672               // is from an implicit instantiation, don't emit an error
15673               // here; we'll catch this in the general case below.
15674               bool IsExplicitSpecializationAfterInstantiation = false;
15675               if (isMemberSpecialization) {
15676                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15677                   IsExplicitSpecializationAfterInstantiation =
15678                     RD->getTemplateSpecializationKind() !=
15679                     TSK_ExplicitSpecialization;
15680                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15681                   IsExplicitSpecializationAfterInstantiation =
15682                     ED->getTemplateSpecializationKind() !=
15683                     TSK_ExplicitSpecialization;
15684               }
15685 
15686               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15687               // not keep more that one definition around (merge them). However,
15688               // ensure the decl passes the structural compatibility check in
15689               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15690               NamedDecl *Hidden = nullptr;
15691               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15692                 // There is a definition of this tag, but it is not visible. We
15693                 // explicitly make use of C++'s one definition rule here, and
15694                 // assume that this definition is identical to the hidden one
15695                 // we already have. Make the existing definition visible and
15696                 // use it in place of this one.
15697                 if (!getLangOpts().CPlusPlus) {
15698                   // Postpone making the old definition visible until after we
15699                   // complete parsing the new one and do the structural
15700                   // comparison.
15701                   SkipBody->CheckSameAsPrevious = true;
15702                   SkipBody->New = createTagFromNewDecl();
15703                   SkipBody->Previous = Def;
15704                   return Def;
15705                 } else {
15706                   SkipBody->ShouldSkip = true;
15707                   SkipBody->Previous = Def;
15708                   makeMergedDefinitionVisible(Hidden);
15709                   // Carry on and handle it like a normal definition. We'll
15710                   // skip starting the definitiion later.
15711                 }
15712               } else if (!IsExplicitSpecializationAfterInstantiation) {
15713                 // A redeclaration in function prototype scope in C isn't
15714                 // visible elsewhere, so merely issue a warning.
15715                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15716                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15717                 else
15718                   Diag(NameLoc, diag::err_redefinition) << Name;
15719                 notePreviousDefinition(Def,
15720                                        NameLoc.isValid() ? NameLoc : KWLoc);
15721                 // If this is a redefinition, recover by making this
15722                 // struct be anonymous, which will make any later
15723                 // references get the previous definition.
15724                 Name = nullptr;
15725                 Previous.clear();
15726                 Invalid = true;
15727               }
15728             } else {
15729               // If the type is currently being defined, complain
15730               // about a nested redefinition.
15731               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15732               if (TD->isBeingDefined()) {
15733                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15734                 Diag(PrevTagDecl->getLocation(),
15735                      diag::note_previous_definition);
15736                 Name = nullptr;
15737                 Previous.clear();
15738                 Invalid = true;
15739               }
15740             }
15741 
15742             // Okay, this is definition of a previously declared or referenced
15743             // tag. We're going to create a new Decl for it.
15744           }
15745 
15746           // Okay, we're going to make a redeclaration.  If this is some kind
15747           // of reference, make sure we build the redeclaration in the same DC
15748           // as the original, and ignore the current access specifier.
15749           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15750             SearchDC = PrevTagDecl->getDeclContext();
15751             AS = AS_none;
15752           }
15753         }
15754         // If we get here we have (another) forward declaration or we
15755         // have a definition.  Just create a new decl.
15756 
15757       } else {
15758         // If we get here, this is a definition of a new tag type in a nested
15759         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15760         // new decl/type.  We set PrevDecl to NULL so that the entities
15761         // have distinct types.
15762         Previous.clear();
15763       }
15764       // If we get here, we're going to create a new Decl. If PrevDecl
15765       // is non-NULL, it's a definition of the tag declared by
15766       // PrevDecl. If it's NULL, we have a new definition.
15767 
15768     // Otherwise, PrevDecl is not a tag, but was found with tag
15769     // lookup.  This is only actually possible in C++, where a few
15770     // things like templates still live in the tag namespace.
15771     } else {
15772       // Use a better diagnostic if an elaborated-type-specifier
15773       // found the wrong kind of type on the first
15774       // (non-redeclaration) lookup.
15775       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15776           !Previous.isForRedeclaration()) {
15777         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15778         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15779                                                        << Kind;
15780         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15781         Invalid = true;
15782 
15783       // Otherwise, only diagnose if the declaration is in scope.
15784       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15785                                 SS.isNotEmpty() || isMemberSpecialization)) {
15786         // do nothing
15787 
15788       // Diagnose implicit declarations introduced by elaborated types.
15789       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15790         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15791         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15792         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15793         Invalid = true;
15794 
15795       // Otherwise it's a declaration.  Call out a particularly common
15796       // case here.
15797       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15798         unsigned Kind = 0;
15799         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15800         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15801           << Name << Kind << TND->getUnderlyingType();
15802         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15803         Invalid = true;
15804 
15805       // Otherwise, diagnose.
15806       } else {
15807         // The tag name clashes with something else in the target scope,
15808         // issue an error and recover by making this tag be anonymous.
15809         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15810         notePreviousDefinition(PrevDecl, NameLoc);
15811         Name = nullptr;
15812         Invalid = true;
15813       }
15814 
15815       // The existing declaration isn't relevant to us; we're in a
15816       // new scope, so clear out the previous declaration.
15817       Previous.clear();
15818     }
15819   }
15820 
15821 CreateNewDecl:
15822 
15823   TagDecl *PrevDecl = nullptr;
15824   if (Previous.isSingleResult())
15825     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15826 
15827   // If there is an identifier, use the location of the identifier as the
15828   // location of the decl, otherwise use the location of the struct/union
15829   // keyword.
15830   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15831 
15832   // Otherwise, create a new declaration. If there is a previous
15833   // declaration of the same entity, the two will be linked via
15834   // PrevDecl.
15835   TagDecl *New;
15836 
15837   if (Kind == TTK_Enum) {
15838     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15839     // enum X { A, B, C } D;    D should chain to X.
15840     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15841                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15842                            ScopedEnumUsesClassTag, IsFixed);
15843 
15844     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15845       StdAlignValT = cast<EnumDecl>(New);
15846 
15847     // If this is an undefined enum, warn.
15848     if (TUK != TUK_Definition && !Invalid) {
15849       TagDecl *Def;
15850       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15851         // C++0x: 7.2p2: opaque-enum-declaration.
15852         // Conflicts are diagnosed above. Do nothing.
15853       }
15854       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15855         Diag(Loc, diag::ext_forward_ref_enum_def)
15856           << New;
15857         Diag(Def->getLocation(), diag::note_previous_definition);
15858       } else {
15859         unsigned DiagID = diag::ext_forward_ref_enum;
15860         if (getLangOpts().MSVCCompat)
15861           DiagID = diag::ext_ms_forward_ref_enum;
15862         else if (getLangOpts().CPlusPlus)
15863           DiagID = diag::err_forward_ref_enum;
15864         Diag(Loc, DiagID);
15865       }
15866     }
15867 
15868     if (EnumUnderlying) {
15869       EnumDecl *ED = cast<EnumDecl>(New);
15870       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15871         ED->setIntegerTypeSourceInfo(TI);
15872       else
15873         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15874       ED->setPromotionType(ED->getIntegerType());
15875       assert(ED->isComplete() && "enum with type should be complete");
15876     }
15877   } else {
15878     // struct/union/class
15879 
15880     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15881     // struct X { int A; } D;    D should chain to X.
15882     if (getLangOpts().CPlusPlus) {
15883       // FIXME: Look for a way to use RecordDecl for simple structs.
15884       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15885                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15886 
15887       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15888         StdBadAlloc = cast<CXXRecordDecl>(New);
15889     } else
15890       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15891                                cast_or_null<RecordDecl>(PrevDecl));
15892   }
15893 
15894   // C++11 [dcl.type]p3:
15895   //   A type-specifier-seq shall not define a class or enumeration [...].
15896   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15897       TUK == TUK_Definition) {
15898     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15899       << Context.getTagDeclType(New);
15900     Invalid = true;
15901   }
15902 
15903   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15904       DC->getDeclKind() == Decl::Enum) {
15905     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15906       << Context.getTagDeclType(New);
15907     Invalid = true;
15908   }
15909 
15910   // Maybe add qualifier info.
15911   if (SS.isNotEmpty()) {
15912     if (SS.isSet()) {
15913       // If this is either a declaration or a definition, check the
15914       // nested-name-specifier against the current context.
15915       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15916           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15917                                        isMemberSpecialization))
15918         Invalid = true;
15919 
15920       New->setQualifierInfo(SS.getWithLocInContext(Context));
15921       if (TemplateParameterLists.size() > 0) {
15922         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15923       }
15924     }
15925     else
15926       Invalid = true;
15927   }
15928 
15929   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15930     // Add alignment attributes if necessary; these attributes are checked when
15931     // the ASTContext lays out the structure.
15932     //
15933     // It is important for implementing the correct semantics that this
15934     // happen here (in ActOnTag). The #pragma pack stack is
15935     // maintained as a result of parser callbacks which can occur at
15936     // many points during the parsing of a struct declaration (because
15937     // the #pragma tokens are effectively skipped over during the
15938     // parsing of the struct).
15939     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15940       AddAlignmentAttributesForRecord(RD);
15941       AddMsStructLayoutForRecord(RD);
15942     }
15943   }
15944 
15945   if (ModulePrivateLoc.isValid()) {
15946     if (isMemberSpecialization)
15947       Diag(New->getLocation(), diag::err_module_private_specialization)
15948         << 2
15949         << FixItHint::CreateRemoval(ModulePrivateLoc);
15950     // __module_private__ does not apply to local classes. However, we only
15951     // diagnose this as an error when the declaration specifiers are
15952     // freestanding. Here, we just ignore the __module_private__.
15953     else if (!SearchDC->isFunctionOrMethod())
15954       New->setModulePrivate();
15955   }
15956 
15957   // If this is a specialization of a member class (of a class template),
15958   // check the specialization.
15959   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15960     Invalid = true;
15961 
15962   // If we're declaring or defining a tag in function prototype scope in C,
15963   // note that this type can only be used within the function and add it to
15964   // the list of decls to inject into the function definition scope.
15965   if ((Name || Kind == TTK_Enum) &&
15966       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15967     if (getLangOpts().CPlusPlus) {
15968       // C++ [dcl.fct]p6:
15969       //   Types shall not be defined in return or parameter types.
15970       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15971         Diag(Loc, diag::err_type_defined_in_param_type)
15972             << Name;
15973         Invalid = true;
15974       }
15975     } else if (!PrevDecl) {
15976       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15977     }
15978   }
15979 
15980   if (Invalid)
15981     New->setInvalidDecl();
15982 
15983   // Set the lexical context. If the tag has a C++ scope specifier, the
15984   // lexical context will be different from the semantic context.
15985   New->setLexicalDeclContext(CurContext);
15986 
15987   // Mark this as a friend decl if applicable.
15988   // In Microsoft mode, a friend declaration also acts as a forward
15989   // declaration so we always pass true to setObjectOfFriendDecl to make
15990   // the tag name visible.
15991   if (TUK == TUK_Friend)
15992     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15993 
15994   // Set the access specifier.
15995   if (!Invalid && SearchDC->isRecord())
15996     SetMemberAccessSpecifier(New, PrevDecl, AS);
15997 
15998   if (PrevDecl)
15999     CheckRedeclarationModuleOwnership(New, PrevDecl);
16000 
16001   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16002     New->startDefinition();
16003 
16004   ProcessDeclAttributeList(S, New, Attrs);
16005   AddPragmaAttributes(S, New);
16006 
16007   // If this has an identifier, add it to the scope stack.
16008   if (TUK == TUK_Friend) {
16009     // We might be replacing an existing declaration in the lookup tables;
16010     // if so, borrow its access specifier.
16011     if (PrevDecl)
16012       New->setAccess(PrevDecl->getAccess());
16013 
16014     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16015     DC->makeDeclVisibleInContext(New);
16016     if (Name) // can be null along some error paths
16017       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16018         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16019   } else if (Name) {
16020     S = getNonFieldDeclScope(S);
16021     PushOnScopeChains(New, S, true);
16022   } else {
16023     CurContext->addDecl(New);
16024   }
16025 
16026   // If this is the C FILE type, notify the AST context.
16027   if (IdentifierInfo *II = New->getIdentifier())
16028     if (!New->isInvalidDecl() &&
16029         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16030         II->isStr("FILE"))
16031       Context.setFILEDecl(New);
16032 
16033   if (PrevDecl)
16034     mergeDeclAttributes(New, PrevDecl);
16035 
16036   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16037     inferGslOwnerPointerAttribute(CXXRD);
16038 
16039   // If there's a #pragma GCC visibility in scope, set the visibility of this
16040   // record.
16041   AddPushedVisibilityAttribute(New);
16042 
16043   if (isMemberSpecialization && !New->isInvalidDecl())
16044     CompleteMemberSpecialization(New, Previous);
16045 
16046   OwnedDecl = true;
16047   // In C++, don't return an invalid declaration. We can't recover well from
16048   // the cases where we make the type anonymous.
16049   if (Invalid && getLangOpts().CPlusPlus) {
16050     if (New->isBeingDefined())
16051       if (auto RD = dyn_cast<RecordDecl>(New))
16052         RD->completeDefinition();
16053     return nullptr;
16054   } else if (SkipBody && SkipBody->ShouldSkip) {
16055     return SkipBody->Previous;
16056   } else {
16057     return New;
16058   }
16059 }
16060 
16061 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16062   AdjustDeclIfTemplate(TagD);
16063   TagDecl *Tag = cast<TagDecl>(TagD);
16064 
16065   // Enter the tag context.
16066   PushDeclContext(S, Tag);
16067 
16068   ActOnDocumentableDecl(TagD);
16069 
16070   // If there's a #pragma GCC visibility in scope, set the visibility of this
16071   // record.
16072   AddPushedVisibilityAttribute(Tag);
16073 }
16074 
16075 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16076                                     SkipBodyInfo &SkipBody) {
16077   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16078     return false;
16079 
16080   // Make the previous decl visible.
16081   makeMergedDefinitionVisible(SkipBody.Previous);
16082   return true;
16083 }
16084 
16085 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16086   assert(isa<ObjCContainerDecl>(IDecl) &&
16087          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16088   DeclContext *OCD = cast<DeclContext>(IDecl);
16089   assert(getContainingDC(OCD) == CurContext &&
16090       "The next DeclContext should be lexically contained in the current one.");
16091   CurContext = OCD;
16092   return IDecl;
16093 }
16094 
16095 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16096                                            SourceLocation FinalLoc,
16097                                            bool IsFinalSpelledSealed,
16098                                            SourceLocation LBraceLoc) {
16099   AdjustDeclIfTemplate(TagD);
16100   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16101 
16102   FieldCollector->StartClass();
16103 
16104   if (!Record->getIdentifier())
16105     return;
16106 
16107   if (FinalLoc.isValid())
16108     Record->addAttr(FinalAttr::Create(
16109         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16110         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16111 
16112   // C++ [class]p2:
16113   //   [...] The class-name is also inserted into the scope of the
16114   //   class itself; this is known as the injected-class-name. For
16115   //   purposes of access checking, the injected-class-name is treated
16116   //   as if it were a public member name.
16117   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16118       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16119       Record->getLocation(), Record->getIdentifier(),
16120       /*PrevDecl=*/nullptr,
16121       /*DelayTypeCreation=*/true);
16122   Context.getTypeDeclType(InjectedClassName, Record);
16123   InjectedClassName->setImplicit();
16124   InjectedClassName->setAccess(AS_public);
16125   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16126       InjectedClassName->setDescribedClassTemplate(Template);
16127   PushOnScopeChains(InjectedClassName, S);
16128   assert(InjectedClassName->isInjectedClassName() &&
16129          "Broken injected-class-name");
16130 }
16131 
16132 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16133                                     SourceRange BraceRange) {
16134   AdjustDeclIfTemplate(TagD);
16135   TagDecl *Tag = cast<TagDecl>(TagD);
16136   Tag->setBraceRange(BraceRange);
16137 
16138   // Make sure we "complete" the definition even it is invalid.
16139   if (Tag->isBeingDefined()) {
16140     assert(Tag->isInvalidDecl() && "We should already have completed it");
16141     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16142       RD->completeDefinition();
16143   }
16144 
16145   if (isa<CXXRecordDecl>(Tag)) {
16146     FieldCollector->FinishClass();
16147   }
16148 
16149   // Exit this scope of this tag's definition.
16150   PopDeclContext();
16151 
16152   if (getCurLexicalContext()->isObjCContainer() &&
16153       Tag->getDeclContext()->isFileContext())
16154     Tag->setTopLevelDeclInObjCContainer();
16155 
16156   // Notify the consumer that we've defined a tag.
16157   if (!Tag->isInvalidDecl())
16158     Consumer.HandleTagDeclDefinition(Tag);
16159 }
16160 
16161 void Sema::ActOnObjCContainerFinishDefinition() {
16162   // Exit this scope of this interface definition.
16163   PopDeclContext();
16164 }
16165 
16166 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16167   assert(DC == CurContext && "Mismatch of container contexts");
16168   OriginalLexicalContext = DC;
16169   ActOnObjCContainerFinishDefinition();
16170 }
16171 
16172 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16173   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16174   OriginalLexicalContext = nullptr;
16175 }
16176 
16177 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16178   AdjustDeclIfTemplate(TagD);
16179   TagDecl *Tag = cast<TagDecl>(TagD);
16180   Tag->setInvalidDecl();
16181 
16182   // Make sure we "complete" the definition even it is invalid.
16183   if (Tag->isBeingDefined()) {
16184     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16185       RD->completeDefinition();
16186   }
16187 
16188   // We're undoing ActOnTagStartDefinition here, not
16189   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16190   // the FieldCollector.
16191 
16192   PopDeclContext();
16193 }
16194 
16195 // Note that FieldName may be null for anonymous bitfields.
16196 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16197                                 IdentifierInfo *FieldName,
16198                                 QualType FieldTy, bool IsMsStruct,
16199                                 Expr *BitWidth, bool *ZeroWidth) {
16200   assert(BitWidth);
16201   if (BitWidth->containsErrors())
16202     return ExprError();
16203 
16204   // Default to true; that shouldn't confuse checks for emptiness
16205   if (ZeroWidth)
16206     *ZeroWidth = true;
16207 
16208   // C99 6.7.2.1p4 - verify the field type.
16209   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16210   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16211     // Handle incomplete and sizeless types with a specific error.
16212     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16213                                  diag::err_field_incomplete_or_sizeless))
16214       return ExprError();
16215     if (FieldName)
16216       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16217         << FieldName << FieldTy << BitWidth->getSourceRange();
16218     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16219       << FieldTy << BitWidth->getSourceRange();
16220   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16221                                              UPPC_BitFieldWidth))
16222     return ExprError();
16223 
16224   // If the bit-width is type- or value-dependent, don't try to check
16225   // it now.
16226   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16227     return BitWidth;
16228 
16229   llvm::APSInt Value;
16230   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16231   if (ICE.isInvalid())
16232     return ICE;
16233   BitWidth = ICE.get();
16234 
16235   if (Value != 0 && ZeroWidth)
16236     *ZeroWidth = false;
16237 
16238   // Zero-width bitfield is ok for anonymous field.
16239   if (Value == 0 && FieldName)
16240     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16241 
16242   if (Value.isSigned() && Value.isNegative()) {
16243     if (FieldName)
16244       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16245                << FieldName << Value.toString(10);
16246     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16247       << Value.toString(10);
16248   }
16249 
16250   if (!FieldTy->isDependentType()) {
16251     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16252     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16253     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16254 
16255     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16256     // ABI.
16257     bool CStdConstraintViolation =
16258         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16259     bool MSBitfieldViolation =
16260         Value.ugt(TypeStorageSize) &&
16261         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16262     if (CStdConstraintViolation || MSBitfieldViolation) {
16263       unsigned DiagWidth =
16264           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16265       if (FieldName)
16266         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16267                << FieldName << (unsigned)Value.getZExtValue()
16268                << !CStdConstraintViolation << DiagWidth;
16269 
16270       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16271              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16272              << DiagWidth;
16273     }
16274 
16275     // Warn on types where the user might conceivably expect to get all
16276     // specified bits as value bits: that's all integral types other than
16277     // 'bool'.
16278     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16279       if (FieldName)
16280         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16281             << FieldName << (unsigned)Value.getZExtValue()
16282             << (unsigned)TypeWidth;
16283       else
16284         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16285             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16286     }
16287   }
16288 
16289   return BitWidth;
16290 }
16291 
16292 /// ActOnField - Each field of a C struct/union is passed into this in order
16293 /// to create a FieldDecl object for it.
16294 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16295                        Declarator &D, Expr *BitfieldWidth) {
16296   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16297                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16298                                /*InitStyle=*/ICIS_NoInit, AS_public);
16299   return Res;
16300 }
16301 
16302 /// HandleField - Analyze a field of a C struct or a C++ data member.
16303 ///
16304 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16305                              SourceLocation DeclStart,
16306                              Declarator &D, Expr *BitWidth,
16307                              InClassInitStyle InitStyle,
16308                              AccessSpecifier AS) {
16309   if (D.isDecompositionDeclarator()) {
16310     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16311     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16312       << Decomp.getSourceRange();
16313     return nullptr;
16314   }
16315 
16316   IdentifierInfo *II = D.getIdentifier();
16317   SourceLocation Loc = DeclStart;
16318   if (II) Loc = D.getIdentifierLoc();
16319 
16320   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16321   QualType T = TInfo->getType();
16322   if (getLangOpts().CPlusPlus) {
16323     CheckExtraCXXDefaultArguments(D);
16324 
16325     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16326                                         UPPC_DataMemberType)) {
16327       D.setInvalidType();
16328       T = Context.IntTy;
16329       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16330     }
16331   }
16332 
16333   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16334 
16335   if (D.getDeclSpec().isInlineSpecified())
16336     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16337         << getLangOpts().CPlusPlus17;
16338   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16339     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16340          diag::err_invalid_thread)
16341       << DeclSpec::getSpecifierName(TSCS);
16342 
16343   // Check to see if this name was declared as a member previously
16344   NamedDecl *PrevDecl = nullptr;
16345   LookupResult Previous(*this, II, Loc, LookupMemberName,
16346                         ForVisibleRedeclaration);
16347   LookupName(Previous, S);
16348   switch (Previous.getResultKind()) {
16349     case LookupResult::Found:
16350     case LookupResult::FoundUnresolvedValue:
16351       PrevDecl = Previous.getAsSingle<NamedDecl>();
16352       break;
16353 
16354     case LookupResult::FoundOverloaded:
16355       PrevDecl = Previous.getRepresentativeDecl();
16356       break;
16357 
16358     case LookupResult::NotFound:
16359     case LookupResult::NotFoundInCurrentInstantiation:
16360     case LookupResult::Ambiguous:
16361       break;
16362   }
16363   Previous.suppressDiagnostics();
16364 
16365   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16366     // Maybe we will complain about the shadowed template parameter.
16367     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16368     // Just pretend that we didn't see the previous declaration.
16369     PrevDecl = nullptr;
16370   }
16371 
16372   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16373     PrevDecl = nullptr;
16374 
16375   bool Mutable
16376     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16377   SourceLocation TSSL = D.getBeginLoc();
16378   FieldDecl *NewFD
16379     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16380                      TSSL, AS, PrevDecl, &D);
16381 
16382   if (NewFD->isInvalidDecl())
16383     Record->setInvalidDecl();
16384 
16385   if (D.getDeclSpec().isModulePrivateSpecified())
16386     NewFD->setModulePrivate();
16387 
16388   if (NewFD->isInvalidDecl() && PrevDecl) {
16389     // Don't introduce NewFD into scope; there's already something
16390     // with the same name in the same scope.
16391   } else if (II) {
16392     PushOnScopeChains(NewFD, S);
16393   } else
16394     Record->addDecl(NewFD);
16395 
16396   return NewFD;
16397 }
16398 
16399 /// Build a new FieldDecl and check its well-formedness.
16400 ///
16401 /// This routine builds a new FieldDecl given the fields name, type,
16402 /// record, etc. \p PrevDecl should refer to any previous declaration
16403 /// with the same name and in the same scope as the field to be
16404 /// created.
16405 ///
16406 /// \returns a new FieldDecl.
16407 ///
16408 /// \todo The Declarator argument is a hack. It will be removed once
16409 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16410                                 TypeSourceInfo *TInfo,
16411                                 RecordDecl *Record, SourceLocation Loc,
16412                                 bool Mutable, Expr *BitWidth,
16413                                 InClassInitStyle InitStyle,
16414                                 SourceLocation TSSL,
16415                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16416                                 Declarator *D) {
16417   IdentifierInfo *II = Name.getAsIdentifierInfo();
16418   bool InvalidDecl = false;
16419   if (D) InvalidDecl = D->isInvalidType();
16420 
16421   // If we receive a broken type, recover by assuming 'int' and
16422   // marking this declaration as invalid.
16423   if (T.isNull()) {
16424     InvalidDecl = true;
16425     T = Context.IntTy;
16426   }
16427 
16428   QualType EltTy = Context.getBaseElementType(T);
16429   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16430     if (RequireCompleteSizedType(Loc, EltTy,
16431                                  diag::err_field_incomplete_or_sizeless)) {
16432       // Fields of incomplete type force their record to be invalid.
16433       Record->setInvalidDecl();
16434       InvalidDecl = true;
16435     } else {
16436       NamedDecl *Def;
16437       EltTy->isIncompleteType(&Def);
16438       if (Def && Def->isInvalidDecl()) {
16439         Record->setInvalidDecl();
16440         InvalidDecl = true;
16441       }
16442     }
16443   }
16444 
16445   // TR 18037 does not allow fields to be declared with address space
16446   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16447       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16448     Diag(Loc, diag::err_field_with_address_space);
16449     Record->setInvalidDecl();
16450     InvalidDecl = true;
16451   }
16452 
16453   if (LangOpts.OpenCL) {
16454     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16455     // used as structure or union field: image, sampler, event or block types.
16456     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16457         T->isBlockPointerType()) {
16458       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16459       Record->setInvalidDecl();
16460       InvalidDecl = true;
16461     }
16462     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16463     if (BitWidth) {
16464       Diag(Loc, diag::err_opencl_bitfields);
16465       InvalidDecl = true;
16466     }
16467   }
16468 
16469   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16470   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16471       T.hasQualifiers()) {
16472     InvalidDecl = true;
16473     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16474   }
16475 
16476   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16477   // than a variably modified type.
16478   if (!InvalidDecl && T->isVariablyModifiedType()) {
16479     bool SizeIsNegative;
16480     llvm::APSInt Oversized;
16481 
16482     TypeSourceInfo *FixedTInfo =
16483       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16484                                                     SizeIsNegative,
16485                                                     Oversized);
16486     if (FixedTInfo) {
16487       Diag(Loc, diag::warn_illegal_constant_array_size);
16488       TInfo = FixedTInfo;
16489       T = FixedTInfo->getType();
16490     } else {
16491       if (SizeIsNegative)
16492         Diag(Loc, diag::err_typecheck_negative_array_size);
16493       else if (Oversized.getBoolValue())
16494         Diag(Loc, diag::err_array_too_large)
16495           << Oversized.toString(10);
16496       else
16497         Diag(Loc, diag::err_typecheck_field_variable_size);
16498       InvalidDecl = true;
16499     }
16500   }
16501 
16502   // Fields can not have abstract class types
16503   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16504                                              diag::err_abstract_type_in_decl,
16505                                              AbstractFieldType))
16506     InvalidDecl = true;
16507 
16508   bool ZeroWidth = false;
16509   if (InvalidDecl)
16510     BitWidth = nullptr;
16511   // If this is declared as a bit-field, check the bit-field.
16512   if (BitWidth) {
16513     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16514                               &ZeroWidth).get();
16515     if (!BitWidth) {
16516       InvalidDecl = true;
16517       BitWidth = nullptr;
16518       ZeroWidth = false;
16519     }
16520 
16521     // Only data members can have in-class initializers.
16522     if (BitWidth && !II && InitStyle) {
16523       Diag(Loc, diag::err_anon_bitfield_init);
16524       InvalidDecl = true;
16525       BitWidth = nullptr;
16526       ZeroWidth = false;
16527     }
16528   }
16529 
16530   // Check that 'mutable' is consistent with the type of the declaration.
16531   if (!InvalidDecl && Mutable) {
16532     unsigned DiagID = 0;
16533     if (T->isReferenceType())
16534       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16535                                         : diag::err_mutable_reference;
16536     else if (T.isConstQualified())
16537       DiagID = diag::err_mutable_const;
16538 
16539     if (DiagID) {
16540       SourceLocation ErrLoc = Loc;
16541       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16542         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16543       Diag(ErrLoc, DiagID);
16544       if (DiagID != diag::ext_mutable_reference) {
16545         Mutable = false;
16546         InvalidDecl = true;
16547       }
16548     }
16549   }
16550 
16551   // C++11 [class.union]p8 (DR1460):
16552   //   At most one variant member of a union may have a
16553   //   brace-or-equal-initializer.
16554   if (InitStyle != ICIS_NoInit)
16555     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16556 
16557   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16558                                        BitWidth, Mutable, InitStyle);
16559   if (InvalidDecl)
16560     NewFD->setInvalidDecl();
16561 
16562   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16563     Diag(Loc, diag::err_duplicate_member) << II;
16564     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16565     NewFD->setInvalidDecl();
16566   }
16567 
16568   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16569     if (Record->isUnion()) {
16570       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16571         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16572         if (RDecl->getDefinition()) {
16573           // C++ [class.union]p1: An object of a class with a non-trivial
16574           // constructor, a non-trivial copy constructor, a non-trivial
16575           // destructor, or a non-trivial copy assignment operator
16576           // cannot be a member of a union, nor can an array of such
16577           // objects.
16578           if (CheckNontrivialField(NewFD))
16579             NewFD->setInvalidDecl();
16580         }
16581       }
16582 
16583       // C++ [class.union]p1: If a union contains a member of reference type,
16584       // the program is ill-formed, except when compiling with MSVC extensions
16585       // enabled.
16586       if (EltTy->isReferenceType()) {
16587         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16588                                     diag::ext_union_member_of_reference_type :
16589                                     diag::err_union_member_of_reference_type)
16590           << NewFD->getDeclName() << EltTy;
16591         if (!getLangOpts().MicrosoftExt)
16592           NewFD->setInvalidDecl();
16593       }
16594     }
16595   }
16596 
16597   // FIXME: We need to pass in the attributes given an AST
16598   // representation, not a parser representation.
16599   if (D) {
16600     // FIXME: The current scope is almost... but not entirely... correct here.
16601     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16602 
16603     if (NewFD->hasAttrs())
16604       CheckAlignasUnderalignment(NewFD);
16605   }
16606 
16607   // In auto-retain/release, infer strong retension for fields of
16608   // retainable type.
16609   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16610     NewFD->setInvalidDecl();
16611 
16612   if (T.isObjCGCWeak())
16613     Diag(Loc, diag::warn_attribute_weak_on_field);
16614 
16615   NewFD->setAccess(AS);
16616   return NewFD;
16617 }
16618 
16619 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16620   assert(FD);
16621   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16622 
16623   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16624     return false;
16625 
16626   QualType EltTy = Context.getBaseElementType(FD->getType());
16627   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16628     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16629     if (RDecl->getDefinition()) {
16630       // We check for copy constructors before constructors
16631       // because otherwise we'll never get complaints about
16632       // copy constructors.
16633 
16634       CXXSpecialMember member = CXXInvalid;
16635       // We're required to check for any non-trivial constructors. Since the
16636       // implicit default constructor is suppressed if there are any
16637       // user-declared constructors, we just need to check that there is a
16638       // trivial default constructor and a trivial copy constructor. (We don't
16639       // worry about move constructors here, since this is a C++98 check.)
16640       if (RDecl->hasNonTrivialCopyConstructor())
16641         member = CXXCopyConstructor;
16642       else if (!RDecl->hasTrivialDefaultConstructor())
16643         member = CXXDefaultConstructor;
16644       else if (RDecl->hasNonTrivialCopyAssignment())
16645         member = CXXCopyAssignment;
16646       else if (RDecl->hasNonTrivialDestructor())
16647         member = CXXDestructor;
16648 
16649       if (member != CXXInvalid) {
16650         if (!getLangOpts().CPlusPlus11 &&
16651             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16652           // Objective-C++ ARC: it is an error to have a non-trivial field of
16653           // a union. However, system headers in Objective-C programs
16654           // occasionally have Objective-C lifetime objects within unions,
16655           // and rather than cause the program to fail, we make those
16656           // members unavailable.
16657           SourceLocation Loc = FD->getLocation();
16658           if (getSourceManager().isInSystemHeader(Loc)) {
16659             if (!FD->hasAttr<UnavailableAttr>())
16660               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16661                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16662             return false;
16663           }
16664         }
16665 
16666         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16667                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16668                diag::err_illegal_union_or_anon_struct_member)
16669           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16670         DiagnoseNontrivial(RDecl, member);
16671         return !getLangOpts().CPlusPlus11;
16672       }
16673     }
16674   }
16675 
16676   return false;
16677 }
16678 
16679 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16680 ///  AST enum value.
16681 static ObjCIvarDecl::AccessControl
16682 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16683   switch (ivarVisibility) {
16684   default: llvm_unreachable("Unknown visitibility kind");
16685   case tok::objc_private: return ObjCIvarDecl::Private;
16686   case tok::objc_public: return ObjCIvarDecl::Public;
16687   case tok::objc_protected: return ObjCIvarDecl::Protected;
16688   case tok::objc_package: return ObjCIvarDecl::Package;
16689   }
16690 }
16691 
16692 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16693 /// in order to create an IvarDecl object for it.
16694 Decl *Sema::ActOnIvar(Scope *S,
16695                                 SourceLocation DeclStart,
16696                                 Declarator &D, Expr *BitfieldWidth,
16697                                 tok::ObjCKeywordKind Visibility) {
16698 
16699   IdentifierInfo *II = D.getIdentifier();
16700   Expr *BitWidth = (Expr*)BitfieldWidth;
16701   SourceLocation Loc = DeclStart;
16702   if (II) Loc = D.getIdentifierLoc();
16703 
16704   // FIXME: Unnamed fields can be handled in various different ways, for
16705   // example, unnamed unions inject all members into the struct namespace!
16706 
16707   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16708   QualType T = TInfo->getType();
16709 
16710   if (BitWidth) {
16711     // 6.7.2.1p3, 6.7.2.1p4
16712     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16713     if (!BitWidth)
16714       D.setInvalidType();
16715   } else {
16716     // Not a bitfield.
16717 
16718     // validate II.
16719 
16720   }
16721   if (T->isReferenceType()) {
16722     Diag(Loc, diag::err_ivar_reference_type);
16723     D.setInvalidType();
16724   }
16725   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16726   // than a variably modified type.
16727   else if (T->isVariablyModifiedType()) {
16728     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16729     D.setInvalidType();
16730   }
16731 
16732   // Get the visibility (access control) for this ivar.
16733   ObjCIvarDecl::AccessControl ac =
16734     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16735                                         : ObjCIvarDecl::None;
16736   // Must set ivar's DeclContext to its enclosing interface.
16737   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16738   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16739     return nullptr;
16740   ObjCContainerDecl *EnclosingContext;
16741   if (ObjCImplementationDecl *IMPDecl =
16742       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16743     if (LangOpts.ObjCRuntime.isFragile()) {
16744     // Case of ivar declared in an implementation. Context is that of its class.
16745       EnclosingContext = IMPDecl->getClassInterface();
16746       assert(EnclosingContext && "Implementation has no class interface!");
16747     }
16748     else
16749       EnclosingContext = EnclosingDecl;
16750   } else {
16751     if (ObjCCategoryDecl *CDecl =
16752         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16753       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16754         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16755         return nullptr;
16756       }
16757     }
16758     EnclosingContext = EnclosingDecl;
16759   }
16760 
16761   // Construct the decl.
16762   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16763                                              DeclStart, Loc, II, T,
16764                                              TInfo, ac, (Expr *)BitfieldWidth);
16765 
16766   if (II) {
16767     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16768                                            ForVisibleRedeclaration);
16769     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16770         && !isa<TagDecl>(PrevDecl)) {
16771       Diag(Loc, diag::err_duplicate_member) << II;
16772       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16773       NewID->setInvalidDecl();
16774     }
16775   }
16776 
16777   // Process attributes attached to the ivar.
16778   ProcessDeclAttributes(S, NewID, D);
16779 
16780   if (D.isInvalidType())
16781     NewID->setInvalidDecl();
16782 
16783   // In ARC, infer 'retaining' for ivars of retainable type.
16784   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16785     NewID->setInvalidDecl();
16786 
16787   if (D.getDeclSpec().isModulePrivateSpecified())
16788     NewID->setModulePrivate();
16789 
16790   if (II) {
16791     // FIXME: When interfaces are DeclContexts, we'll need to add
16792     // these to the interface.
16793     S->AddDecl(NewID);
16794     IdResolver.AddDecl(NewID);
16795   }
16796 
16797   if (LangOpts.ObjCRuntime.isNonFragile() &&
16798       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16799     Diag(Loc, diag::warn_ivars_in_interface);
16800 
16801   return NewID;
16802 }
16803 
16804 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16805 /// class and class extensions. For every class \@interface and class
16806 /// extension \@interface, if the last ivar is a bitfield of any type,
16807 /// then add an implicit `char :0` ivar to the end of that interface.
16808 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16809                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16810   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16811     return;
16812 
16813   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16814   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16815 
16816   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16817     return;
16818   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16819   if (!ID) {
16820     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16821       if (!CD->IsClassExtension())
16822         return;
16823     }
16824     // No need to add this to end of @implementation.
16825     else
16826       return;
16827   }
16828   // All conditions are met. Add a new bitfield to the tail end of ivars.
16829   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16830   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16831 
16832   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16833                               DeclLoc, DeclLoc, nullptr,
16834                               Context.CharTy,
16835                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16836                                                                DeclLoc),
16837                               ObjCIvarDecl::Private, BW,
16838                               true);
16839   AllIvarDecls.push_back(Ivar);
16840 }
16841 
16842 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16843                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16844                        SourceLocation RBrac,
16845                        const ParsedAttributesView &Attrs) {
16846   assert(EnclosingDecl && "missing record or interface decl");
16847 
16848   // If this is an Objective-C @implementation or category and we have
16849   // new fields here we should reset the layout of the interface since
16850   // it will now change.
16851   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16852     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16853     switch (DC->getKind()) {
16854     default: break;
16855     case Decl::ObjCCategory:
16856       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16857       break;
16858     case Decl::ObjCImplementation:
16859       Context.
16860         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16861       break;
16862     }
16863   }
16864 
16865   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16866   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16867 
16868   // Start counting up the number of named members; make sure to include
16869   // members of anonymous structs and unions in the total.
16870   unsigned NumNamedMembers = 0;
16871   if (Record) {
16872     for (const auto *I : Record->decls()) {
16873       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16874         if (IFD->getDeclName())
16875           ++NumNamedMembers;
16876     }
16877   }
16878 
16879   // Verify that all the fields are okay.
16880   SmallVector<FieldDecl*, 32> RecFields;
16881 
16882   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16883        i != end; ++i) {
16884     FieldDecl *FD = cast<FieldDecl>(*i);
16885 
16886     // Get the type for the field.
16887     const Type *FDTy = FD->getType().getTypePtr();
16888 
16889     if (!FD->isAnonymousStructOrUnion()) {
16890       // Remember all fields written by the user.
16891       RecFields.push_back(FD);
16892     }
16893 
16894     // If the field is already invalid for some reason, don't emit more
16895     // diagnostics about it.
16896     if (FD->isInvalidDecl()) {
16897       EnclosingDecl->setInvalidDecl();
16898       continue;
16899     }
16900 
16901     // C99 6.7.2.1p2:
16902     //   A structure or union shall not contain a member with
16903     //   incomplete or function type (hence, a structure shall not
16904     //   contain an instance of itself, but may contain a pointer to
16905     //   an instance of itself), except that the last member of a
16906     //   structure with more than one named member may have incomplete
16907     //   array type; such a structure (and any union containing,
16908     //   possibly recursively, a member that is such a structure)
16909     //   shall not be a member of a structure or an element of an
16910     //   array.
16911     bool IsLastField = (i + 1 == Fields.end());
16912     if (FDTy->isFunctionType()) {
16913       // Field declared as a function.
16914       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16915         << FD->getDeclName();
16916       FD->setInvalidDecl();
16917       EnclosingDecl->setInvalidDecl();
16918       continue;
16919     } else if (FDTy->isIncompleteArrayType() &&
16920                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16921       if (Record) {
16922         // Flexible array member.
16923         // Microsoft and g++ is more permissive regarding flexible array.
16924         // It will accept flexible array in union and also
16925         // as the sole element of a struct/class.
16926         unsigned DiagID = 0;
16927         if (!Record->isUnion() && !IsLastField) {
16928           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16929             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16930           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16931           FD->setInvalidDecl();
16932           EnclosingDecl->setInvalidDecl();
16933           continue;
16934         } else if (Record->isUnion())
16935           DiagID = getLangOpts().MicrosoftExt
16936                        ? diag::ext_flexible_array_union_ms
16937                        : getLangOpts().CPlusPlus
16938                              ? diag::ext_flexible_array_union_gnu
16939                              : diag::err_flexible_array_union;
16940         else if (NumNamedMembers < 1)
16941           DiagID = getLangOpts().MicrosoftExt
16942                        ? diag::ext_flexible_array_empty_aggregate_ms
16943                        : getLangOpts().CPlusPlus
16944                              ? diag::ext_flexible_array_empty_aggregate_gnu
16945                              : diag::err_flexible_array_empty_aggregate;
16946 
16947         if (DiagID)
16948           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16949                                           << Record->getTagKind();
16950         // While the layout of types that contain virtual bases is not specified
16951         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16952         // virtual bases after the derived members.  This would make a flexible
16953         // array member declared at the end of an object not adjacent to the end
16954         // of the type.
16955         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16956           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16957               << FD->getDeclName() << Record->getTagKind();
16958         if (!getLangOpts().C99)
16959           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16960             << FD->getDeclName() << Record->getTagKind();
16961 
16962         // If the element type has a non-trivial destructor, we would not
16963         // implicitly destroy the elements, so disallow it for now.
16964         //
16965         // FIXME: GCC allows this. We should probably either implicitly delete
16966         // the destructor of the containing class, or just allow this.
16967         QualType BaseElem = Context.getBaseElementType(FD->getType());
16968         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16969           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16970             << FD->getDeclName() << FD->getType();
16971           FD->setInvalidDecl();
16972           EnclosingDecl->setInvalidDecl();
16973           continue;
16974         }
16975         // Okay, we have a legal flexible array member at the end of the struct.
16976         Record->setHasFlexibleArrayMember(true);
16977       } else {
16978         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16979         // unless they are followed by another ivar. That check is done
16980         // elsewhere, after synthesized ivars are known.
16981       }
16982     } else if (!FDTy->isDependentType() &&
16983                RequireCompleteSizedType(
16984                    FD->getLocation(), FD->getType(),
16985                    diag::err_field_incomplete_or_sizeless)) {
16986       // Incomplete type
16987       FD->setInvalidDecl();
16988       EnclosingDecl->setInvalidDecl();
16989       continue;
16990     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16991       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16992         // A type which contains a flexible array member is considered to be a
16993         // flexible array member.
16994         Record->setHasFlexibleArrayMember(true);
16995         if (!Record->isUnion()) {
16996           // If this is a struct/class and this is not the last element, reject
16997           // it.  Note that GCC supports variable sized arrays in the middle of
16998           // structures.
16999           if (!IsLastField)
17000             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17001               << FD->getDeclName() << FD->getType();
17002           else {
17003             // We support flexible arrays at the end of structs in
17004             // other structs as an extension.
17005             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17006               << FD->getDeclName();
17007           }
17008         }
17009       }
17010       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17011           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17012                                  diag::err_abstract_type_in_decl,
17013                                  AbstractIvarType)) {
17014         // Ivars can not have abstract class types
17015         FD->setInvalidDecl();
17016       }
17017       if (Record && FDTTy->getDecl()->hasObjectMember())
17018         Record->setHasObjectMember(true);
17019       if (Record && FDTTy->getDecl()->hasVolatileMember())
17020         Record->setHasVolatileMember(true);
17021     } else if (FDTy->isObjCObjectType()) {
17022       /// A field cannot be an Objective-c object
17023       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17024         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17025       QualType T = Context.getObjCObjectPointerType(FD->getType());
17026       FD->setType(T);
17027     } else if (Record && Record->isUnion() &&
17028                FD->getType().hasNonTrivialObjCLifetime() &&
17029                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17030                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17031                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17032                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17033       // For backward compatibility, fields of C unions declared in system
17034       // headers that have non-trivial ObjC ownership qualifications are marked
17035       // as unavailable unless the qualifier is explicit and __strong. This can
17036       // break ABI compatibility between programs compiled with ARC and MRR, but
17037       // is a better option than rejecting programs using those unions under
17038       // ARC.
17039       FD->addAttr(UnavailableAttr::CreateImplicit(
17040           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17041           FD->getLocation()));
17042     } else if (getLangOpts().ObjC &&
17043                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17044                !Record->hasObjectMember()) {
17045       if (FD->getType()->isObjCObjectPointerType() ||
17046           FD->getType().isObjCGCStrong())
17047         Record->setHasObjectMember(true);
17048       else if (Context.getAsArrayType(FD->getType())) {
17049         QualType BaseType = Context.getBaseElementType(FD->getType());
17050         if (BaseType->isRecordType() &&
17051             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17052           Record->setHasObjectMember(true);
17053         else if (BaseType->isObjCObjectPointerType() ||
17054                  BaseType.isObjCGCStrong())
17055                Record->setHasObjectMember(true);
17056       }
17057     }
17058 
17059     if (Record && !getLangOpts().CPlusPlus &&
17060         !shouldIgnoreForRecordTriviality(FD)) {
17061       QualType FT = FD->getType();
17062       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17063         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17064         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17065             Record->isUnion())
17066           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17067       }
17068       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17069       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17070         Record->setNonTrivialToPrimitiveCopy(true);
17071         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17072           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17073       }
17074       if (FT.isDestructedType()) {
17075         Record->setNonTrivialToPrimitiveDestroy(true);
17076         Record->setParamDestroyedInCallee(true);
17077         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17078           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17079       }
17080 
17081       if (const auto *RT = FT->getAs<RecordType>()) {
17082         if (RT->getDecl()->getArgPassingRestrictions() ==
17083             RecordDecl::APK_CanNeverPassInRegs)
17084           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17085       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17086         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17087     }
17088 
17089     if (Record && FD->getType().isVolatileQualified())
17090       Record->setHasVolatileMember(true);
17091     // Keep track of the number of named members.
17092     if (FD->getIdentifier())
17093       ++NumNamedMembers;
17094   }
17095 
17096   // Okay, we successfully defined 'Record'.
17097   if (Record) {
17098     bool Completed = false;
17099     if (CXXRecord) {
17100       if (!CXXRecord->isInvalidDecl()) {
17101         // Set access bits correctly on the directly-declared conversions.
17102         for (CXXRecordDecl::conversion_iterator
17103                I = CXXRecord->conversion_begin(),
17104                E = CXXRecord->conversion_end(); I != E; ++I)
17105           I.setAccess((*I)->getAccess());
17106       }
17107 
17108       if (!CXXRecord->isDependentType()) {
17109         // Add any implicitly-declared members to this class.
17110         AddImplicitlyDeclaredMembersToClass(CXXRecord);
17111 
17112         if (!CXXRecord->isInvalidDecl()) {
17113           // If we have virtual base classes, we may end up finding multiple
17114           // final overriders for a given virtual function. Check for this
17115           // problem now.
17116           if (CXXRecord->getNumVBases()) {
17117             CXXFinalOverriderMap FinalOverriders;
17118             CXXRecord->getFinalOverriders(FinalOverriders);
17119 
17120             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17121                                              MEnd = FinalOverriders.end();
17122                  M != MEnd; ++M) {
17123               for (OverridingMethods::iterator SO = M->second.begin(),
17124                                             SOEnd = M->second.end();
17125                    SO != SOEnd; ++SO) {
17126                 assert(SO->second.size() > 0 &&
17127                        "Virtual function without overriding functions?");
17128                 if (SO->second.size() == 1)
17129                   continue;
17130 
17131                 // C++ [class.virtual]p2:
17132                 //   In a derived class, if a virtual member function of a base
17133                 //   class subobject has more than one final overrider the
17134                 //   program is ill-formed.
17135                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17136                   << (const NamedDecl *)M->first << Record;
17137                 Diag(M->first->getLocation(),
17138                      diag::note_overridden_virtual_function);
17139                 for (OverridingMethods::overriding_iterator
17140                           OM = SO->second.begin(),
17141                        OMEnd = SO->second.end();
17142                      OM != OMEnd; ++OM)
17143                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17144                     << (const NamedDecl *)M->first << OM->Method->getParent();
17145 
17146                 Record->setInvalidDecl();
17147               }
17148             }
17149             CXXRecord->completeDefinition(&FinalOverriders);
17150             Completed = true;
17151           }
17152         }
17153       }
17154     }
17155 
17156     if (!Completed)
17157       Record->completeDefinition();
17158 
17159     // Handle attributes before checking the layout.
17160     ProcessDeclAttributeList(S, Record, Attrs);
17161 
17162     // We may have deferred checking for a deleted destructor. Check now.
17163     if (CXXRecord) {
17164       auto *Dtor = CXXRecord->getDestructor();
17165       if (Dtor && Dtor->isImplicit() &&
17166           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17167         CXXRecord->setImplicitDestructorIsDeleted();
17168         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17169       }
17170     }
17171 
17172     if (Record->hasAttrs()) {
17173       CheckAlignasUnderalignment(Record);
17174 
17175       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17176         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17177                                            IA->getRange(), IA->getBestCase(),
17178                                            IA->getInheritanceModel());
17179     }
17180 
17181     // Check if the structure/union declaration is a type that can have zero
17182     // size in C. For C this is a language extension, for C++ it may cause
17183     // compatibility problems.
17184     bool CheckForZeroSize;
17185     if (!getLangOpts().CPlusPlus) {
17186       CheckForZeroSize = true;
17187     } else {
17188       // For C++ filter out types that cannot be referenced in C code.
17189       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17190       CheckForZeroSize =
17191           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17192           !CXXRecord->isDependentType() &&
17193           CXXRecord->isCLike();
17194     }
17195     if (CheckForZeroSize) {
17196       bool ZeroSize = true;
17197       bool IsEmpty = true;
17198       unsigned NonBitFields = 0;
17199       for (RecordDecl::field_iterator I = Record->field_begin(),
17200                                       E = Record->field_end();
17201            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17202         IsEmpty = false;
17203         if (I->isUnnamedBitfield()) {
17204           if (!I->isZeroLengthBitField(Context))
17205             ZeroSize = false;
17206         } else {
17207           ++NonBitFields;
17208           QualType FieldType = I->getType();
17209           if (FieldType->isIncompleteType() ||
17210               !Context.getTypeSizeInChars(FieldType).isZero())
17211             ZeroSize = false;
17212         }
17213       }
17214 
17215       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17216       // allowed in C++, but warn if its declaration is inside
17217       // extern "C" block.
17218       if (ZeroSize) {
17219         Diag(RecLoc, getLangOpts().CPlusPlus ?
17220                          diag::warn_zero_size_struct_union_in_extern_c :
17221                          diag::warn_zero_size_struct_union_compat)
17222           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17223       }
17224 
17225       // Structs without named members are extension in C (C99 6.7.2.1p7),
17226       // but are accepted by GCC.
17227       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17228         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17229                                diag::ext_no_named_members_in_struct_union)
17230           << Record->isUnion();
17231       }
17232     }
17233   } else {
17234     ObjCIvarDecl **ClsFields =
17235       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17236     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17237       ID->setEndOfDefinitionLoc(RBrac);
17238       // Add ivar's to class's DeclContext.
17239       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17240         ClsFields[i]->setLexicalDeclContext(ID);
17241         ID->addDecl(ClsFields[i]);
17242       }
17243       // Must enforce the rule that ivars in the base classes may not be
17244       // duplicates.
17245       if (ID->getSuperClass())
17246         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17247     } else if (ObjCImplementationDecl *IMPDecl =
17248                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17249       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17250       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17251         // Ivar declared in @implementation never belongs to the implementation.
17252         // Only it is in implementation's lexical context.
17253         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17254       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17255       IMPDecl->setIvarLBraceLoc(LBrac);
17256       IMPDecl->setIvarRBraceLoc(RBrac);
17257     } else if (ObjCCategoryDecl *CDecl =
17258                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17259       // case of ivars in class extension; all other cases have been
17260       // reported as errors elsewhere.
17261       // FIXME. Class extension does not have a LocEnd field.
17262       // CDecl->setLocEnd(RBrac);
17263       // Add ivar's to class extension's DeclContext.
17264       // Diagnose redeclaration of private ivars.
17265       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17266       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17267         if (IDecl) {
17268           if (const ObjCIvarDecl *ClsIvar =
17269               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17270             Diag(ClsFields[i]->getLocation(),
17271                  diag::err_duplicate_ivar_declaration);
17272             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17273             continue;
17274           }
17275           for (const auto *Ext : IDecl->known_extensions()) {
17276             if (const ObjCIvarDecl *ClsExtIvar
17277                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17278               Diag(ClsFields[i]->getLocation(),
17279                    diag::err_duplicate_ivar_declaration);
17280               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17281               continue;
17282             }
17283           }
17284         }
17285         ClsFields[i]->setLexicalDeclContext(CDecl);
17286         CDecl->addDecl(ClsFields[i]);
17287       }
17288       CDecl->setIvarLBraceLoc(LBrac);
17289       CDecl->setIvarRBraceLoc(RBrac);
17290     }
17291   }
17292 }
17293 
17294 /// Determine whether the given integral value is representable within
17295 /// the given type T.
17296 static bool isRepresentableIntegerValue(ASTContext &Context,
17297                                         llvm::APSInt &Value,
17298                                         QualType T) {
17299   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17300          "Integral type required!");
17301   unsigned BitWidth = Context.getIntWidth(T);
17302 
17303   if (Value.isUnsigned() || Value.isNonNegative()) {
17304     if (T->isSignedIntegerOrEnumerationType())
17305       --BitWidth;
17306     return Value.getActiveBits() <= BitWidth;
17307   }
17308   return Value.getMinSignedBits() <= BitWidth;
17309 }
17310 
17311 // Given an integral type, return the next larger integral type
17312 // (or a NULL type of no such type exists).
17313 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17314   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17315   // enum checking below.
17316   assert((T->isIntegralType(Context) ||
17317          T->isEnumeralType()) && "Integral type required!");
17318   const unsigned NumTypes = 4;
17319   QualType SignedIntegralTypes[NumTypes] = {
17320     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17321   };
17322   QualType UnsignedIntegralTypes[NumTypes] = {
17323     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17324     Context.UnsignedLongLongTy
17325   };
17326 
17327   unsigned BitWidth = Context.getTypeSize(T);
17328   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17329                                                         : UnsignedIntegralTypes;
17330   for (unsigned I = 0; I != NumTypes; ++I)
17331     if (Context.getTypeSize(Types[I]) > BitWidth)
17332       return Types[I];
17333 
17334   return QualType();
17335 }
17336 
17337 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17338                                           EnumConstantDecl *LastEnumConst,
17339                                           SourceLocation IdLoc,
17340                                           IdentifierInfo *Id,
17341                                           Expr *Val) {
17342   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17343   llvm::APSInt EnumVal(IntWidth);
17344   QualType EltTy;
17345 
17346   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17347     Val = nullptr;
17348 
17349   if (Val)
17350     Val = DefaultLvalueConversion(Val).get();
17351 
17352   if (Val) {
17353     if (Enum->isDependentType() || Val->isTypeDependent())
17354       EltTy = Context.DependentTy;
17355     else {
17356       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17357         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17358         // constant-expression in the enumerator-definition shall be a converted
17359         // constant expression of the underlying type.
17360         EltTy = Enum->getIntegerType();
17361         ExprResult Converted =
17362           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17363                                            CCEK_Enumerator);
17364         if (Converted.isInvalid())
17365           Val = nullptr;
17366         else
17367           Val = Converted.get();
17368       } else if (!Val->isValueDependent() &&
17369                  !(Val = VerifyIntegerConstantExpression(Val,
17370                                                          &EnumVal).get())) {
17371         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17372       } else {
17373         if (Enum->isComplete()) {
17374           EltTy = Enum->getIntegerType();
17375 
17376           // In Obj-C and Microsoft mode, require the enumeration value to be
17377           // representable in the underlying type of the enumeration. In C++11,
17378           // we perform a non-narrowing conversion as part of converted constant
17379           // expression checking.
17380           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17381             if (Context.getTargetInfo()
17382                     .getTriple()
17383                     .isWindowsMSVCEnvironment()) {
17384               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17385             } else {
17386               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17387             }
17388           }
17389 
17390           // Cast to the underlying type.
17391           Val = ImpCastExprToType(Val, EltTy,
17392                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17393                                                          : CK_IntegralCast)
17394                     .get();
17395         } else if (getLangOpts().CPlusPlus) {
17396           // C++11 [dcl.enum]p5:
17397           //   If the underlying type is not fixed, the type of each enumerator
17398           //   is the type of its initializing value:
17399           //     - If an initializer is specified for an enumerator, the
17400           //       initializing value has the same type as the expression.
17401           EltTy = Val->getType();
17402         } else {
17403           // C99 6.7.2.2p2:
17404           //   The expression that defines the value of an enumeration constant
17405           //   shall be an integer constant expression that has a value
17406           //   representable as an int.
17407 
17408           // Complain if the value is not representable in an int.
17409           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17410             Diag(IdLoc, diag::ext_enum_value_not_int)
17411               << EnumVal.toString(10) << Val->getSourceRange()
17412               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17413           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17414             // Force the type of the expression to 'int'.
17415             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17416           }
17417           EltTy = Val->getType();
17418         }
17419       }
17420     }
17421   }
17422 
17423   if (!Val) {
17424     if (Enum->isDependentType())
17425       EltTy = Context.DependentTy;
17426     else if (!LastEnumConst) {
17427       // C++0x [dcl.enum]p5:
17428       //   If the underlying type is not fixed, the type of each enumerator
17429       //   is the type of its initializing value:
17430       //     - If no initializer is specified for the first enumerator, the
17431       //       initializing value has an unspecified integral type.
17432       //
17433       // GCC uses 'int' for its unspecified integral type, as does
17434       // C99 6.7.2.2p3.
17435       if (Enum->isFixed()) {
17436         EltTy = Enum->getIntegerType();
17437       }
17438       else {
17439         EltTy = Context.IntTy;
17440       }
17441     } else {
17442       // Assign the last value + 1.
17443       EnumVal = LastEnumConst->getInitVal();
17444       ++EnumVal;
17445       EltTy = LastEnumConst->getType();
17446 
17447       // Check for overflow on increment.
17448       if (EnumVal < LastEnumConst->getInitVal()) {
17449         // C++0x [dcl.enum]p5:
17450         //   If the underlying type is not fixed, the type of each enumerator
17451         //   is the type of its initializing value:
17452         //
17453         //     - Otherwise the type of the initializing value is the same as
17454         //       the type of the initializing value of the preceding enumerator
17455         //       unless the incremented value is not representable in that type,
17456         //       in which case the type is an unspecified integral type
17457         //       sufficient to contain the incremented value. If no such type
17458         //       exists, the program is ill-formed.
17459         QualType T = getNextLargerIntegralType(Context, EltTy);
17460         if (T.isNull() || Enum->isFixed()) {
17461           // There is no integral type larger enough to represent this
17462           // value. Complain, then allow the value to wrap around.
17463           EnumVal = LastEnumConst->getInitVal();
17464           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17465           ++EnumVal;
17466           if (Enum->isFixed())
17467             // When the underlying type is fixed, this is ill-formed.
17468             Diag(IdLoc, diag::err_enumerator_wrapped)
17469               << EnumVal.toString(10)
17470               << EltTy;
17471           else
17472             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17473               << EnumVal.toString(10);
17474         } else {
17475           EltTy = T;
17476         }
17477 
17478         // Retrieve the last enumerator's value, extent that type to the
17479         // type that is supposed to be large enough to represent the incremented
17480         // value, then increment.
17481         EnumVal = LastEnumConst->getInitVal();
17482         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17483         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17484         ++EnumVal;
17485 
17486         // If we're not in C++, diagnose the overflow of enumerator values,
17487         // which in C99 means that the enumerator value is not representable in
17488         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17489         // permits enumerator values that are representable in some larger
17490         // integral type.
17491         if (!getLangOpts().CPlusPlus && !T.isNull())
17492           Diag(IdLoc, diag::warn_enum_value_overflow);
17493       } else if (!getLangOpts().CPlusPlus &&
17494                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17495         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17496         Diag(IdLoc, diag::ext_enum_value_not_int)
17497           << EnumVal.toString(10) << 1;
17498       }
17499     }
17500   }
17501 
17502   if (!EltTy->isDependentType()) {
17503     // Make the enumerator value match the signedness and size of the
17504     // enumerator's type.
17505     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17506     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17507   }
17508 
17509   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17510                                   Val, EnumVal);
17511 }
17512 
17513 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17514                                                 SourceLocation IILoc) {
17515   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17516       !getLangOpts().CPlusPlus)
17517     return SkipBodyInfo();
17518 
17519   // We have an anonymous enum definition. Look up the first enumerator to
17520   // determine if we should merge the definition with an existing one and
17521   // skip the body.
17522   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17523                                          forRedeclarationInCurContext());
17524   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17525   if (!PrevECD)
17526     return SkipBodyInfo();
17527 
17528   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17529   NamedDecl *Hidden;
17530   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17531     SkipBodyInfo Skip;
17532     Skip.Previous = Hidden;
17533     return Skip;
17534   }
17535 
17536   return SkipBodyInfo();
17537 }
17538 
17539 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17540                               SourceLocation IdLoc, IdentifierInfo *Id,
17541                               const ParsedAttributesView &Attrs,
17542                               SourceLocation EqualLoc, Expr *Val) {
17543   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17544   EnumConstantDecl *LastEnumConst =
17545     cast_or_null<EnumConstantDecl>(lastEnumConst);
17546 
17547   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17548   // we find one that is.
17549   S = getNonFieldDeclScope(S);
17550 
17551   // Verify that there isn't already something declared with this name in this
17552   // scope.
17553   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17554   LookupName(R, S);
17555   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17556 
17557   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17558     // Maybe we will complain about the shadowed template parameter.
17559     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17560     // Just pretend that we didn't see the previous declaration.
17561     PrevDecl = nullptr;
17562   }
17563 
17564   // C++ [class.mem]p15:
17565   // If T is the name of a class, then each of the following shall have a name
17566   // different from T:
17567   // - every enumerator of every member of class T that is an unscoped
17568   // enumerated type
17569   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17570     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17571                             DeclarationNameInfo(Id, IdLoc));
17572 
17573   EnumConstantDecl *New =
17574     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17575   if (!New)
17576     return nullptr;
17577 
17578   if (PrevDecl) {
17579     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17580       // Check for other kinds of shadowing not already handled.
17581       CheckShadow(New, PrevDecl, R);
17582     }
17583 
17584     // When in C++, we may get a TagDecl with the same name; in this case the
17585     // enum constant will 'hide' the tag.
17586     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17587            "Received TagDecl when not in C++!");
17588     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17589       if (isa<EnumConstantDecl>(PrevDecl))
17590         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17591       else
17592         Diag(IdLoc, diag::err_redefinition) << Id;
17593       notePreviousDefinition(PrevDecl, IdLoc);
17594       return nullptr;
17595     }
17596   }
17597 
17598   // Process attributes.
17599   ProcessDeclAttributeList(S, New, Attrs);
17600   AddPragmaAttributes(S, New);
17601 
17602   // Register this decl in the current scope stack.
17603   New->setAccess(TheEnumDecl->getAccess());
17604   PushOnScopeChains(New, S);
17605 
17606   ActOnDocumentableDecl(New);
17607 
17608   return New;
17609 }
17610 
17611 // Returns true when the enum initial expression does not trigger the
17612 // duplicate enum warning.  A few common cases are exempted as follows:
17613 // Element2 = Element1
17614 // Element2 = Element1 + 1
17615 // Element2 = Element1 - 1
17616 // Where Element2 and Element1 are from the same enum.
17617 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17618   Expr *InitExpr = ECD->getInitExpr();
17619   if (!InitExpr)
17620     return true;
17621   InitExpr = InitExpr->IgnoreImpCasts();
17622 
17623   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17624     if (!BO->isAdditiveOp())
17625       return true;
17626     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17627     if (!IL)
17628       return true;
17629     if (IL->getValue() != 1)
17630       return true;
17631 
17632     InitExpr = BO->getLHS();
17633   }
17634 
17635   // This checks if the elements are from the same enum.
17636   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17637   if (!DRE)
17638     return true;
17639 
17640   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17641   if (!EnumConstant)
17642     return true;
17643 
17644   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17645       Enum)
17646     return true;
17647 
17648   return false;
17649 }
17650 
17651 // Emits a warning when an element is implicitly set a value that
17652 // a previous element has already been set to.
17653 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17654                                         EnumDecl *Enum, QualType EnumType) {
17655   // Avoid anonymous enums
17656   if (!Enum->getIdentifier())
17657     return;
17658 
17659   // Only check for small enums.
17660   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17661     return;
17662 
17663   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17664     return;
17665 
17666   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17667   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17668 
17669   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17670 
17671   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17672   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17673 
17674   // Use int64_t as a key to avoid needing special handling for map keys.
17675   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17676     llvm::APSInt Val = D->getInitVal();
17677     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17678   };
17679 
17680   DuplicatesVector DupVector;
17681   ValueToVectorMap EnumMap;
17682 
17683   // Populate the EnumMap with all values represented by enum constants without
17684   // an initializer.
17685   for (auto *Element : Elements) {
17686     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17687 
17688     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17689     // this constant.  Skip this enum since it may be ill-formed.
17690     if (!ECD) {
17691       return;
17692     }
17693 
17694     // Constants with initalizers are handled in the next loop.
17695     if (ECD->getInitExpr())
17696       continue;
17697 
17698     // Duplicate values are handled in the next loop.
17699     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17700   }
17701 
17702   if (EnumMap.size() == 0)
17703     return;
17704 
17705   // Create vectors for any values that has duplicates.
17706   for (auto *Element : Elements) {
17707     // The last loop returned if any constant was null.
17708     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17709     if (!ValidDuplicateEnum(ECD, Enum))
17710       continue;
17711 
17712     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17713     if (Iter == EnumMap.end())
17714       continue;
17715 
17716     DeclOrVector& Entry = Iter->second;
17717     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17718       // Ensure constants are different.
17719       if (D == ECD)
17720         continue;
17721 
17722       // Create new vector and push values onto it.
17723       auto Vec = std::make_unique<ECDVector>();
17724       Vec->push_back(D);
17725       Vec->push_back(ECD);
17726 
17727       // Update entry to point to the duplicates vector.
17728       Entry = Vec.get();
17729 
17730       // Store the vector somewhere we can consult later for quick emission of
17731       // diagnostics.
17732       DupVector.emplace_back(std::move(Vec));
17733       continue;
17734     }
17735 
17736     ECDVector *Vec = Entry.get<ECDVector*>();
17737     // Make sure constants are not added more than once.
17738     if (*Vec->begin() == ECD)
17739       continue;
17740 
17741     Vec->push_back(ECD);
17742   }
17743 
17744   // Emit diagnostics.
17745   for (const auto &Vec : DupVector) {
17746     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17747 
17748     // Emit warning for one enum constant.
17749     auto *FirstECD = Vec->front();
17750     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17751       << FirstECD << FirstECD->getInitVal().toString(10)
17752       << FirstECD->getSourceRange();
17753 
17754     // Emit one note for each of the remaining enum constants with
17755     // the same value.
17756     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17757       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17758         << ECD << ECD->getInitVal().toString(10)
17759         << ECD->getSourceRange();
17760   }
17761 }
17762 
17763 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17764                              bool AllowMask) const {
17765   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17766   assert(ED->isCompleteDefinition() && "expected enum definition");
17767 
17768   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17769   llvm::APInt &FlagBits = R.first->second;
17770 
17771   if (R.second) {
17772     for (auto *E : ED->enumerators()) {
17773       const auto &EVal = E->getInitVal();
17774       // Only single-bit enumerators introduce new flag values.
17775       if (EVal.isPowerOf2())
17776         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17777     }
17778   }
17779 
17780   // A value is in a flag enum if either its bits are a subset of the enum's
17781   // flag bits (the first condition) or we are allowing masks and the same is
17782   // true of its complement (the second condition). When masks are allowed, we
17783   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17784   //
17785   // While it's true that any value could be used as a mask, the assumption is
17786   // that a mask will have all of the insignificant bits set. Anything else is
17787   // likely a logic error.
17788   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17789   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17790 }
17791 
17792 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17793                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17794                          const ParsedAttributesView &Attrs) {
17795   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17796   QualType EnumType = Context.getTypeDeclType(Enum);
17797 
17798   ProcessDeclAttributeList(S, Enum, Attrs);
17799 
17800   if (Enum->isDependentType()) {
17801     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17802       EnumConstantDecl *ECD =
17803         cast_or_null<EnumConstantDecl>(Elements[i]);
17804       if (!ECD) continue;
17805 
17806       ECD->setType(EnumType);
17807     }
17808 
17809     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17810     return;
17811   }
17812 
17813   // TODO: If the result value doesn't fit in an int, it must be a long or long
17814   // long value.  ISO C does not support this, but GCC does as an extension,
17815   // emit a warning.
17816   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17817   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17818   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17819 
17820   // Verify that all the values are okay, compute the size of the values, and
17821   // reverse the list.
17822   unsigned NumNegativeBits = 0;
17823   unsigned NumPositiveBits = 0;
17824 
17825   // Keep track of whether all elements have type int.
17826   bool AllElementsInt = true;
17827 
17828   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17829     EnumConstantDecl *ECD =
17830       cast_or_null<EnumConstantDecl>(Elements[i]);
17831     if (!ECD) continue;  // Already issued a diagnostic.
17832 
17833     const llvm::APSInt &InitVal = ECD->getInitVal();
17834 
17835     // Keep track of the size of positive and negative values.
17836     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17837       NumPositiveBits = std::max(NumPositiveBits,
17838                                  (unsigned)InitVal.getActiveBits());
17839     else
17840       NumNegativeBits = std::max(NumNegativeBits,
17841                                  (unsigned)InitVal.getMinSignedBits());
17842 
17843     // Keep track of whether every enum element has type int (very common).
17844     if (AllElementsInt)
17845       AllElementsInt = ECD->getType() == Context.IntTy;
17846   }
17847 
17848   // Figure out the type that should be used for this enum.
17849   QualType BestType;
17850   unsigned BestWidth;
17851 
17852   // C++0x N3000 [conv.prom]p3:
17853   //   An rvalue of an unscoped enumeration type whose underlying
17854   //   type is not fixed can be converted to an rvalue of the first
17855   //   of the following types that can represent all the values of
17856   //   the enumeration: int, unsigned int, long int, unsigned long
17857   //   int, long long int, or unsigned long long int.
17858   // C99 6.4.4.3p2:
17859   //   An identifier declared as an enumeration constant has type int.
17860   // The C99 rule is modified by a gcc extension
17861   QualType BestPromotionType;
17862 
17863   bool Packed = Enum->hasAttr<PackedAttr>();
17864   // -fshort-enums is the equivalent to specifying the packed attribute on all
17865   // enum definitions.
17866   if (LangOpts.ShortEnums)
17867     Packed = true;
17868 
17869   // If the enum already has a type because it is fixed or dictated by the
17870   // target, promote that type instead of analyzing the enumerators.
17871   if (Enum->isComplete()) {
17872     BestType = Enum->getIntegerType();
17873     if (BestType->isPromotableIntegerType())
17874       BestPromotionType = Context.getPromotedIntegerType(BestType);
17875     else
17876       BestPromotionType = BestType;
17877 
17878     BestWidth = Context.getIntWidth(BestType);
17879   }
17880   else if (NumNegativeBits) {
17881     // If there is a negative value, figure out the smallest integer type (of
17882     // int/long/longlong) that fits.
17883     // If it's packed, check also if it fits a char or a short.
17884     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17885       BestType = Context.SignedCharTy;
17886       BestWidth = CharWidth;
17887     } else if (Packed && NumNegativeBits <= ShortWidth &&
17888                NumPositiveBits < ShortWidth) {
17889       BestType = Context.ShortTy;
17890       BestWidth = ShortWidth;
17891     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17892       BestType = Context.IntTy;
17893       BestWidth = IntWidth;
17894     } else {
17895       BestWidth = Context.getTargetInfo().getLongWidth();
17896 
17897       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17898         BestType = Context.LongTy;
17899       } else {
17900         BestWidth = Context.getTargetInfo().getLongLongWidth();
17901 
17902         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17903           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17904         BestType = Context.LongLongTy;
17905       }
17906     }
17907     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17908   } else {
17909     // If there is no negative value, figure out the smallest type that fits
17910     // all of the enumerator values.
17911     // If it's packed, check also if it fits a char or a short.
17912     if (Packed && NumPositiveBits <= CharWidth) {
17913       BestType = Context.UnsignedCharTy;
17914       BestPromotionType = Context.IntTy;
17915       BestWidth = CharWidth;
17916     } else if (Packed && NumPositiveBits <= ShortWidth) {
17917       BestType = Context.UnsignedShortTy;
17918       BestPromotionType = Context.IntTy;
17919       BestWidth = ShortWidth;
17920     } else if (NumPositiveBits <= IntWidth) {
17921       BestType = Context.UnsignedIntTy;
17922       BestWidth = IntWidth;
17923       BestPromotionType
17924         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17925                            ? Context.UnsignedIntTy : Context.IntTy;
17926     } else if (NumPositiveBits <=
17927                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17928       BestType = Context.UnsignedLongTy;
17929       BestPromotionType
17930         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17931                            ? Context.UnsignedLongTy : Context.LongTy;
17932     } else {
17933       BestWidth = Context.getTargetInfo().getLongLongWidth();
17934       assert(NumPositiveBits <= BestWidth &&
17935              "How could an initializer get larger than ULL?");
17936       BestType = Context.UnsignedLongLongTy;
17937       BestPromotionType
17938         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17939                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17940     }
17941   }
17942 
17943   // Loop over all of the enumerator constants, changing their types to match
17944   // the type of the enum if needed.
17945   for (auto *D : Elements) {
17946     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17947     if (!ECD) continue;  // Already issued a diagnostic.
17948 
17949     // Standard C says the enumerators have int type, but we allow, as an
17950     // extension, the enumerators to be larger than int size.  If each
17951     // enumerator value fits in an int, type it as an int, otherwise type it the
17952     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17953     // that X has type 'int', not 'unsigned'.
17954 
17955     // Determine whether the value fits into an int.
17956     llvm::APSInt InitVal = ECD->getInitVal();
17957 
17958     // If it fits into an integer type, force it.  Otherwise force it to match
17959     // the enum decl type.
17960     QualType NewTy;
17961     unsigned NewWidth;
17962     bool NewSign;
17963     if (!getLangOpts().CPlusPlus &&
17964         !Enum->isFixed() &&
17965         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17966       NewTy = Context.IntTy;
17967       NewWidth = IntWidth;
17968       NewSign = true;
17969     } else if (ECD->getType() == BestType) {
17970       // Already the right type!
17971       if (getLangOpts().CPlusPlus)
17972         // C++ [dcl.enum]p4: Following the closing brace of an
17973         // enum-specifier, each enumerator has the type of its
17974         // enumeration.
17975         ECD->setType(EnumType);
17976       continue;
17977     } else {
17978       NewTy = BestType;
17979       NewWidth = BestWidth;
17980       NewSign = BestType->isSignedIntegerOrEnumerationType();
17981     }
17982 
17983     // Adjust the APSInt value.
17984     InitVal = InitVal.extOrTrunc(NewWidth);
17985     InitVal.setIsSigned(NewSign);
17986     ECD->setInitVal(InitVal);
17987 
17988     // Adjust the Expr initializer and type.
17989     if (ECD->getInitExpr() &&
17990         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17991       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17992                                                 CK_IntegralCast,
17993                                                 ECD->getInitExpr(),
17994                                                 /*base paths*/ nullptr,
17995                                                 VK_RValue));
17996     if (getLangOpts().CPlusPlus)
17997       // C++ [dcl.enum]p4: Following the closing brace of an
17998       // enum-specifier, each enumerator has the type of its
17999       // enumeration.
18000       ECD->setType(EnumType);
18001     else
18002       ECD->setType(NewTy);
18003   }
18004 
18005   Enum->completeDefinition(BestType, BestPromotionType,
18006                            NumPositiveBits, NumNegativeBits);
18007 
18008   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18009 
18010   if (Enum->isClosedFlag()) {
18011     for (Decl *D : Elements) {
18012       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18013       if (!ECD) continue;  // Already issued a diagnostic.
18014 
18015       llvm::APSInt InitVal = ECD->getInitVal();
18016       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18017           !IsValueInFlagEnum(Enum, InitVal, true))
18018         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18019           << ECD << Enum;
18020     }
18021   }
18022 
18023   // Now that the enum type is defined, ensure it's not been underaligned.
18024   if (Enum->hasAttrs())
18025     CheckAlignasUnderalignment(Enum);
18026 }
18027 
18028 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18029                                   SourceLocation StartLoc,
18030                                   SourceLocation EndLoc) {
18031   StringLiteral *AsmString = cast<StringLiteral>(expr);
18032 
18033   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18034                                                    AsmString, StartLoc,
18035                                                    EndLoc);
18036   CurContext->addDecl(New);
18037   return New;
18038 }
18039 
18040 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18041                                       IdentifierInfo* AliasName,
18042                                       SourceLocation PragmaLoc,
18043                                       SourceLocation NameLoc,
18044                                       SourceLocation AliasNameLoc) {
18045   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18046                                          LookupOrdinaryName);
18047   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18048                            AttributeCommonInfo::AS_Pragma);
18049   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18050       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18051 
18052   // If a declaration that:
18053   // 1) declares a function or a variable
18054   // 2) has external linkage
18055   // already exists, add a label attribute to it.
18056   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18057     if (isDeclExternC(PrevDecl))
18058       PrevDecl->addAttr(Attr);
18059     else
18060       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18061           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18062   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18063   } else
18064     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18065 }
18066 
18067 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18068                              SourceLocation PragmaLoc,
18069                              SourceLocation NameLoc) {
18070   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18071 
18072   if (PrevDecl) {
18073     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18074   } else {
18075     (void)WeakUndeclaredIdentifiers.insert(
18076       std::pair<IdentifierInfo*,WeakInfo>
18077         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18078   }
18079 }
18080 
18081 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18082                                 IdentifierInfo* AliasName,
18083                                 SourceLocation PragmaLoc,
18084                                 SourceLocation NameLoc,
18085                                 SourceLocation AliasNameLoc) {
18086   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18087                                     LookupOrdinaryName);
18088   WeakInfo W = WeakInfo(Name, NameLoc);
18089 
18090   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18091     if (!PrevDecl->hasAttr<AliasAttr>())
18092       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18093         DeclApplyPragmaWeak(TUScope, ND, W);
18094   } else {
18095     (void)WeakUndeclaredIdentifiers.insert(
18096       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18097   }
18098 }
18099 
18100 Decl *Sema::getObjCDeclContext() const {
18101   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18102 }
18103 
18104 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18105                                                      bool Final) {
18106   // Templates are emitted when they're instantiated.
18107   if (FD->isDependentContext())
18108     return FunctionEmissionStatus::TemplateDiscarded;
18109 
18110   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18111   if (LangOpts.OpenMPIsDevice) {
18112     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18113         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18114     if (DevTy.hasValue()) {
18115       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18116         OMPES = FunctionEmissionStatus::OMPDiscarded;
18117       else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18118                *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18119         OMPES = FunctionEmissionStatus::Emitted;
18120       }
18121     }
18122   } else if (LangOpts.OpenMP) {
18123     // In OpenMP 4.5 all the functions are host functions.
18124     if (LangOpts.OpenMP <= 45) {
18125       OMPES = FunctionEmissionStatus::Emitted;
18126     } else {
18127       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18128           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18129       // In OpenMP 5.0 or above, DevTy may be changed later by
18130       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18131       // having no value does not imply host. The emission status will be
18132       // checked again at the end of compilation unit.
18133       if (DevTy.hasValue()) {
18134         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18135           OMPES = FunctionEmissionStatus::OMPDiscarded;
18136         } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18137                    *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18138           OMPES = FunctionEmissionStatus::Emitted;
18139       } else if (Final)
18140         OMPES = FunctionEmissionStatus::Emitted;
18141     }
18142   }
18143   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18144       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18145     return OMPES;
18146 
18147   if (LangOpts.CUDA) {
18148     // When compiling for device, host functions are never emitted.  Similarly,
18149     // when compiling for host, device and global functions are never emitted.
18150     // (Technically, we do emit a host-side stub for global functions, but this
18151     // doesn't count for our purposes here.)
18152     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18153     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18154       return FunctionEmissionStatus::CUDADiscarded;
18155     if (!LangOpts.CUDAIsDevice &&
18156         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18157       return FunctionEmissionStatus::CUDADiscarded;
18158 
18159     // Check whether this function is externally visible -- if so, it's
18160     // known-emitted.
18161     //
18162     // We have to check the GVA linkage of the function's *definition* -- if we
18163     // only have a declaration, we don't know whether or not the function will
18164     // be emitted, because (say) the definition could include "inline".
18165     FunctionDecl *Def = FD->getDefinition();
18166 
18167     if (Def &&
18168         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18169         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18170       return FunctionEmissionStatus::Emitted;
18171   }
18172 
18173   // Otherwise, the function is known-emitted if it's in our set of
18174   // known-emitted functions.
18175   return FunctionEmissionStatus::Unknown;
18176 }
18177 
18178 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18179   // Host-side references to a __global__ function refer to the stub, so the
18180   // function itself is never emitted and therefore should not be marked.
18181   // If we have host fn calls kernel fn calls host+device, the HD function
18182   // does not get instantiated on the host. We model this by omitting at the
18183   // call to the kernel from the callgraph. This ensures that, when compiling
18184   // for host, only HD functions actually called from the host get marked as
18185   // known-emitted.
18186   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18187          IdentifyCUDATarget(Callee) == CFT_Global;
18188 }
18189