1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/NonTrivialTypeVisitor.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109   std::unique_ptr<CorrectionCandidateCallback> clone() override {
110     return std::make_unique<TypeNameValidatorCCC>(*this);
111   }
112 
113  private:
114   bool AllowInvalidDecl;
115   bool WantClassName;
116   bool AllowTemplates;
117   bool AllowNonTemplates;
118 };
119 
120 } // end anonymous namespace
121 
122 /// Determine whether the token kind starts a simple-type-specifier.
123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
124   switch (Kind) {
125   // FIXME: Take into account the current language when deciding whether a
126   // token kind is a valid type specifier
127   case tok::kw_short:
128   case tok::kw_long:
129   case tok::kw___int64:
130   case tok::kw___int128:
131   case tok::kw_signed:
132   case tok::kw_unsigned:
133   case tok::kw_void:
134   case tok::kw_char:
135   case tok::kw_int:
136   case tok::kw_half:
137   case tok::kw_float:
138   case tok::kw_double:
139   case tok::kw__Float16:
140   case tok::kw___float128:
141   case tok::kw_wchar_t:
142   case tok::kw_bool:
143   case tok::kw___underlying_type:
144   case tok::kw___auto_type:
145     return true;
146 
147   case tok::annot_typename:
148   case tok::kw_char16_t:
149   case tok::kw_char32_t:
150   case tok::kw_typeof:
151   case tok::annot_decltype:
152   case tok::kw_decltype:
153     return getLangOpts().CPlusPlus;
154 
155   case tok::kw_char8_t:
156     return getLangOpts().Char8;
157 
158   default:
159     break;
160   }
161 
162   return false;
163 }
164 
165 namespace {
166 enum class UnqualifiedTypeNameLookupResult {
167   NotFound,
168   FoundNonType,
169   FoundType
170 };
171 } // end anonymous namespace
172 
173 /// Tries to perform unqualified lookup of the type decls in bases for
174 /// dependent class.
175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
176 /// type decl, \a FoundType if only type decls are found.
177 static UnqualifiedTypeNameLookupResult
178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
179                                 SourceLocation NameLoc,
180                                 const CXXRecordDecl *RD) {
181   if (!RD->hasDefinition())
182     return UnqualifiedTypeNameLookupResult::NotFound;
183   // Look for type decls in base classes.
184   UnqualifiedTypeNameLookupResult FoundTypeDecl =
185       UnqualifiedTypeNameLookupResult::NotFound;
186   for (const auto &Base : RD->bases()) {
187     const CXXRecordDecl *BaseRD = nullptr;
188     if (auto *BaseTT = Base.getType()->getAs<TagType>())
189       BaseRD = BaseTT->getAsCXXRecordDecl();
190     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
191       // Look for type decls in dependent base classes that have known primary
192       // templates.
193       if (!TST || !TST->isDependentType())
194         continue;
195       auto *TD = TST->getTemplateName().getAsTemplateDecl();
196       if (!TD)
197         continue;
198       if (auto *BasePrimaryTemplate =
199           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
200         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
201           BaseRD = BasePrimaryTemplate;
202         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
203           if (const ClassTemplatePartialSpecializationDecl *PS =
204                   CTD->findPartialSpecialization(Base.getType()))
205             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
206               BaseRD = PS;
207         }
208       }
209     }
210     if (BaseRD) {
211       for (NamedDecl *ND : BaseRD->lookup(&II)) {
212         if (!isa<TypeDecl>(ND))
213           return UnqualifiedTypeNameLookupResult::FoundNonType;
214         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215       }
216       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
217         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
218         case UnqualifiedTypeNameLookupResult::FoundNonType:
219           return UnqualifiedTypeNameLookupResult::FoundNonType;
220         case UnqualifiedTypeNameLookupResult::FoundType:
221           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
222           break;
223         case UnqualifiedTypeNameLookupResult::NotFound:
224           break;
225         }
226       }
227     }
228   }
229 
230   return FoundTypeDecl;
231 }
232 
233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
234                                                       const IdentifierInfo &II,
235                                                       SourceLocation NameLoc) {
236   // Lookup in the parent class template context, if any.
237   const CXXRecordDecl *RD = nullptr;
238   UnqualifiedTypeNameLookupResult FoundTypeDecl =
239       UnqualifiedTypeNameLookupResult::NotFound;
240   for (DeclContext *DC = S.CurContext;
241        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
242        DC = DC->getParent()) {
243     // Look for type decls in dependent base classes that have known primary
244     // templates.
245     RD = dyn_cast<CXXRecordDecl>(DC);
246     if (RD && RD->getDescribedClassTemplate())
247       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
248   }
249   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
250     return nullptr;
251 
252   // We found some types in dependent base classes.  Recover as if the user
253   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
254   // lookup during template instantiation.
255   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
256 
257   ASTContext &Context = S.Context;
258   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
259                                           cast<Type>(Context.getRecordType(RD)));
260   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
261 
262   CXXScopeSpec SS;
263   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
264 
265   TypeLocBuilder Builder;
266   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
267   DepTL.setNameLoc(NameLoc);
268   DepTL.setElaboratedKeywordLoc(SourceLocation());
269   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
270   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
271 }
272 
273 /// If the identifier refers to a type name within this scope,
274 /// return the declaration of that type.
275 ///
276 /// This routine performs ordinary name lookup of the identifier II
277 /// within the given scope, with optional C++ scope specifier SS, to
278 /// determine whether the name refers to a type. If so, returns an
279 /// opaque pointer (actually a QualType) corresponding to that
280 /// type. Otherwise, returns NULL.
281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
282                              Scope *S, CXXScopeSpec *SS,
283                              bool isClassName, bool HasTrailingDot,
284                              ParsedType ObjectTypePtr,
285                              bool IsCtorOrDtorName,
286                              bool WantNontrivialTypeSourceInfo,
287                              bool IsClassTemplateDeductionContext,
288                              IdentifierInfo **CorrectedII) {
289   // FIXME: Consider allowing this outside C++1z mode as an extension.
290   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
291                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
292                               !isClassName && !HasTrailingDot;
293 
294   // Determine where we will perform name lookup.
295   DeclContext *LookupCtx = nullptr;
296   if (ObjectTypePtr) {
297     QualType ObjectType = ObjectTypePtr.get();
298     if (ObjectType->isRecordType())
299       LookupCtx = computeDeclContext(ObjectType);
300   } else if (SS && SS->isNotEmpty()) {
301     LookupCtx = computeDeclContext(*SS, false);
302 
303     if (!LookupCtx) {
304       if (isDependentScopeSpecifier(*SS)) {
305         // C++ [temp.res]p3:
306         //   A qualified-id that refers to a type and in which the
307         //   nested-name-specifier depends on a template-parameter (14.6.2)
308         //   shall be prefixed by the keyword typename to indicate that the
309         //   qualified-id denotes a type, forming an
310         //   elaborated-type-specifier (7.1.5.3).
311         //
312         // We therefore do not perform any name lookup if the result would
313         // refer to a member of an unknown specialization.
314         if (!isClassName && !IsCtorOrDtorName)
315           return nullptr;
316 
317         // We know from the grammar that this name refers to a type,
318         // so build a dependent node to describe the type.
319         if (WantNontrivialTypeSourceInfo)
320           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
321 
322         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
323         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
324                                        II, NameLoc);
325         return ParsedType::make(T);
326       }
327 
328       return nullptr;
329     }
330 
331     if (!LookupCtx->isDependentContext() &&
332         RequireCompleteDeclContext(*SS, LookupCtx))
333       return nullptr;
334   }
335 
336   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
337   // lookup for class-names.
338   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
339                                       LookupOrdinaryName;
340   LookupResult Result(*this, &II, NameLoc, Kind);
341   if (LookupCtx) {
342     // Perform "qualified" name lookup into the declaration context we
343     // computed, which is either the type of the base of a member access
344     // expression or the declaration context associated with a prior
345     // nested-name-specifier.
346     LookupQualifiedName(Result, LookupCtx);
347 
348     if (ObjectTypePtr && Result.empty()) {
349       // C++ [basic.lookup.classref]p3:
350       //   If the unqualified-id is ~type-name, the type-name is looked up
351       //   in the context of the entire postfix-expression. If the type T of
352       //   the object expression is of a class type C, the type-name is also
353       //   looked up in the scope of class C. At least one of the lookups shall
354       //   find a name that refers to (possibly cv-qualified) T.
355       LookupName(Result, S);
356     }
357   } else {
358     // Perform unqualified name lookup.
359     LookupName(Result, S);
360 
361     // For unqualified lookup in a class template in MSVC mode, look into
362     // dependent base classes where the primary class template is known.
363     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
364       if (ParsedType TypeInBase =
365               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
366         return TypeInBase;
367     }
368   }
369 
370   NamedDecl *IIDecl = nullptr;
371   switch (Result.getResultKind()) {
372   case LookupResult::NotFound:
373   case LookupResult::NotFoundInCurrentInstantiation:
374     if (CorrectedII) {
375       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
376                                AllowDeducedTemplate);
377       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
378                                               S, SS, CCC, CTK_ErrorRecovery);
379       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
380       TemplateTy Template;
381       bool MemberOfUnknownSpecialization;
382       UnqualifiedId TemplateName;
383       TemplateName.setIdentifier(NewII, NameLoc);
384       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
385       CXXScopeSpec NewSS, *NewSSPtr = SS;
386       if (SS && NNS) {
387         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
388         NewSSPtr = &NewSS;
389       }
390       if (Correction && (NNS || NewII != &II) &&
391           // Ignore a correction to a template type as the to-be-corrected
392           // identifier is not a template (typo correction for template names
393           // is handled elsewhere).
394           !(getLangOpts().CPlusPlus && NewSSPtr &&
395             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
396                            Template, MemberOfUnknownSpecialization))) {
397         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
398                                     isClassName, HasTrailingDot, ObjectTypePtr,
399                                     IsCtorOrDtorName,
400                                     WantNontrivialTypeSourceInfo,
401                                     IsClassTemplateDeductionContext);
402         if (Ty) {
403           diagnoseTypo(Correction,
404                        PDiag(diag::err_unknown_type_or_class_name_suggest)
405                          << Result.getLookupName() << isClassName);
406           if (SS && NNS)
407             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
408           *CorrectedII = NewII;
409           return Ty;
410         }
411       }
412     }
413     // If typo correction failed or was not performed, fall through
414     LLVM_FALLTHROUGH;
415   case LookupResult::FoundOverloaded:
416   case LookupResult::FoundUnresolvedValue:
417     Result.suppressDiagnostics();
418     return nullptr;
419 
420   case LookupResult::Ambiguous:
421     // Recover from type-hiding ambiguities by hiding the type.  We'll
422     // do the lookup again when looking for an object, and we can
423     // diagnose the error then.  If we don't do this, then the error
424     // about hiding the type will be immediately followed by an error
425     // that only makes sense if the identifier was treated like a type.
426     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
427       Result.suppressDiagnostics();
428       return nullptr;
429     }
430 
431     // Look to see if we have a type anywhere in the list of results.
432     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
433          Res != ResEnd; ++Res) {
434       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
435           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
436         if (!IIDecl ||
437             (*Res)->getLocation().getRawEncoding() <
438               IIDecl->getLocation().getRawEncoding())
439           IIDecl = *Res;
440       }
441     }
442 
443     if (!IIDecl) {
444       // None of the entities we found is a type, so there is no way
445       // to even assume that the result is a type. In this case, don't
446       // complain about the ambiguity. The parser will either try to
447       // perform this lookup again (e.g., as an object name), which
448       // will produce the ambiguity, or will complain that it expected
449       // a type name.
450       Result.suppressDiagnostics();
451       return nullptr;
452     }
453 
454     // We found a type within the ambiguous lookup; diagnose the
455     // ambiguity and then return that type. This might be the right
456     // answer, or it might not be, but it suppresses any attempt to
457     // perform the name lookup again.
458     break;
459 
460   case LookupResult::Found:
461     IIDecl = Result.getFoundDecl();
462     break;
463   }
464 
465   assert(IIDecl && "Didn't find decl");
466 
467   QualType T;
468   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
469     // C++ [class.qual]p2: A lookup that would find the injected-class-name
470     // instead names the constructors of the class, except when naming a class.
471     // This is ill-formed when we're not actually forming a ctor or dtor name.
472     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
473     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
474     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
475         FoundRD->isInjectedClassName() &&
476         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
477       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
478           << &II << /*Type*/1;
479 
480     DiagnoseUseOfDecl(IIDecl, NameLoc);
481 
482     T = Context.getTypeDeclType(TD);
483     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
484   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
485     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
486     if (!HasTrailingDot)
487       T = Context.getObjCInterfaceType(IDecl);
488   } else if (AllowDeducedTemplate) {
489     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
490       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
491                                                        QualType(), false);
492   }
493 
494   if (T.isNull()) {
495     // If it's not plausibly a type, suppress diagnostics.
496     Result.suppressDiagnostics();
497     return nullptr;
498   }
499 
500   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
501   // constructor or destructor name (in such a case, the scope specifier
502   // will be attached to the enclosing Expr or Decl node).
503   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
504       !isa<ObjCInterfaceDecl>(IIDecl)) {
505     if (WantNontrivialTypeSourceInfo) {
506       // Construct a type with type-source information.
507       TypeLocBuilder Builder;
508       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
509 
510       T = getElaboratedType(ETK_None, *SS, T);
511       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
512       ElabTL.setElaboratedKeywordLoc(SourceLocation());
513       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
514       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
515     } else {
516       T = getElaboratedType(ETK_None, *SS, T);
517     }
518   }
519 
520   return ParsedType::make(T);
521 }
522 
523 // Builds a fake NNS for the given decl context.
524 static NestedNameSpecifier *
525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
526   for (;; DC = DC->getLookupParent()) {
527     DC = DC->getPrimaryContext();
528     auto *ND = dyn_cast<NamespaceDecl>(DC);
529     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
530       return NestedNameSpecifier::Create(Context, nullptr, ND);
531     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
532       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
533                                          RD->getTypeForDecl());
534     else if (isa<TranslationUnitDecl>(DC))
535       return NestedNameSpecifier::GlobalSpecifier(Context);
536   }
537   llvm_unreachable("something isn't in TU scope?");
538 }
539 
540 /// Find the parent class with dependent bases of the innermost enclosing method
541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
542 /// up allowing unqualified dependent type names at class-level, which MSVC
543 /// correctly rejects.
544 static const CXXRecordDecl *
545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
546   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
547     DC = DC->getPrimaryContext();
548     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
549       if (MD->getParent()->hasAnyDependentBases())
550         return MD->getParent();
551   }
552   return nullptr;
553 }
554 
555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
556                                           SourceLocation NameLoc,
557                                           bool IsTemplateTypeArg) {
558   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
559 
560   NestedNameSpecifier *NNS = nullptr;
561   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
562     // If we weren't able to parse a default template argument, delay lookup
563     // until instantiation time by making a non-dependent DependentTypeName. We
564     // pretend we saw a NestedNameSpecifier referring to the current scope, and
565     // lookup is retried.
566     // FIXME: This hurts our diagnostic quality, since we get errors like "no
567     // type named 'Foo' in 'current_namespace'" when the user didn't write any
568     // name specifiers.
569     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
570     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
571   } else if (const CXXRecordDecl *RD =
572                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
573     // Build a DependentNameType that will perform lookup into RD at
574     // instantiation time.
575     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
576                                       RD->getTypeForDecl());
577 
578     // Diagnose that this identifier was undeclared, and retry the lookup during
579     // template instantiation.
580     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
581                                                                       << RD;
582   } else {
583     // This is not a situation that we should recover from.
584     return ParsedType();
585   }
586 
587   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
588 
589   // Build type location information.  We synthesized the qualifier, so we have
590   // to build a fake NestedNameSpecifierLoc.
591   NestedNameSpecifierLocBuilder NNSLocBuilder;
592   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
593   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
594 
595   TypeLocBuilder Builder;
596   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
597   DepTL.setNameLoc(NameLoc);
598   DepTL.setElaboratedKeywordLoc(SourceLocation());
599   DepTL.setQualifierLoc(QualifierLoc);
600   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
601 }
602 
603 /// isTagName() - This method is called *for error recovery purposes only*
604 /// to determine if the specified name is a valid tag name ("struct foo").  If
605 /// so, this returns the TST for the tag corresponding to it (TST_enum,
606 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
607 /// cases in C where the user forgot to specify the tag.
608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
609   // Do a tag name lookup in this scope.
610   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
611   LookupName(R, S, false);
612   R.suppressDiagnostics();
613   if (R.getResultKind() == LookupResult::Found)
614     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
615       switch (TD->getTagKind()) {
616       case TTK_Struct: return DeclSpec::TST_struct;
617       case TTK_Interface: return DeclSpec::TST_interface;
618       case TTK_Union:  return DeclSpec::TST_union;
619       case TTK_Class:  return DeclSpec::TST_class;
620       case TTK_Enum:   return DeclSpec::TST_enum;
621       }
622     }
623 
624   return DeclSpec::TST_unspecified;
625 }
626 
627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
629 /// then downgrade the missing typename error to a warning.
630 /// This is needed for MSVC compatibility; Example:
631 /// @code
632 /// template<class T> class A {
633 /// public:
634 ///   typedef int TYPE;
635 /// };
636 /// template<class T> class B : public A<T> {
637 /// public:
638 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
639 /// };
640 /// @endcode
641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
642   if (CurContext->isRecord()) {
643     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
644       return true;
645 
646     const Type *Ty = SS->getScopeRep()->getAsType();
647 
648     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
649     for (const auto &Base : RD->bases())
650       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
651         return true;
652     return S->isFunctionPrototypeScope();
653   }
654   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
655 }
656 
657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
658                                    SourceLocation IILoc,
659                                    Scope *S,
660                                    CXXScopeSpec *SS,
661                                    ParsedType &SuggestedType,
662                                    bool IsTemplateName) {
663   // Don't report typename errors for editor placeholders.
664   if (II->isEditorPlaceholder())
665     return;
666   // We don't have anything to suggest (yet).
667   SuggestedType = nullptr;
668 
669   // There may have been a typo in the name of the type. Look up typo
670   // results, in case we have something that we can suggest.
671   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
672                            /*AllowTemplates=*/IsTemplateName,
673                            /*AllowNonTemplates=*/!IsTemplateName);
674   if (TypoCorrection Corrected =
675           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
676                       CCC, CTK_ErrorRecovery)) {
677     // FIXME: Support error recovery for the template-name case.
678     bool CanRecover = !IsTemplateName;
679     if (Corrected.isKeyword()) {
680       // We corrected to a keyword.
681       diagnoseTypo(Corrected,
682                    PDiag(IsTemplateName ? diag::err_no_template_suggest
683                                         : diag::err_unknown_typename_suggest)
684                        << II);
685       II = Corrected.getCorrectionAsIdentifierInfo();
686     } else {
687       // We found a similarly-named type or interface; suggest that.
688       if (!SS || !SS->isSet()) {
689         diagnoseTypo(Corrected,
690                      PDiag(IsTemplateName ? diag::err_no_template_suggest
691                                           : diag::err_unknown_typename_suggest)
692                          << II, CanRecover);
693       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
694         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
695         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
696                                 II->getName().equals(CorrectedStr);
697         diagnoseTypo(Corrected,
698                      PDiag(IsTemplateName
699                                ? diag::err_no_member_template_suggest
700                                : diag::err_unknown_nested_typename_suggest)
701                          << II << DC << DroppedSpecifier << SS->getRange(),
702                      CanRecover);
703       } else {
704         llvm_unreachable("could not have corrected a typo here");
705       }
706 
707       if (!CanRecover)
708         return;
709 
710       CXXScopeSpec tmpSS;
711       if (Corrected.getCorrectionSpecifier())
712         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
713                           SourceRange(IILoc));
714       // FIXME: Support class template argument deduction here.
715       SuggestedType =
716           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
717                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
718                       /*IsCtorOrDtorName=*/false,
719                       /*WantNontrivialTypeSourceInfo=*/true);
720     }
721     return;
722   }
723 
724   if (getLangOpts().CPlusPlus && !IsTemplateName) {
725     // See if II is a class template that the user forgot to pass arguments to.
726     UnqualifiedId Name;
727     Name.setIdentifier(II, IILoc);
728     CXXScopeSpec EmptySS;
729     TemplateTy TemplateResult;
730     bool MemberOfUnknownSpecialization;
731     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
732                        Name, nullptr, true, TemplateResult,
733                        MemberOfUnknownSpecialization) == TNK_Type_template) {
734       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
735       return;
736     }
737   }
738 
739   // FIXME: Should we move the logic that tries to recover from a missing tag
740   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
741 
742   if (!SS || (!SS->isSet() && !SS->isInvalid()))
743     Diag(IILoc, IsTemplateName ? diag::err_no_template
744                                : diag::err_unknown_typename)
745         << II;
746   else if (DeclContext *DC = computeDeclContext(*SS, false))
747     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
748                                : diag::err_typename_nested_not_found)
749         << II << DC << SS->getRange();
750   else if (isDependentScopeSpecifier(*SS)) {
751     unsigned DiagID = diag::err_typename_missing;
752     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
753       DiagID = diag::ext_typename_missing;
754 
755     Diag(SS->getRange().getBegin(), DiagID)
756       << SS->getScopeRep() << II->getName()
757       << SourceRange(SS->getRange().getBegin(), IILoc)
758       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
759     SuggestedType = ActOnTypenameType(S, SourceLocation(),
760                                       *SS, *II, IILoc).get();
761   } else {
762     assert(SS && SS->isInvalid() &&
763            "Invalid scope specifier has already been diagnosed");
764   }
765 }
766 
767 /// Determine whether the given result set contains either a type name
768 /// or
769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
770   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
771                        NextToken.is(tok::less);
772 
773   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
774     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
775       return true;
776 
777     if (CheckTemplate && isa<TemplateDecl>(*I))
778       return true;
779   }
780 
781   return false;
782 }
783 
784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
785                                     Scope *S, CXXScopeSpec &SS,
786                                     IdentifierInfo *&Name,
787                                     SourceLocation NameLoc) {
788   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
789   SemaRef.LookupParsedName(R, S, &SS);
790   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
791     StringRef FixItTagName;
792     switch (Tag->getTagKind()) {
793       case TTK_Class:
794         FixItTagName = "class ";
795         break;
796 
797       case TTK_Enum:
798         FixItTagName = "enum ";
799         break;
800 
801       case TTK_Struct:
802         FixItTagName = "struct ";
803         break;
804 
805       case TTK_Interface:
806         FixItTagName = "__interface ";
807         break;
808 
809       case TTK_Union:
810         FixItTagName = "union ";
811         break;
812     }
813 
814     StringRef TagName = FixItTagName.drop_back();
815     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
816       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
817       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
818 
819     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
820          I != IEnd; ++I)
821       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
822         << Name << TagName;
823 
824     // Replace lookup results with just the tag decl.
825     Result.clear(Sema::LookupTagName);
826     SemaRef.LookupParsedName(Result, S, &SS);
827     return true;
828   }
829 
830   return false;
831 }
832 
833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
835                                   QualType T, SourceLocation NameLoc) {
836   ASTContext &Context = S.Context;
837 
838   TypeLocBuilder Builder;
839   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
840 
841   T = S.getElaboratedType(ETK_None, SS, T);
842   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
843   ElabTL.setElaboratedKeywordLoc(SourceLocation());
844   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
845   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
846 }
847 
848 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
849                                             IdentifierInfo *&Name,
850                                             SourceLocation NameLoc,
851                                             const Token &NextToken,
852                                             CorrectionCandidateCallback *CCC) {
853   DeclarationNameInfo NameInfo(Name, NameLoc);
854   ObjCMethodDecl *CurMethod = getCurMethodDecl();
855 
856   assert(NextToken.isNot(tok::coloncolon) &&
857          "parse nested name specifiers before calling ClassifyName");
858   if (getLangOpts().CPlusPlus && SS.isSet() &&
859       isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   if (SS.isInvalid())
871     return NameClassification::Error();
872 
873   // For unqualified lookup in a class template in MSVC mode, look into
874   // dependent base classes where the primary class template is known.
875   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
876     if (ParsedType TypeInBase =
877             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
878       return TypeInBase;
879   }
880 
881   // Perform lookup for Objective-C instance variables (including automatically
882   // synthesized instance variables), if we're in an Objective-C method.
883   // FIXME: This lookup really, really needs to be folded in to the normal
884   // unqualified lookup mechanism.
885   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
886     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
887     if (Ivar.isInvalid())
888       return NameClassification::Error();
889     if (Ivar.isUsable())
890       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
891 
892     // We defer builtin creation until after ivar lookup inside ObjC methods.
893     if (Result.empty())
894       LookupBuiltin(Result);
895   }
896 
897   bool SecondTry = false;
898   bool IsFilteredTemplateName = false;
899 
900 Corrected:
901   switch (Result.getResultKind()) {
902   case LookupResult::NotFound:
903     // If an unqualified-id is followed by a '(', then we have a function
904     // call.
905     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
906       // In C++, this is an ADL-only call.
907       // FIXME: Reference?
908       if (getLangOpts().CPlusPlus)
909         return NameClassification::UndeclaredNonType();
910 
911       // C90 6.3.2.2:
912       //   If the expression that precedes the parenthesized argument list in a
913       //   function call consists solely of an identifier, and if no
914       //   declaration is visible for this identifier, the identifier is
915       //   implicitly declared exactly as if, in the innermost block containing
916       //   the function call, the declaration
917       //
918       //     extern int identifier ();
919       //
920       //   appeared.
921       //
922       // We also allow this in C99 as an extension.
923       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
924         return NameClassification::NonType(D);
925     }
926 
927     if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) {
928       // In C++20 onwards, this could be an ADL-only call to a function
929       // template, and we're required to assume that this is a template name.
930       //
931       // FIXME: Find a way to still do typo correction in this case.
932       TemplateName Template =
933           Context.getAssumedTemplateName(NameInfo.getName());
934       return NameClassification::UndeclaredTemplate(Template);
935     }
936 
937     // In C, we first see whether there is a tag type by the same name, in
938     // which case it's likely that the user just forgot to write "enum",
939     // "struct", or "union".
940     if (!getLangOpts().CPlusPlus && !SecondTry &&
941         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
942       break;
943     }
944 
945     // Perform typo correction to determine if there is another name that is
946     // close to this name.
947     if (!SecondTry && CCC) {
948       SecondTry = true;
949       if (TypoCorrection Corrected =
950               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
951                           &SS, *CCC, CTK_ErrorRecovery)) {
952         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
953         unsigned QualifiedDiag = diag::err_no_member_suggest;
954 
955         NamedDecl *FirstDecl = Corrected.getFoundDecl();
956         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
957         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
958             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
959           UnqualifiedDiag = diag::err_no_template_suggest;
960           QualifiedDiag = diag::err_no_member_template_suggest;
961         } else if (UnderlyingFirstDecl &&
962                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
963                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
964                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
965           UnqualifiedDiag = diag::err_unknown_typename_suggest;
966           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
967         }
968 
969         if (SS.isEmpty()) {
970           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
971         } else {// FIXME: is this even reachable? Test it.
972           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
973           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
974                                   Name->getName().equals(CorrectedStr);
975           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
976                                     << Name << computeDeclContext(SS, false)
977                                     << DroppedSpecifier << SS.getRange());
978         }
979 
980         // Update the name, so that the caller has the new name.
981         Name = Corrected.getCorrectionAsIdentifierInfo();
982 
983         // Typo correction corrected to a keyword.
984         if (Corrected.isKeyword())
985           return Name;
986 
987         // Also update the LookupResult...
988         // FIXME: This should probably go away at some point
989         Result.clear();
990         Result.setLookupName(Corrected.getCorrection());
991         if (FirstDecl)
992           Result.addDecl(FirstDecl);
993 
994         // If we found an Objective-C instance variable, let
995         // LookupInObjCMethod build the appropriate expression to
996         // reference the ivar.
997         // FIXME: This is a gross hack.
998         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
999           DeclResult R =
1000               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1001           if (R.isInvalid())
1002             return NameClassification::Error();
1003           if (R.isUsable())
1004             return NameClassification::NonType(Ivar);
1005         }
1006 
1007         goto Corrected;
1008       }
1009     }
1010 
1011     // We failed to correct; just fall through and let the parser deal with it.
1012     Result.suppressDiagnostics();
1013     return NameClassification::Unknown();
1014 
1015   case LookupResult::NotFoundInCurrentInstantiation: {
1016     // We performed name lookup into the current instantiation, and there were
1017     // dependent bases, so we treat this result the same way as any other
1018     // dependent nested-name-specifier.
1019 
1020     // C++ [temp.res]p2:
1021     //   A name used in a template declaration or definition and that is
1022     //   dependent on a template-parameter is assumed not to name a type
1023     //   unless the applicable name lookup finds a type name or the name is
1024     //   qualified by the keyword typename.
1025     //
1026     // FIXME: If the next token is '<', we might want to ask the parser to
1027     // perform some heroics to see if we actually have a
1028     // template-argument-list, which would indicate a missing 'template'
1029     // keyword here.
1030     return NameClassification::DependentNonType();
1031   }
1032 
1033   case LookupResult::Found:
1034   case LookupResult::FoundOverloaded:
1035   case LookupResult::FoundUnresolvedValue:
1036     break;
1037 
1038   case LookupResult::Ambiguous:
1039     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1040         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1041                                       /*AllowDependent=*/false)) {
1042       // C++ [temp.local]p3:
1043       //   A lookup that finds an injected-class-name (10.2) can result in an
1044       //   ambiguity in certain cases (for example, if it is found in more than
1045       //   one base class). If all of the injected-class-names that are found
1046       //   refer to specializations of the same class template, and if the name
1047       //   is followed by a template-argument-list, the reference refers to the
1048       //   class template itself and not a specialization thereof, and is not
1049       //   ambiguous.
1050       //
1051       // This filtering can make an ambiguous result into an unambiguous one,
1052       // so try again after filtering out template names.
1053       FilterAcceptableTemplateNames(Result);
1054       if (!Result.isAmbiguous()) {
1055         IsFilteredTemplateName = true;
1056         break;
1057       }
1058     }
1059 
1060     // Diagnose the ambiguity and return an error.
1061     return NameClassification::Error();
1062   }
1063 
1064   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1065       (IsFilteredTemplateName ||
1066        hasAnyAcceptableTemplateNames(
1067            Result, /*AllowFunctionTemplates=*/true,
1068            /*AllowDependent=*/false,
1069            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1070                getLangOpts().CPlusPlus2a))) {
1071     // C++ [temp.names]p3:
1072     //   After name lookup (3.4) finds that a name is a template-name or that
1073     //   an operator-function-id or a literal- operator-id refers to a set of
1074     //   overloaded functions any member of which is a function template if
1075     //   this is followed by a <, the < is always taken as the delimiter of a
1076     //   template-argument-list and never as the less-than operator.
1077     // C++2a [temp.names]p2:
1078     //   A name is also considered to refer to a template if it is an
1079     //   unqualified-id followed by a < and name lookup finds either one
1080     //   or more functions or finds nothing.
1081     if (!IsFilteredTemplateName)
1082       FilterAcceptableTemplateNames(Result);
1083 
1084     bool IsFunctionTemplate;
1085     bool IsVarTemplate;
1086     TemplateName Template;
1087     if (Result.end() - Result.begin() > 1) {
1088       IsFunctionTemplate = true;
1089       Template = Context.getOverloadedTemplateName(Result.begin(),
1090                                                    Result.end());
1091     } else if (!Result.empty()) {
1092       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1093           *Result.begin(), /*AllowFunctionTemplates=*/true,
1094           /*AllowDependent=*/false));
1095       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1096       IsVarTemplate = isa<VarTemplateDecl>(TD);
1097 
1098       if (SS.isNotEmpty())
1099         Template =
1100             Context.getQualifiedTemplateName(SS.getScopeRep(),
1101                                              /*TemplateKeyword=*/false, TD);
1102       else
1103         Template = TemplateName(TD);
1104     } else {
1105       // All results were non-template functions. This is a function template
1106       // name.
1107       IsFunctionTemplate = true;
1108       Template = Context.getAssumedTemplateName(NameInfo.getName());
1109     }
1110 
1111     if (IsFunctionTemplate) {
1112       // Function templates always go through overload resolution, at which
1113       // point we'll perform the various checks (e.g., accessibility) we need
1114       // to based on which function we selected.
1115       Result.suppressDiagnostics();
1116 
1117       return NameClassification::FunctionTemplate(Template);
1118     }
1119 
1120     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1121                          : NameClassification::TypeTemplate(Template);
1122   }
1123 
1124   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1125   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1126     DiagnoseUseOfDecl(Type, NameLoc);
1127     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1128     QualType T = Context.getTypeDeclType(Type);
1129     if (SS.isNotEmpty())
1130       return buildNestedType(*this, SS, T, NameLoc);
1131     return ParsedType::make(T);
1132   }
1133 
1134   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1135   if (!Class) {
1136     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1137     if (ObjCCompatibleAliasDecl *Alias =
1138             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1139       Class = Alias->getClassInterface();
1140   }
1141 
1142   if (Class) {
1143     DiagnoseUseOfDecl(Class, NameLoc);
1144 
1145     if (NextToken.is(tok::period)) {
1146       // Interface. <something> is parsed as a property reference expression.
1147       // Just return "unknown" as a fall-through for now.
1148       Result.suppressDiagnostics();
1149       return NameClassification::Unknown();
1150     }
1151 
1152     QualType T = Context.getObjCInterfaceType(Class);
1153     return ParsedType::make(T);
1154   }
1155 
1156   // We can have a type template here if we're classifying a template argument.
1157   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1158       !isa<VarTemplateDecl>(FirstDecl))
1159     return NameClassification::TypeTemplate(
1160         TemplateName(cast<TemplateDecl>(FirstDecl)));
1161 
1162   // Check for a tag type hidden by a non-type decl in a few cases where it
1163   // seems likely a type is wanted instead of the non-type that was found.
1164   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1165   if ((NextToken.is(tok::identifier) ||
1166        (NextIsOp &&
1167         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1168       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1169     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1170     DiagnoseUseOfDecl(Type, NameLoc);
1171     QualType T = Context.getTypeDeclType(Type);
1172     if (SS.isNotEmpty())
1173       return buildNestedType(*this, SS, T, NameLoc);
1174     return ParsedType::make(T);
1175   }
1176 
1177   // FIXME: This is context-dependent. We need to defer building the member
1178   // expression until the classification is consumed.
1179   if (FirstDecl->isCXXClassMember())
1180     return NameClassification::ContextIndependentExpr(
1181         BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
1182                                         S));
1183 
1184   // If we already know which single declaration is referenced, just annotate
1185   // that declaration directly.
1186   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1187   if (Result.isSingleResult() && !ADL)
1188     return NameClassification::NonType(Result.getRepresentativeDecl());
1189 
1190   // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
1191   // context in which we performed classification, so it's safe to do now.
1192   return NameClassification::ContextIndependentExpr(
1193       BuildDeclarationNameExpr(SS, Result, ADL));
1194 }
1195 
1196 ExprResult
1197 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1198                                              SourceLocation NameLoc) {
1199   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1200   CXXScopeSpec SS;
1201   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1202   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1203 }
1204 
1205 ExprResult
1206 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1207                                             IdentifierInfo *Name,
1208                                             SourceLocation NameLoc,
1209                                             bool IsAddressOfOperand) {
1210   DeclarationNameInfo NameInfo(Name, NameLoc);
1211   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1212                                     NameInfo, IsAddressOfOperand,
1213                                     /*TemplateArgs=*/nullptr);
1214 }
1215 
1216 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1217                                               NamedDecl *Found,
1218                                               SourceLocation NameLoc,
1219                                               const Token &NextToken) {
1220   if (getCurMethodDecl() && SS.isEmpty())
1221     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1222       return BuildIvarRefExpr(S, NameLoc, Ivar);
1223 
1224   // Reconstruct the lookup result.
1225   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1226   Result.addDecl(Found);
1227   Result.resolveKind();
1228 
1229   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1230   return BuildDeclarationNameExpr(SS, Result, ADL);
1231 }
1232 
1233 Sema::TemplateNameKindForDiagnostics
1234 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1235   auto *TD = Name.getAsTemplateDecl();
1236   if (!TD)
1237     return TemplateNameKindForDiagnostics::DependentTemplate;
1238   if (isa<ClassTemplateDecl>(TD))
1239     return TemplateNameKindForDiagnostics::ClassTemplate;
1240   if (isa<FunctionTemplateDecl>(TD))
1241     return TemplateNameKindForDiagnostics::FunctionTemplate;
1242   if (isa<VarTemplateDecl>(TD))
1243     return TemplateNameKindForDiagnostics::VarTemplate;
1244   if (isa<TypeAliasTemplateDecl>(TD))
1245     return TemplateNameKindForDiagnostics::AliasTemplate;
1246   if (isa<TemplateTemplateParmDecl>(TD))
1247     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1248   if (isa<ConceptDecl>(TD))
1249     return TemplateNameKindForDiagnostics::Concept;
1250   return TemplateNameKindForDiagnostics::DependentTemplate;
1251 }
1252 
1253 // Determines the context to return to after temporarily entering a
1254 // context.  This depends in an unnecessarily complicated way on the
1255 // exact ordering of callbacks from the parser.
1256 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1257 
1258   // Functions defined inline within classes aren't parsed until we've
1259   // finished parsing the top-level class, so the top-level class is
1260   // the context we'll need to return to.
1261   // A Lambda call operator whose parent is a class must not be treated
1262   // as an inline member function.  A Lambda can be used legally
1263   // either as an in-class member initializer or a default argument.  These
1264   // are parsed once the class has been marked complete and so the containing
1265   // context would be the nested class (when the lambda is defined in one);
1266   // If the class is not complete, then the lambda is being used in an
1267   // ill-formed fashion (such as to specify the width of a bit-field, or
1268   // in an array-bound) - in which case we still want to return the
1269   // lexically containing DC (which could be a nested class).
1270   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1271     DC = DC->getLexicalParent();
1272 
1273     // A function not defined within a class will always return to its
1274     // lexical context.
1275     if (!isa<CXXRecordDecl>(DC))
1276       return DC;
1277 
1278     // A C++ inline method/friend is parsed *after* the topmost class
1279     // it was declared in is fully parsed ("complete");  the topmost
1280     // class is the context we need to return to.
1281     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1282       DC = RD;
1283 
1284     // Return the declaration context of the topmost class the inline method is
1285     // declared in.
1286     return DC;
1287   }
1288 
1289   return DC->getLexicalParent();
1290 }
1291 
1292 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1293   assert(getContainingDC(DC) == CurContext &&
1294       "The next DeclContext should be lexically contained in the current one.");
1295   CurContext = DC;
1296   S->setEntity(DC);
1297 }
1298 
1299 void Sema::PopDeclContext() {
1300   assert(CurContext && "DeclContext imbalance!");
1301 
1302   CurContext = getContainingDC(CurContext);
1303   assert(CurContext && "Popped translation unit!");
1304 }
1305 
1306 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1307                                                                     Decl *D) {
1308   // Unlike PushDeclContext, the context to which we return is not necessarily
1309   // the containing DC of TD, because the new context will be some pre-existing
1310   // TagDecl definition instead of a fresh one.
1311   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1312   CurContext = cast<TagDecl>(D)->getDefinition();
1313   assert(CurContext && "skipping definition of undefined tag");
1314   // Start lookups from the parent of the current context; we don't want to look
1315   // into the pre-existing complete definition.
1316   S->setEntity(CurContext->getLookupParent());
1317   return Result;
1318 }
1319 
1320 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1321   CurContext = static_cast<decltype(CurContext)>(Context);
1322 }
1323 
1324 /// EnterDeclaratorContext - Used when we must lookup names in the context
1325 /// of a declarator's nested name specifier.
1326 ///
1327 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1328   // C++0x [basic.lookup.unqual]p13:
1329   //   A name used in the definition of a static data member of class
1330   //   X (after the qualified-id of the static member) is looked up as
1331   //   if the name was used in a member function of X.
1332   // C++0x [basic.lookup.unqual]p14:
1333   //   If a variable member of a namespace is defined outside of the
1334   //   scope of its namespace then any name used in the definition of
1335   //   the variable member (after the declarator-id) is looked up as
1336   //   if the definition of the variable member occurred in its
1337   //   namespace.
1338   // Both of these imply that we should push a scope whose context
1339   // is the semantic context of the declaration.  We can't use
1340   // PushDeclContext here because that context is not necessarily
1341   // lexically contained in the current context.  Fortunately,
1342   // the containing scope should have the appropriate information.
1343 
1344   assert(!S->getEntity() && "scope already has entity");
1345 
1346 #ifndef NDEBUG
1347   Scope *Ancestor = S->getParent();
1348   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1349   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1350 #endif
1351 
1352   CurContext = DC;
1353   S->setEntity(DC);
1354 }
1355 
1356 void Sema::ExitDeclaratorContext(Scope *S) {
1357   assert(S->getEntity() == CurContext && "Context imbalance!");
1358 
1359   // Switch back to the lexical context.  The safety of this is
1360   // enforced by an assert in EnterDeclaratorContext.
1361   Scope *Ancestor = S->getParent();
1362   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1363   CurContext = Ancestor->getEntity();
1364 
1365   // We don't need to do anything with the scope, which is going to
1366   // disappear.
1367 }
1368 
1369 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1370   // We assume that the caller has already called
1371   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1372   FunctionDecl *FD = D->getAsFunction();
1373   if (!FD)
1374     return;
1375 
1376   // Same implementation as PushDeclContext, but enters the context
1377   // from the lexical parent, rather than the top-level class.
1378   assert(CurContext == FD->getLexicalParent() &&
1379     "The next DeclContext should be lexically contained in the current one.");
1380   CurContext = FD;
1381   S->setEntity(CurContext);
1382 
1383   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1384     ParmVarDecl *Param = FD->getParamDecl(P);
1385     // If the parameter has an identifier, then add it to the scope
1386     if (Param->getIdentifier()) {
1387       S->AddDecl(Param);
1388       IdResolver.AddDecl(Param);
1389     }
1390   }
1391 }
1392 
1393 void Sema::ActOnExitFunctionContext() {
1394   // Same implementation as PopDeclContext, but returns to the lexical parent,
1395   // rather than the top-level class.
1396   assert(CurContext && "DeclContext imbalance!");
1397   CurContext = CurContext->getLexicalParent();
1398   assert(CurContext && "Popped translation unit!");
1399 }
1400 
1401 /// Determine whether we allow overloading of the function
1402 /// PrevDecl with another declaration.
1403 ///
1404 /// This routine determines whether overloading is possible, not
1405 /// whether some new function is actually an overload. It will return
1406 /// true in C++ (where we can always provide overloads) or, as an
1407 /// extension, in C when the previous function is already an
1408 /// overloaded function declaration or has the "overloadable"
1409 /// attribute.
1410 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1411                                        ASTContext &Context,
1412                                        const FunctionDecl *New) {
1413   if (Context.getLangOpts().CPlusPlus)
1414     return true;
1415 
1416   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1417     return true;
1418 
1419   return Previous.getResultKind() == LookupResult::Found &&
1420          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1421           New->hasAttr<OverloadableAttr>());
1422 }
1423 
1424 /// Add this decl to the scope shadowed decl chains.
1425 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1426   // Move up the scope chain until we find the nearest enclosing
1427   // non-transparent context. The declaration will be introduced into this
1428   // scope.
1429   while (S->getEntity() && S->getEntity()->isTransparentContext())
1430     S = S->getParent();
1431 
1432   // Add scoped declarations into their context, so that they can be
1433   // found later. Declarations without a context won't be inserted
1434   // into any context.
1435   if (AddToContext)
1436     CurContext->addDecl(D);
1437 
1438   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1439   // are function-local declarations.
1440   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1441       !D->getDeclContext()->getRedeclContext()->Equals(
1442         D->getLexicalDeclContext()->getRedeclContext()) &&
1443       !D->getLexicalDeclContext()->isFunctionOrMethod())
1444     return;
1445 
1446   // Template instantiations should also not be pushed into scope.
1447   if (isa<FunctionDecl>(D) &&
1448       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1449     return;
1450 
1451   // If this replaces anything in the current scope,
1452   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1453                                IEnd = IdResolver.end();
1454   for (; I != IEnd; ++I) {
1455     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1456       S->RemoveDecl(*I);
1457       IdResolver.RemoveDecl(*I);
1458 
1459       // Should only need to replace one decl.
1460       break;
1461     }
1462   }
1463 
1464   S->AddDecl(D);
1465 
1466   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1467     // Implicitly-generated labels may end up getting generated in an order that
1468     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1469     // the label at the appropriate place in the identifier chain.
1470     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1471       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1472       if (IDC == CurContext) {
1473         if (!S->isDeclScope(*I))
1474           continue;
1475       } else if (IDC->Encloses(CurContext))
1476         break;
1477     }
1478 
1479     IdResolver.InsertDeclAfter(I, D);
1480   } else {
1481     IdResolver.AddDecl(D);
1482   }
1483 }
1484 
1485 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1486                          bool AllowInlineNamespace) {
1487   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1488 }
1489 
1490 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1491   DeclContext *TargetDC = DC->getPrimaryContext();
1492   do {
1493     if (DeclContext *ScopeDC = S->getEntity())
1494       if (ScopeDC->getPrimaryContext() == TargetDC)
1495         return S;
1496   } while ((S = S->getParent()));
1497 
1498   return nullptr;
1499 }
1500 
1501 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1502                                             DeclContext*,
1503                                             ASTContext&);
1504 
1505 /// Filters out lookup results that don't fall within the given scope
1506 /// as determined by isDeclInScope.
1507 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1508                                 bool ConsiderLinkage,
1509                                 bool AllowInlineNamespace) {
1510   LookupResult::Filter F = R.makeFilter();
1511   while (F.hasNext()) {
1512     NamedDecl *D = F.next();
1513 
1514     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1515       continue;
1516 
1517     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1518       continue;
1519 
1520     F.erase();
1521   }
1522 
1523   F.done();
1524 }
1525 
1526 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1527 /// have compatible owning modules.
1528 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1529   // FIXME: The Modules TS is not clear about how friend declarations are
1530   // to be treated. It's not meaningful to have different owning modules for
1531   // linkage in redeclarations of the same entity, so for now allow the
1532   // redeclaration and change the owning modules to match.
1533   if (New->getFriendObjectKind() &&
1534       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1535     New->setLocalOwningModule(Old->getOwningModule());
1536     makeMergedDefinitionVisible(New);
1537     return false;
1538   }
1539 
1540   Module *NewM = New->getOwningModule();
1541   Module *OldM = Old->getOwningModule();
1542 
1543   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1544     NewM = NewM->Parent;
1545   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1546     OldM = OldM->Parent;
1547 
1548   if (NewM == OldM)
1549     return false;
1550 
1551   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1552   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1553   if (NewIsModuleInterface || OldIsModuleInterface) {
1554     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1555     //   if a declaration of D [...] appears in the purview of a module, all
1556     //   other such declarations shall appear in the purview of the same module
1557     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1558       << New
1559       << NewIsModuleInterface
1560       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1561       << OldIsModuleInterface
1562       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1563     Diag(Old->getLocation(), diag::note_previous_declaration);
1564     New->setInvalidDecl();
1565     return true;
1566   }
1567 
1568   return false;
1569 }
1570 
1571 static bool isUsingDecl(NamedDecl *D) {
1572   return isa<UsingShadowDecl>(D) ||
1573          isa<UnresolvedUsingTypenameDecl>(D) ||
1574          isa<UnresolvedUsingValueDecl>(D);
1575 }
1576 
1577 /// Removes using shadow declarations from the lookup results.
1578 static void RemoveUsingDecls(LookupResult &R) {
1579   LookupResult::Filter F = R.makeFilter();
1580   while (F.hasNext())
1581     if (isUsingDecl(F.next()))
1582       F.erase();
1583 
1584   F.done();
1585 }
1586 
1587 /// Check for this common pattern:
1588 /// @code
1589 /// class S {
1590 ///   S(const S&); // DO NOT IMPLEMENT
1591 ///   void operator=(const S&); // DO NOT IMPLEMENT
1592 /// };
1593 /// @endcode
1594 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1595   // FIXME: Should check for private access too but access is set after we get
1596   // the decl here.
1597   if (D->doesThisDeclarationHaveABody())
1598     return false;
1599 
1600   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1601     return CD->isCopyConstructor();
1602   return D->isCopyAssignmentOperator();
1603 }
1604 
1605 // We need this to handle
1606 //
1607 // typedef struct {
1608 //   void *foo() { return 0; }
1609 // } A;
1610 //
1611 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1612 // for example. If 'A', foo will have external linkage. If we have '*A',
1613 // foo will have no linkage. Since we can't know until we get to the end
1614 // of the typedef, this function finds out if D might have non-external linkage.
1615 // Callers should verify at the end of the TU if it D has external linkage or
1616 // not.
1617 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1618   const DeclContext *DC = D->getDeclContext();
1619   while (!DC->isTranslationUnit()) {
1620     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1621       if (!RD->hasNameForLinkage())
1622         return true;
1623     }
1624     DC = DC->getParent();
1625   }
1626 
1627   return !D->isExternallyVisible();
1628 }
1629 
1630 // FIXME: This needs to be refactored; some other isInMainFile users want
1631 // these semantics.
1632 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1633   if (S.TUKind != TU_Complete)
1634     return false;
1635   return S.SourceMgr.isInMainFile(Loc);
1636 }
1637 
1638 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1639   assert(D);
1640 
1641   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1642     return false;
1643 
1644   // Ignore all entities declared within templates, and out-of-line definitions
1645   // of members of class templates.
1646   if (D->getDeclContext()->isDependentContext() ||
1647       D->getLexicalDeclContext()->isDependentContext())
1648     return false;
1649 
1650   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1651     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1652       return false;
1653     // A non-out-of-line declaration of a member specialization was implicitly
1654     // instantiated; it's the out-of-line declaration that we're interested in.
1655     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1656         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1657       return false;
1658 
1659     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1660       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1661         return false;
1662     } else {
1663       // 'static inline' functions are defined in headers; don't warn.
1664       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1665         return false;
1666     }
1667 
1668     if (FD->doesThisDeclarationHaveABody() &&
1669         Context.DeclMustBeEmitted(FD))
1670       return false;
1671   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1672     // Constants and utility variables are defined in headers with internal
1673     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1674     // like "inline".)
1675     if (!isMainFileLoc(*this, VD->getLocation()))
1676       return false;
1677 
1678     if (Context.DeclMustBeEmitted(VD))
1679       return false;
1680 
1681     if (VD->isStaticDataMember() &&
1682         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1683       return false;
1684     if (VD->isStaticDataMember() &&
1685         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1686         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1687       return false;
1688 
1689     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1690       return false;
1691   } else {
1692     return false;
1693   }
1694 
1695   // Only warn for unused decls internal to the translation unit.
1696   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1697   // for inline functions defined in the main source file, for instance.
1698   return mightHaveNonExternalLinkage(D);
1699 }
1700 
1701 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1702   if (!D)
1703     return;
1704 
1705   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1706     const FunctionDecl *First = FD->getFirstDecl();
1707     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1708       return; // First should already be in the vector.
1709   }
1710 
1711   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1712     const VarDecl *First = VD->getFirstDecl();
1713     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1714       return; // First should already be in the vector.
1715   }
1716 
1717   if (ShouldWarnIfUnusedFileScopedDecl(D))
1718     UnusedFileScopedDecls.push_back(D);
1719 }
1720 
1721 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1722   if (D->isInvalidDecl())
1723     return false;
1724 
1725   bool Referenced = false;
1726   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1727     // For a decomposition declaration, warn if none of the bindings are
1728     // referenced, instead of if the variable itself is referenced (which
1729     // it is, by the bindings' expressions).
1730     for (auto *BD : DD->bindings()) {
1731       if (BD->isReferenced()) {
1732         Referenced = true;
1733         break;
1734       }
1735     }
1736   } else if (!D->getDeclName()) {
1737     return false;
1738   } else if (D->isReferenced() || D->isUsed()) {
1739     Referenced = true;
1740   }
1741 
1742   if (Referenced || D->hasAttr<UnusedAttr>() ||
1743       D->hasAttr<ObjCPreciseLifetimeAttr>())
1744     return false;
1745 
1746   if (isa<LabelDecl>(D))
1747     return true;
1748 
1749   // Except for labels, we only care about unused decls that are local to
1750   // functions.
1751   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1752   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1753     // For dependent types, the diagnostic is deferred.
1754     WithinFunction =
1755         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1756   if (!WithinFunction)
1757     return false;
1758 
1759   if (isa<TypedefNameDecl>(D))
1760     return true;
1761 
1762   // White-list anything that isn't a local variable.
1763   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1764     return false;
1765 
1766   // Types of valid local variables should be complete, so this should succeed.
1767   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1768 
1769     // White-list anything with an __attribute__((unused)) type.
1770     const auto *Ty = VD->getType().getTypePtr();
1771 
1772     // Only look at the outermost level of typedef.
1773     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1774       if (TT->getDecl()->hasAttr<UnusedAttr>())
1775         return false;
1776     }
1777 
1778     // If we failed to complete the type for some reason, or if the type is
1779     // dependent, don't diagnose the variable.
1780     if (Ty->isIncompleteType() || Ty->isDependentType())
1781       return false;
1782 
1783     // Look at the element type to ensure that the warning behaviour is
1784     // consistent for both scalars and arrays.
1785     Ty = Ty->getBaseElementTypeUnsafe();
1786 
1787     if (const TagType *TT = Ty->getAs<TagType>()) {
1788       const TagDecl *Tag = TT->getDecl();
1789       if (Tag->hasAttr<UnusedAttr>())
1790         return false;
1791 
1792       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1793         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1794           return false;
1795 
1796         if (const Expr *Init = VD->getInit()) {
1797           if (const ExprWithCleanups *Cleanups =
1798                   dyn_cast<ExprWithCleanups>(Init))
1799             Init = Cleanups->getSubExpr();
1800           const CXXConstructExpr *Construct =
1801             dyn_cast<CXXConstructExpr>(Init);
1802           if (Construct && !Construct->isElidable()) {
1803             CXXConstructorDecl *CD = Construct->getConstructor();
1804             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1805                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1806               return false;
1807           }
1808 
1809           // Suppress the warning if we don't know how this is constructed, and
1810           // it could possibly be non-trivial constructor.
1811           if (Init->isTypeDependent())
1812             for (const CXXConstructorDecl *Ctor : RD->ctors())
1813               if (!Ctor->isTrivial())
1814                 return false;
1815         }
1816       }
1817     }
1818 
1819     // TODO: __attribute__((unused)) templates?
1820   }
1821 
1822   return true;
1823 }
1824 
1825 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1826                                      FixItHint &Hint) {
1827   if (isa<LabelDecl>(D)) {
1828     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1829         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1830         true);
1831     if (AfterColon.isInvalid())
1832       return;
1833     Hint = FixItHint::CreateRemoval(
1834         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1835   }
1836 }
1837 
1838 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1839   if (D->getTypeForDecl()->isDependentType())
1840     return;
1841 
1842   for (auto *TmpD : D->decls()) {
1843     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1844       DiagnoseUnusedDecl(T);
1845     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1846       DiagnoseUnusedNestedTypedefs(R);
1847   }
1848 }
1849 
1850 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1851 /// unless they are marked attr(unused).
1852 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1853   if (!ShouldDiagnoseUnusedDecl(D))
1854     return;
1855 
1856   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1857     // typedefs can be referenced later on, so the diagnostics are emitted
1858     // at end-of-translation-unit.
1859     UnusedLocalTypedefNameCandidates.insert(TD);
1860     return;
1861   }
1862 
1863   FixItHint Hint;
1864   GenerateFixForUnusedDecl(D, Context, Hint);
1865 
1866   unsigned DiagID;
1867   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1868     DiagID = diag::warn_unused_exception_param;
1869   else if (isa<LabelDecl>(D))
1870     DiagID = diag::warn_unused_label;
1871   else
1872     DiagID = diag::warn_unused_variable;
1873 
1874   Diag(D->getLocation(), DiagID) << D << Hint;
1875 }
1876 
1877 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1878   // Verify that we have no forward references left.  If so, there was a goto
1879   // or address of a label taken, but no definition of it.  Label fwd
1880   // definitions are indicated with a null substmt which is also not a resolved
1881   // MS inline assembly label name.
1882   bool Diagnose = false;
1883   if (L->isMSAsmLabel())
1884     Diagnose = !L->isResolvedMSAsmLabel();
1885   else
1886     Diagnose = L->getStmt() == nullptr;
1887   if (Diagnose)
1888     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1889 }
1890 
1891 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1892   S->mergeNRVOIntoParent();
1893 
1894   if (S->decl_empty()) return;
1895   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1896          "Scope shouldn't contain decls!");
1897 
1898   for (auto *TmpD : S->decls()) {
1899     assert(TmpD && "This decl didn't get pushed??");
1900 
1901     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1902     NamedDecl *D = cast<NamedDecl>(TmpD);
1903 
1904     // Diagnose unused variables in this scope.
1905     if (!S->hasUnrecoverableErrorOccurred()) {
1906       DiagnoseUnusedDecl(D);
1907       if (const auto *RD = dyn_cast<RecordDecl>(D))
1908         DiagnoseUnusedNestedTypedefs(RD);
1909     }
1910 
1911     if (!D->getDeclName()) continue;
1912 
1913     // If this was a forward reference to a label, verify it was defined.
1914     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1915       CheckPoppedLabel(LD, *this);
1916 
1917     // Remove this name from our lexical scope, and warn on it if we haven't
1918     // already.
1919     IdResolver.RemoveDecl(D);
1920     auto ShadowI = ShadowingDecls.find(D);
1921     if (ShadowI != ShadowingDecls.end()) {
1922       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1923         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1924             << D << FD << FD->getParent();
1925         Diag(FD->getLocation(), diag::note_previous_declaration);
1926       }
1927       ShadowingDecls.erase(ShadowI);
1928     }
1929   }
1930 }
1931 
1932 /// Look for an Objective-C class in the translation unit.
1933 ///
1934 /// \param Id The name of the Objective-C class we're looking for. If
1935 /// typo-correction fixes this name, the Id will be updated
1936 /// to the fixed name.
1937 ///
1938 /// \param IdLoc The location of the name in the translation unit.
1939 ///
1940 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1941 /// if there is no class with the given name.
1942 ///
1943 /// \returns The declaration of the named Objective-C class, or NULL if the
1944 /// class could not be found.
1945 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1946                                               SourceLocation IdLoc,
1947                                               bool DoTypoCorrection) {
1948   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1949   // creation from this context.
1950   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1951 
1952   if (!IDecl && DoTypoCorrection) {
1953     // Perform typo correction at the given location, but only if we
1954     // find an Objective-C class name.
1955     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1956     if (TypoCorrection C =
1957             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1958                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1959       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1960       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1961       Id = IDecl->getIdentifier();
1962     }
1963   }
1964   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1965   // This routine must always return a class definition, if any.
1966   if (Def && Def->getDefinition())
1967       Def = Def->getDefinition();
1968   return Def;
1969 }
1970 
1971 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1972 /// from S, where a non-field would be declared. This routine copes
1973 /// with the difference between C and C++ scoping rules in structs and
1974 /// unions. For example, the following code is well-formed in C but
1975 /// ill-formed in C++:
1976 /// @code
1977 /// struct S6 {
1978 ///   enum { BAR } e;
1979 /// };
1980 ///
1981 /// void test_S6() {
1982 ///   struct S6 a;
1983 ///   a.e = BAR;
1984 /// }
1985 /// @endcode
1986 /// For the declaration of BAR, this routine will return a different
1987 /// scope. The scope S will be the scope of the unnamed enumeration
1988 /// within S6. In C++, this routine will return the scope associated
1989 /// with S6, because the enumeration's scope is a transparent
1990 /// context but structures can contain non-field names. In C, this
1991 /// routine will return the translation unit scope, since the
1992 /// enumeration's scope is a transparent context and structures cannot
1993 /// contain non-field names.
1994 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1995   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1996          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1997          (S->isClassScope() && !getLangOpts().CPlusPlus))
1998     S = S->getParent();
1999   return S;
2000 }
2001 
2002 /// Looks up the declaration of "struct objc_super" and
2003 /// saves it for later use in building builtin declaration of
2004 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2005 /// pre-existing declaration exists no action takes place.
2006 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2007                                         IdentifierInfo *II) {
2008   if (!II->isStr("objc_msgSendSuper"))
2009     return;
2010   ASTContext &Context = ThisSema.Context;
2011 
2012   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2013                       SourceLocation(), Sema::LookupTagName);
2014   ThisSema.LookupName(Result, S);
2015   if (Result.getResultKind() == LookupResult::Found)
2016     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2017       Context.setObjCSuperType(Context.getTagDeclType(TD));
2018 }
2019 
2020 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2021                                ASTContext::GetBuiltinTypeError Error) {
2022   switch (Error) {
2023   case ASTContext::GE_None:
2024     return "";
2025   case ASTContext::GE_Missing_type:
2026     return BuiltinInfo.getHeaderName(ID);
2027   case ASTContext::GE_Missing_stdio:
2028     return "stdio.h";
2029   case ASTContext::GE_Missing_setjmp:
2030     return "setjmp.h";
2031   case ASTContext::GE_Missing_ucontext:
2032     return "ucontext.h";
2033   }
2034   llvm_unreachable("unhandled error kind");
2035 }
2036 
2037 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2038 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2039 /// if we're creating this built-in in anticipation of redeclaring the
2040 /// built-in.
2041 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2042                                      Scope *S, bool ForRedeclaration,
2043                                      SourceLocation Loc) {
2044   LookupPredefedObjCSuperType(*this, S, II);
2045 
2046   ASTContext::GetBuiltinTypeError Error;
2047   QualType R = Context.GetBuiltinType(ID, Error);
2048   if (Error) {
2049     if (!ForRedeclaration)
2050       return nullptr;
2051 
2052     // If we have a builtin without an associated type we should not emit a
2053     // warning when we were not able to find a type for it.
2054     if (Error == ASTContext::GE_Missing_type)
2055       return nullptr;
2056 
2057     // If we could not find a type for setjmp it is because the jmp_buf type was
2058     // not defined prior to the setjmp declaration.
2059     if (Error == ASTContext::GE_Missing_setjmp) {
2060       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2061           << Context.BuiltinInfo.getName(ID);
2062       return nullptr;
2063     }
2064 
2065     // Generally, we emit a warning that the declaration requires the
2066     // appropriate header.
2067     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2068         << getHeaderName(Context.BuiltinInfo, ID, Error)
2069         << Context.BuiltinInfo.getName(ID);
2070     return nullptr;
2071   }
2072 
2073   if (!ForRedeclaration &&
2074       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2075        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2076     Diag(Loc, diag::ext_implicit_lib_function_decl)
2077         << Context.BuiltinInfo.getName(ID) << R;
2078     if (Context.BuiltinInfo.getHeaderName(ID) &&
2079         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2080       Diag(Loc, diag::note_include_header_or_declare)
2081           << Context.BuiltinInfo.getHeaderName(ID)
2082           << Context.BuiltinInfo.getName(ID);
2083   }
2084 
2085   if (R.isNull())
2086     return nullptr;
2087 
2088   DeclContext *Parent = Context.getTranslationUnitDecl();
2089   if (getLangOpts().CPlusPlus) {
2090     LinkageSpecDecl *CLinkageDecl =
2091         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2092                                 LinkageSpecDecl::lang_c, false);
2093     CLinkageDecl->setImplicit();
2094     Parent->addDecl(CLinkageDecl);
2095     Parent = CLinkageDecl;
2096   }
2097 
2098   FunctionDecl *New = FunctionDecl::Create(Context,
2099                                            Parent,
2100                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2101                                            SC_Extern,
2102                                            false,
2103                                            R->isFunctionProtoType());
2104   New->setImplicit();
2105 
2106   // Create Decl objects for each parameter, adding them to the
2107   // FunctionDecl.
2108   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2109     SmallVector<ParmVarDecl*, 16> Params;
2110     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2111       ParmVarDecl *parm =
2112           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2113                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2114                               SC_None, nullptr);
2115       parm->setScopeInfo(0, i);
2116       Params.push_back(parm);
2117     }
2118     New->setParams(Params);
2119   }
2120 
2121   AddKnownFunctionAttributes(New);
2122   RegisterLocallyScopedExternCDecl(New, S);
2123 
2124   // TUScope is the translation-unit scope to insert this function into.
2125   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2126   // relate Scopes to DeclContexts, and probably eliminate CurContext
2127   // entirely, but we're not there yet.
2128   DeclContext *SavedContext = CurContext;
2129   CurContext = Parent;
2130   PushOnScopeChains(New, TUScope);
2131   CurContext = SavedContext;
2132   return New;
2133 }
2134 
2135 /// Typedef declarations don't have linkage, but they still denote the same
2136 /// entity if their types are the same.
2137 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2138 /// isSameEntity.
2139 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2140                                                      TypedefNameDecl *Decl,
2141                                                      LookupResult &Previous) {
2142   // This is only interesting when modules are enabled.
2143   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2144     return;
2145 
2146   // Empty sets are uninteresting.
2147   if (Previous.empty())
2148     return;
2149 
2150   LookupResult::Filter Filter = Previous.makeFilter();
2151   while (Filter.hasNext()) {
2152     NamedDecl *Old = Filter.next();
2153 
2154     // Non-hidden declarations are never ignored.
2155     if (S.isVisible(Old))
2156       continue;
2157 
2158     // Declarations of the same entity are not ignored, even if they have
2159     // different linkages.
2160     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2161       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2162                                 Decl->getUnderlyingType()))
2163         continue;
2164 
2165       // If both declarations give a tag declaration a typedef name for linkage
2166       // purposes, then they declare the same entity.
2167       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2168           Decl->getAnonDeclWithTypedefName())
2169         continue;
2170     }
2171 
2172     Filter.erase();
2173   }
2174 
2175   Filter.done();
2176 }
2177 
2178 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2179   QualType OldType;
2180   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2181     OldType = OldTypedef->getUnderlyingType();
2182   else
2183     OldType = Context.getTypeDeclType(Old);
2184   QualType NewType = New->getUnderlyingType();
2185 
2186   if (NewType->isVariablyModifiedType()) {
2187     // Must not redefine a typedef with a variably-modified type.
2188     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2189     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2190       << Kind << NewType;
2191     if (Old->getLocation().isValid())
2192       notePreviousDefinition(Old, New->getLocation());
2193     New->setInvalidDecl();
2194     return true;
2195   }
2196 
2197   if (OldType != NewType &&
2198       !OldType->isDependentType() &&
2199       !NewType->isDependentType() &&
2200       !Context.hasSameType(OldType, NewType)) {
2201     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2202     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2203       << Kind << NewType << OldType;
2204     if (Old->getLocation().isValid())
2205       notePreviousDefinition(Old, New->getLocation());
2206     New->setInvalidDecl();
2207     return true;
2208   }
2209   return false;
2210 }
2211 
2212 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2213 /// same name and scope as a previous declaration 'Old'.  Figure out
2214 /// how to resolve this situation, merging decls or emitting
2215 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2216 ///
2217 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2218                                 LookupResult &OldDecls) {
2219   // If the new decl is known invalid already, don't bother doing any
2220   // merging checks.
2221   if (New->isInvalidDecl()) return;
2222 
2223   // Allow multiple definitions for ObjC built-in typedefs.
2224   // FIXME: Verify the underlying types are equivalent!
2225   if (getLangOpts().ObjC) {
2226     const IdentifierInfo *TypeID = New->getIdentifier();
2227     switch (TypeID->getLength()) {
2228     default: break;
2229     case 2:
2230       {
2231         if (!TypeID->isStr("id"))
2232           break;
2233         QualType T = New->getUnderlyingType();
2234         if (!T->isPointerType())
2235           break;
2236         if (!T->isVoidPointerType()) {
2237           QualType PT = T->castAs<PointerType>()->getPointeeType();
2238           if (!PT->isStructureType())
2239             break;
2240         }
2241         Context.setObjCIdRedefinitionType(T);
2242         // Install the built-in type for 'id', ignoring the current definition.
2243         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2244         return;
2245       }
2246     case 5:
2247       if (!TypeID->isStr("Class"))
2248         break;
2249       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2250       // Install the built-in type for 'Class', ignoring the current definition.
2251       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2252       return;
2253     case 3:
2254       if (!TypeID->isStr("SEL"))
2255         break;
2256       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2257       // Install the built-in type for 'SEL', ignoring the current definition.
2258       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2259       return;
2260     }
2261     // Fall through - the typedef name was not a builtin type.
2262   }
2263 
2264   // Verify the old decl was also a type.
2265   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2266   if (!Old) {
2267     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2268       << New->getDeclName();
2269 
2270     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2271     if (OldD->getLocation().isValid())
2272       notePreviousDefinition(OldD, New->getLocation());
2273 
2274     return New->setInvalidDecl();
2275   }
2276 
2277   // If the old declaration is invalid, just give up here.
2278   if (Old->isInvalidDecl())
2279     return New->setInvalidDecl();
2280 
2281   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2282     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2283     auto *NewTag = New->getAnonDeclWithTypedefName();
2284     NamedDecl *Hidden = nullptr;
2285     if (OldTag && NewTag &&
2286         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2287         !hasVisibleDefinition(OldTag, &Hidden)) {
2288       // There is a definition of this tag, but it is not visible. Use it
2289       // instead of our tag.
2290       New->setTypeForDecl(OldTD->getTypeForDecl());
2291       if (OldTD->isModed())
2292         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2293                                     OldTD->getUnderlyingType());
2294       else
2295         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2296 
2297       // Make the old tag definition visible.
2298       makeMergedDefinitionVisible(Hidden);
2299 
2300       // If this was an unscoped enumeration, yank all of its enumerators
2301       // out of the scope.
2302       if (isa<EnumDecl>(NewTag)) {
2303         Scope *EnumScope = getNonFieldDeclScope(S);
2304         for (auto *D : NewTag->decls()) {
2305           auto *ED = cast<EnumConstantDecl>(D);
2306           assert(EnumScope->isDeclScope(ED));
2307           EnumScope->RemoveDecl(ED);
2308           IdResolver.RemoveDecl(ED);
2309           ED->getLexicalDeclContext()->removeDecl(ED);
2310         }
2311       }
2312     }
2313   }
2314 
2315   // If the typedef types are not identical, reject them in all languages and
2316   // with any extensions enabled.
2317   if (isIncompatibleTypedef(Old, New))
2318     return;
2319 
2320   // The types match.  Link up the redeclaration chain and merge attributes if
2321   // the old declaration was a typedef.
2322   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2323     New->setPreviousDecl(Typedef);
2324     mergeDeclAttributes(New, Old);
2325   }
2326 
2327   if (getLangOpts().MicrosoftExt)
2328     return;
2329 
2330   if (getLangOpts().CPlusPlus) {
2331     // C++ [dcl.typedef]p2:
2332     //   In a given non-class scope, a typedef specifier can be used to
2333     //   redefine the name of any type declared in that scope to refer
2334     //   to the type to which it already refers.
2335     if (!isa<CXXRecordDecl>(CurContext))
2336       return;
2337 
2338     // C++0x [dcl.typedef]p4:
2339     //   In a given class scope, a typedef specifier can be used to redefine
2340     //   any class-name declared in that scope that is not also a typedef-name
2341     //   to refer to the type to which it already refers.
2342     //
2343     // This wording came in via DR424, which was a correction to the
2344     // wording in DR56, which accidentally banned code like:
2345     //
2346     //   struct S {
2347     //     typedef struct A { } A;
2348     //   };
2349     //
2350     // in the C++03 standard. We implement the C++0x semantics, which
2351     // allow the above but disallow
2352     //
2353     //   struct S {
2354     //     typedef int I;
2355     //     typedef int I;
2356     //   };
2357     //
2358     // since that was the intent of DR56.
2359     if (!isa<TypedefNameDecl>(Old))
2360       return;
2361 
2362     Diag(New->getLocation(), diag::err_redefinition)
2363       << New->getDeclName();
2364     notePreviousDefinition(Old, New->getLocation());
2365     return New->setInvalidDecl();
2366   }
2367 
2368   // Modules always permit redefinition of typedefs, as does C11.
2369   if (getLangOpts().Modules || getLangOpts().C11)
2370     return;
2371 
2372   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2373   // is normally mapped to an error, but can be controlled with
2374   // -Wtypedef-redefinition.  If either the original or the redefinition is
2375   // in a system header, don't emit this for compatibility with GCC.
2376   if (getDiagnostics().getSuppressSystemWarnings() &&
2377       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2378       (Old->isImplicit() ||
2379        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2380        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2381     return;
2382 
2383   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2384     << New->getDeclName();
2385   notePreviousDefinition(Old, New->getLocation());
2386 }
2387 
2388 /// DeclhasAttr - returns true if decl Declaration already has the target
2389 /// attribute.
2390 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2391   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2392   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2393   for (const auto *i : D->attrs())
2394     if (i->getKind() == A->getKind()) {
2395       if (Ann) {
2396         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2397           return true;
2398         continue;
2399       }
2400       // FIXME: Don't hardcode this check
2401       if (OA && isa<OwnershipAttr>(i))
2402         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2403       return true;
2404     }
2405 
2406   return false;
2407 }
2408 
2409 static bool isAttributeTargetADefinition(Decl *D) {
2410   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2411     return VD->isThisDeclarationADefinition();
2412   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2413     return TD->isCompleteDefinition() || TD->isBeingDefined();
2414   return true;
2415 }
2416 
2417 /// Merge alignment attributes from \p Old to \p New, taking into account the
2418 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2419 ///
2420 /// \return \c true if any attributes were added to \p New.
2421 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2422   // Look for alignas attributes on Old, and pick out whichever attribute
2423   // specifies the strictest alignment requirement.
2424   AlignedAttr *OldAlignasAttr = nullptr;
2425   AlignedAttr *OldStrictestAlignAttr = nullptr;
2426   unsigned OldAlign = 0;
2427   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2428     // FIXME: We have no way of representing inherited dependent alignments
2429     // in a case like:
2430     //   template<int A, int B> struct alignas(A) X;
2431     //   template<int A, int B> struct alignas(B) X {};
2432     // For now, we just ignore any alignas attributes which are not on the
2433     // definition in such a case.
2434     if (I->isAlignmentDependent())
2435       return false;
2436 
2437     if (I->isAlignas())
2438       OldAlignasAttr = I;
2439 
2440     unsigned Align = I->getAlignment(S.Context);
2441     if (Align > OldAlign) {
2442       OldAlign = Align;
2443       OldStrictestAlignAttr = I;
2444     }
2445   }
2446 
2447   // Look for alignas attributes on New.
2448   AlignedAttr *NewAlignasAttr = nullptr;
2449   unsigned NewAlign = 0;
2450   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2451     if (I->isAlignmentDependent())
2452       return false;
2453 
2454     if (I->isAlignas())
2455       NewAlignasAttr = I;
2456 
2457     unsigned Align = I->getAlignment(S.Context);
2458     if (Align > NewAlign)
2459       NewAlign = Align;
2460   }
2461 
2462   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2463     // Both declarations have 'alignas' attributes. We require them to match.
2464     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2465     // fall short. (If two declarations both have alignas, they must both match
2466     // every definition, and so must match each other if there is a definition.)
2467 
2468     // If either declaration only contains 'alignas(0)' specifiers, then it
2469     // specifies the natural alignment for the type.
2470     if (OldAlign == 0 || NewAlign == 0) {
2471       QualType Ty;
2472       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2473         Ty = VD->getType();
2474       else
2475         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2476 
2477       if (OldAlign == 0)
2478         OldAlign = S.Context.getTypeAlign(Ty);
2479       if (NewAlign == 0)
2480         NewAlign = S.Context.getTypeAlign(Ty);
2481     }
2482 
2483     if (OldAlign != NewAlign) {
2484       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2485         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2486         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2487       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2488     }
2489   }
2490 
2491   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2492     // C++11 [dcl.align]p6:
2493     //   if any declaration of an entity has an alignment-specifier,
2494     //   every defining declaration of that entity shall specify an
2495     //   equivalent alignment.
2496     // C11 6.7.5/7:
2497     //   If the definition of an object does not have an alignment
2498     //   specifier, any other declaration of that object shall also
2499     //   have no alignment specifier.
2500     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2501       << OldAlignasAttr;
2502     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2503       << OldAlignasAttr;
2504   }
2505 
2506   bool AnyAdded = false;
2507 
2508   // Ensure we have an attribute representing the strictest alignment.
2509   if (OldAlign > NewAlign) {
2510     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2511     Clone->setInherited(true);
2512     New->addAttr(Clone);
2513     AnyAdded = true;
2514   }
2515 
2516   // Ensure we have an alignas attribute if the old declaration had one.
2517   if (OldAlignasAttr && !NewAlignasAttr &&
2518       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2519     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2520     Clone->setInherited(true);
2521     New->addAttr(Clone);
2522     AnyAdded = true;
2523   }
2524 
2525   return AnyAdded;
2526 }
2527 
2528 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2529                                const InheritableAttr *Attr,
2530                                Sema::AvailabilityMergeKind AMK) {
2531   // This function copies an attribute Attr from a previous declaration to the
2532   // new declaration D if the new declaration doesn't itself have that attribute
2533   // yet or if that attribute allows duplicates.
2534   // If you're adding a new attribute that requires logic different from
2535   // "use explicit attribute on decl if present, else use attribute from
2536   // previous decl", for example if the attribute needs to be consistent
2537   // between redeclarations, you need to call a custom merge function here.
2538   InheritableAttr *NewAttr = nullptr;
2539   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2540     NewAttr = S.mergeAvailabilityAttr(
2541         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2542         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2543         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2544         AA->getPriority());
2545   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2546     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2547   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2548     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2549   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2550     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2551   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2552     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2553   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2554     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2555                                 FA->getFirstArg());
2556   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2557     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2558   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2559     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2560   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2561     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2562                                        IA->getInheritanceModel());
2563   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2564     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2565                                       &S.Context.Idents.get(AA->getSpelling()));
2566   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2567            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2568             isa<CUDAGlobalAttr>(Attr))) {
2569     // CUDA target attributes are part of function signature for
2570     // overloading purposes and must not be merged.
2571     return false;
2572   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2573     NewAttr = S.mergeMinSizeAttr(D, *MA);
2574   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2575     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2576   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2577     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2578   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2579     NewAttr = S.mergeCommonAttr(D, *CommonA);
2580   else if (isa<AlignedAttr>(Attr))
2581     // AlignedAttrs are handled separately, because we need to handle all
2582     // such attributes on a declaration at the same time.
2583     NewAttr = nullptr;
2584   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2585            (AMK == Sema::AMK_Override ||
2586             AMK == Sema::AMK_ProtocolImplementation))
2587     NewAttr = nullptr;
2588   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2589     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
2590   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2591     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2592   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2593     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2594   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2595     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2596 
2597   if (NewAttr) {
2598     NewAttr->setInherited(true);
2599     D->addAttr(NewAttr);
2600     if (isa<MSInheritanceAttr>(NewAttr))
2601       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2602     return true;
2603   }
2604 
2605   return false;
2606 }
2607 
2608 static const NamedDecl *getDefinition(const Decl *D) {
2609   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2610     return TD->getDefinition();
2611   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2612     const VarDecl *Def = VD->getDefinition();
2613     if (Def)
2614       return Def;
2615     return VD->getActingDefinition();
2616   }
2617   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2618     return FD->getDefinition();
2619   return nullptr;
2620 }
2621 
2622 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2623   for (const auto *Attribute : D->attrs())
2624     if (Attribute->getKind() == Kind)
2625       return true;
2626   return false;
2627 }
2628 
2629 /// checkNewAttributesAfterDef - If we already have a definition, check that
2630 /// there are no new attributes in this declaration.
2631 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2632   if (!New->hasAttrs())
2633     return;
2634 
2635   const NamedDecl *Def = getDefinition(Old);
2636   if (!Def || Def == New)
2637     return;
2638 
2639   AttrVec &NewAttributes = New->getAttrs();
2640   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2641     const Attr *NewAttribute = NewAttributes[I];
2642 
2643     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2644       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2645         Sema::SkipBodyInfo SkipBody;
2646         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2647 
2648         // If we're skipping this definition, drop the "alias" attribute.
2649         if (SkipBody.ShouldSkip) {
2650           NewAttributes.erase(NewAttributes.begin() + I);
2651           --E;
2652           continue;
2653         }
2654       } else {
2655         VarDecl *VD = cast<VarDecl>(New);
2656         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2657                                 VarDecl::TentativeDefinition
2658                             ? diag::err_alias_after_tentative
2659                             : diag::err_redefinition;
2660         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2661         if (Diag == diag::err_redefinition)
2662           S.notePreviousDefinition(Def, VD->getLocation());
2663         else
2664           S.Diag(Def->getLocation(), diag::note_previous_definition);
2665         VD->setInvalidDecl();
2666       }
2667       ++I;
2668       continue;
2669     }
2670 
2671     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2672       // Tentative definitions are only interesting for the alias check above.
2673       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2674         ++I;
2675         continue;
2676       }
2677     }
2678 
2679     if (hasAttribute(Def, NewAttribute->getKind())) {
2680       ++I;
2681       continue; // regular attr merging will take care of validating this.
2682     }
2683 
2684     if (isa<C11NoReturnAttr>(NewAttribute)) {
2685       // C's _Noreturn is allowed to be added to a function after it is defined.
2686       ++I;
2687       continue;
2688     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2689       if (AA->isAlignas()) {
2690         // C++11 [dcl.align]p6:
2691         //   if any declaration of an entity has an alignment-specifier,
2692         //   every defining declaration of that entity shall specify an
2693         //   equivalent alignment.
2694         // C11 6.7.5/7:
2695         //   If the definition of an object does not have an alignment
2696         //   specifier, any other declaration of that object shall also
2697         //   have no alignment specifier.
2698         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2699           << AA;
2700         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2701           << AA;
2702         NewAttributes.erase(NewAttributes.begin() + I);
2703         --E;
2704         continue;
2705       }
2706     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2707                cast<VarDecl>(New)->isInline() &&
2708                !cast<VarDecl>(New)->isInlineSpecified()) {
2709       // Don't warn about applying selectany to implicitly inline variables.
2710       // Older compilers and language modes would require the use of selectany
2711       // to make such variables inline, and it would have no effect if we
2712       // honored it.
2713       ++I;
2714       continue;
2715     }
2716 
2717     S.Diag(NewAttribute->getLocation(),
2718            diag::warn_attribute_precede_definition);
2719     S.Diag(Def->getLocation(), diag::note_previous_definition);
2720     NewAttributes.erase(NewAttributes.begin() + I);
2721     --E;
2722   }
2723 }
2724 
2725 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2726                                      const ConstInitAttr *CIAttr,
2727                                      bool AttrBeforeInit) {
2728   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2729 
2730   // Figure out a good way to write this specifier on the old declaration.
2731   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2732   // enough of the attribute list spelling information to extract that without
2733   // heroics.
2734   std::string SuitableSpelling;
2735   if (S.getLangOpts().CPlusPlus2a)
2736     SuitableSpelling =
2737         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
2738   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2739     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2740         InsertLoc,
2741         {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
2742          tok::coloncolon,
2743          S.PP.getIdentifierInfo("require_constant_initialization"),
2744          tok::r_square, tok::r_square});
2745   if (SuitableSpelling.empty())
2746     SuitableSpelling = S.PP.getLastMacroWithSpelling(
2747         InsertLoc,
2748         {tok::kw___attribute, tok::l_paren, tok::r_paren,
2749          S.PP.getIdentifierInfo("require_constant_initialization"),
2750          tok::r_paren, tok::r_paren});
2751   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
2752     SuitableSpelling = "constinit";
2753   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2754     SuitableSpelling = "[[clang::require_constant_initialization]]";
2755   if (SuitableSpelling.empty())
2756     SuitableSpelling = "__attribute__((require_constant_initialization))";
2757   SuitableSpelling += " ";
2758 
2759   if (AttrBeforeInit) {
2760     // extern constinit int a;
2761     // int a = 0; // error (missing 'constinit'), accepted as extension
2762     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2763     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2764         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2765     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2766   } else {
2767     // int a = 0;
2768     // constinit extern int a; // error (missing 'constinit')
2769     S.Diag(CIAttr->getLocation(),
2770            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2771                                  : diag::warn_require_const_init_added_too_late)
2772         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2773     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2774         << CIAttr->isConstinit()
2775         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2776   }
2777 }
2778 
2779 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2780 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2781                                AvailabilityMergeKind AMK) {
2782   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2783     UsedAttr *NewAttr = OldAttr->clone(Context);
2784     NewAttr->setInherited(true);
2785     New->addAttr(NewAttr);
2786   }
2787 
2788   if (!Old->hasAttrs() && !New->hasAttrs())
2789     return;
2790 
2791   // [dcl.constinit]p1:
2792   //   If the [constinit] specifier is applied to any declaration of a
2793   //   variable, it shall be applied to the initializing declaration.
2794   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2795   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2796   if (bool(OldConstInit) != bool(NewConstInit)) {
2797     const auto *OldVD = cast<VarDecl>(Old);
2798     auto *NewVD = cast<VarDecl>(New);
2799 
2800     // Find the initializing declaration. Note that we might not have linked
2801     // the new declaration into the redeclaration chain yet.
2802     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2803     if (!InitDecl &&
2804         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2805       InitDecl = NewVD;
2806 
2807     if (InitDecl == NewVD) {
2808       // This is the initializing declaration. If it would inherit 'constinit',
2809       // that's ill-formed. (Note that we do not apply this to the attribute
2810       // form).
2811       if (OldConstInit && OldConstInit->isConstinit())
2812         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2813                                  /*AttrBeforeInit=*/true);
2814     } else if (NewConstInit) {
2815       // This is the first time we've been told that this declaration should
2816       // have a constant initializer. If we already saw the initializing
2817       // declaration, this is too late.
2818       if (InitDecl && InitDecl != NewVD) {
2819         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2820                                  /*AttrBeforeInit=*/false);
2821         NewVD->dropAttr<ConstInitAttr>();
2822       }
2823     }
2824   }
2825 
2826   // Attributes declared post-definition are currently ignored.
2827   checkNewAttributesAfterDef(*this, New, Old);
2828 
2829   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2830     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2831       if (!OldA->isEquivalent(NewA)) {
2832         // This redeclaration changes __asm__ label.
2833         Diag(New->getLocation(), diag::err_different_asm_label);
2834         Diag(OldA->getLocation(), diag::note_previous_declaration);
2835       }
2836     } else if (Old->isUsed()) {
2837       // This redeclaration adds an __asm__ label to a declaration that has
2838       // already been ODR-used.
2839       Diag(New->getLocation(), diag::err_late_asm_label_name)
2840         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2841     }
2842   }
2843 
2844   // Re-declaration cannot add abi_tag's.
2845   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2846     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2847       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2848         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2849                       NewTag) == OldAbiTagAttr->tags_end()) {
2850           Diag(NewAbiTagAttr->getLocation(),
2851                diag::err_new_abi_tag_on_redeclaration)
2852               << NewTag;
2853           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2854         }
2855       }
2856     } else {
2857       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2858       Diag(Old->getLocation(), diag::note_previous_declaration);
2859     }
2860   }
2861 
2862   // This redeclaration adds a section attribute.
2863   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2864     if (auto *VD = dyn_cast<VarDecl>(New)) {
2865       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2866         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2867         Diag(Old->getLocation(), diag::note_previous_declaration);
2868       }
2869     }
2870   }
2871 
2872   // Redeclaration adds code-seg attribute.
2873   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2874   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2875       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2876     Diag(New->getLocation(), diag::warn_mismatched_section)
2877          << 0 /*codeseg*/;
2878     Diag(Old->getLocation(), diag::note_previous_declaration);
2879   }
2880 
2881   if (!Old->hasAttrs())
2882     return;
2883 
2884   bool foundAny = New->hasAttrs();
2885 
2886   // Ensure that any moving of objects within the allocated map is done before
2887   // we process them.
2888   if (!foundAny) New->setAttrs(AttrVec());
2889 
2890   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2891     // Ignore deprecated/unavailable/availability attributes if requested.
2892     AvailabilityMergeKind LocalAMK = AMK_None;
2893     if (isa<DeprecatedAttr>(I) ||
2894         isa<UnavailableAttr>(I) ||
2895         isa<AvailabilityAttr>(I)) {
2896       switch (AMK) {
2897       case AMK_None:
2898         continue;
2899 
2900       case AMK_Redeclaration:
2901       case AMK_Override:
2902       case AMK_ProtocolImplementation:
2903         LocalAMK = AMK;
2904         break;
2905       }
2906     }
2907 
2908     // Already handled.
2909     if (isa<UsedAttr>(I))
2910       continue;
2911 
2912     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2913       foundAny = true;
2914   }
2915 
2916   if (mergeAlignedAttrs(*this, New, Old))
2917     foundAny = true;
2918 
2919   if (!foundAny) New->dropAttrs();
2920 }
2921 
2922 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2923 /// to the new one.
2924 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2925                                      const ParmVarDecl *oldDecl,
2926                                      Sema &S) {
2927   // C++11 [dcl.attr.depend]p2:
2928   //   The first declaration of a function shall specify the
2929   //   carries_dependency attribute for its declarator-id if any declaration
2930   //   of the function specifies the carries_dependency attribute.
2931   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2932   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2933     S.Diag(CDA->getLocation(),
2934            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2935     // Find the first declaration of the parameter.
2936     // FIXME: Should we build redeclaration chains for function parameters?
2937     const FunctionDecl *FirstFD =
2938       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2939     const ParmVarDecl *FirstVD =
2940       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2941     S.Diag(FirstVD->getLocation(),
2942            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2943   }
2944 
2945   if (!oldDecl->hasAttrs())
2946     return;
2947 
2948   bool foundAny = newDecl->hasAttrs();
2949 
2950   // Ensure that any moving of objects within the allocated map is
2951   // done before we process them.
2952   if (!foundAny) newDecl->setAttrs(AttrVec());
2953 
2954   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2955     if (!DeclHasAttr(newDecl, I)) {
2956       InheritableAttr *newAttr =
2957         cast<InheritableParamAttr>(I->clone(S.Context));
2958       newAttr->setInherited(true);
2959       newDecl->addAttr(newAttr);
2960       foundAny = true;
2961     }
2962   }
2963 
2964   if (!foundAny) newDecl->dropAttrs();
2965 }
2966 
2967 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2968                                 const ParmVarDecl *OldParam,
2969                                 Sema &S) {
2970   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2971     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2972       if (*Oldnullability != *Newnullability) {
2973         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2974           << DiagNullabilityKind(
2975                *Newnullability,
2976                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2977                 != 0))
2978           << DiagNullabilityKind(
2979                *Oldnullability,
2980                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2981                 != 0));
2982         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2983       }
2984     } else {
2985       QualType NewT = NewParam->getType();
2986       NewT = S.Context.getAttributedType(
2987                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2988                          NewT, NewT);
2989       NewParam->setType(NewT);
2990     }
2991   }
2992 }
2993 
2994 namespace {
2995 
2996 /// Used in MergeFunctionDecl to keep track of function parameters in
2997 /// C.
2998 struct GNUCompatibleParamWarning {
2999   ParmVarDecl *OldParm;
3000   ParmVarDecl *NewParm;
3001   QualType PromotedType;
3002 };
3003 
3004 } // end anonymous namespace
3005 
3006 // Determine whether the previous declaration was a definition, implicit
3007 // declaration, or a declaration.
3008 template <typename T>
3009 static std::pair<diag::kind, SourceLocation>
3010 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3011   diag::kind PrevDiag;
3012   SourceLocation OldLocation = Old->getLocation();
3013   if (Old->isThisDeclarationADefinition())
3014     PrevDiag = diag::note_previous_definition;
3015   else if (Old->isImplicit()) {
3016     PrevDiag = diag::note_previous_implicit_declaration;
3017     if (OldLocation.isInvalid())
3018       OldLocation = New->getLocation();
3019   } else
3020     PrevDiag = diag::note_previous_declaration;
3021   return std::make_pair(PrevDiag, OldLocation);
3022 }
3023 
3024 /// canRedefineFunction - checks if a function can be redefined. Currently,
3025 /// only extern inline functions can be redefined, and even then only in
3026 /// GNU89 mode.
3027 static bool canRedefineFunction(const FunctionDecl *FD,
3028                                 const LangOptions& LangOpts) {
3029   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3030           !LangOpts.CPlusPlus &&
3031           FD->isInlineSpecified() &&
3032           FD->getStorageClass() == SC_Extern);
3033 }
3034 
3035 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3036   const AttributedType *AT = T->getAs<AttributedType>();
3037   while (AT && !AT->isCallingConv())
3038     AT = AT->getModifiedType()->getAs<AttributedType>();
3039   return AT;
3040 }
3041 
3042 template <typename T>
3043 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3044   const DeclContext *DC = Old->getDeclContext();
3045   if (DC->isRecord())
3046     return false;
3047 
3048   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3049   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3050     return true;
3051   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3052     return true;
3053   return false;
3054 }
3055 
3056 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3057 static bool isExternC(VarTemplateDecl *) { return false; }
3058 
3059 /// Check whether a redeclaration of an entity introduced by a
3060 /// using-declaration is valid, given that we know it's not an overload
3061 /// (nor a hidden tag declaration).
3062 template<typename ExpectedDecl>
3063 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3064                                    ExpectedDecl *New) {
3065   // C++11 [basic.scope.declarative]p4:
3066   //   Given a set of declarations in a single declarative region, each of
3067   //   which specifies the same unqualified name,
3068   //   -- they shall all refer to the same entity, or all refer to functions
3069   //      and function templates; or
3070   //   -- exactly one declaration shall declare a class name or enumeration
3071   //      name that is not a typedef name and the other declarations shall all
3072   //      refer to the same variable or enumerator, or all refer to functions
3073   //      and function templates; in this case the class name or enumeration
3074   //      name is hidden (3.3.10).
3075 
3076   // C++11 [namespace.udecl]p14:
3077   //   If a function declaration in namespace scope or block scope has the
3078   //   same name and the same parameter-type-list as a function introduced
3079   //   by a using-declaration, and the declarations do not declare the same
3080   //   function, the program is ill-formed.
3081 
3082   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3083   if (Old &&
3084       !Old->getDeclContext()->getRedeclContext()->Equals(
3085           New->getDeclContext()->getRedeclContext()) &&
3086       !(isExternC(Old) && isExternC(New)))
3087     Old = nullptr;
3088 
3089   if (!Old) {
3090     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3091     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3092     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3093     return true;
3094   }
3095   return false;
3096 }
3097 
3098 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3099                                             const FunctionDecl *B) {
3100   assert(A->getNumParams() == B->getNumParams());
3101 
3102   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3103     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3104     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3105     if (AttrA == AttrB)
3106       return true;
3107     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3108            AttrA->isDynamic() == AttrB->isDynamic();
3109   };
3110 
3111   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3112 }
3113 
3114 /// If necessary, adjust the semantic declaration context for a qualified
3115 /// declaration to name the correct inline namespace within the qualifier.
3116 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3117                                                DeclaratorDecl *OldD) {
3118   // The only case where we need to update the DeclContext is when
3119   // redeclaration lookup for a qualified name finds a declaration
3120   // in an inline namespace within the context named by the qualifier:
3121   //
3122   //   inline namespace N { int f(); }
3123   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3124   //
3125   // For unqualified declarations, the semantic context *can* change
3126   // along the redeclaration chain (for local extern declarations,
3127   // extern "C" declarations, and friend declarations in particular).
3128   if (!NewD->getQualifier())
3129     return;
3130 
3131   // NewD is probably already in the right context.
3132   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3133   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3134   if (NamedDC->Equals(SemaDC))
3135     return;
3136 
3137   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3138           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3139          "unexpected context for redeclaration");
3140 
3141   auto *LexDC = NewD->getLexicalDeclContext();
3142   auto FixSemaDC = [=](NamedDecl *D) {
3143     if (!D)
3144       return;
3145     D->setDeclContext(SemaDC);
3146     D->setLexicalDeclContext(LexDC);
3147   };
3148 
3149   FixSemaDC(NewD);
3150   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3151     FixSemaDC(FD->getDescribedFunctionTemplate());
3152   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3153     FixSemaDC(VD->getDescribedVarTemplate());
3154 }
3155 
3156 /// MergeFunctionDecl - We just parsed a function 'New' from
3157 /// declarator D which has the same name and scope as a previous
3158 /// declaration 'Old'.  Figure out how to resolve this situation,
3159 /// merging decls or emitting diagnostics as appropriate.
3160 ///
3161 /// In C++, New and Old must be declarations that are not
3162 /// overloaded. Use IsOverload to determine whether New and Old are
3163 /// overloaded, and to select the Old declaration that New should be
3164 /// merged with.
3165 ///
3166 /// Returns true if there was an error, false otherwise.
3167 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3168                              Scope *S, bool MergeTypeWithOld) {
3169   // Verify the old decl was also a function.
3170   FunctionDecl *Old = OldD->getAsFunction();
3171   if (!Old) {
3172     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3173       if (New->getFriendObjectKind()) {
3174         Diag(New->getLocation(), diag::err_using_decl_friend);
3175         Diag(Shadow->getTargetDecl()->getLocation(),
3176              diag::note_using_decl_target);
3177         Diag(Shadow->getUsingDecl()->getLocation(),
3178              diag::note_using_decl) << 0;
3179         return true;
3180       }
3181 
3182       // Check whether the two declarations might declare the same function.
3183       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3184         return true;
3185       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3186     } else {
3187       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3188         << New->getDeclName();
3189       notePreviousDefinition(OldD, New->getLocation());
3190       return true;
3191     }
3192   }
3193 
3194   // If the old declaration is invalid, just give up here.
3195   if (Old->isInvalidDecl())
3196     return true;
3197 
3198   // Disallow redeclaration of some builtins.
3199   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3200     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3201     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3202         << Old << Old->getType();
3203     return true;
3204   }
3205 
3206   diag::kind PrevDiag;
3207   SourceLocation OldLocation;
3208   std::tie(PrevDiag, OldLocation) =
3209       getNoteDiagForInvalidRedeclaration(Old, New);
3210 
3211   // Don't complain about this if we're in GNU89 mode and the old function
3212   // is an extern inline function.
3213   // Don't complain about specializations. They are not supposed to have
3214   // storage classes.
3215   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3216       New->getStorageClass() == SC_Static &&
3217       Old->hasExternalFormalLinkage() &&
3218       !New->getTemplateSpecializationInfo() &&
3219       !canRedefineFunction(Old, getLangOpts())) {
3220     if (getLangOpts().MicrosoftExt) {
3221       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3222       Diag(OldLocation, PrevDiag);
3223     } else {
3224       Diag(New->getLocation(), diag::err_static_non_static) << New;
3225       Diag(OldLocation, PrevDiag);
3226       return true;
3227     }
3228   }
3229 
3230   if (New->hasAttr<InternalLinkageAttr>() &&
3231       !Old->hasAttr<InternalLinkageAttr>()) {
3232     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3233         << New->getDeclName();
3234     notePreviousDefinition(Old, New->getLocation());
3235     New->dropAttr<InternalLinkageAttr>();
3236   }
3237 
3238   if (CheckRedeclarationModuleOwnership(New, Old))
3239     return true;
3240 
3241   if (!getLangOpts().CPlusPlus) {
3242     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3243     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3244       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3245         << New << OldOvl;
3246 
3247       // Try our best to find a decl that actually has the overloadable
3248       // attribute for the note. In most cases (e.g. programs with only one
3249       // broken declaration/definition), this won't matter.
3250       //
3251       // FIXME: We could do this if we juggled some extra state in
3252       // OverloadableAttr, rather than just removing it.
3253       const Decl *DiagOld = Old;
3254       if (OldOvl) {
3255         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3256           const auto *A = D->getAttr<OverloadableAttr>();
3257           return A && !A->isImplicit();
3258         });
3259         // If we've implicitly added *all* of the overloadable attrs to this
3260         // chain, emitting a "previous redecl" note is pointless.
3261         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3262       }
3263 
3264       if (DiagOld)
3265         Diag(DiagOld->getLocation(),
3266              diag::note_attribute_overloadable_prev_overload)
3267           << OldOvl;
3268 
3269       if (OldOvl)
3270         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3271       else
3272         New->dropAttr<OverloadableAttr>();
3273     }
3274   }
3275 
3276   // If a function is first declared with a calling convention, but is later
3277   // declared or defined without one, all following decls assume the calling
3278   // convention of the first.
3279   //
3280   // It's OK if a function is first declared without a calling convention,
3281   // but is later declared or defined with the default calling convention.
3282   //
3283   // To test if either decl has an explicit calling convention, we look for
3284   // AttributedType sugar nodes on the type as written.  If they are missing or
3285   // were canonicalized away, we assume the calling convention was implicit.
3286   //
3287   // Note also that we DO NOT return at this point, because we still have
3288   // other tests to run.
3289   QualType OldQType = Context.getCanonicalType(Old->getType());
3290   QualType NewQType = Context.getCanonicalType(New->getType());
3291   const FunctionType *OldType = cast<FunctionType>(OldQType);
3292   const FunctionType *NewType = cast<FunctionType>(NewQType);
3293   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3294   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3295   bool RequiresAdjustment = false;
3296 
3297   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3298     FunctionDecl *First = Old->getFirstDecl();
3299     const FunctionType *FT =
3300         First->getType().getCanonicalType()->castAs<FunctionType>();
3301     FunctionType::ExtInfo FI = FT->getExtInfo();
3302     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3303     if (!NewCCExplicit) {
3304       // Inherit the CC from the previous declaration if it was specified
3305       // there but not here.
3306       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3307       RequiresAdjustment = true;
3308     } else if (New->getBuiltinID()) {
3309       // Calling Conventions on a Builtin aren't really useful and setting a
3310       // default calling convention and cdecl'ing some builtin redeclarations is
3311       // common, so warn and ignore the calling convention on the redeclaration.
3312       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3313           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3314           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3315       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3316       RequiresAdjustment = true;
3317     } else {
3318       // Calling conventions aren't compatible, so complain.
3319       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3320       Diag(New->getLocation(), diag::err_cconv_change)
3321         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3322         << !FirstCCExplicit
3323         << (!FirstCCExplicit ? "" :
3324             FunctionType::getNameForCallConv(FI.getCC()));
3325 
3326       // Put the note on the first decl, since it is the one that matters.
3327       Diag(First->getLocation(), diag::note_previous_declaration);
3328       return true;
3329     }
3330   }
3331 
3332   // FIXME: diagnose the other way around?
3333   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3334     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3335     RequiresAdjustment = true;
3336   }
3337 
3338   // Merge regparm attribute.
3339   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3340       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3341     if (NewTypeInfo.getHasRegParm()) {
3342       Diag(New->getLocation(), diag::err_regparm_mismatch)
3343         << NewType->getRegParmType()
3344         << OldType->getRegParmType();
3345       Diag(OldLocation, diag::note_previous_declaration);
3346       return true;
3347     }
3348 
3349     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3350     RequiresAdjustment = true;
3351   }
3352 
3353   // Merge ns_returns_retained attribute.
3354   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3355     if (NewTypeInfo.getProducesResult()) {
3356       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3357           << "'ns_returns_retained'";
3358       Diag(OldLocation, diag::note_previous_declaration);
3359       return true;
3360     }
3361 
3362     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3363     RequiresAdjustment = true;
3364   }
3365 
3366   if (OldTypeInfo.getNoCallerSavedRegs() !=
3367       NewTypeInfo.getNoCallerSavedRegs()) {
3368     if (NewTypeInfo.getNoCallerSavedRegs()) {
3369       AnyX86NoCallerSavedRegistersAttr *Attr =
3370         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3371       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3372       Diag(OldLocation, diag::note_previous_declaration);
3373       return true;
3374     }
3375 
3376     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3377     RequiresAdjustment = true;
3378   }
3379 
3380   if (RequiresAdjustment) {
3381     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3382     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3383     New->setType(QualType(AdjustedType, 0));
3384     NewQType = Context.getCanonicalType(New->getType());
3385   }
3386 
3387   // If this redeclaration makes the function inline, we may need to add it to
3388   // UndefinedButUsed.
3389   if (!Old->isInlined() && New->isInlined() &&
3390       !New->hasAttr<GNUInlineAttr>() &&
3391       !getLangOpts().GNUInline &&
3392       Old->isUsed(false) &&
3393       !Old->isDefined() && !New->isThisDeclarationADefinition())
3394     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3395                                            SourceLocation()));
3396 
3397   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3398   // about it.
3399   if (New->hasAttr<GNUInlineAttr>() &&
3400       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3401     UndefinedButUsed.erase(Old->getCanonicalDecl());
3402   }
3403 
3404   // If pass_object_size params don't match up perfectly, this isn't a valid
3405   // redeclaration.
3406   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3407       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3408     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3409         << New->getDeclName();
3410     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3411     return true;
3412   }
3413 
3414   if (getLangOpts().CPlusPlus) {
3415     // C++1z [over.load]p2
3416     //   Certain function declarations cannot be overloaded:
3417     //     -- Function declarations that differ only in the return type,
3418     //        the exception specification, or both cannot be overloaded.
3419 
3420     // Check the exception specifications match. This may recompute the type of
3421     // both Old and New if it resolved exception specifications, so grab the
3422     // types again after this. Because this updates the type, we do this before
3423     // any of the other checks below, which may update the "de facto" NewQType
3424     // but do not necessarily update the type of New.
3425     if (CheckEquivalentExceptionSpec(Old, New))
3426       return true;
3427     OldQType = Context.getCanonicalType(Old->getType());
3428     NewQType = Context.getCanonicalType(New->getType());
3429 
3430     // Go back to the type source info to compare the declared return types,
3431     // per C++1y [dcl.type.auto]p13:
3432     //   Redeclarations or specializations of a function or function template
3433     //   with a declared return type that uses a placeholder type shall also
3434     //   use that placeholder, not a deduced type.
3435     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3436     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3437     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3438         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3439                                        OldDeclaredReturnType)) {
3440       QualType ResQT;
3441       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3442           OldDeclaredReturnType->isObjCObjectPointerType())
3443         // FIXME: This does the wrong thing for a deduced return type.
3444         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3445       if (ResQT.isNull()) {
3446         if (New->isCXXClassMember() && New->isOutOfLine())
3447           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3448               << New << New->getReturnTypeSourceRange();
3449         else
3450           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3451               << New->getReturnTypeSourceRange();
3452         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3453                                     << Old->getReturnTypeSourceRange();
3454         return true;
3455       }
3456       else
3457         NewQType = ResQT;
3458     }
3459 
3460     QualType OldReturnType = OldType->getReturnType();
3461     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3462     if (OldReturnType != NewReturnType) {
3463       // If this function has a deduced return type and has already been
3464       // defined, copy the deduced value from the old declaration.
3465       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3466       if (OldAT && OldAT->isDeduced()) {
3467         New->setType(
3468             SubstAutoType(New->getType(),
3469                           OldAT->isDependentType() ? Context.DependentTy
3470                                                    : OldAT->getDeducedType()));
3471         NewQType = Context.getCanonicalType(
3472             SubstAutoType(NewQType,
3473                           OldAT->isDependentType() ? Context.DependentTy
3474                                                    : OldAT->getDeducedType()));
3475       }
3476     }
3477 
3478     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3479     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3480     if (OldMethod && NewMethod) {
3481       // Preserve triviality.
3482       NewMethod->setTrivial(OldMethod->isTrivial());
3483 
3484       // MSVC allows explicit template specialization at class scope:
3485       // 2 CXXMethodDecls referring to the same function will be injected.
3486       // We don't want a redeclaration error.
3487       bool IsClassScopeExplicitSpecialization =
3488                               OldMethod->isFunctionTemplateSpecialization() &&
3489                               NewMethod->isFunctionTemplateSpecialization();
3490       bool isFriend = NewMethod->getFriendObjectKind();
3491 
3492       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3493           !IsClassScopeExplicitSpecialization) {
3494         //    -- Member function declarations with the same name and the
3495         //       same parameter types cannot be overloaded if any of them
3496         //       is a static member function declaration.
3497         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3498           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3499           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3500           return true;
3501         }
3502 
3503         // C++ [class.mem]p1:
3504         //   [...] A member shall not be declared twice in the
3505         //   member-specification, except that a nested class or member
3506         //   class template can be declared and then later defined.
3507         if (!inTemplateInstantiation()) {
3508           unsigned NewDiag;
3509           if (isa<CXXConstructorDecl>(OldMethod))
3510             NewDiag = diag::err_constructor_redeclared;
3511           else if (isa<CXXDestructorDecl>(NewMethod))
3512             NewDiag = diag::err_destructor_redeclared;
3513           else if (isa<CXXConversionDecl>(NewMethod))
3514             NewDiag = diag::err_conv_function_redeclared;
3515           else
3516             NewDiag = diag::err_member_redeclared;
3517 
3518           Diag(New->getLocation(), NewDiag);
3519         } else {
3520           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3521             << New << New->getType();
3522         }
3523         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3524         return true;
3525 
3526       // Complain if this is an explicit declaration of a special
3527       // member that was initially declared implicitly.
3528       //
3529       // As an exception, it's okay to befriend such methods in order
3530       // to permit the implicit constructor/destructor/operator calls.
3531       } else if (OldMethod->isImplicit()) {
3532         if (isFriend) {
3533           NewMethod->setImplicit();
3534         } else {
3535           Diag(NewMethod->getLocation(),
3536                diag::err_definition_of_implicitly_declared_member)
3537             << New << getSpecialMember(OldMethod);
3538           return true;
3539         }
3540       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3541         Diag(NewMethod->getLocation(),
3542              diag::err_definition_of_explicitly_defaulted_member)
3543           << getSpecialMember(OldMethod);
3544         return true;
3545       }
3546     }
3547 
3548     // C++11 [dcl.attr.noreturn]p1:
3549     //   The first declaration of a function shall specify the noreturn
3550     //   attribute if any declaration of that function specifies the noreturn
3551     //   attribute.
3552     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3553     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3554       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3555       Diag(Old->getFirstDecl()->getLocation(),
3556            diag::note_noreturn_missing_first_decl);
3557     }
3558 
3559     // C++11 [dcl.attr.depend]p2:
3560     //   The first declaration of a function shall specify the
3561     //   carries_dependency attribute for its declarator-id if any declaration
3562     //   of the function specifies the carries_dependency attribute.
3563     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3564     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3565       Diag(CDA->getLocation(),
3566            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3567       Diag(Old->getFirstDecl()->getLocation(),
3568            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3569     }
3570 
3571     // (C++98 8.3.5p3):
3572     //   All declarations for a function shall agree exactly in both the
3573     //   return type and the parameter-type-list.
3574     // We also want to respect all the extended bits except noreturn.
3575 
3576     // noreturn should now match unless the old type info didn't have it.
3577     QualType OldQTypeForComparison = OldQType;
3578     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3579       auto *OldType = OldQType->castAs<FunctionProtoType>();
3580       const FunctionType *OldTypeForComparison
3581         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3582       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3583       assert(OldQTypeForComparison.isCanonical());
3584     }
3585 
3586     if (haveIncompatibleLanguageLinkages(Old, New)) {
3587       // As a special case, retain the language linkage from previous
3588       // declarations of a friend function as an extension.
3589       //
3590       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3591       // and is useful because there's otherwise no way to specify language
3592       // linkage within class scope.
3593       //
3594       // Check cautiously as the friend object kind isn't yet complete.
3595       if (New->getFriendObjectKind() != Decl::FOK_None) {
3596         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3597         Diag(OldLocation, PrevDiag);
3598       } else {
3599         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3600         Diag(OldLocation, PrevDiag);
3601         return true;
3602       }
3603     }
3604 
3605     // If the function types are compatible, merge the declarations. Ignore the
3606     // exception specifier because it was already checked above in
3607     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3608     // about incompatible types under -fms-compatibility.
3609     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3610                                                          NewQType))
3611       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3612 
3613     // If the types are imprecise (due to dependent constructs in friends or
3614     // local extern declarations), it's OK if they differ. We'll check again
3615     // during instantiation.
3616     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3617       return false;
3618 
3619     // Fall through for conflicting redeclarations and redefinitions.
3620   }
3621 
3622   // C: Function types need to be compatible, not identical. This handles
3623   // duplicate function decls like "void f(int); void f(enum X);" properly.
3624   if (!getLangOpts().CPlusPlus &&
3625       Context.typesAreCompatible(OldQType, NewQType)) {
3626     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3627     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3628     const FunctionProtoType *OldProto = nullptr;
3629     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3630         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3631       // The old declaration provided a function prototype, but the
3632       // new declaration does not. Merge in the prototype.
3633       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3634       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3635       NewQType =
3636           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3637                                   OldProto->getExtProtoInfo());
3638       New->setType(NewQType);
3639       New->setHasInheritedPrototype();
3640 
3641       // Synthesize parameters with the same types.
3642       SmallVector<ParmVarDecl*, 16> Params;
3643       for (const auto &ParamType : OldProto->param_types()) {
3644         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3645                                                  SourceLocation(), nullptr,
3646                                                  ParamType, /*TInfo=*/nullptr,
3647                                                  SC_None, nullptr);
3648         Param->setScopeInfo(0, Params.size());
3649         Param->setImplicit();
3650         Params.push_back(Param);
3651       }
3652 
3653       New->setParams(Params);
3654     }
3655 
3656     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3657   }
3658 
3659   // Check if the function types are compatible when pointer size address
3660   // spaces are ignored.
3661   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3662     return false;
3663 
3664   // GNU C permits a K&R definition to follow a prototype declaration
3665   // if the declared types of the parameters in the K&R definition
3666   // match the types in the prototype declaration, even when the
3667   // promoted types of the parameters from the K&R definition differ
3668   // from the types in the prototype. GCC then keeps the types from
3669   // the prototype.
3670   //
3671   // If a variadic prototype is followed by a non-variadic K&R definition,
3672   // the K&R definition becomes variadic.  This is sort of an edge case, but
3673   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3674   // C99 6.9.1p8.
3675   if (!getLangOpts().CPlusPlus &&
3676       Old->hasPrototype() && !New->hasPrototype() &&
3677       New->getType()->getAs<FunctionProtoType>() &&
3678       Old->getNumParams() == New->getNumParams()) {
3679     SmallVector<QualType, 16> ArgTypes;
3680     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3681     const FunctionProtoType *OldProto
3682       = Old->getType()->getAs<FunctionProtoType>();
3683     const FunctionProtoType *NewProto
3684       = New->getType()->getAs<FunctionProtoType>();
3685 
3686     // Determine whether this is the GNU C extension.
3687     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3688                                                NewProto->getReturnType());
3689     bool LooseCompatible = !MergedReturn.isNull();
3690     for (unsigned Idx = 0, End = Old->getNumParams();
3691          LooseCompatible && Idx != End; ++Idx) {
3692       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3693       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3694       if (Context.typesAreCompatible(OldParm->getType(),
3695                                      NewProto->getParamType(Idx))) {
3696         ArgTypes.push_back(NewParm->getType());
3697       } else if (Context.typesAreCompatible(OldParm->getType(),
3698                                             NewParm->getType(),
3699                                             /*CompareUnqualified=*/true)) {
3700         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3701                                            NewProto->getParamType(Idx) };
3702         Warnings.push_back(Warn);
3703         ArgTypes.push_back(NewParm->getType());
3704       } else
3705         LooseCompatible = false;
3706     }
3707 
3708     if (LooseCompatible) {
3709       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3710         Diag(Warnings[Warn].NewParm->getLocation(),
3711              diag::ext_param_promoted_not_compatible_with_prototype)
3712           << Warnings[Warn].PromotedType
3713           << Warnings[Warn].OldParm->getType();
3714         if (Warnings[Warn].OldParm->getLocation().isValid())
3715           Diag(Warnings[Warn].OldParm->getLocation(),
3716                diag::note_previous_declaration);
3717       }
3718 
3719       if (MergeTypeWithOld)
3720         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3721                                              OldProto->getExtProtoInfo()));
3722       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3723     }
3724 
3725     // Fall through to diagnose conflicting types.
3726   }
3727 
3728   // A function that has already been declared has been redeclared or
3729   // defined with a different type; show an appropriate diagnostic.
3730 
3731   // If the previous declaration was an implicitly-generated builtin
3732   // declaration, then at the very least we should use a specialized note.
3733   unsigned BuiltinID;
3734   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3735     // If it's actually a library-defined builtin function like 'malloc'
3736     // or 'printf', just warn about the incompatible redeclaration.
3737     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3738       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3739       Diag(OldLocation, diag::note_previous_builtin_declaration)
3740         << Old << Old->getType();
3741 
3742       // If this is a global redeclaration, just forget hereafter
3743       // about the "builtin-ness" of the function.
3744       //
3745       // Doing this for local extern declarations is problematic.  If
3746       // the builtin declaration remains visible, a second invalid
3747       // local declaration will produce a hard error; if it doesn't
3748       // remain visible, a single bogus local redeclaration (which is
3749       // actually only a warning) could break all the downstream code.
3750       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3751         New->getIdentifier()->revertBuiltin();
3752 
3753       return false;
3754     }
3755 
3756     PrevDiag = diag::note_previous_builtin_declaration;
3757   }
3758 
3759   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3760   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3761   return true;
3762 }
3763 
3764 /// Completes the merge of two function declarations that are
3765 /// known to be compatible.
3766 ///
3767 /// This routine handles the merging of attributes and other
3768 /// properties of function declarations from the old declaration to
3769 /// the new declaration, once we know that New is in fact a
3770 /// redeclaration of Old.
3771 ///
3772 /// \returns false
3773 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3774                                         Scope *S, bool MergeTypeWithOld) {
3775   // Merge the attributes
3776   mergeDeclAttributes(New, Old);
3777 
3778   // Merge "pure" flag.
3779   if (Old->isPure())
3780     New->setPure();
3781 
3782   // Merge "used" flag.
3783   if (Old->getMostRecentDecl()->isUsed(false))
3784     New->setIsUsed();
3785 
3786   // Merge attributes from the parameters.  These can mismatch with K&R
3787   // declarations.
3788   if (New->getNumParams() == Old->getNumParams())
3789       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3790         ParmVarDecl *NewParam = New->getParamDecl(i);
3791         ParmVarDecl *OldParam = Old->getParamDecl(i);
3792         mergeParamDeclAttributes(NewParam, OldParam, *this);
3793         mergeParamDeclTypes(NewParam, OldParam, *this);
3794       }
3795 
3796   if (getLangOpts().CPlusPlus)
3797     return MergeCXXFunctionDecl(New, Old, S);
3798 
3799   // Merge the function types so the we get the composite types for the return
3800   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3801   // was visible.
3802   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3803   if (!Merged.isNull() && MergeTypeWithOld)
3804     New->setType(Merged);
3805 
3806   return false;
3807 }
3808 
3809 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3810                                 ObjCMethodDecl *oldMethod) {
3811   // Merge the attributes, including deprecated/unavailable
3812   AvailabilityMergeKind MergeKind =
3813     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3814       ? AMK_ProtocolImplementation
3815       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3816                                                        : AMK_Override;
3817 
3818   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3819 
3820   // Merge attributes from the parameters.
3821   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3822                                        oe = oldMethod->param_end();
3823   for (ObjCMethodDecl::param_iterator
3824          ni = newMethod->param_begin(), ne = newMethod->param_end();
3825        ni != ne && oi != oe; ++ni, ++oi)
3826     mergeParamDeclAttributes(*ni, *oi, *this);
3827 
3828   CheckObjCMethodOverride(newMethod, oldMethod);
3829 }
3830 
3831 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3832   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3833 
3834   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3835          ? diag::err_redefinition_different_type
3836          : diag::err_redeclaration_different_type)
3837     << New->getDeclName() << New->getType() << Old->getType();
3838 
3839   diag::kind PrevDiag;
3840   SourceLocation OldLocation;
3841   std::tie(PrevDiag, OldLocation)
3842     = getNoteDiagForInvalidRedeclaration(Old, New);
3843   S.Diag(OldLocation, PrevDiag);
3844   New->setInvalidDecl();
3845 }
3846 
3847 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3848 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3849 /// emitting diagnostics as appropriate.
3850 ///
3851 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3852 /// to here in AddInitializerToDecl. We can't check them before the initializer
3853 /// is attached.
3854 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3855                              bool MergeTypeWithOld) {
3856   if (New->isInvalidDecl() || Old->isInvalidDecl())
3857     return;
3858 
3859   QualType MergedT;
3860   if (getLangOpts().CPlusPlus) {
3861     if (New->getType()->isUndeducedType()) {
3862       // We don't know what the new type is until the initializer is attached.
3863       return;
3864     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3865       // These could still be something that needs exception specs checked.
3866       return MergeVarDeclExceptionSpecs(New, Old);
3867     }
3868     // C++ [basic.link]p10:
3869     //   [...] the types specified by all declarations referring to a given
3870     //   object or function shall be identical, except that declarations for an
3871     //   array object can specify array types that differ by the presence or
3872     //   absence of a major array bound (8.3.4).
3873     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3874       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3875       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3876 
3877       // We are merging a variable declaration New into Old. If it has an array
3878       // bound, and that bound differs from Old's bound, we should diagnose the
3879       // mismatch.
3880       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3881         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3882              PrevVD = PrevVD->getPreviousDecl()) {
3883           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3884           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3885             continue;
3886 
3887           if (!Context.hasSameType(NewArray, PrevVDTy))
3888             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3889         }
3890       }
3891 
3892       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3893         if (Context.hasSameType(OldArray->getElementType(),
3894                                 NewArray->getElementType()))
3895           MergedT = New->getType();
3896       }
3897       // FIXME: Check visibility. New is hidden but has a complete type. If New
3898       // has no array bound, it should not inherit one from Old, if Old is not
3899       // visible.
3900       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3901         if (Context.hasSameType(OldArray->getElementType(),
3902                                 NewArray->getElementType()))
3903           MergedT = Old->getType();
3904       }
3905     }
3906     else if (New->getType()->isObjCObjectPointerType() &&
3907                Old->getType()->isObjCObjectPointerType()) {
3908       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3909                                               Old->getType());
3910     }
3911   } else {
3912     // C 6.2.7p2:
3913     //   All declarations that refer to the same object or function shall have
3914     //   compatible type.
3915     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3916   }
3917   if (MergedT.isNull()) {
3918     // It's OK if we couldn't merge types if either type is dependent, for a
3919     // block-scope variable. In other cases (static data members of class
3920     // templates, variable templates, ...), we require the types to be
3921     // equivalent.
3922     // FIXME: The C++ standard doesn't say anything about this.
3923     if ((New->getType()->isDependentType() ||
3924          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3925       // If the old type was dependent, we can't merge with it, so the new type
3926       // becomes dependent for now. We'll reproduce the original type when we
3927       // instantiate the TypeSourceInfo for the variable.
3928       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3929         New->setType(Context.DependentTy);
3930       return;
3931     }
3932     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3933   }
3934 
3935   // Don't actually update the type on the new declaration if the old
3936   // declaration was an extern declaration in a different scope.
3937   if (MergeTypeWithOld)
3938     New->setType(MergedT);
3939 }
3940 
3941 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3942                                   LookupResult &Previous) {
3943   // C11 6.2.7p4:
3944   //   For an identifier with internal or external linkage declared
3945   //   in a scope in which a prior declaration of that identifier is
3946   //   visible, if the prior declaration specifies internal or
3947   //   external linkage, the type of the identifier at the later
3948   //   declaration becomes the composite type.
3949   //
3950   // If the variable isn't visible, we do not merge with its type.
3951   if (Previous.isShadowed())
3952     return false;
3953 
3954   if (S.getLangOpts().CPlusPlus) {
3955     // C++11 [dcl.array]p3:
3956     //   If there is a preceding declaration of the entity in the same
3957     //   scope in which the bound was specified, an omitted array bound
3958     //   is taken to be the same as in that earlier declaration.
3959     return NewVD->isPreviousDeclInSameBlockScope() ||
3960            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3961             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3962   } else {
3963     // If the old declaration was function-local, don't merge with its
3964     // type unless we're in the same function.
3965     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3966            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3967   }
3968 }
3969 
3970 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3971 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3972 /// situation, merging decls or emitting diagnostics as appropriate.
3973 ///
3974 /// Tentative definition rules (C99 6.9.2p2) are checked by
3975 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3976 /// definitions here, since the initializer hasn't been attached.
3977 ///
3978 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3979   // If the new decl is already invalid, don't do any other checking.
3980   if (New->isInvalidDecl())
3981     return;
3982 
3983   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3984     return;
3985 
3986   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3987 
3988   // Verify the old decl was also a variable or variable template.
3989   VarDecl *Old = nullptr;
3990   VarTemplateDecl *OldTemplate = nullptr;
3991   if (Previous.isSingleResult()) {
3992     if (NewTemplate) {
3993       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3994       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3995 
3996       if (auto *Shadow =
3997               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3998         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3999           return New->setInvalidDecl();
4000     } else {
4001       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4002 
4003       if (auto *Shadow =
4004               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4005         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4006           return New->setInvalidDecl();
4007     }
4008   }
4009   if (!Old) {
4010     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4011         << New->getDeclName();
4012     notePreviousDefinition(Previous.getRepresentativeDecl(),
4013                            New->getLocation());
4014     return New->setInvalidDecl();
4015   }
4016 
4017   // Ensure the template parameters are compatible.
4018   if (NewTemplate &&
4019       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4020                                       OldTemplate->getTemplateParameters(),
4021                                       /*Complain=*/true, TPL_TemplateMatch))
4022     return New->setInvalidDecl();
4023 
4024   // C++ [class.mem]p1:
4025   //   A member shall not be declared twice in the member-specification [...]
4026   //
4027   // Here, we need only consider static data members.
4028   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4029     Diag(New->getLocation(), diag::err_duplicate_member)
4030       << New->getIdentifier();
4031     Diag(Old->getLocation(), diag::note_previous_declaration);
4032     New->setInvalidDecl();
4033   }
4034 
4035   mergeDeclAttributes(New, Old);
4036   // Warn if an already-declared variable is made a weak_import in a subsequent
4037   // declaration
4038   if (New->hasAttr<WeakImportAttr>() &&
4039       Old->getStorageClass() == SC_None &&
4040       !Old->hasAttr<WeakImportAttr>()) {
4041     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4042     notePreviousDefinition(Old, New->getLocation());
4043     // Remove weak_import attribute on new declaration.
4044     New->dropAttr<WeakImportAttr>();
4045   }
4046 
4047   if (New->hasAttr<InternalLinkageAttr>() &&
4048       !Old->hasAttr<InternalLinkageAttr>()) {
4049     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4050         << New->getDeclName();
4051     notePreviousDefinition(Old, New->getLocation());
4052     New->dropAttr<InternalLinkageAttr>();
4053   }
4054 
4055   // Merge the types.
4056   VarDecl *MostRecent = Old->getMostRecentDecl();
4057   if (MostRecent != Old) {
4058     MergeVarDeclTypes(New, MostRecent,
4059                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4060     if (New->isInvalidDecl())
4061       return;
4062   }
4063 
4064   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4065   if (New->isInvalidDecl())
4066     return;
4067 
4068   diag::kind PrevDiag;
4069   SourceLocation OldLocation;
4070   std::tie(PrevDiag, OldLocation) =
4071       getNoteDiagForInvalidRedeclaration(Old, New);
4072 
4073   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4074   if (New->getStorageClass() == SC_Static &&
4075       !New->isStaticDataMember() &&
4076       Old->hasExternalFormalLinkage()) {
4077     if (getLangOpts().MicrosoftExt) {
4078       Diag(New->getLocation(), diag::ext_static_non_static)
4079           << New->getDeclName();
4080       Diag(OldLocation, PrevDiag);
4081     } else {
4082       Diag(New->getLocation(), diag::err_static_non_static)
4083           << New->getDeclName();
4084       Diag(OldLocation, PrevDiag);
4085       return New->setInvalidDecl();
4086     }
4087   }
4088   // C99 6.2.2p4:
4089   //   For an identifier declared with the storage-class specifier
4090   //   extern in a scope in which a prior declaration of that
4091   //   identifier is visible,23) if the prior declaration specifies
4092   //   internal or external linkage, the linkage of the identifier at
4093   //   the later declaration is the same as the linkage specified at
4094   //   the prior declaration. If no prior declaration is visible, or
4095   //   if the prior declaration specifies no linkage, then the
4096   //   identifier has external linkage.
4097   if (New->hasExternalStorage() && Old->hasLinkage())
4098     /* Okay */;
4099   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4100            !New->isStaticDataMember() &&
4101            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4102     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4103     Diag(OldLocation, PrevDiag);
4104     return New->setInvalidDecl();
4105   }
4106 
4107   // Check if extern is followed by non-extern and vice-versa.
4108   if (New->hasExternalStorage() &&
4109       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4110     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4111     Diag(OldLocation, PrevDiag);
4112     return New->setInvalidDecl();
4113   }
4114   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4115       !New->hasExternalStorage()) {
4116     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4117     Diag(OldLocation, PrevDiag);
4118     return New->setInvalidDecl();
4119   }
4120 
4121   if (CheckRedeclarationModuleOwnership(New, Old))
4122     return;
4123 
4124   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4125 
4126   // FIXME: The test for external storage here seems wrong? We still
4127   // need to check for mismatches.
4128   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4129       // Don't complain about out-of-line definitions of static members.
4130       !(Old->getLexicalDeclContext()->isRecord() &&
4131         !New->getLexicalDeclContext()->isRecord())) {
4132     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4133     Diag(OldLocation, PrevDiag);
4134     return New->setInvalidDecl();
4135   }
4136 
4137   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4138     if (VarDecl *Def = Old->getDefinition()) {
4139       // C++1z [dcl.fcn.spec]p4:
4140       //   If the definition of a variable appears in a translation unit before
4141       //   its first declaration as inline, the program is ill-formed.
4142       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4143       Diag(Def->getLocation(), diag::note_previous_definition);
4144     }
4145   }
4146 
4147   // If this redeclaration makes the variable inline, we may need to add it to
4148   // UndefinedButUsed.
4149   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4150       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4151     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4152                                            SourceLocation()));
4153 
4154   if (New->getTLSKind() != Old->getTLSKind()) {
4155     if (!Old->getTLSKind()) {
4156       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4157       Diag(OldLocation, PrevDiag);
4158     } else if (!New->getTLSKind()) {
4159       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4160       Diag(OldLocation, PrevDiag);
4161     } else {
4162       // Do not allow redeclaration to change the variable between requiring
4163       // static and dynamic initialization.
4164       // FIXME: GCC allows this, but uses the TLS keyword on the first
4165       // declaration to determine the kind. Do we need to be compatible here?
4166       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4167         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4168       Diag(OldLocation, PrevDiag);
4169     }
4170   }
4171 
4172   // C++ doesn't have tentative definitions, so go right ahead and check here.
4173   if (getLangOpts().CPlusPlus &&
4174       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4175     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4176         Old->getCanonicalDecl()->isConstexpr()) {
4177       // This definition won't be a definition any more once it's been merged.
4178       Diag(New->getLocation(),
4179            diag::warn_deprecated_redundant_constexpr_static_def);
4180     } else if (VarDecl *Def = Old->getDefinition()) {
4181       if (checkVarDeclRedefinition(Def, New))
4182         return;
4183     }
4184   }
4185 
4186   if (haveIncompatibleLanguageLinkages(Old, New)) {
4187     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4188     Diag(OldLocation, PrevDiag);
4189     New->setInvalidDecl();
4190     return;
4191   }
4192 
4193   // Merge "used" flag.
4194   if (Old->getMostRecentDecl()->isUsed(false))
4195     New->setIsUsed();
4196 
4197   // Keep a chain of previous declarations.
4198   New->setPreviousDecl(Old);
4199   if (NewTemplate)
4200     NewTemplate->setPreviousDecl(OldTemplate);
4201   adjustDeclContextForDeclaratorDecl(New, Old);
4202 
4203   // Inherit access appropriately.
4204   New->setAccess(Old->getAccess());
4205   if (NewTemplate)
4206     NewTemplate->setAccess(New->getAccess());
4207 
4208   if (Old->isInline())
4209     New->setImplicitlyInline();
4210 }
4211 
4212 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4213   SourceManager &SrcMgr = getSourceManager();
4214   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4215   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4216   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4217   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4218   auto &HSI = PP.getHeaderSearchInfo();
4219   StringRef HdrFilename =
4220       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4221 
4222   auto noteFromModuleOrInclude = [&](Module *Mod,
4223                                      SourceLocation IncLoc) -> bool {
4224     // Redefinition errors with modules are common with non modular mapped
4225     // headers, example: a non-modular header H in module A that also gets
4226     // included directly in a TU. Pointing twice to the same header/definition
4227     // is confusing, try to get better diagnostics when modules is on.
4228     if (IncLoc.isValid()) {
4229       if (Mod) {
4230         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4231             << HdrFilename.str() << Mod->getFullModuleName();
4232         if (!Mod->DefinitionLoc.isInvalid())
4233           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4234               << Mod->getFullModuleName();
4235       } else {
4236         Diag(IncLoc, diag::note_redefinition_include_same_file)
4237             << HdrFilename.str();
4238       }
4239       return true;
4240     }
4241 
4242     return false;
4243   };
4244 
4245   // Is it the same file and same offset? Provide more information on why
4246   // this leads to a redefinition error.
4247   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4248     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4249     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4250     bool EmittedDiag =
4251         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4252     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4253 
4254     // If the header has no guards, emit a note suggesting one.
4255     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4256       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4257 
4258     if (EmittedDiag)
4259       return;
4260   }
4261 
4262   // Redefinition coming from different files or couldn't do better above.
4263   if (Old->getLocation().isValid())
4264     Diag(Old->getLocation(), diag::note_previous_definition);
4265 }
4266 
4267 /// We've just determined that \p Old and \p New both appear to be definitions
4268 /// of the same variable. Either diagnose or fix the problem.
4269 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4270   if (!hasVisibleDefinition(Old) &&
4271       (New->getFormalLinkage() == InternalLinkage ||
4272        New->isInline() ||
4273        New->getDescribedVarTemplate() ||
4274        New->getNumTemplateParameterLists() ||
4275        New->getDeclContext()->isDependentContext())) {
4276     // The previous definition is hidden, and multiple definitions are
4277     // permitted (in separate TUs). Demote this to a declaration.
4278     New->demoteThisDefinitionToDeclaration();
4279 
4280     // Make the canonical definition visible.
4281     if (auto *OldTD = Old->getDescribedVarTemplate())
4282       makeMergedDefinitionVisible(OldTD);
4283     makeMergedDefinitionVisible(Old);
4284     return false;
4285   } else {
4286     Diag(New->getLocation(), diag::err_redefinition) << New;
4287     notePreviousDefinition(Old, New->getLocation());
4288     New->setInvalidDecl();
4289     return true;
4290   }
4291 }
4292 
4293 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4294 /// no declarator (e.g. "struct foo;") is parsed.
4295 Decl *
4296 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4297                                  RecordDecl *&AnonRecord) {
4298   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4299                                     AnonRecord);
4300 }
4301 
4302 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4303 // disambiguate entities defined in different scopes.
4304 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4305 // compatibility.
4306 // We will pick our mangling number depending on which version of MSVC is being
4307 // targeted.
4308 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4309   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4310              ? S->getMSCurManglingNumber()
4311              : S->getMSLastManglingNumber();
4312 }
4313 
4314 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4315   if (!Context.getLangOpts().CPlusPlus)
4316     return;
4317 
4318   if (isa<CXXRecordDecl>(Tag->getParent())) {
4319     // If this tag is the direct child of a class, number it if
4320     // it is anonymous.
4321     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4322       return;
4323     MangleNumberingContext &MCtx =
4324         Context.getManglingNumberContext(Tag->getParent());
4325     Context.setManglingNumber(
4326         Tag, MCtx.getManglingNumber(
4327                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4328     return;
4329   }
4330 
4331   // If this tag isn't a direct child of a class, number it if it is local.
4332   MangleNumberingContext *MCtx;
4333   Decl *ManglingContextDecl;
4334   std::tie(MCtx, ManglingContextDecl) =
4335       getCurrentMangleNumberContext(Tag->getDeclContext());
4336   if (MCtx) {
4337     Context.setManglingNumber(
4338         Tag, MCtx->getManglingNumber(
4339                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4340   }
4341 }
4342 
4343 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4344                                         TypedefNameDecl *NewTD) {
4345   if (TagFromDeclSpec->isInvalidDecl())
4346     return;
4347 
4348   // Do nothing if the tag already has a name for linkage purposes.
4349   if (TagFromDeclSpec->hasNameForLinkage())
4350     return;
4351 
4352   // A well-formed anonymous tag must always be a TUK_Definition.
4353   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4354 
4355   // The type must match the tag exactly;  no qualifiers allowed.
4356   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4357                            Context.getTagDeclType(TagFromDeclSpec))) {
4358     if (getLangOpts().CPlusPlus)
4359       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4360     return;
4361   }
4362 
4363   // If we've already computed linkage for the anonymous tag, then
4364   // adding a typedef name for the anonymous decl can change that
4365   // linkage, which might be a serious problem.  Diagnose this as
4366   // unsupported and ignore the typedef name.  TODO: we should
4367   // pursue this as a language defect and establish a formal rule
4368   // for how to handle it.
4369   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4370     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4371 
4372     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4373     tagLoc = getLocForEndOfToken(tagLoc);
4374 
4375     llvm::SmallString<40> textToInsert;
4376     textToInsert += ' ';
4377     textToInsert += NewTD->getIdentifier()->getName();
4378     Diag(tagLoc, diag::note_typedef_changes_linkage)
4379         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4380     return;
4381   }
4382 
4383   // Otherwise, set this is the anon-decl typedef for the tag.
4384   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4385 }
4386 
4387 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4388   switch (T) {
4389   case DeclSpec::TST_class:
4390     return 0;
4391   case DeclSpec::TST_struct:
4392     return 1;
4393   case DeclSpec::TST_interface:
4394     return 2;
4395   case DeclSpec::TST_union:
4396     return 3;
4397   case DeclSpec::TST_enum:
4398     return 4;
4399   default:
4400     llvm_unreachable("unexpected type specifier");
4401   }
4402 }
4403 
4404 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4405 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4406 /// parameters to cope with template friend declarations.
4407 Decl *
4408 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4409                                  MultiTemplateParamsArg TemplateParams,
4410                                  bool IsExplicitInstantiation,
4411                                  RecordDecl *&AnonRecord) {
4412   Decl *TagD = nullptr;
4413   TagDecl *Tag = nullptr;
4414   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4415       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4416       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4417       DS.getTypeSpecType() == DeclSpec::TST_union ||
4418       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4419     TagD = DS.getRepAsDecl();
4420 
4421     if (!TagD) // We probably had an error
4422       return nullptr;
4423 
4424     // Note that the above type specs guarantee that the
4425     // type rep is a Decl, whereas in many of the others
4426     // it's a Type.
4427     if (isa<TagDecl>(TagD))
4428       Tag = cast<TagDecl>(TagD);
4429     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4430       Tag = CTD->getTemplatedDecl();
4431   }
4432 
4433   if (Tag) {
4434     handleTagNumbering(Tag, S);
4435     Tag->setFreeStanding();
4436     if (Tag->isInvalidDecl())
4437       return Tag;
4438   }
4439 
4440   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4441     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4442     // or incomplete types shall not be restrict-qualified."
4443     if (TypeQuals & DeclSpec::TQ_restrict)
4444       Diag(DS.getRestrictSpecLoc(),
4445            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4446            << DS.getSourceRange();
4447   }
4448 
4449   if (DS.isInlineSpecified())
4450     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4451         << getLangOpts().CPlusPlus17;
4452 
4453   if (DS.hasConstexprSpecifier()) {
4454     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4455     // and definitions of functions and variables.
4456     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4457     // the declaration of a function or function template
4458     if (Tag)
4459       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4460           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4461           << DS.getConstexprSpecifier();
4462     else
4463       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4464           << DS.getConstexprSpecifier();
4465     // Don't emit warnings after this error.
4466     return TagD;
4467   }
4468 
4469   DiagnoseFunctionSpecifiers(DS);
4470 
4471   if (DS.isFriendSpecified()) {
4472     // If we're dealing with a decl but not a TagDecl, assume that
4473     // whatever routines created it handled the friendship aspect.
4474     if (TagD && !Tag)
4475       return nullptr;
4476     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4477   }
4478 
4479   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4480   bool IsExplicitSpecialization =
4481     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4482   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4483       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4484       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4485     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4486     // nested-name-specifier unless it is an explicit instantiation
4487     // or an explicit specialization.
4488     //
4489     // FIXME: We allow class template partial specializations here too, per the
4490     // obvious intent of DR1819.
4491     //
4492     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4493     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4494         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4495     return nullptr;
4496   }
4497 
4498   // Track whether this decl-specifier declares anything.
4499   bool DeclaresAnything = true;
4500 
4501   // Handle anonymous struct definitions.
4502   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4503     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4504         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4505       if (getLangOpts().CPlusPlus ||
4506           Record->getDeclContext()->isRecord()) {
4507         // If CurContext is a DeclContext that can contain statements,
4508         // RecursiveASTVisitor won't visit the decls that
4509         // BuildAnonymousStructOrUnion() will put into CurContext.
4510         // Also store them here so that they can be part of the
4511         // DeclStmt that gets created in this case.
4512         // FIXME: Also return the IndirectFieldDecls created by
4513         // BuildAnonymousStructOr union, for the same reason?
4514         if (CurContext->isFunctionOrMethod())
4515           AnonRecord = Record;
4516         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4517                                            Context.getPrintingPolicy());
4518       }
4519 
4520       DeclaresAnything = false;
4521     }
4522   }
4523 
4524   // C11 6.7.2.1p2:
4525   //   A struct-declaration that does not declare an anonymous structure or
4526   //   anonymous union shall contain a struct-declarator-list.
4527   //
4528   // This rule also existed in C89 and C99; the grammar for struct-declaration
4529   // did not permit a struct-declaration without a struct-declarator-list.
4530   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4531       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4532     // Check for Microsoft C extension: anonymous struct/union member.
4533     // Handle 2 kinds of anonymous struct/union:
4534     //   struct STRUCT;
4535     //   union UNION;
4536     // and
4537     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4538     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4539     if ((Tag && Tag->getDeclName()) ||
4540         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4541       RecordDecl *Record = nullptr;
4542       if (Tag)
4543         Record = dyn_cast<RecordDecl>(Tag);
4544       else if (const RecordType *RT =
4545                    DS.getRepAsType().get()->getAsStructureType())
4546         Record = RT->getDecl();
4547       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4548         Record = UT->getDecl();
4549 
4550       if (Record && getLangOpts().MicrosoftExt) {
4551         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4552             << Record->isUnion() << DS.getSourceRange();
4553         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4554       }
4555 
4556       DeclaresAnything = false;
4557     }
4558   }
4559 
4560   // Skip all the checks below if we have a type error.
4561   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4562       (TagD && TagD->isInvalidDecl()))
4563     return TagD;
4564 
4565   if (getLangOpts().CPlusPlus &&
4566       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4567     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4568       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4569           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4570         DeclaresAnything = false;
4571 
4572   if (!DS.isMissingDeclaratorOk()) {
4573     // Customize diagnostic for a typedef missing a name.
4574     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4575       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4576           << DS.getSourceRange();
4577     else
4578       DeclaresAnything = false;
4579   }
4580 
4581   if (DS.isModulePrivateSpecified() &&
4582       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4583     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4584       << Tag->getTagKind()
4585       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4586 
4587   ActOnDocumentableDecl(TagD);
4588 
4589   // C 6.7/2:
4590   //   A declaration [...] shall declare at least a declarator [...], a tag,
4591   //   or the members of an enumeration.
4592   // C++ [dcl.dcl]p3:
4593   //   [If there are no declarators], and except for the declaration of an
4594   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4595   //   names into the program, or shall redeclare a name introduced by a
4596   //   previous declaration.
4597   if (!DeclaresAnything) {
4598     // In C, we allow this as a (popular) extension / bug. Don't bother
4599     // producing further diagnostics for redundant qualifiers after this.
4600     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4601     return TagD;
4602   }
4603 
4604   // C++ [dcl.stc]p1:
4605   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4606   //   init-declarator-list of the declaration shall not be empty.
4607   // C++ [dcl.fct.spec]p1:
4608   //   If a cv-qualifier appears in a decl-specifier-seq, the
4609   //   init-declarator-list of the declaration shall not be empty.
4610   //
4611   // Spurious qualifiers here appear to be valid in C.
4612   unsigned DiagID = diag::warn_standalone_specifier;
4613   if (getLangOpts().CPlusPlus)
4614     DiagID = diag::ext_standalone_specifier;
4615 
4616   // Note that a linkage-specification sets a storage class, but
4617   // 'extern "C" struct foo;' is actually valid and not theoretically
4618   // useless.
4619   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4620     if (SCS == DeclSpec::SCS_mutable)
4621       // Since mutable is not a viable storage class specifier in C, there is
4622       // no reason to treat it as an extension. Instead, diagnose as an error.
4623       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4624     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4625       Diag(DS.getStorageClassSpecLoc(), DiagID)
4626         << DeclSpec::getSpecifierName(SCS);
4627   }
4628 
4629   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4630     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4631       << DeclSpec::getSpecifierName(TSCS);
4632   if (DS.getTypeQualifiers()) {
4633     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4634       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4635     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4636       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4637     // Restrict is covered above.
4638     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4639       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4640     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4641       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4642   }
4643 
4644   // Warn about ignored type attributes, for example:
4645   // __attribute__((aligned)) struct A;
4646   // Attributes should be placed after tag to apply to type declaration.
4647   if (!DS.getAttributes().empty()) {
4648     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4649     if (TypeSpecType == DeclSpec::TST_class ||
4650         TypeSpecType == DeclSpec::TST_struct ||
4651         TypeSpecType == DeclSpec::TST_interface ||
4652         TypeSpecType == DeclSpec::TST_union ||
4653         TypeSpecType == DeclSpec::TST_enum) {
4654       for (const ParsedAttr &AL : DS.getAttributes())
4655         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4656             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4657     }
4658   }
4659 
4660   return TagD;
4661 }
4662 
4663 /// We are trying to inject an anonymous member into the given scope;
4664 /// check if there's an existing declaration that can't be overloaded.
4665 ///
4666 /// \return true if this is a forbidden redeclaration
4667 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4668                                          Scope *S,
4669                                          DeclContext *Owner,
4670                                          DeclarationName Name,
4671                                          SourceLocation NameLoc,
4672                                          bool IsUnion) {
4673   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4674                  Sema::ForVisibleRedeclaration);
4675   if (!SemaRef.LookupName(R, S)) return false;
4676 
4677   // Pick a representative declaration.
4678   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4679   assert(PrevDecl && "Expected a non-null Decl");
4680 
4681   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4682     return false;
4683 
4684   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4685     << IsUnion << Name;
4686   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4687 
4688   return true;
4689 }
4690 
4691 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4692 /// anonymous struct or union AnonRecord into the owning context Owner
4693 /// and scope S. This routine will be invoked just after we realize
4694 /// that an unnamed union or struct is actually an anonymous union or
4695 /// struct, e.g.,
4696 ///
4697 /// @code
4698 /// union {
4699 ///   int i;
4700 ///   float f;
4701 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4702 ///    // f into the surrounding scope.x
4703 /// @endcode
4704 ///
4705 /// This routine is recursive, injecting the names of nested anonymous
4706 /// structs/unions into the owning context and scope as well.
4707 static bool
4708 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4709                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4710                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4711   bool Invalid = false;
4712 
4713   // Look every FieldDecl and IndirectFieldDecl with a name.
4714   for (auto *D : AnonRecord->decls()) {
4715     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4716         cast<NamedDecl>(D)->getDeclName()) {
4717       ValueDecl *VD = cast<ValueDecl>(D);
4718       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4719                                        VD->getLocation(),
4720                                        AnonRecord->isUnion())) {
4721         // C++ [class.union]p2:
4722         //   The names of the members of an anonymous union shall be
4723         //   distinct from the names of any other entity in the
4724         //   scope in which the anonymous union is declared.
4725         Invalid = true;
4726       } else {
4727         // C++ [class.union]p2:
4728         //   For the purpose of name lookup, after the anonymous union
4729         //   definition, the members of the anonymous union are
4730         //   considered to have been defined in the scope in which the
4731         //   anonymous union is declared.
4732         unsigned OldChainingSize = Chaining.size();
4733         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4734           Chaining.append(IF->chain_begin(), IF->chain_end());
4735         else
4736           Chaining.push_back(VD);
4737 
4738         assert(Chaining.size() >= 2);
4739         NamedDecl **NamedChain =
4740           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4741         for (unsigned i = 0; i < Chaining.size(); i++)
4742           NamedChain[i] = Chaining[i];
4743 
4744         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4745             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4746             VD->getType(), {NamedChain, Chaining.size()});
4747 
4748         for (const auto *Attr : VD->attrs())
4749           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4750 
4751         IndirectField->setAccess(AS);
4752         IndirectField->setImplicit();
4753         SemaRef.PushOnScopeChains(IndirectField, S);
4754 
4755         // That includes picking up the appropriate access specifier.
4756         if (AS != AS_none) IndirectField->setAccess(AS);
4757 
4758         Chaining.resize(OldChainingSize);
4759       }
4760     }
4761   }
4762 
4763   return Invalid;
4764 }
4765 
4766 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4767 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4768 /// illegal input values are mapped to SC_None.
4769 static StorageClass
4770 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4771   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4772   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4773          "Parser allowed 'typedef' as storage class VarDecl.");
4774   switch (StorageClassSpec) {
4775   case DeclSpec::SCS_unspecified:    return SC_None;
4776   case DeclSpec::SCS_extern:
4777     if (DS.isExternInLinkageSpec())
4778       return SC_None;
4779     return SC_Extern;
4780   case DeclSpec::SCS_static:         return SC_Static;
4781   case DeclSpec::SCS_auto:           return SC_Auto;
4782   case DeclSpec::SCS_register:       return SC_Register;
4783   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4784     // Illegal SCSs map to None: error reporting is up to the caller.
4785   case DeclSpec::SCS_mutable:        // Fall through.
4786   case DeclSpec::SCS_typedef:        return SC_None;
4787   }
4788   llvm_unreachable("unknown storage class specifier");
4789 }
4790 
4791 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4792   assert(Record->hasInClassInitializer());
4793 
4794   for (const auto *I : Record->decls()) {
4795     const auto *FD = dyn_cast<FieldDecl>(I);
4796     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4797       FD = IFD->getAnonField();
4798     if (FD && FD->hasInClassInitializer())
4799       return FD->getLocation();
4800   }
4801 
4802   llvm_unreachable("couldn't find in-class initializer");
4803 }
4804 
4805 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4806                                       SourceLocation DefaultInitLoc) {
4807   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4808     return;
4809 
4810   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4811   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4812 }
4813 
4814 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4815                                       CXXRecordDecl *AnonUnion) {
4816   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4817     return;
4818 
4819   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4820 }
4821 
4822 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4823 /// anonymous structure or union. Anonymous unions are a C++ feature
4824 /// (C++ [class.union]) and a C11 feature; anonymous structures
4825 /// are a C11 feature and GNU C++ extension.
4826 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4827                                         AccessSpecifier AS,
4828                                         RecordDecl *Record,
4829                                         const PrintingPolicy &Policy) {
4830   DeclContext *Owner = Record->getDeclContext();
4831 
4832   // Diagnose whether this anonymous struct/union is an extension.
4833   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4834     Diag(Record->getLocation(), diag::ext_anonymous_union);
4835   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4836     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4837   else if (!Record->isUnion() && !getLangOpts().C11)
4838     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4839 
4840   // C and C++ require different kinds of checks for anonymous
4841   // structs/unions.
4842   bool Invalid = false;
4843   if (getLangOpts().CPlusPlus) {
4844     const char *PrevSpec = nullptr;
4845     if (Record->isUnion()) {
4846       // C++ [class.union]p6:
4847       // C++17 [class.union.anon]p2:
4848       //   Anonymous unions declared in a named namespace or in the
4849       //   global namespace shall be declared static.
4850       unsigned DiagID;
4851       DeclContext *OwnerScope = Owner->getRedeclContext();
4852       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4853           (OwnerScope->isTranslationUnit() ||
4854            (OwnerScope->isNamespace() &&
4855             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4856         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4857           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4858 
4859         // Recover by adding 'static'.
4860         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4861                                PrevSpec, DiagID, Policy);
4862       }
4863       // C++ [class.union]p6:
4864       //   A storage class is not allowed in a declaration of an
4865       //   anonymous union in a class scope.
4866       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4867                isa<RecordDecl>(Owner)) {
4868         Diag(DS.getStorageClassSpecLoc(),
4869              diag::err_anonymous_union_with_storage_spec)
4870           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4871 
4872         // Recover by removing the storage specifier.
4873         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4874                                SourceLocation(),
4875                                PrevSpec, DiagID, Context.getPrintingPolicy());
4876       }
4877     }
4878 
4879     // Ignore const/volatile/restrict qualifiers.
4880     if (DS.getTypeQualifiers()) {
4881       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4882         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4883           << Record->isUnion() << "const"
4884           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4885       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4886         Diag(DS.getVolatileSpecLoc(),
4887              diag::ext_anonymous_struct_union_qualified)
4888           << Record->isUnion() << "volatile"
4889           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4890       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4891         Diag(DS.getRestrictSpecLoc(),
4892              diag::ext_anonymous_struct_union_qualified)
4893           << Record->isUnion() << "restrict"
4894           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4895       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4896         Diag(DS.getAtomicSpecLoc(),
4897              diag::ext_anonymous_struct_union_qualified)
4898           << Record->isUnion() << "_Atomic"
4899           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4900       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4901         Diag(DS.getUnalignedSpecLoc(),
4902              diag::ext_anonymous_struct_union_qualified)
4903           << Record->isUnion() << "__unaligned"
4904           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4905 
4906       DS.ClearTypeQualifiers();
4907     }
4908 
4909     // C++ [class.union]p2:
4910     //   The member-specification of an anonymous union shall only
4911     //   define non-static data members. [Note: nested types and
4912     //   functions cannot be declared within an anonymous union. ]
4913     for (auto *Mem : Record->decls()) {
4914       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4915         // C++ [class.union]p3:
4916         //   An anonymous union shall not have private or protected
4917         //   members (clause 11).
4918         assert(FD->getAccess() != AS_none);
4919         if (FD->getAccess() != AS_public) {
4920           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4921             << Record->isUnion() << (FD->getAccess() == AS_protected);
4922           Invalid = true;
4923         }
4924 
4925         // C++ [class.union]p1
4926         //   An object of a class with a non-trivial constructor, a non-trivial
4927         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4928         //   assignment operator cannot be a member of a union, nor can an
4929         //   array of such objects.
4930         if (CheckNontrivialField(FD))
4931           Invalid = true;
4932       } else if (Mem->isImplicit()) {
4933         // Any implicit members are fine.
4934       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4935         // This is a type that showed up in an
4936         // elaborated-type-specifier inside the anonymous struct or
4937         // union, but which actually declares a type outside of the
4938         // anonymous struct or union. It's okay.
4939       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4940         if (!MemRecord->isAnonymousStructOrUnion() &&
4941             MemRecord->getDeclName()) {
4942           // Visual C++ allows type definition in anonymous struct or union.
4943           if (getLangOpts().MicrosoftExt)
4944             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4945               << Record->isUnion();
4946           else {
4947             // This is a nested type declaration.
4948             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4949               << Record->isUnion();
4950             Invalid = true;
4951           }
4952         } else {
4953           // This is an anonymous type definition within another anonymous type.
4954           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4955           // not part of standard C++.
4956           Diag(MemRecord->getLocation(),
4957                diag::ext_anonymous_record_with_anonymous_type)
4958             << Record->isUnion();
4959         }
4960       } else if (isa<AccessSpecDecl>(Mem)) {
4961         // Any access specifier is fine.
4962       } else if (isa<StaticAssertDecl>(Mem)) {
4963         // In C++1z, static_assert declarations are also fine.
4964       } else {
4965         // We have something that isn't a non-static data
4966         // member. Complain about it.
4967         unsigned DK = diag::err_anonymous_record_bad_member;
4968         if (isa<TypeDecl>(Mem))
4969           DK = diag::err_anonymous_record_with_type;
4970         else if (isa<FunctionDecl>(Mem))
4971           DK = diag::err_anonymous_record_with_function;
4972         else if (isa<VarDecl>(Mem))
4973           DK = diag::err_anonymous_record_with_static;
4974 
4975         // Visual C++ allows type definition in anonymous struct or union.
4976         if (getLangOpts().MicrosoftExt &&
4977             DK == diag::err_anonymous_record_with_type)
4978           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4979             << Record->isUnion();
4980         else {
4981           Diag(Mem->getLocation(), DK) << Record->isUnion();
4982           Invalid = true;
4983         }
4984       }
4985     }
4986 
4987     // C++11 [class.union]p8 (DR1460):
4988     //   At most one variant member of a union may have a
4989     //   brace-or-equal-initializer.
4990     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4991         Owner->isRecord())
4992       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4993                                 cast<CXXRecordDecl>(Record));
4994   }
4995 
4996   if (!Record->isUnion() && !Owner->isRecord()) {
4997     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4998       << getLangOpts().CPlusPlus;
4999     Invalid = true;
5000   }
5001 
5002   // C++ [dcl.dcl]p3:
5003   //   [If there are no declarators], and except for the declaration of an
5004   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5005   //   names into the program
5006   // C++ [class.mem]p2:
5007   //   each such member-declaration shall either declare at least one member
5008   //   name of the class or declare at least one unnamed bit-field
5009   //
5010   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5011   if (getLangOpts().CPlusPlus && Record->field_empty())
5012     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5013 
5014   // Mock up a declarator.
5015   Declarator Dc(DS, DeclaratorContext::MemberContext);
5016   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5017   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5018 
5019   // Create a declaration for this anonymous struct/union.
5020   NamedDecl *Anon = nullptr;
5021   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5022     Anon = FieldDecl::Create(
5023         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5024         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5025         /*BitWidth=*/nullptr, /*Mutable=*/false,
5026         /*InitStyle=*/ICIS_NoInit);
5027     Anon->setAccess(AS);
5028     ProcessDeclAttributes(S, Anon, Dc);
5029 
5030     if (getLangOpts().CPlusPlus)
5031       FieldCollector->Add(cast<FieldDecl>(Anon));
5032   } else {
5033     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5034     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5035     if (SCSpec == DeclSpec::SCS_mutable) {
5036       // mutable can only appear on non-static class members, so it's always
5037       // an error here
5038       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5039       Invalid = true;
5040       SC = SC_None;
5041     }
5042 
5043     assert(DS.getAttributes().empty() && "No attribute expected");
5044     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5045                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5046                            Context.getTypeDeclType(Record), TInfo, SC);
5047 
5048     // Default-initialize the implicit variable. This initialization will be
5049     // trivial in almost all cases, except if a union member has an in-class
5050     // initializer:
5051     //   union { int n = 0; };
5052     ActOnUninitializedDecl(Anon);
5053   }
5054   Anon->setImplicit();
5055 
5056   // Mark this as an anonymous struct/union type.
5057   Record->setAnonymousStructOrUnion(true);
5058 
5059   // Add the anonymous struct/union object to the current
5060   // context. We'll be referencing this object when we refer to one of
5061   // its members.
5062   Owner->addDecl(Anon);
5063 
5064   // Inject the members of the anonymous struct/union into the owning
5065   // context and into the identifier resolver chain for name lookup
5066   // purposes.
5067   SmallVector<NamedDecl*, 2> Chain;
5068   Chain.push_back(Anon);
5069 
5070   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5071     Invalid = true;
5072 
5073   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5074     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5075       MangleNumberingContext *MCtx;
5076       Decl *ManglingContextDecl;
5077       std::tie(MCtx, ManglingContextDecl) =
5078           getCurrentMangleNumberContext(NewVD->getDeclContext());
5079       if (MCtx) {
5080         Context.setManglingNumber(
5081             NewVD, MCtx->getManglingNumber(
5082                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5083         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5084       }
5085     }
5086   }
5087 
5088   if (Invalid)
5089     Anon->setInvalidDecl();
5090 
5091   return Anon;
5092 }
5093 
5094 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5095 /// Microsoft C anonymous structure.
5096 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5097 /// Example:
5098 ///
5099 /// struct A { int a; };
5100 /// struct B { struct A; int b; };
5101 ///
5102 /// void foo() {
5103 ///   B var;
5104 ///   var.a = 3;
5105 /// }
5106 ///
5107 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5108                                            RecordDecl *Record) {
5109   assert(Record && "expected a record!");
5110 
5111   // Mock up a declarator.
5112   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5113   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5114   assert(TInfo && "couldn't build declarator info for anonymous struct");
5115 
5116   auto *ParentDecl = cast<RecordDecl>(CurContext);
5117   QualType RecTy = Context.getTypeDeclType(Record);
5118 
5119   // Create a declaration for this anonymous struct.
5120   NamedDecl *Anon =
5121       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5122                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5123                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5124                         /*InitStyle=*/ICIS_NoInit);
5125   Anon->setImplicit();
5126 
5127   // Add the anonymous struct object to the current context.
5128   CurContext->addDecl(Anon);
5129 
5130   // Inject the members of the anonymous struct into the current
5131   // context and into the identifier resolver chain for name lookup
5132   // purposes.
5133   SmallVector<NamedDecl*, 2> Chain;
5134   Chain.push_back(Anon);
5135 
5136   RecordDecl *RecordDef = Record->getDefinition();
5137   if (RequireCompleteType(Anon->getLocation(), RecTy,
5138                           diag::err_field_incomplete) ||
5139       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5140                                           AS_none, Chain)) {
5141     Anon->setInvalidDecl();
5142     ParentDecl->setInvalidDecl();
5143   }
5144 
5145   return Anon;
5146 }
5147 
5148 /// GetNameForDeclarator - Determine the full declaration name for the
5149 /// given Declarator.
5150 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5151   return GetNameFromUnqualifiedId(D.getName());
5152 }
5153 
5154 /// Retrieves the declaration name from a parsed unqualified-id.
5155 DeclarationNameInfo
5156 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5157   DeclarationNameInfo NameInfo;
5158   NameInfo.setLoc(Name.StartLocation);
5159 
5160   switch (Name.getKind()) {
5161 
5162   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5163   case UnqualifiedIdKind::IK_Identifier:
5164     NameInfo.setName(Name.Identifier);
5165     return NameInfo;
5166 
5167   case UnqualifiedIdKind::IK_DeductionGuideName: {
5168     // C++ [temp.deduct.guide]p3:
5169     //   The simple-template-id shall name a class template specialization.
5170     //   The template-name shall be the same identifier as the template-name
5171     //   of the simple-template-id.
5172     // These together intend to imply that the template-name shall name a
5173     // class template.
5174     // FIXME: template<typename T> struct X {};
5175     //        template<typename T> using Y = X<T>;
5176     //        Y(int) -> Y<int>;
5177     //   satisfies these rules but does not name a class template.
5178     TemplateName TN = Name.TemplateName.get().get();
5179     auto *Template = TN.getAsTemplateDecl();
5180     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5181       Diag(Name.StartLocation,
5182            diag::err_deduction_guide_name_not_class_template)
5183         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5184       if (Template)
5185         Diag(Template->getLocation(), diag::note_template_decl_here);
5186       return DeclarationNameInfo();
5187     }
5188 
5189     NameInfo.setName(
5190         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5191     return NameInfo;
5192   }
5193 
5194   case UnqualifiedIdKind::IK_OperatorFunctionId:
5195     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5196                                            Name.OperatorFunctionId.Operator));
5197     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5198       = Name.OperatorFunctionId.SymbolLocations[0];
5199     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5200       = Name.EndLocation.getRawEncoding();
5201     return NameInfo;
5202 
5203   case UnqualifiedIdKind::IK_LiteralOperatorId:
5204     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5205                                                            Name.Identifier));
5206     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5207     return NameInfo;
5208 
5209   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5210     TypeSourceInfo *TInfo;
5211     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5212     if (Ty.isNull())
5213       return DeclarationNameInfo();
5214     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5215                                                Context.getCanonicalType(Ty)));
5216     NameInfo.setNamedTypeInfo(TInfo);
5217     return NameInfo;
5218   }
5219 
5220   case UnqualifiedIdKind::IK_ConstructorName: {
5221     TypeSourceInfo *TInfo;
5222     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5223     if (Ty.isNull())
5224       return DeclarationNameInfo();
5225     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5226                                               Context.getCanonicalType(Ty)));
5227     NameInfo.setNamedTypeInfo(TInfo);
5228     return NameInfo;
5229   }
5230 
5231   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5232     // In well-formed code, we can only have a constructor
5233     // template-id that refers to the current context, so go there
5234     // to find the actual type being constructed.
5235     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5236     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5237       return DeclarationNameInfo();
5238 
5239     // Determine the type of the class being constructed.
5240     QualType CurClassType = Context.getTypeDeclType(CurClass);
5241 
5242     // FIXME: Check two things: that the template-id names the same type as
5243     // CurClassType, and that the template-id does not occur when the name
5244     // was qualified.
5245 
5246     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5247                                     Context.getCanonicalType(CurClassType)));
5248     // FIXME: should we retrieve TypeSourceInfo?
5249     NameInfo.setNamedTypeInfo(nullptr);
5250     return NameInfo;
5251   }
5252 
5253   case UnqualifiedIdKind::IK_DestructorName: {
5254     TypeSourceInfo *TInfo;
5255     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5256     if (Ty.isNull())
5257       return DeclarationNameInfo();
5258     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5259                                               Context.getCanonicalType(Ty)));
5260     NameInfo.setNamedTypeInfo(TInfo);
5261     return NameInfo;
5262   }
5263 
5264   case UnqualifiedIdKind::IK_TemplateId: {
5265     TemplateName TName = Name.TemplateId->Template.get();
5266     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5267     return Context.getNameForTemplate(TName, TNameLoc);
5268   }
5269 
5270   } // switch (Name.getKind())
5271 
5272   llvm_unreachable("Unknown name kind");
5273 }
5274 
5275 static QualType getCoreType(QualType Ty) {
5276   do {
5277     if (Ty->isPointerType() || Ty->isReferenceType())
5278       Ty = Ty->getPointeeType();
5279     else if (Ty->isArrayType())
5280       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5281     else
5282       return Ty.withoutLocalFastQualifiers();
5283   } while (true);
5284 }
5285 
5286 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5287 /// and Definition have "nearly" matching parameters. This heuristic is
5288 /// used to improve diagnostics in the case where an out-of-line function
5289 /// definition doesn't match any declaration within the class or namespace.
5290 /// Also sets Params to the list of indices to the parameters that differ
5291 /// between the declaration and the definition. If hasSimilarParameters
5292 /// returns true and Params is empty, then all of the parameters match.
5293 static bool hasSimilarParameters(ASTContext &Context,
5294                                      FunctionDecl *Declaration,
5295                                      FunctionDecl *Definition,
5296                                      SmallVectorImpl<unsigned> &Params) {
5297   Params.clear();
5298   if (Declaration->param_size() != Definition->param_size())
5299     return false;
5300   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5301     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5302     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5303 
5304     // The parameter types are identical
5305     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5306       continue;
5307 
5308     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5309     QualType DefParamBaseTy = getCoreType(DefParamTy);
5310     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5311     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5312 
5313     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5314         (DeclTyName && DeclTyName == DefTyName))
5315       Params.push_back(Idx);
5316     else  // The two parameters aren't even close
5317       return false;
5318   }
5319 
5320   return true;
5321 }
5322 
5323 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5324 /// declarator needs to be rebuilt in the current instantiation.
5325 /// Any bits of declarator which appear before the name are valid for
5326 /// consideration here.  That's specifically the type in the decl spec
5327 /// and the base type in any member-pointer chunks.
5328 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5329                                                     DeclarationName Name) {
5330   // The types we specifically need to rebuild are:
5331   //   - typenames, typeofs, and decltypes
5332   //   - types which will become injected class names
5333   // Of course, we also need to rebuild any type referencing such a
5334   // type.  It's safest to just say "dependent", but we call out a
5335   // few cases here.
5336 
5337   DeclSpec &DS = D.getMutableDeclSpec();
5338   switch (DS.getTypeSpecType()) {
5339   case DeclSpec::TST_typename:
5340   case DeclSpec::TST_typeofType:
5341   case DeclSpec::TST_underlyingType:
5342   case DeclSpec::TST_atomic: {
5343     // Grab the type from the parser.
5344     TypeSourceInfo *TSI = nullptr;
5345     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5346     if (T.isNull() || !T->isDependentType()) break;
5347 
5348     // Make sure there's a type source info.  This isn't really much
5349     // of a waste; most dependent types should have type source info
5350     // attached already.
5351     if (!TSI)
5352       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5353 
5354     // Rebuild the type in the current instantiation.
5355     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5356     if (!TSI) return true;
5357 
5358     // Store the new type back in the decl spec.
5359     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5360     DS.UpdateTypeRep(LocType);
5361     break;
5362   }
5363 
5364   case DeclSpec::TST_decltype:
5365   case DeclSpec::TST_typeofExpr: {
5366     Expr *E = DS.getRepAsExpr();
5367     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5368     if (Result.isInvalid()) return true;
5369     DS.UpdateExprRep(Result.get());
5370     break;
5371   }
5372 
5373   default:
5374     // Nothing to do for these decl specs.
5375     break;
5376   }
5377 
5378   // It doesn't matter what order we do this in.
5379   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5380     DeclaratorChunk &Chunk = D.getTypeObject(I);
5381 
5382     // The only type information in the declarator which can come
5383     // before the declaration name is the base type of a member
5384     // pointer.
5385     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5386       continue;
5387 
5388     // Rebuild the scope specifier in-place.
5389     CXXScopeSpec &SS = Chunk.Mem.Scope();
5390     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5391       return true;
5392   }
5393 
5394   return false;
5395 }
5396 
5397 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5398   D.setFunctionDefinitionKind(FDK_Declaration);
5399   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5400 
5401   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5402       Dcl && Dcl->getDeclContext()->isFileContext())
5403     Dcl->setTopLevelDeclInObjCContainer();
5404 
5405   if (getLangOpts().OpenCL)
5406     setCurrentOpenCLExtensionForDecl(Dcl);
5407 
5408   return Dcl;
5409 }
5410 
5411 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5412 ///   If T is the name of a class, then each of the following shall have a
5413 ///   name different from T:
5414 ///     - every static data member of class T;
5415 ///     - every member function of class T
5416 ///     - every member of class T that is itself a type;
5417 /// \returns true if the declaration name violates these rules.
5418 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5419                                    DeclarationNameInfo NameInfo) {
5420   DeclarationName Name = NameInfo.getName();
5421 
5422   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5423   while (Record && Record->isAnonymousStructOrUnion())
5424     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5425   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5426     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5427     return true;
5428   }
5429 
5430   return false;
5431 }
5432 
5433 /// Diagnose a declaration whose declarator-id has the given
5434 /// nested-name-specifier.
5435 ///
5436 /// \param SS The nested-name-specifier of the declarator-id.
5437 ///
5438 /// \param DC The declaration context to which the nested-name-specifier
5439 /// resolves.
5440 ///
5441 /// \param Name The name of the entity being declared.
5442 ///
5443 /// \param Loc The location of the name of the entity being declared.
5444 ///
5445 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5446 /// we're declaring an explicit / partial specialization / instantiation.
5447 ///
5448 /// \returns true if we cannot safely recover from this error, false otherwise.
5449 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5450                                         DeclarationName Name,
5451                                         SourceLocation Loc, bool IsTemplateId) {
5452   DeclContext *Cur = CurContext;
5453   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5454     Cur = Cur->getParent();
5455 
5456   // If the user provided a superfluous scope specifier that refers back to the
5457   // class in which the entity is already declared, diagnose and ignore it.
5458   //
5459   // class X {
5460   //   void X::f();
5461   // };
5462   //
5463   // Note, it was once ill-formed to give redundant qualification in all
5464   // contexts, but that rule was removed by DR482.
5465   if (Cur->Equals(DC)) {
5466     if (Cur->isRecord()) {
5467       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5468                                       : diag::err_member_extra_qualification)
5469         << Name << FixItHint::CreateRemoval(SS.getRange());
5470       SS.clear();
5471     } else {
5472       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5473     }
5474     return false;
5475   }
5476 
5477   // Check whether the qualifying scope encloses the scope of the original
5478   // declaration. For a template-id, we perform the checks in
5479   // CheckTemplateSpecializationScope.
5480   if (!Cur->Encloses(DC) && !IsTemplateId) {
5481     if (Cur->isRecord())
5482       Diag(Loc, diag::err_member_qualification)
5483         << Name << SS.getRange();
5484     else if (isa<TranslationUnitDecl>(DC))
5485       Diag(Loc, diag::err_invalid_declarator_global_scope)
5486         << Name << SS.getRange();
5487     else if (isa<FunctionDecl>(Cur))
5488       Diag(Loc, diag::err_invalid_declarator_in_function)
5489         << Name << SS.getRange();
5490     else if (isa<BlockDecl>(Cur))
5491       Diag(Loc, diag::err_invalid_declarator_in_block)
5492         << Name << SS.getRange();
5493     else
5494       Diag(Loc, diag::err_invalid_declarator_scope)
5495       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5496 
5497     return true;
5498   }
5499 
5500   if (Cur->isRecord()) {
5501     // Cannot qualify members within a class.
5502     Diag(Loc, diag::err_member_qualification)
5503       << Name << SS.getRange();
5504     SS.clear();
5505 
5506     // C++ constructors and destructors with incorrect scopes can break
5507     // our AST invariants by having the wrong underlying types. If
5508     // that's the case, then drop this declaration entirely.
5509     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5510          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5511         !Context.hasSameType(Name.getCXXNameType(),
5512                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5513       return true;
5514 
5515     return false;
5516   }
5517 
5518   // C++11 [dcl.meaning]p1:
5519   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5520   //   not begin with a decltype-specifer"
5521   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5522   while (SpecLoc.getPrefix())
5523     SpecLoc = SpecLoc.getPrefix();
5524   if (dyn_cast_or_null<DecltypeType>(
5525         SpecLoc.getNestedNameSpecifier()->getAsType()))
5526     Diag(Loc, diag::err_decltype_in_declarator)
5527       << SpecLoc.getTypeLoc().getSourceRange();
5528 
5529   return false;
5530 }
5531 
5532 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5533                                   MultiTemplateParamsArg TemplateParamLists) {
5534   // TODO: consider using NameInfo for diagnostic.
5535   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5536   DeclarationName Name = NameInfo.getName();
5537 
5538   // All of these full declarators require an identifier.  If it doesn't have
5539   // one, the ParsedFreeStandingDeclSpec action should be used.
5540   if (D.isDecompositionDeclarator()) {
5541     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5542   } else if (!Name) {
5543     if (!D.isInvalidType())  // Reject this if we think it is valid.
5544       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5545           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5546     return nullptr;
5547   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5548     return nullptr;
5549 
5550   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5551   // we find one that is.
5552   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5553          (S->getFlags() & Scope::TemplateParamScope) != 0)
5554     S = S->getParent();
5555 
5556   DeclContext *DC = CurContext;
5557   if (D.getCXXScopeSpec().isInvalid())
5558     D.setInvalidType();
5559   else if (D.getCXXScopeSpec().isSet()) {
5560     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5561                                         UPPC_DeclarationQualifier))
5562       return nullptr;
5563 
5564     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5565     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5566     if (!DC || isa<EnumDecl>(DC)) {
5567       // If we could not compute the declaration context, it's because the
5568       // declaration context is dependent but does not refer to a class,
5569       // class template, or class template partial specialization. Complain
5570       // and return early, to avoid the coming semantic disaster.
5571       Diag(D.getIdentifierLoc(),
5572            diag::err_template_qualified_declarator_no_match)
5573         << D.getCXXScopeSpec().getScopeRep()
5574         << D.getCXXScopeSpec().getRange();
5575       return nullptr;
5576     }
5577     bool IsDependentContext = DC->isDependentContext();
5578 
5579     if (!IsDependentContext &&
5580         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5581       return nullptr;
5582 
5583     // If a class is incomplete, do not parse entities inside it.
5584     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5585       Diag(D.getIdentifierLoc(),
5586            diag::err_member_def_undefined_record)
5587         << Name << DC << D.getCXXScopeSpec().getRange();
5588       return nullptr;
5589     }
5590     if (!D.getDeclSpec().isFriendSpecified()) {
5591       if (diagnoseQualifiedDeclaration(
5592               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5593               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5594         if (DC->isRecord())
5595           return nullptr;
5596 
5597         D.setInvalidType();
5598       }
5599     }
5600 
5601     // Check whether we need to rebuild the type of the given
5602     // declaration in the current instantiation.
5603     if (EnteringContext && IsDependentContext &&
5604         TemplateParamLists.size() != 0) {
5605       ContextRAII SavedContext(*this, DC);
5606       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5607         D.setInvalidType();
5608     }
5609   }
5610 
5611   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5612   QualType R = TInfo->getType();
5613 
5614   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5615                                       UPPC_DeclarationType))
5616     D.setInvalidType();
5617 
5618   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5619                         forRedeclarationInCurContext());
5620 
5621   // See if this is a redefinition of a variable in the same scope.
5622   if (!D.getCXXScopeSpec().isSet()) {
5623     bool IsLinkageLookup = false;
5624     bool CreateBuiltins = false;
5625 
5626     // If the declaration we're planning to build will be a function
5627     // or object with linkage, then look for another declaration with
5628     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5629     //
5630     // If the declaration we're planning to build will be declared with
5631     // external linkage in the translation unit, create any builtin with
5632     // the same name.
5633     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5634       /* Do nothing*/;
5635     else if (CurContext->isFunctionOrMethod() &&
5636              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5637               R->isFunctionType())) {
5638       IsLinkageLookup = true;
5639       CreateBuiltins =
5640           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5641     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5642                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5643       CreateBuiltins = true;
5644 
5645     if (IsLinkageLookup) {
5646       Previous.clear(LookupRedeclarationWithLinkage);
5647       Previous.setRedeclarationKind(ForExternalRedeclaration);
5648     }
5649 
5650     LookupName(Previous, S, CreateBuiltins);
5651   } else { // Something like "int foo::x;"
5652     LookupQualifiedName(Previous, DC);
5653 
5654     // C++ [dcl.meaning]p1:
5655     //   When the declarator-id is qualified, the declaration shall refer to a
5656     //  previously declared member of the class or namespace to which the
5657     //  qualifier refers (or, in the case of a namespace, of an element of the
5658     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5659     //  thereof; [...]
5660     //
5661     // Note that we already checked the context above, and that we do not have
5662     // enough information to make sure that Previous contains the declaration
5663     // we want to match. For example, given:
5664     //
5665     //   class X {
5666     //     void f();
5667     //     void f(float);
5668     //   };
5669     //
5670     //   void X::f(int) { } // ill-formed
5671     //
5672     // In this case, Previous will point to the overload set
5673     // containing the two f's declared in X, but neither of them
5674     // matches.
5675 
5676     // C++ [dcl.meaning]p1:
5677     //   [...] the member shall not merely have been introduced by a
5678     //   using-declaration in the scope of the class or namespace nominated by
5679     //   the nested-name-specifier of the declarator-id.
5680     RemoveUsingDecls(Previous);
5681   }
5682 
5683   if (Previous.isSingleResult() &&
5684       Previous.getFoundDecl()->isTemplateParameter()) {
5685     // Maybe we will complain about the shadowed template parameter.
5686     if (!D.isInvalidType())
5687       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5688                                       Previous.getFoundDecl());
5689 
5690     // Just pretend that we didn't see the previous declaration.
5691     Previous.clear();
5692   }
5693 
5694   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5695     // Forget that the previous declaration is the injected-class-name.
5696     Previous.clear();
5697 
5698   // In C++, the previous declaration we find might be a tag type
5699   // (class or enum). In this case, the new declaration will hide the
5700   // tag type. Note that this applies to functions, function templates, and
5701   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5702   if (Previous.isSingleTagDecl() &&
5703       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5704       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5705     Previous.clear();
5706 
5707   // Check that there are no default arguments other than in the parameters
5708   // of a function declaration (C++ only).
5709   if (getLangOpts().CPlusPlus)
5710     CheckExtraCXXDefaultArguments(D);
5711 
5712   NamedDecl *New;
5713 
5714   bool AddToScope = true;
5715   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5716     if (TemplateParamLists.size()) {
5717       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5718       return nullptr;
5719     }
5720 
5721     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5722   } else if (R->isFunctionType()) {
5723     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5724                                   TemplateParamLists,
5725                                   AddToScope);
5726   } else {
5727     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5728                                   AddToScope);
5729   }
5730 
5731   if (!New)
5732     return nullptr;
5733 
5734   // If this has an identifier and is not a function template specialization,
5735   // add it to the scope stack.
5736   if (New->getDeclName() && AddToScope)
5737     PushOnScopeChains(New, S);
5738 
5739   if (isInOpenMPDeclareTargetContext())
5740     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5741 
5742   return New;
5743 }
5744 
5745 /// Helper method to turn variable array types into constant array
5746 /// types in certain situations which would otherwise be errors (for
5747 /// GCC compatibility).
5748 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5749                                                     ASTContext &Context,
5750                                                     bool &SizeIsNegative,
5751                                                     llvm::APSInt &Oversized) {
5752   // This method tries to turn a variable array into a constant
5753   // array even when the size isn't an ICE.  This is necessary
5754   // for compatibility with code that depends on gcc's buggy
5755   // constant expression folding, like struct {char x[(int)(char*)2];}
5756   SizeIsNegative = false;
5757   Oversized = 0;
5758 
5759   if (T->isDependentType())
5760     return QualType();
5761 
5762   QualifierCollector Qs;
5763   const Type *Ty = Qs.strip(T);
5764 
5765   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5766     QualType Pointee = PTy->getPointeeType();
5767     QualType FixedType =
5768         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5769                                             Oversized);
5770     if (FixedType.isNull()) return FixedType;
5771     FixedType = Context.getPointerType(FixedType);
5772     return Qs.apply(Context, FixedType);
5773   }
5774   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5775     QualType Inner = PTy->getInnerType();
5776     QualType FixedType =
5777         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5778                                             Oversized);
5779     if (FixedType.isNull()) return FixedType;
5780     FixedType = Context.getParenType(FixedType);
5781     return Qs.apply(Context, FixedType);
5782   }
5783 
5784   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5785   if (!VLATy)
5786     return QualType();
5787   // FIXME: We should probably handle this case
5788   if (VLATy->getElementType()->isVariablyModifiedType())
5789     return QualType();
5790 
5791   Expr::EvalResult Result;
5792   if (!VLATy->getSizeExpr() ||
5793       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5794     return QualType();
5795 
5796   llvm::APSInt Res = Result.Val.getInt();
5797 
5798   // Check whether the array size is negative.
5799   if (Res.isSigned() && Res.isNegative()) {
5800     SizeIsNegative = true;
5801     return QualType();
5802   }
5803 
5804   // Check whether the array is too large to be addressed.
5805   unsigned ActiveSizeBits
5806     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5807                                               Res);
5808   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5809     Oversized = Res;
5810     return QualType();
5811   }
5812 
5813   return Context.getConstantArrayType(
5814       VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5815 }
5816 
5817 static void
5818 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5819   SrcTL = SrcTL.getUnqualifiedLoc();
5820   DstTL = DstTL.getUnqualifiedLoc();
5821   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5822     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5823     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5824                                       DstPTL.getPointeeLoc());
5825     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5826     return;
5827   }
5828   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5829     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5830     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5831                                       DstPTL.getInnerLoc());
5832     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5833     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5834     return;
5835   }
5836   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5837   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5838   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5839   TypeLoc DstElemTL = DstATL.getElementLoc();
5840   DstElemTL.initializeFullCopy(SrcElemTL);
5841   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5842   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5843   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5844 }
5845 
5846 /// Helper method to turn variable array types into constant array
5847 /// types in certain situations which would otherwise be errors (for
5848 /// GCC compatibility).
5849 static TypeSourceInfo*
5850 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5851                                               ASTContext &Context,
5852                                               bool &SizeIsNegative,
5853                                               llvm::APSInt &Oversized) {
5854   QualType FixedTy
5855     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5856                                           SizeIsNegative, Oversized);
5857   if (FixedTy.isNull())
5858     return nullptr;
5859   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5860   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5861                                     FixedTInfo->getTypeLoc());
5862   return FixedTInfo;
5863 }
5864 
5865 /// Register the given locally-scoped extern "C" declaration so
5866 /// that it can be found later for redeclarations. We include any extern "C"
5867 /// declaration that is not visible in the translation unit here, not just
5868 /// function-scope declarations.
5869 void
5870 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5871   if (!getLangOpts().CPlusPlus &&
5872       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5873     // Don't need to track declarations in the TU in C.
5874     return;
5875 
5876   // Note that we have a locally-scoped external with this name.
5877   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5878 }
5879 
5880 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5881   // FIXME: We can have multiple results via __attribute__((overloadable)).
5882   auto Result = Context.getExternCContextDecl()->lookup(Name);
5883   return Result.empty() ? nullptr : *Result.begin();
5884 }
5885 
5886 /// Diagnose function specifiers on a declaration of an identifier that
5887 /// does not identify a function.
5888 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5889   // FIXME: We should probably indicate the identifier in question to avoid
5890   // confusion for constructs like "virtual int a(), b;"
5891   if (DS.isVirtualSpecified())
5892     Diag(DS.getVirtualSpecLoc(),
5893          diag::err_virtual_non_function);
5894 
5895   if (DS.hasExplicitSpecifier())
5896     Diag(DS.getExplicitSpecLoc(),
5897          diag::err_explicit_non_function);
5898 
5899   if (DS.isNoreturnSpecified())
5900     Diag(DS.getNoreturnSpecLoc(),
5901          diag::err_noreturn_non_function);
5902 }
5903 
5904 NamedDecl*
5905 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5906                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5907   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5908   if (D.getCXXScopeSpec().isSet()) {
5909     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5910       << D.getCXXScopeSpec().getRange();
5911     D.setInvalidType();
5912     // Pretend we didn't see the scope specifier.
5913     DC = CurContext;
5914     Previous.clear();
5915   }
5916 
5917   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5918 
5919   if (D.getDeclSpec().isInlineSpecified())
5920     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5921         << getLangOpts().CPlusPlus17;
5922   if (D.getDeclSpec().hasConstexprSpecifier())
5923     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5924         << 1 << D.getDeclSpec().getConstexprSpecifier();
5925 
5926   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5927     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5928       Diag(D.getName().StartLocation,
5929            diag::err_deduction_guide_invalid_specifier)
5930           << "typedef";
5931     else
5932       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5933           << D.getName().getSourceRange();
5934     return nullptr;
5935   }
5936 
5937   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5938   if (!NewTD) return nullptr;
5939 
5940   // Handle attributes prior to checking for duplicates in MergeVarDecl
5941   ProcessDeclAttributes(S, NewTD, D);
5942 
5943   CheckTypedefForVariablyModifiedType(S, NewTD);
5944 
5945   bool Redeclaration = D.isRedeclaration();
5946   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5947   D.setRedeclaration(Redeclaration);
5948   return ND;
5949 }
5950 
5951 void
5952 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5953   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5954   // then it shall have block scope.
5955   // Note that variably modified types must be fixed before merging the decl so
5956   // that redeclarations will match.
5957   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5958   QualType T = TInfo->getType();
5959   if (T->isVariablyModifiedType()) {
5960     setFunctionHasBranchProtectedScope();
5961 
5962     if (S->getFnParent() == nullptr) {
5963       bool SizeIsNegative;
5964       llvm::APSInt Oversized;
5965       TypeSourceInfo *FixedTInfo =
5966         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5967                                                       SizeIsNegative,
5968                                                       Oversized);
5969       if (FixedTInfo) {
5970         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5971         NewTD->setTypeSourceInfo(FixedTInfo);
5972       } else {
5973         if (SizeIsNegative)
5974           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5975         else if (T->isVariableArrayType())
5976           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5977         else if (Oversized.getBoolValue())
5978           Diag(NewTD->getLocation(), diag::err_array_too_large)
5979             << Oversized.toString(10);
5980         else
5981           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5982         NewTD->setInvalidDecl();
5983       }
5984     }
5985   }
5986 }
5987 
5988 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5989 /// declares a typedef-name, either using the 'typedef' type specifier or via
5990 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5991 NamedDecl*
5992 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5993                            LookupResult &Previous, bool &Redeclaration) {
5994 
5995   // Find the shadowed declaration before filtering for scope.
5996   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5997 
5998   // Merge the decl with the existing one if appropriate. If the decl is
5999   // in an outer scope, it isn't the same thing.
6000   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6001                        /*AllowInlineNamespace*/false);
6002   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6003   if (!Previous.empty()) {
6004     Redeclaration = true;
6005     MergeTypedefNameDecl(S, NewTD, Previous);
6006   } else {
6007     inferGslPointerAttribute(NewTD);
6008   }
6009 
6010   if (ShadowedDecl && !Redeclaration)
6011     CheckShadow(NewTD, ShadowedDecl, Previous);
6012 
6013   // If this is the C FILE type, notify the AST context.
6014   if (IdentifierInfo *II = NewTD->getIdentifier())
6015     if (!NewTD->isInvalidDecl() &&
6016         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6017       if (II->isStr("FILE"))
6018         Context.setFILEDecl(NewTD);
6019       else if (II->isStr("jmp_buf"))
6020         Context.setjmp_bufDecl(NewTD);
6021       else if (II->isStr("sigjmp_buf"))
6022         Context.setsigjmp_bufDecl(NewTD);
6023       else if (II->isStr("ucontext_t"))
6024         Context.setucontext_tDecl(NewTD);
6025     }
6026 
6027   return NewTD;
6028 }
6029 
6030 /// Determines whether the given declaration is an out-of-scope
6031 /// previous declaration.
6032 ///
6033 /// This routine should be invoked when name lookup has found a
6034 /// previous declaration (PrevDecl) that is not in the scope where a
6035 /// new declaration by the same name is being introduced. If the new
6036 /// declaration occurs in a local scope, previous declarations with
6037 /// linkage may still be considered previous declarations (C99
6038 /// 6.2.2p4-5, C++ [basic.link]p6).
6039 ///
6040 /// \param PrevDecl the previous declaration found by name
6041 /// lookup
6042 ///
6043 /// \param DC the context in which the new declaration is being
6044 /// declared.
6045 ///
6046 /// \returns true if PrevDecl is an out-of-scope previous declaration
6047 /// for a new delcaration with the same name.
6048 static bool
6049 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6050                                 ASTContext &Context) {
6051   if (!PrevDecl)
6052     return false;
6053 
6054   if (!PrevDecl->hasLinkage())
6055     return false;
6056 
6057   if (Context.getLangOpts().CPlusPlus) {
6058     // C++ [basic.link]p6:
6059     //   If there is a visible declaration of an entity with linkage
6060     //   having the same name and type, ignoring entities declared
6061     //   outside the innermost enclosing namespace scope, the block
6062     //   scope declaration declares that same entity and receives the
6063     //   linkage of the previous declaration.
6064     DeclContext *OuterContext = DC->getRedeclContext();
6065     if (!OuterContext->isFunctionOrMethod())
6066       // This rule only applies to block-scope declarations.
6067       return false;
6068 
6069     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6070     if (PrevOuterContext->isRecord())
6071       // We found a member function: ignore it.
6072       return false;
6073 
6074     // Find the innermost enclosing namespace for the new and
6075     // previous declarations.
6076     OuterContext = OuterContext->getEnclosingNamespaceContext();
6077     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6078 
6079     // The previous declaration is in a different namespace, so it
6080     // isn't the same function.
6081     if (!OuterContext->Equals(PrevOuterContext))
6082       return false;
6083   }
6084 
6085   return true;
6086 }
6087 
6088 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6089   CXXScopeSpec &SS = D.getCXXScopeSpec();
6090   if (!SS.isSet()) return;
6091   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6092 }
6093 
6094 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6095   QualType type = decl->getType();
6096   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6097   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6098     // Various kinds of declaration aren't allowed to be __autoreleasing.
6099     unsigned kind = -1U;
6100     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6101       if (var->hasAttr<BlocksAttr>())
6102         kind = 0; // __block
6103       else if (!var->hasLocalStorage())
6104         kind = 1; // global
6105     } else if (isa<ObjCIvarDecl>(decl)) {
6106       kind = 3; // ivar
6107     } else if (isa<FieldDecl>(decl)) {
6108       kind = 2; // field
6109     }
6110 
6111     if (kind != -1U) {
6112       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6113         << kind;
6114     }
6115   } else if (lifetime == Qualifiers::OCL_None) {
6116     // Try to infer lifetime.
6117     if (!type->isObjCLifetimeType())
6118       return false;
6119 
6120     lifetime = type->getObjCARCImplicitLifetime();
6121     type = Context.getLifetimeQualifiedType(type, lifetime);
6122     decl->setType(type);
6123   }
6124 
6125   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6126     // Thread-local variables cannot have lifetime.
6127     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6128         var->getTLSKind()) {
6129       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6130         << var->getType();
6131       return true;
6132     }
6133   }
6134 
6135   return false;
6136 }
6137 
6138 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6139   if (Decl->getType().hasAddressSpace())
6140     return;
6141   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6142     QualType Type = Var->getType();
6143     if (Type->isSamplerT() || Type->isVoidType())
6144       return;
6145     LangAS ImplAS = LangAS::opencl_private;
6146     if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6147         Var->hasGlobalStorage())
6148       ImplAS = LangAS::opencl_global;
6149     // If the original type from a decayed type is an array type and that array
6150     // type has no address space yet, deduce it now.
6151     if (auto DT = dyn_cast<DecayedType>(Type)) {
6152       auto OrigTy = DT->getOriginalType();
6153       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6154         // Add the address space to the original array type and then propagate
6155         // that to the element type through `getAsArrayType`.
6156         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6157         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6158         // Re-generate the decayed type.
6159         Type = Context.getDecayedType(OrigTy);
6160       }
6161     }
6162     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6163     // Apply any qualifiers (including address space) from the array type to
6164     // the element type. This implements C99 6.7.3p8: "If the specification of
6165     // an array type includes any type qualifiers, the element type is so
6166     // qualified, not the array type."
6167     if (Type->isArrayType())
6168       Type = QualType(Context.getAsArrayType(Type), 0);
6169     Decl->setType(Type);
6170   }
6171 }
6172 
6173 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6174   // Ensure that an auto decl is deduced otherwise the checks below might cache
6175   // the wrong linkage.
6176   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6177 
6178   // 'weak' only applies to declarations with external linkage.
6179   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6180     if (!ND.isExternallyVisible()) {
6181       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6182       ND.dropAttr<WeakAttr>();
6183     }
6184   }
6185   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6186     if (ND.isExternallyVisible()) {
6187       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6188       ND.dropAttr<WeakRefAttr>();
6189       ND.dropAttr<AliasAttr>();
6190     }
6191   }
6192 
6193   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6194     if (VD->hasInit()) {
6195       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6196         assert(VD->isThisDeclarationADefinition() &&
6197                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6198         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6199         VD->dropAttr<AliasAttr>();
6200       }
6201     }
6202   }
6203 
6204   // 'selectany' only applies to externally visible variable declarations.
6205   // It does not apply to functions.
6206   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6207     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6208       S.Diag(Attr->getLocation(),
6209              diag::err_attribute_selectany_non_extern_data);
6210       ND.dropAttr<SelectAnyAttr>();
6211     }
6212   }
6213 
6214   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6215     auto *VD = dyn_cast<VarDecl>(&ND);
6216     bool IsAnonymousNS = false;
6217     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6218     if (VD) {
6219       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6220       while (NS && !IsAnonymousNS) {
6221         IsAnonymousNS = NS->isAnonymousNamespace();
6222         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6223       }
6224     }
6225     // dll attributes require external linkage. Static locals may have external
6226     // linkage but still cannot be explicitly imported or exported.
6227     // In Microsoft mode, a variable defined in anonymous namespace must have
6228     // external linkage in order to be exported.
6229     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6230     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6231         (!AnonNSInMicrosoftMode &&
6232          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6233       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6234         << &ND << Attr;
6235       ND.setInvalidDecl();
6236     }
6237   }
6238 
6239   // Virtual functions cannot be marked as 'notail'.
6240   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6241     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6242       if (MD->isVirtual()) {
6243         S.Diag(ND.getLocation(),
6244                diag::err_invalid_attribute_on_virtual_function)
6245             << Attr;
6246         ND.dropAttr<NotTailCalledAttr>();
6247       }
6248 
6249   // Check the attributes on the function type, if any.
6250   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6251     // Don't declare this variable in the second operand of the for-statement;
6252     // GCC miscompiles that by ending its lifetime before evaluating the
6253     // third operand. See gcc.gnu.org/PR86769.
6254     AttributedTypeLoc ATL;
6255     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6256          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6257          TL = ATL.getModifiedLoc()) {
6258       // The [[lifetimebound]] attribute can be applied to the implicit object
6259       // parameter of a non-static member function (other than a ctor or dtor)
6260       // by applying it to the function type.
6261       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6262         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6263         if (!MD || MD->isStatic()) {
6264           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6265               << !MD << A->getRange();
6266         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6267           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6268               << isa<CXXDestructorDecl>(MD) << A->getRange();
6269         }
6270       }
6271     }
6272   }
6273 }
6274 
6275 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6276                                            NamedDecl *NewDecl,
6277                                            bool IsSpecialization,
6278                                            bool IsDefinition) {
6279   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6280     return;
6281 
6282   bool IsTemplate = false;
6283   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6284     OldDecl = OldTD->getTemplatedDecl();
6285     IsTemplate = true;
6286     if (!IsSpecialization)
6287       IsDefinition = false;
6288   }
6289   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6290     NewDecl = NewTD->getTemplatedDecl();
6291     IsTemplate = true;
6292   }
6293 
6294   if (!OldDecl || !NewDecl)
6295     return;
6296 
6297   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6298   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6299   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6300   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6301 
6302   // dllimport and dllexport are inheritable attributes so we have to exclude
6303   // inherited attribute instances.
6304   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6305                     (NewExportAttr && !NewExportAttr->isInherited());
6306 
6307   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6308   // the only exception being explicit specializations.
6309   // Implicitly generated declarations are also excluded for now because there
6310   // is no other way to switch these to use dllimport or dllexport.
6311   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6312 
6313   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6314     // Allow with a warning for free functions and global variables.
6315     bool JustWarn = false;
6316     if (!OldDecl->isCXXClassMember()) {
6317       auto *VD = dyn_cast<VarDecl>(OldDecl);
6318       if (VD && !VD->getDescribedVarTemplate())
6319         JustWarn = true;
6320       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6321       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6322         JustWarn = true;
6323     }
6324 
6325     // We cannot change a declaration that's been used because IR has already
6326     // been emitted. Dllimported functions will still work though (modulo
6327     // address equality) as they can use the thunk.
6328     if (OldDecl->isUsed())
6329       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6330         JustWarn = false;
6331 
6332     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6333                                : diag::err_attribute_dll_redeclaration;
6334     S.Diag(NewDecl->getLocation(), DiagID)
6335         << NewDecl
6336         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6337     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6338     if (!JustWarn) {
6339       NewDecl->setInvalidDecl();
6340       return;
6341     }
6342   }
6343 
6344   // A redeclaration is not allowed to drop a dllimport attribute, the only
6345   // exceptions being inline function definitions (except for function
6346   // templates), local extern declarations, qualified friend declarations or
6347   // special MSVC extension: in the last case, the declaration is treated as if
6348   // it were marked dllexport.
6349   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6350   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6351   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6352     // Ignore static data because out-of-line definitions are diagnosed
6353     // separately.
6354     IsStaticDataMember = VD->isStaticDataMember();
6355     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6356                    VarDecl::DeclarationOnly;
6357   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6358     IsInline = FD->isInlined();
6359     IsQualifiedFriend = FD->getQualifier() &&
6360                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6361   }
6362 
6363   if (OldImportAttr && !HasNewAttr &&
6364       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6365       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6366     if (IsMicrosoft && IsDefinition) {
6367       S.Diag(NewDecl->getLocation(),
6368              diag::warn_redeclaration_without_import_attribute)
6369           << NewDecl;
6370       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6371       NewDecl->dropAttr<DLLImportAttr>();
6372       NewDecl->addAttr(
6373           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6374     } else {
6375       S.Diag(NewDecl->getLocation(),
6376              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6377           << NewDecl << OldImportAttr;
6378       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6379       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6380       OldDecl->dropAttr<DLLImportAttr>();
6381       NewDecl->dropAttr<DLLImportAttr>();
6382     }
6383   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6384     // In MinGW, seeing a function declared inline drops the dllimport
6385     // attribute.
6386     OldDecl->dropAttr<DLLImportAttr>();
6387     NewDecl->dropAttr<DLLImportAttr>();
6388     S.Diag(NewDecl->getLocation(),
6389            diag::warn_dllimport_dropped_from_inline_function)
6390         << NewDecl << OldImportAttr;
6391   }
6392 
6393   // A specialization of a class template member function is processed here
6394   // since it's a redeclaration. If the parent class is dllexport, the
6395   // specialization inherits that attribute. This doesn't happen automatically
6396   // since the parent class isn't instantiated until later.
6397   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6398     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6399         !NewImportAttr && !NewExportAttr) {
6400       if (const DLLExportAttr *ParentExportAttr =
6401               MD->getParent()->getAttr<DLLExportAttr>()) {
6402         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6403         NewAttr->setInherited(true);
6404         NewDecl->addAttr(NewAttr);
6405       }
6406     }
6407   }
6408 }
6409 
6410 /// Given that we are within the definition of the given function,
6411 /// will that definition behave like C99's 'inline', where the
6412 /// definition is discarded except for optimization purposes?
6413 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6414   // Try to avoid calling GetGVALinkageForFunction.
6415 
6416   // All cases of this require the 'inline' keyword.
6417   if (!FD->isInlined()) return false;
6418 
6419   // This is only possible in C++ with the gnu_inline attribute.
6420   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6421     return false;
6422 
6423   // Okay, go ahead and call the relatively-more-expensive function.
6424   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6425 }
6426 
6427 /// Determine whether a variable is extern "C" prior to attaching
6428 /// an initializer. We can't just call isExternC() here, because that
6429 /// will also compute and cache whether the declaration is externally
6430 /// visible, which might change when we attach the initializer.
6431 ///
6432 /// This can only be used if the declaration is known to not be a
6433 /// redeclaration of an internal linkage declaration.
6434 ///
6435 /// For instance:
6436 ///
6437 ///   auto x = []{};
6438 ///
6439 /// Attaching the initializer here makes this declaration not externally
6440 /// visible, because its type has internal linkage.
6441 ///
6442 /// FIXME: This is a hack.
6443 template<typename T>
6444 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6445   if (S.getLangOpts().CPlusPlus) {
6446     // In C++, the overloadable attribute negates the effects of extern "C".
6447     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6448       return false;
6449 
6450     // So do CUDA's host/device attributes.
6451     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6452                                  D->template hasAttr<CUDAHostAttr>()))
6453       return false;
6454   }
6455   return D->isExternC();
6456 }
6457 
6458 static bool shouldConsiderLinkage(const VarDecl *VD) {
6459   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6460   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6461       isa<OMPDeclareMapperDecl>(DC))
6462     return VD->hasExternalStorage();
6463   if (DC->isFileContext())
6464     return true;
6465   if (DC->isRecord())
6466     return false;
6467   llvm_unreachable("Unexpected context");
6468 }
6469 
6470 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6471   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6472   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6473       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6474     return true;
6475   if (DC->isRecord())
6476     return false;
6477   llvm_unreachable("Unexpected context");
6478 }
6479 
6480 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6481                           ParsedAttr::Kind Kind) {
6482   // Check decl attributes on the DeclSpec.
6483   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6484     return true;
6485 
6486   // Walk the declarator structure, checking decl attributes that were in a type
6487   // position to the decl itself.
6488   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6489     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6490       return true;
6491   }
6492 
6493   // Finally, check attributes on the decl itself.
6494   return PD.getAttributes().hasAttribute(Kind);
6495 }
6496 
6497 /// Adjust the \c DeclContext for a function or variable that might be a
6498 /// function-local external declaration.
6499 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6500   if (!DC->isFunctionOrMethod())
6501     return false;
6502 
6503   // If this is a local extern function or variable declared within a function
6504   // template, don't add it into the enclosing namespace scope until it is
6505   // instantiated; it might have a dependent type right now.
6506   if (DC->isDependentContext())
6507     return true;
6508 
6509   // C++11 [basic.link]p7:
6510   //   When a block scope declaration of an entity with linkage is not found to
6511   //   refer to some other declaration, then that entity is a member of the
6512   //   innermost enclosing namespace.
6513   //
6514   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6515   // semantically-enclosing namespace, not a lexically-enclosing one.
6516   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6517     DC = DC->getParent();
6518   return true;
6519 }
6520 
6521 /// Returns true if given declaration has external C language linkage.
6522 static bool isDeclExternC(const Decl *D) {
6523   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6524     return FD->isExternC();
6525   if (const auto *VD = dyn_cast<VarDecl>(D))
6526     return VD->isExternC();
6527 
6528   llvm_unreachable("Unknown type of decl!");
6529 }
6530 /// Returns true if there hasn't been any invalid type diagnosed.
6531 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6532                                 DeclContext *DC, QualType R) {
6533   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6534   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6535   // argument.
6536   if (R->isImageType() || R->isPipeType()) {
6537     Se.Diag(D.getIdentifierLoc(),
6538             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6539         << R;
6540     D.setInvalidType();
6541     return false;
6542   }
6543 
6544   // OpenCL v1.2 s6.9.r:
6545   // The event type cannot be used to declare a program scope variable.
6546   // OpenCL v2.0 s6.9.q:
6547   // The clk_event_t and reserve_id_t types cannot be declared in program
6548   // scope.
6549   if (NULL == S->getParent()) {
6550     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6551       Se.Diag(D.getIdentifierLoc(),
6552               diag::err_invalid_type_for_program_scope_var)
6553           << R;
6554       D.setInvalidType();
6555       return false;
6556     }
6557   }
6558 
6559   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6560   QualType NR = R;
6561   while (NR->isPointerType()) {
6562     if (NR->isFunctionPointerType()) {
6563       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6564       D.setInvalidType();
6565       return false;
6566     }
6567     NR = NR->getPointeeType();
6568   }
6569 
6570   if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6571     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6572     // half array type (unless the cl_khr_fp16 extension is enabled).
6573     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6574       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6575       D.setInvalidType();
6576       return false;
6577     }
6578   }
6579 
6580   // OpenCL v1.2 s6.9.r:
6581   // The event type cannot be used with the __local, __constant and __global
6582   // address space qualifiers.
6583   if (R->isEventT()) {
6584     if (R.getAddressSpace() != LangAS::opencl_private) {
6585       Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6586       D.setInvalidType();
6587       return false;
6588     }
6589   }
6590 
6591   // C++ for OpenCL does not allow the thread_local storage qualifier.
6592   // OpenCL C does not support thread_local either, and
6593   // also reject all other thread storage class specifiers.
6594   DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6595   if (TSC != TSCS_unspecified) {
6596     bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6597     Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6598             diag::err_opencl_unknown_type_specifier)
6599         << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6600         << DeclSpec::getSpecifierName(TSC) << 1;
6601     D.setInvalidType();
6602     return false;
6603   }
6604 
6605   if (R->isSamplerT()) {
6606     // OpenCL v1.2 s6.9.b p4:
6607     // The sampler type cannot be used with the __local and __global address
6608     // space qualifiers.
6609     if (R.getAddressSpace() == LangAS::opencl_local ||
6610         R.getAddressSpace() == LangAS::opencl_global) {
6611       Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6612       D.setInvalidType();
6613     }
6614 
6615     // OpenCL v1.2 s6.12.14.1:
6616     // A global sampler must be declared with either the constant address
6617     // space qualifier or with the const qualifier.
6618     if (DC->isTranslationUnit() &&
6619         !(R.getAddressSpace() == LangAS::opencl_constant ||
6620           R.isConstQualified())) {
6621       Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6622       D.setInvalidType();
6623     }
6624     if (D.isInvalidType())
6625       return false;
6626   }
6627   return true;
6628 }
6629 
6630 NamedDecl *Sema::ActOnVariableDeclarator(
6631     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6632     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6633     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6634   QualType R = TInfo->getType();
6635   DeclarationName Name = GetNameForDeclarator(D).getName();
6636 
6637   IdentifierInfo *II = Name.getAsIdentifierInfo();
6638 
6639   if (D.isDecompositionDeclarator()) {
6640     // Take the name of the first declarator as our name for diagnostic
6641     // purposes.
6642     auto &Decomp = D.getDecompositionDeclarator();
6643     if (!Decomp.bindings().empty()) {
6644       II = Decomp.bindings()[0].Name;
6645       Name = II;
6646     }
6647   } else if (!II) {
6648     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6649     return nullptr;
6650   }
6651 
6652 
6653   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6654   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6655 
6656   // dllimport globals without explicit storage class are treated as extern. We
6657   // have to change the storage class this early to get the right DeclContext.
6658   if (SC == SC_None && !DC->isRecord() &&
6659       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6660       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6661     SC = SC_Extern;
6662 
6663   DeclContext *OriginalDC = DC;
6664   bool IsLocalExternDecl = SC == SC_Extern &&
6665                            adjustContextForLocalExternDecl(DC);
6666 
6667   if (SCSpec == DeclSpec::SCS_mutable) {
6668     // mutable can only appear on non-static class members, so it's always
6669     // an error here
6670     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6671     D.setInvalidType();
6672     SC = SC_None;
6673   }
6674 
6675   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6676       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6677                               D.getDeclSpec().getStorageClassSpecLoc())) {
6678     // In C++11, the 'register' storage class specifier is deprecated.
6679     // Suppress the warning in system macros, it's used in macros in some
6680     // popular C system headers, such as in glibc's htonl() macro.
6681     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6682          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6683                                    : diag::warn_deprecated_register)
6684       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6685   }
6686 
6687   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6688 
6689   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6690     // C99 6.9p2: The storage-class specifiers auto and register shall not
6691     // appear in the declaration specifiers in an external declaration.
6692     // Global Register+Asm is a GNU extension we support.
6693     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6694       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6695       D.setInvalidType();
6696     }
6697   }
6698 
6699   bool IsMemberSpecialization = false;
6700   bool IsVariableTemplateSpecialization = false;
6701   bool IsPartialSpecialization = false;
6702   bool IsVariableTemplate = false;
6703   VarDecl *NewVD = nullptr;
6704   VarTemplateDecl *NewTemplate = nullptr;
6705   TemplateParameterList *TemplateParams = nullptr;
6706   if (!getLangOpts().CPlusPlus) {
6707     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6708                             II, R, TInfo, SC);
6709 
6710     if (R->getContainedDeducedType())
6711       ParsingInitForAutoVars.insert(NewVD);
6712 
6713     if (D.isInvalidType())
6714       NewVD->setInvalidDecl();
6715 
6716     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6717         NewVD->hasLocalStorage())
6718       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6719                             NTCUC_AutoVar, NTCUK_Destruct);
6720   } else {
6721     bool Invalid = false;
6722 
6723     if (DC->isRecord() && !CurContext->isRecord()) {
6724       // This is an out-of-line definition of a static data member.
6725       switch (SC) {
6726       case SC_None:
6727         break;
6728       case SC_Static:
6729         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6730              diag::err_static_out_of_line)
6731           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6732         break;
6733       case SC_Auto:
6734       case SC_Register:
6735       case SC_Extern:
6736         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6737         // to names of variables declared in a block or to function parameters.
6738         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6739         // of class members
6740 
6741         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6742              diag::err_storage_class_for_static_member)
6743           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6744         break;
6745       case SC_PrivateExtern:
6746         llvm_unreachable("C storage class in c++!");
6747       }
6748     }
6749 
6750     if (SC == SC_Static && CurContext->isRecord()) {
6751       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6752         if (RD->isLocalClass())
6753           Diag(D.getIdentifierLoc(),
6754                diag::err_static_data_member_not_allowed_in_local_class)
6755             << Name << RD->getDeclName();
6756 
6757         // C++98 [class.union]p1: If a union contains a static data member,
6758         // the program is ill-formed. C++11 drops this restriction.
6759         if (RD->isUnion())
6760           Diag(D.getIdentifierLoc(),
6761                getLangOpts().CPlusPlus11
6762                  ? diag::warn_cxx98_compat_static_data_member_in_union
6763                  : diag::ext_static_data_member_in_union) << Name;
6764         // We conservatively disallow static data members in anonymous structs.
6765         else if (!RD->getDeclName())
6766           Diag(D.getIdentifierLoc(),
6767                diag::err_static_data_member_not_allowed_in_anon_struct)
6768             << Name << RD->isUnion();
6769       }
6770     }
6771 
6772     // Match up the template parameter lists with the scope specifier, then
6773     // determine whether we have a template or a template specialization.
6774     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6775         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6776         D.getCXXScopeSpec(),
6777         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6778             ? D.getName().TemplateId
6779             : nullptr,
6780         TemplateParamLists,
6781         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6782 
6783     if (TemplateParams) {
6784       if (!TemplateParams->size() &&
6785           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6786         // There is an extraneous 'template<>' for this variable. Complain
6787         // about it, but allow the declaration of the variable.
6788         Diag(TemplateParams->getTemplateLoc(),
6789              diag::err_template_variable_noparams)
6790           << II
6791           << SourceRange(TemplateParams->getTemplateLoc(),
6792                          TemplateParams->getRAngleLoc());
6793         TemplateParams = nullptr;
6794       } else {
6795         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6796           // This is an explicit specialization or a partial specialization.
6797           // FIXME: Check that we can declare a specialization here.
6798           IsVariableTemplateSpecialization = true;
6799           IsPartialSpecialization = TemplateParams->size() > 0;
6800         } else { // if (TemplateParams->size() > 0)
6801           // This is a template declaration.
6802           IsVariableTemplate = true;
6803 
6804           // Check that we can declare a template here.
6805           if (CheckTemplateDeclScope(S, TemplateParams))
6806             return nullptr;
6807 
6808           // Only C++1y supports variable templates (N3651).
6809           Diag(D.getIdentifierLoc(),
6810                getLangOpts().CPlusPlus14
6811                    ? diag::warn_cxx11_compat_variable_template
6812                    : diag::ext_variable_template);
6813         }
6814       }
6815     } else {
6816       assert((Invalid ||
6817               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6818              "should have a 'template<>' for this decl");
6819     }
6820 
6821     if (IsVariableTemplateSpecialization) {
6822       SourceLocation TemplateKWLoc =
6823           TemplateParamLists.size() > 0
6824               ? TemplateParamLists[0]->getTemplateLoc()
6825               : SourceLocation();
6826       DeclResult Res = ActOnVarTemplateSpecialization(
6827           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6828           IsPartialSpecialization);
6829       if (Res.isInvalid())
6830         return nullptr;
6831       NewVD = cast<VarDecl>(Res.get());
6832       AddToScope = false;
6833     } else if (D.isDecompositionDeclarator()) {
6834       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6835                                         D.getIdentifierLoc(), R, TInfo, SC,
6836                                         Bindings);
6837     } else
6838       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6839                               D.getIdentifierLoc(), II, R, TInfo, SC);
6840 
6841     // If this is supposed to be a variable template, create it as such.
6842     if (IsVariableTemplate) {
6843       NewTemplate =
6844           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6845                                   TemplateParams, NewVD);
6846       NewVD->setDescribedVarTemplate(NewTemplate);
6847     }
6848 
6849     // If this decl has an auto type in need of deduction, make a note of the
6850     // Decl so we can diagnose uses of it in its own initializer.
6851     if (R->getContainedDeducedType())
6852       ParsingInitForAutoVars.insert(NewVD);
6853 
6854     if (D.isInvalidType() || Invalid) {
6855       NewVD->setInvalidDecl();
6856       if (NewTemplate)
6857         NewTemplate->setInvalidDecl();
6858     }
6859 
6860     SetNestedNameSpecifier(*this, NewVD, D);
6861 
6862     // If we have any template parameter lists that don't directly belong to
6863     // the variable (matching the scope specifier), store them.
6864     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6865     if (TemplateParamLists.size() > VDTemplateParamLists)
6866       NewVD->setTemplateParameterListsInfo(
6867           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6868   }
6869 
6870   if (D.getDeclSpec().isInlineSpecified()) {
6871     if (!getLangOpts().CPlusPlus) {
6872       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6873           << 0;
6874     } else if (CurContext->isFunctionOrMethod()) {
6875       // 'inline' is not allowed on block scope variable declaration.
6876       Diag(D.getDeclSpec().getInlineSpecLoc(),
6877            diag::err_inline_declaration_block_scope) << Name
6878         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6879     } else {
6880       Diag(D.getDeclSpec().getInlineSpecLoc(),
6881            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6882                                      : diag::ext_inline_variable);
6883       NewVD->setInlineSpecified();
6884     }
6885   }
6886 
6887   // Set the lexical context. If the declarator has a C++ scope specifier, the
6888   // lexical context will be different from the semantic context.
6889   NewVD->setLexicalDeclContext(CurContext);
6890   if (NewTemplate)
6891     NewTemplate->setLexicalDeclContext(CurContext);
6892 
6893   if (IsLocalExternDecl) {
6894     if (D.isDecompositionDeclarator())
6895       for (auto *B : Bindings)
6896         B->setLocalExternDecl();
6897     else
6898       NewVD->setLocalExternDecl();
6899   }
6900 
6901   bool EmitTLSUnsupportedError = false;
6902   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6903     // C++11 [dcl.stc]p4:
6904     //   When thread_local is applied to a variable of block scope the
6905     //   storage-class-specifier static is implied if it does not appear
6906     //   explicitly.
6907     // Core issue: 'static' is not implied if the variable is declared
6908     //   'extern'.
6909     if (NewVD->hasLocalStorage() &&
6910         (SCSpec != DeclSpec::SCS_unspecified ||
6911          TSCS != DeclSpec::TSCS_thread_local ||
6912          !DC->isFunctionOrMethod()))
6913       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6914            diag::err_thread_non_global)
6915         << DeclSpec::getSpecifierName(TSCS);
6916     else if (!Context.getTargetInfo().isTLSSupported()) {
6917       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6918         // Postpone error emission until we've collected attributes required to
6919         // figure out whether it's a host or device variable and whether the
6920         // error should be ignored.
6921         EmitTLSUnsupportedError = true;
6922         // We still need to mark the variable as TLS so it shows up in AST with
6923         // proper storage class for other tools to use even if we're not going
6924         // to emit any code for it.
6925         NewVD->setTSCSpec(TSCS);
6926       } else
6927         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6928              diag::err_thread_unsupported);
6929     } else
6930       NewVD->setTSCSpec(TSCS);
6931   }
6932 
6933   switch (D.getDeclSpec().getConstexprSpecifier()) {
6934   case CSK_unspecified:
6935     break;
6936 
6937   case CSK_consteval:
6938     Diag(D.getDeclSpec().getConstexprSpecLoc(),
6939         diag::err_constexpr_wrong_decl_kind)
6940       << D.getDeclSpec().getConstexprSpecifier();
6941     LLVM_FALLTHROUGH;
6942 
6943   case CSK_constexpr:
6944     NewVD->setConstexpr(true);
6945     // C++1z [dcl.spec.constexpr]p1:
6946     //   A static data member declared with the constexpr specifier is
6947     //   implicitly an inline variable.
6948     if (NewVD->isStaticDataMember() &&
6949         (getLangOpts().CPlusPlus17 ||
6950          Context.getTargetInfo().getCXXABI().isMicrosoft()))
6951       NewVD->setImplicitlyInline();
6952     break;
6953 
6954   case CSK_constinit:
6955     if (!NewVD->hasGlobalStorage())
6956       Diag(D.getDeclSpec().getConstexprSpecLoc(),
6957            diag::err_constinit_local_variable);
6958     else
6959       NewVD->addAttr(ConstInitAttr::Create(
6960           Context, D.getDeclSpec().getConstexprSpecLoc(),
6961           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
6962     break;
6963   }
6964 
6965   // C99 6.7.4p3
6966   //   An inline definition of a function with external linkage shall
6967   //   not contain a definition of a modifiable object with static or
6968   //   thread storage duration...
6969   // We only apply this when the function is required to be defined
6970   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6971   // that a local variable with thread storage duration still has to
6972   // be marked 'static'.  Also note that it's possible to get these
6973   // semantics in C++ using __attribute__((gnu_inline)).
6974   if (SC == SC_Static && S->getFnParent() != nullptr &&
6975       !NewVD->getType().isConstQualified()) {
6976     FunctionDecl *CurFD = getCurFunctionDecl();
6977     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6978       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6979            diag::warn_static_local_in_extern_inline);
6980       MaybeSuggestAddingStaticToDecl(CurFD);
6981     }
6982   }
6983 
6984   if (D.getDeclSpec().isModulePrivateSpecified()) {
6985     if (IsVariableTemplateSpecialization)
6986       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6987           << (IsPartialSpecialization ? 1 : 0)
6988           << FixItHint::CreateRemoval(
6989                  D.getDeclSpec().getModulePrivateSpecLoc());
6990     else if (IsMemberSpecialization)
6991       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6992         << 2
6993         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6994     else if (NewVD->hasLocalStorage())
6995       Diag(NewVD->getLocation(), diag::err_module_private_local)
6996         << 0 << NewVD->getDeclName()
6997         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6998         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6999     else {
7000       NewVD->setModulePrivate();
7001       if (NewTemplate)
7002         NewTemplate->setModulePrivate();
7003       for (auto *B : Bindings)
7004         B->setModulePrivate();
7005     }
7006   }
7007 
7008   if (getLangOpts().OpenCL) {
7009 
7010     deduceOpenCLAddressSpace(NewVD);
7011 
7012     diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7013   }
7014 
7015   // Handle attributes prior to checking for duplicates in MergeVarDecl
7016   ProcessDeclAttributes(S, NewVD, D);
7017 
7018   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
7019     if (EmitTLSUnsupportedError &&
7020         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7021          (getLangOpts().OpenMPIsDevice &&
7022           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7023       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7024            diag::err_thread_unsupported);
7025     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7026     // storage [duration]."
7027     if (SC == SC_None && S->getFnParent() != nullptr &&
7028         (NewVD->hasAttr<CUDASharedAttr>() ||
7029          NewVD->hasAttr<CUDAConstantAttr>())) {
7030       NewVD->setStorageClass(SC_Static);
7031     }
7032   }
7033 
7034   // Ensure that dllimport globals without explicit storage class are treated as
7035   // extern. The storage class is set above using parsed attributes. Now we can
7036   // check the VarDecl itself.
7037   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7038          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7039          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7040 
7041   // In auto-retain/release, infer strong retension for variables of
7042   // retainable type.
7043   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7044     NewVD->setInvalidDecl();
7045 
7046   // Handle GNU asm-label extension (encoded as an attribute).
7047   if (Expr *E = (Expr*)D.getAsmLabel()) {
7048     // The parser guarantees this is a string.
7049     StringLiteral *SE = cast<StringLiteral>(E);
7050     StringRef Label = SE->getString();
7051     if (S->getFnParent() != nullptr) {
7052       switch (SC) {
7053       case SC_None:
7054       case SC_Auto:
7055         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7056         break;
7057       case SC_Register:
7058         // Local Named register
7059         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7060             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7061           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7062         break;
7063       case SC_Static:
7064       case SC_Extern:
7065       case SC_PrivateExtern:
7066         break;
7067       }
7068     } else if (SC == SC_Register) {
7069       // Global Named register
7070       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7071         const auto &TI = Context.getTargetInfo();
7072         bool HasSizeMismatch;
7073 
7074         if (!TI.isValidGCCRegisterName(Label))
7075           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7076         else if (!TI.validateGlobalRegisterVariable(Label,
7077                                                     Context.getTypeSize(R),
7078                                                     HasSizeMismatch))
7079           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7080         else if (HasSizeMismatch)
7081           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7082       }
7083 
7084       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7085         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7086         NewVD->setInvalidDecl(true);
7087       }
7088     }
7089 
7090     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7091                                         /*IsLiteralLabel=*/true,
7092                                         SE->getStrTokenLoc(0)));
7093   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7094     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7095       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7096     if (I != ExtnameUndeclaredIdentifiers.end()) {
7097       if (isDeclExternC(NewVD)) {
7098         NewVD->addAttr(I->second);
7099         ExtnameUndeclaredIdentifiers.erase(I);
7100       } else
7101         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7102             << /*Variable*/1 << NewVD;
7103     }
7104   }
7105 
7106   // Find the shadowed declaration before filtering for scope.
7107   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7108                                 ? getShadowedDeclaration(NewVD, Previous)
7109                                 : nullptr;
7110 
7111   // Don't consider existing declarations that are in a different
7112   // scope and are out-of-semantic-context declarations (if the new
7113   // declaration has linkage).
7114   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7115                        D.getCXXScopeSpec().isNotEmpty() ||
7116                        IsMemberSpecialization ||
7117                        IsVariableTemplateSpecialization);
7118 
7119   // Check whether the previous declaration is in the same block scope. This
7120   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7121   if (getLangOpts().CPlusPlus &&
7122       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7123     NewVD->setPreviousDeclInSameBlockScope(
7124         Previous.isSingleResult() && !Previous.isShadowed() &&
7125         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7126 
7127   if (!getLangOpts().CPlusPlus) {
7128     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7129   } else {
7130     // If this is an explicit specialization of a static data member, check it.
7131     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7132         CheckMemberSpecialization(NewVD, Previous))
7133       NewVD->setInvalidDecl();
7134 
7135     // Merge the decl with the existing one if appropriate.
7136     if (!Previous.empty()) {
7137       if (Previous.isSingleResult() &&
7138           isa<FieldDecl>(Previous.getFoundDecl()) &&
7139           D.getCXXScopeSpec().isSet()) {
7140         // The user tried to define a non-static data member
7141         // out-of-line (C++ [dcl.meaning]p1).
7142         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7143           << D.getCXXScopeSpec().getRange();
7144         Previous.clear();
7145         NewVD->setInvalidDecl();
7146       }
7147     } else if (D.getCXXScopeSpec().isSet()) {
7148       // No previous declaration in the qualifying scope.
7149       Diag(D.getIdentifierLoc(), diag::err_no_member)
7150         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7151         << D.getCXXScopeSpec().getRange();
7152       NewVD->setInvalidDecl();
7153     }
7154 
7155     if (!IsVariableTemplateSpecialization)
7156       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7157 
7158     if (NewTemplate) {
7159       VarTemplateDecl *PrevVarTemplate =
7160           NewVD->getPreviousDecl()
7161               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7162               : nullptr;
7163 
7164       // Check the template parameter list of this declaration, possibly
7165       // merging in the template parameter list from the previous variable
7166       // template declaration.
7167       if (CheckTemplateParameterList(
7168               TemplateParams,
7169               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7170                               : nullptr,
7171               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7172                DC->isDependentContext())
7173                   ? TPC_ClassTemplateMember
7174                   : TPC_VarTemplate))
7175         NewVD->setInvalidDecl();
7176 
7177       // If we are providing an explicit specialization of a static variable
7178       // template, make a note of that.
7179       if (PrevVarTemplate &&
7180           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7181         PrevVarTemplate->setMemberSpecialization();
7182     }
7183   }
7184 
7185   // Diagnose shadowed variables iff this isn't a redeclaration.
7186   if (ShadowedDecl && !D.isRedeclaration())
7187     CheckShadow(NewVD, ShadowedDecl, Previous);
7188 
7189   ProcessPragmaWeak(S, NewVD);
7190 
7191   // If this is the first declaration of an extern C variable, update
7192   // the map of such variables.
7193   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7194       isIncompleteDeclExternC(*this, NewVD))
7195     RegisterLocallyScopedExternCDecl(NewVD, S);
7196 
7197   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7198     MangleNumberingContext *MCtx;
7199     Decl *ManglingContextDecl;
7200     std::tie(MCtx, ManglingContextDecl) =
7201         getCurrentMangleNumberContext(NewVD->getDeclContext());
7202     if (MCtx) {
7203       Context.setManglingNumber(
7204           NewVD, MCtx->getManglingNumber(
7205                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7206       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7207     }
7208   }
7209 
7210   // Special handling of variable named 'main'.
7211   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7212       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7213       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7214 
7215     // C++ [basic.start.main]p3
7216     // A program that declares a variable main at global scope is ill-formed.
7217     if (getLangOpts().CPlusPlus)
7218       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7219 
7220     // In C, and external-linkage variable named main results in undefined
7221     // behavior.
7222     else if (NewVD->hasExternalFormalLinkage())
7223       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7224   }
7225 
7226   if (D.isRedeclaration() && !Previous.empty()) {
7227     NamedDecl *Prev = Previous.getRepresentativeDecl();
7228     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7229                                    D.isFunctionDefinition());
7230   }
7231 
7232   if (NewTemplate) {
7233     if (NewVD->isInvalidDecl())
7234       NewTemplate->setInvalidDecl();
7235     ActOnDocumentableDecl(NewTemplate);
7236     return NewTemplate;
7237   }
7238 
7239   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7240     CompleteMemberSpecialization(NewVD, Previous);
7241 
7242   return NewVD;
7243 }
7244 
7245 /// Enum describing the %select options in diag::warn_decl_shadow.
7246 enum ShadowedDeclKind {
7247   SDK_Local,
7248   SDK_Global,
7249   SDK_StaticMember,
7250   SDK_Field,
7251   SDK_Typedef,
7252   SDK_Using
7253 };
7254 
7255 /// Determine what kind of declaration we're shadowing.
7256 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7257                                                 const DeclContext *OldDC) {
7258   if (isa<TypeAliasDecl>(ShadowedDecl))
7259     return SDK_Using;
7260   else if (isa<TypedefDecl>(ShadowedDecl))
7261     return SDK_Typedef;
7262   else if (isa<RecordDecl>(OldDC))
7263     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7264 
7265   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7266 }
7267 
7268 /// Return the location of the capture if the given lambda captures the given
7269 /// variable \p VD, or an invalid source location otherwise.
7270 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7271                                          const VarDecl *VD) {
7272   for (const Capture &Capture : LSI->Captures) {
7273     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7274       return Capture.getLocation();
7275   }
7276   return SourceLocation();
7277 }
7278 
7279 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7280                                      const LookupResult &R) {
7281   // Only diagnose if we're shadowing an unambiguous field or variable.
7282   if (R.getResultKind() != LookupResult::Found)
7283     return false;
7284 
7285   // Return false if warning is ignored.
7286   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7287 }
7288 
7289 /// Return the declaration shadowed by the given variable \p D, or null
7290 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7291 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7292                                         const LookupResult &R) {
7293   if (!shouldWarnIfShadowedDecl(Diags, R))
7294     return nullptr;
7295 
7296   // Don't diagnose declarations at file scope.
7297   if (D->hasGlobalStorage())
7298     return nullptr;
7299 
7300   NamedDecl *ShadowedDecl = R.getFoundDecl();
7301   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7302              ? ShadowedDecl
7303              : nullptr;
7304 }
7305 
7306 /// Return the declaration shadowed by the given typedef \p D, or null
7307 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7308 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7309                                         const LookupResult &R) {
7310   // Don't warn if typedef declaration is part of a class
7311   if (D->getDeclContext()->isRecord())
7312     return nullptr;
7313 
7314   if (!shouldWarnIfShadowedDecl(Diags, R))
7315     return nullptr;
7316 
7317   NamedDecl *ShadowedDecl = R.getFoundDecl();
7318   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7319 }
7320 
7321 /// Diagnose variable or built-in function shadowing.  Implements
7322 /// -Wshadow.
7323 ///
7324 /// This method is called whenever a VarDecl is added to a "useful"
7325 /// scope.
7326 ///
7327 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7328 /// \param R the lookup of the name
7329 ///
7330 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7331                        const LookupResult &R) {
7332   DeclContext *NewDC = D->getDeclContext();
7333 
7334   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7335     // Fields are not shadowed by variables in C++ static methods.
7336     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7337       if (MD->isStatic())
7338         return;
7339 
7340     // Fields shadowed by constructor parameters are a special case. Usually
7341     // the constructor initializes the field with the parameter.
7342     if (isa<CXXConstructorDecl>(NewDC))
7343       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7344         // Remember that this was shadowed so we can either warn about its
7345         // modification or its existence depending on warning settings.
7346         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7347         return;
7348       }
7349   }
7350 
7351   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7352     if (shadowedVar->isExternC()) {
7353       // For shadowing external vars, make sure that we point to the global
7354       // declaration, not a locally scoped extern declaration.
7355       for (auto I : shadowedVar->redecls())
7356         if (I->isFileVarDecl()) {
7357           ShadowedDecl = I;
7358           break;
7359         }
7360     }
7361 
7362   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7363 
7364   unsigned WarningDiag = diag::warn_decl_shadow;
7365   SourceLocation CaptureLoc;
7366   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7367       isa<CXXMethodDecl>(NewDC)) {
7368     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7369       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7370         if (RD->getLambdaCaptureDefault() == LCD_None) {
7371           // Try to avoid warnings for lambdas with an explicit capture list.
7372           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7373           // Warn only when the lambda captures the shadowed decl explicitly.
7374           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7375           if (CaptureLoc.isInvalid())
7376             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7377         } else {
7378           // Remember that this was shadowed so we can avoid the warning if the
7379           // shadowed decl isn't captured and the warning settings allow it.
7380           cast<LambdaScopeInfo>(getCurFunction())
7381               ->ShadowingDecls.push_back(
7382                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7383           return;
7384         }
7385       }
7386 
7387       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7388         // A variable can't shadow a local variable in an enclosing scope, if
7389         // they are separated by a non-capturing declaration context.
7390         for (DeclContext *ParentDC = NewDC;
7391              ParentDC && !ParentDC->Equals(OldDC);
7392              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7393           // Only block literals, captured statements, and lambda expressions
7394           // can capture; other scopes don't.
7395           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7396               !isLambdaCallOperator(ParentDC)) {
7397             return;
7398           }
7399         }
7400       }
7401     }
7402   }
7403 
7404   // Only warn about certain kinds of shadowing for class members.
7405   if (NewDC && NewDC->isRecord()) {
7406     // In particular, don't warn about shadowing non-class members.
7407     if (!OldDC->isRecord())
7408       return;
7409 
7410     // TODO: should we warn about static data members shadowing
7411     // static data members from base classes?
7412 
7413     // TODO: don't diagnose for inaccessible shadowed members.
7414     // This is hard to do perfectly because we might friend the
7415     // shadowing context, but that's just a false negative.
7416   }
7417 
7418 
7419   DeclarationName Name = R.getLookupName();
7420 
7421   // Emit warning and note.
7422   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7423     return;
7424   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7425   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7426   if (!CaptureLoc.isInvalid())
7427     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7428         << Name << /*explicitly*/ 1;
7429   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7430 }
7431 
7432 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7433 /// when these variables are captured by the lambda.
7434 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7435   for (const auto &Shadow : LSI->ShadowingDecls) {
7436     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7437     // Try to avoid the warning when the shadowed decl isn't captured.
7438     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7439     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7440     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7441                                        ? diag::warn_decl_shadow_uncaptured_local
7442                                        : diag::warn_decl_shadow)
7443         << Shadow.VD->getDeclName()
7444         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7445     if (!CaptureLoc.isInvalid())
7446       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7447           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7448     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7449   }
7450 }
7451 
7452 /// Check -Wshadow without the advantage of a previous lookup.
7453 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7454   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7455     return;
7456 
7457   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7458                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7459   LookupName(R, S);
7460   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7461     CheckShadow(D, ShadowedDecl, R);
7462 }
7463 
7464 /// Check if 'E', which is an expression that is about to be modified, refers
7465 /// to a constructor parameter that shadows a field.
7466 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7467   // Quickly ignore expressions that can't be shadowing ctor parameters.
7468   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7469     return;
7470   E = E->IgnoreParenImpCasts();
7471   auto *DRE = dyn_cast<DeclRefExpr>(E);
7472   if (!DRE)
7473     return;
7474   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7475   auto I = ShadowingDecls.find(D);
7476   if (I == ShadowingDecls.end())
7477     return;
7478   const NamedDecl *ShadowedDecl = I->second;
7479   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7480   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7481   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7482   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7483 
7484   // Avoid issuing multiple warnings about the same decl.
7485   ShadowingDecls.erase(I);
7486 }
7487 
7488 /// Check for conflict between this global or extern "C" declaration and
7489 /// previous global or extern "C" declarations. This is only used in C++.
7490 template<typename T>
7491 static bool checkGlobalOrExternCConflict(
7492     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7493   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7494   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7495 
7496   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7497     // The common case: this global doesn't conflict with any extern "C"
7498     // declaration.
7499     return false;
7500   }
7501 
7502   if (Prev) {
7503     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7504       // Both the old and new declarations have C language linkage. This is a
7505       // redeclaration.
7506       Previous.clear();
7507       Previous.addDecl(Prev);
7508       return true;
7509     }
7510 
7511     // This is a global, non-extern "C" declaration, and there is a previous
7512     // non-global extern "C" declaration. Diagnose if this is a variable
7513     // declaration.
7514     if (!isa<VarDecl>(ND))
7515       return false;
7516   } else {
7517     // The declaration is extern "C". Check for any declaration in the
7518     // translation unit which might conflict.
7519     if (IsGlobal) {
7520       // We have already performed the lookup into the translation unit.
7521       IsGlobal = false;
7522       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7523            I != E; ++I) {
7524         if (isa<VarDecl>(*I)) {
7525           Prev = *I;
7526           break;
7527         }
7528       }
7529     } else {
7530       DeclContext::lookup_result R =
7531           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7532       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7533            I != E; ++I) {
7534         if (isa<VarDecl>(*I)) {
7535           Prev = *I;
7536           break;
7537         }
7538         // FIXME: If we have any other entity with this name in global scope,
7539         // the declaration is ill-formed, but that is a defect: it breaks the
7540         // 'stat' hack, for instance. Only variables can have mangled name
7541         // clashes with extern "C" declarations, so only they deserve a
7542         // diagnostic.
7543       }
7544     }
7545 
7546     if (!Prev)
7547       return false;
7548   }
7549 
7550   // Use the first declaration's location to ensure we point at something which
7551   // is lexically inside an extern "C" linkage-spec.
7552   assert(Prev && "should have found a previous declaration to diagnose");
7553   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7554     Prev = FD->getFirstDecl();
7555   else
7556     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7557 
7558   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7559     << IsGlobal << ND;
7560   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7561     << IsGlobal;
7562   return false;
7563 }
7564 
7565 /// Apply special rules for handling extern "C" declarations. Returns \c true
7566 /// if we have found that this is a redeclaration of some prior entity.
7567 ///
7568 /// Per C++ [dcl.link]p6:
7569 ///   Two declarations [for a function or variable] with C language linkage
7570 ///   with the same name that appear in different scopes refer to the same
7571 ///   [entity]. An entity with C language linkage shall not be declared with
7572 ///   the same name as an entity in global scope.
7573 template<typename T>
7574 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7575                                                   LookupResult &Previous) {
7576   if (!S.getLangOpts().CPlusPlus) {
7577     // In C, when declaring a global variable, look for a corresponding 'extern'
7578     // variable declared in function scope. We don't need this in C++, because
7579     // we find local extern decls in the surrounding file-scope DeclContext.
7580     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7581       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7582         Previous.clear();
7583         Previous.addDecl(Prev);
7584         return true;
7585       }
7586     }
7587     return false;
7588   }
7589 
7590   // A declaration in the translation unit can conflict with an extern "C"
7591   // declaration.
7592   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7593     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7594 
7595   // An extern "C" declaration can conflict with a declaration in the
7596   // translation unit or can be a redeclaration of an extern "C" declaration
7597   // in another scope.
7598   if (isIncompleteDeclExternC(S,ND))
7599     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7600 
7601   // Neither global nor extern "C": nothing to do.
7602   return false;
7603 }
7604 
7605 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7606   // If the decl is already known invalid, don't check it.
7607   if (NewVD->isInvalidDecl())
7608     return;
7609 
7610   QualType T = NewVD->getType();
7611 
7612   // Defer checking an 'auto' type until its initializer is attached.
7613   if (T->isUndeducedType())
7614     return;
7615 
7616   if (NewVD->hasAttrs())
7617     CheckAlignasUnderalignment(NewVD);
7618 
7619   if (T->isObjCObjectType()) {
7620     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7621       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7622     T = Context.getObjCObjectPointerType(T);
7623     NewVD->setType(T);
7624   }
7625 
7626   // Emit an error if an address space was applied to decl with local storage.
7627   // This includes arrays of objects with address space qualifiers, but not
7628   // automatic variables that point to other address spaces.
7629   // ISO/IEC TR 18037 S5.1.2
7630   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7631       T.getAddressSpace() != LangAS::Default) {
7632     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7633     NewVD->setInvalidDecl();
7634     return;
7635   }
7636 
7637   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7638   // scope.
7639   if (getLangOpts().OpenCLVersion == 120 &&
7640       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7641       NewVD->isStaticLocal()) {
7642     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7643     NewVD->setInvalidDecl();
7644     return;
7645   }
7646 
7647   if (getLangOpts().OpenCL) {
7648     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7649     if (NewVD->hasAttr<BlocksAttr>()) {
7650       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7651       return;
7652     }
7653 
7654     if (T->isBlockPointerType()) {
7655       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7656       // can't use 'extern' storage class.
7657       if (!T.isConstQualified()) {
7658         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7659             << 0 /*const*/;
7660         NewVD->setInvalidDecl();
7661         return;
7662       }
7663       if (NewVD->hasExternalStorage()) {
7664         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7665         NewVD->setInvalidDecl();
7666         return;
7667       }
7668     }
7669     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7670     // __constant address space.
7671     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7672     // variables inside a function can also be declared in the global
7673     // address space.
7674     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7675     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7676     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7677         NewVD->hasExternalStorage()) {
7678       if (!T->isSamplerT() &&
7679           !(T.getAddressSpace() == LangAS::opencl_constant ||
7680             (T.getAddressSpace() == LangAS::opencl_global &&
7681              (getLangOpts().OpenCLVersion == 200 ||
7682               getLangOpts().OpenCLCPlusPlus)))) {
7683         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7684         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7685           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7686               << Scope << "global or constant";
7687         else
7688           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7689               << Scope << "constant";
7690         NewVD->setInvalidDecl();
7691         return;
7692       }
7693     } else {
7694       if (T.getAddressSpace() == LangAS::opencl_global) {
7695         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7696             << 1 /*is any function*/ << "global";
7697         NewVD->setInvalidDecl();
7698         return;
7699       }
7700       if (T.getAddressSpace() == LangAS::opencl_constant ||
7701           T.getAddressSpace() == LangAS::opencl_local) {
7702         FunctionDecl *FD = getCurFunctionDecl();
7703         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7704         // in functions.
7705         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7706           if (T.getAddressSpace() == LangAS::opencl_constant)
7707             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7708                 << 0 /*non-kernel only*/ << "constant";
7709           else
7710             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7711                 << 0 /*non-kernel only*/ << "local";
7712           NewVD->setInvalidDecl();
7713           return;
7714         }
7715         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7716         // in the outermost scope of a kernel function.
7717         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7718           if (!getCurScope()->isFunctionScope()) {
7719             if (T.getAddressSpace() == LangAS::opencl_constant)
7720               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7721                   << "constant";
7722             else
7723               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7724                   << "local";
7725             NewVD->setInvalidDecl();
7726             return;
7727           }
7728         }
7729       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7730                  // If we are parsing a template we didn't deduce an addr
7731                  // space yet.
7732                  T.getAddressSpace() != LangAS::Default) {
7733         // Do not allow other address spaces on automatic variable.
7734         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7735         NewVD->setInvalidDecl();
7736         return;
7737       }
7738     }
7739   }
7740 
7741   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7742       && !NewVD->hasAttr<BlocksAttr>()) {
7743     if (getLangOpts().getGC() != LangOptions::NonGC)
7744       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7745     else {
7746       assert(!getLangOpts().ObjCAutoRefCount);
7747       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7748     }
7749   }
7750 
7751   bool isVM = T->isVariablyModifiedType();
7752   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7753       NewVD->hasAttr<BlocksAttr>())
7754     setFunctionHasBranchProtectedScope();
7755 
7756   if ((isVM && NewVD->hasLinkage()) ||
7757       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7758     bool SizeIsNegative;
7759     llvm::APSInt Oversized;
7760     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7761         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7762     QualType FixedT;
7763     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7764       FixedT = FixedTInfo->getType();
7765     else if (FixedTInfo) {
7766       // Type and type-as-written are canonically different. We need to fix up
7767       // both types separately.
7768       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7769                                                    Oversized);
7770     }
7771     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7772       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7773       // FIXME: This won't give the correct result for
7774       // int a[10][n];
7775       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7776 
7777       if (NewVD->isFileVarDecl())
7778         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7779         << SizeRange;
7780       else if (NewVD->isStaticLocal())
7781         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7782         << SizeRange;
7783       else
7784         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7785         << SizeRange;
7786       NewVD->setInvalidDecl();
7787       return;
7788     }
7789 
7790     if (!FixedTInfo) {
7791       if (NewVD->isFileVarDecl())
7792         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7793       else
7794         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7795       NewVD->setInvalidDecl();
7796       return;
7797     }
7798 
7799     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7800     NewVD->setType(FixedT);
7801     NewVD->setTypeSourceInfo(FixedTInfo);
7802   }
7803 
7804   if (T->isVoidType()) {
7805     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7806     //                    of objects and functions.
7807     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7808       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7809         << T;
7810       NewVD->setInvalidDecl();
7811       return;
7812     }
7813   }
7814 
7815   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7816     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7817     NewVD->setInvalidDecl();
7818     return;
7819   }
7820 
7821   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7822     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7823     NewVD->setInvalidDecl();
7824     return;
7825   }
7826 
7827   if (NewVD->isConstexpr() && !T->isDependentType() &&
7828       RequireLiteralType(NewVD->getLocation(), T,
7829                          diag::err_constexpr_var_non_literal)) {
7830     NewVD->setInvalidDecl();
7831     return;
7832   }
7833 }
7834 
7835 /// Perform semantic checking on a newly-created variable
7836 /// declaration.
7837 ///
7838 /// This routine performs all of the type-checking required for a
7839 /// variable declaration once it has been built. It is used both to
7840 /// check variables after they have been parsed and their declarators
7841 /// have been translated into a declaration, and to check variables
7842 /// that have been instantiated from a template.
7843 ///
7844 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7845 ///
7846 /// Returns true if the variable declaration is a redeclaration.
7847 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7848   CheckVariableDeclarationType(NewVD);
7849 
7850   // If the decl is already known invalid, don't check it.
7851   if (NewVD->isInvalidDecl())
7852     return false;
7853 
7854   // If we did not find anything by this name, look for a non-visible
7855   // extern "C" declaration with the same name.
7856   if (Previous.empty() &&
7857       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7858     Previous.setShadowed();
7859 
7860   if (!Previous.empty()) {
7861     MergeVarDecl(NewVD, Previous);
7862     return true;
7863   }
7864   return false;
7865 }
7866 
7867 namespace {
7868 struct FindOverriddenMethod {
7869   Sema *S;
7870   CXXMethodDecl *Method;
7871 
7872   /// Member lookup function that determines whether a given C++
7873   /// method overrides a method in a base class, to be used with
7874   /// CXXRecordDecl::lookupInBases().
7875   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7876     RecordDecl *BaseRecord =
7877         Specifier->getType()->castAs<RecordType>()->getDecl();
7878 
7879     DeclarationName Name = Method->getDeclName();
7880 
7881     // FIXME: Do we care about other names here too?
7882     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7883       // We really want to find the base class destructor here.
7884       QualType T = S->Context.getTypeDeclType(BaseRecord);
7885       CanQualType CT = S->Context.getCanonicalType(T);
7886 
7887       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7888     }
7889 
7890     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7891          Path.Decls = Path.Decls.slice(1)) {
7892       NamedDecl *D = Path.Decls.front();
7893       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7894         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7895           return true;
7896       }
7897     }
7898 
7899     return false;
7900   }
7901 };
7902 
7903 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7904 } // end anonymous namespace
7905 
7906 /// Report an error regarding overriding, along with any relevant
7907 /// overridden methods.
7908 ///
7909 /// \param DiagID the primary error to report.
7910 /// \param MD the overriding method.
7911 /// \param OEK which overrides to include as notes.
7912 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7913                             OverrideErrorKind OEK = OEK_All) {
7914   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7915   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7916     // This check (& the OEK parameter) could be replaced by a predicate, but
7917     // without lambdas that would be overkill. This is still nicer than writing
7918     // out the diag loop 3 times.
7919     if ((OEK == OEK_All) ||
7920         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7921         (OEK == OEK_Deleted && O->isDeleted()))
7922       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7923   }
7924 }
7925 
7926 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7927 /// and if so, check that it's a valid override and remember it.
7928 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7929   // Look for methods in base classes that this method might override.
7930   CXXBasePaths Paths;
7931   FindOverriddenMethod FOM;
7932   FOM.Method = MD;
7933   FOM.S = this;
7934   bool hasDeletedOverridenMethods = false;
7935   bool hasNonDeletedOverridenMethods = false;
7936   bool AddedAny = false;
7937   if (DC->lookupInBases(FOM, Paths)) {
7938     for (auto *I : Paths.found_decls()) {
7939       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7940         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7941         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7942             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7943             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7944             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7945           hasDeletedOverridenMethods |= OldMD->isDeleted();
7946           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7947           AddedAny = true;
7948         }
7949       }
7950     }
7951   }
7952 
7953   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7954     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7955   }
7956   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7957     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7958   }
7959 
7960   return AddedAny;
7961 }
7962 
7963 namespace {
7964   // Struct for holding all of the extra arguments needed by
7965   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7966   struct ActOnFDArgs {
7967     Scope *S;
7968     Declarator &D;
7969     MultiTemplateParamsArg TemplateParamLists;
7970     bool AddToScope;
7971   };
7972 } // end anonymous namespace
7973 
7974 namespace {
7975 
7976 // Callback to only accept typo corrections that have a non-zero edit distance.
7977 // Also only accept corrections that have the same parent decl.
7978 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7979  public:
7980   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7981                             CXXRecordDecl *Parent)
7982       : Context(Context), OriginalFD(TypoFD),
7983         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7984 
7985   bool ValidateCandidate(const TypoCorrection &candidate) override {
7986     if (candidate.getEditDistance() == 0)
7987       return false;
7988 
7989     SmallVector<unsigned, 1> MismatchedParams;
7990     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7991                                           CDeclEnd = candidate.end();
7992          CDecl != CDeclEnd; ++CDecl) {
7993       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7994 
7995       if (FD && !FD->hasBody() &&
7996           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7997         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7998           CXXRecordDecl *Parent = MD->getParent();
7999           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8000             return true;
8001         } else if (!ExpectedParent) {
8002           return true;
8003         }
8004       }
8005     }
8006 
8007     return false;
8008   }
8009 
8010   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8011     return std::make_unique<DifferentNameValidatorCCC>(*this);
8012   }
8013 
8014  private:
8015   ASTContext &Context;
8016   FunctionDecl *OriginalFD;
8017   CXXRecordDecl *ExpectedParent;
8018 };
8019 
8020 } // end anonymous namespace
8021 
8022 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8023   TypoCorrectedFunctionDefinitions.insert(F);
8024 }
8025 
8026 /// Generate diagnostics for an invalid function redeclaration.
8027 ///
8028 /// This routine handles generating the diagnostic messages for an invalid
8029 /// function redeclaration, including finding possible similar declarations
8030 /// or performing typo correction if there are no previous declarations with
8031 /// the same name.
8032 ///
8033 /// Returns a NamedDecl iff typo correction was performed and substituting in
8034 /// the new declaration name does not cause new errors.
8035 static NamedDecl *DiagnoseInvalidRedeclaration(
8036     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8037     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8038   DeclarationName Name = NewFD->getDeclName();
8039   DeclContext *NewDC = NewFD->getDeclContext();
8040   SmallVector<unsigned, 1> MismatchedParams;
8041   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8042   TypoCorrection Correction;
8043   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8044   unsigned DiagMsg =
8045     IsLocalFriend ? diag::err_no_matching_local_friend :
8046     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8047     diag::err_member_decl_does_not_match;
8048   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8049                     IsLocalFriend ? Sema::LookupLocalFriendName
8050                                   : Sema::LookupOrdinaryName,
8051                     Sema::ForVisibleRedeclaration);
8052 
8053   NewFD->setInvalidDecl();
8054   if (IsLocalFriend)
8055     SemaRef.LookupName(Prev, S);
8056   else
8057     SemaRef.LookupQualifiedName(Prev, NewDC);
8058   assert(!Prev.isAmbiguous() &&
8059          "Cannot have an ambiguity in previous-declaration lookup");
8060   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8061   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8062                                 MD ? MD->getParent() : nullptr);
8063   if (!Prev.empty()) {
8064     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8065          Func != FuncEnd; ++Func) {
8066       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8067       if (FD &&
8068           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8069         // Add 1 to the index so that 0 can mean the mismatch didn't
8070         // involve a parameter
8071         unsigned ParamNum =
8072             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8073         NearMatches.push_back(std::make_pair(FD, ParamNum));
8074       }
8075     }
8076   // If the qualified name lookup yielded nothing, try typo correction
8077   } else if ((Correction = SemaRef.CorrectTypo(
8078                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8079                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8080                   IsLocalFriend ? nullptr : NewDC))) {
8081     // Set up everything for the call to ActOnFunctionDeclarator
8082     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8083                               ExtraArgs.D.getIdentifierLoc());
8084     Previous.clear();
8085     Previous.setLookupName(Correction.getCorrection());
8086     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8087                                     CDeclEnd = Correction.end();
8088          CDecl != CDeclEnd; ++CDecl) {
8089       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8090       if (FD && !FD->hasBody() &&
8091           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8092         Previous.addDecl(FD);
8093       }
8094     }
8095     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8096 
8097     NamedDecl *Result;
8098     // Retry building the function declaration with the new previous
8099     // declarations, and with errors suppressed.
8100     {
8101       // Trap errors.
8102       Sema::SFINAETrap Trap(SemaRef);
8103 
8104       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8105       // pieces need to verify the typo-corrected C++ declaration and hopefully
8106       // eliminate the need for the parameter pack ExtraArgs.
8107       Result = SemaRef.ActOnFunctionDeclarator(
8108           ExtraArgs.S, ExtraArgs.D,
8109           Correction.getCorrectionDecl()->getDeclContext(),
8110           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8111           ExtraArgs.AddToScope);
8112 
8113       if (Trap.hasErrorOccurred())
8114         Result = nullptr;
8115     }
8116 
8117     if (Result) {
8118       // Determine which correction we picked.
8119       Decl *Canonical = Result->getCanonicalDecl();
8120       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8121            I != E; ++I)
8122         if ((*I)->getCanonicalDecl() == Canonical)
8123           Correction.setCorrectionDecl(*I);
8124 
8125       // Let Sema know about the correction.
8126       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8127       SemaRef.diagnoseTypo(
8128           Correction,
8129           SemaRef.PDiag(IsLocalFriend
8130                           ? diag::err_no_matching_local_friend_suggest
8131                           : diag::err_member_decl_does_not_match_suggest)
8132             << Name << NewDC << IsDefinition);
8133       return Result;
8134     }
8135 
8136     // Pretend the typo correction never occurred
8137     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8138                               ExtraArgs.D.getIdentifierLoc());
8139     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8140     Previous.clear();
8141     Previous.setLookupName(Name);
8142   }
8143 
8144   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8145       << Name << NewDC << IsDefinition << NewFD->getLocation();
8146 
8147   bool NewFDisConst = false;
8148   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8149     NewFDisConst = NewMD->isConst();
8150 
8151   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8152        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8153        NearMatch != NearMatchEnd; ++NearMatch) {
8154     FunctionDecl *FD = NearMatch->first;
8155     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8156     bool FDisConst = MD && MD->isConst();
8157     bool IsMember = MD || !IsLocalFriend;
8158 
8159     // FIXME: These notes are poorly worded for the local friend case.
8160     if (unsigned Idx = NearMatch->second) {
8161       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8162       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8163       if (Loc.isInvalid()) Loc = FD->getLocation();
8164       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8165                                  : diag::note_local_decl_close_param_match)
8166         << Idx << FDParam->getType()
8167         << NewFD->getParamDecl(Idx - 1)->getType();
8168     } else if (FDisConst != NewFDisConst) {
8169       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8170           << NewFDisConst << FD->getSourceRange().getEnd();
8171     } else
8172       SemaRef.Diag(FD->getLocation(),
8173                    IsMember ? diag::note_member_def_close_match
8174                             : diag::note_local_decl_close_match);
8175   }
8176   return nullptr;
8177 }
8178 
8179 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8180   switch (D.getDeclSpec().getStorageClassSpec()) {
8181   default: llvm_unreachable("Unknown storage class!");
8182   case DeclSpec::SCS_auto:
8183   case DeclSpec::SCS_register:
8184   case DeclSpec::SCS_mutable:
8185     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8186                  diag::err_typecheck_sclass_func);
8187     D.getMutableDeclSpec().ClearStorageClassSpecs();
8188     D.setInvalidType();
8189     break;
8190   case DeclSpec::SCS_unspecified: break;
8191   case DeclSpec::SCS_extern:
8192     if (D.getDeclSpec().isExternInLinkageSpec())
8193       return SC_None;
8194     return SC_Extern;
8195   case DeclSpec::SCS_static: {
8196     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8197       // C99 6.7.1p5:
8198       //   The declaration of an identifier for a function that has
8199       //   block scope shall have no explicit storage-class specifier
8200       //   other than extern
8201       // See also (C++ [dcl.stc]p4).
8202       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8203                    diag::err_static_block_func);
8204       break;
8205     } else
8206       return SC_Static;
8207   }
8208   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8209   }
8210 
8211   // No explicit storage class has already been returned
8212   return SC_None;
8213 }
8214 
8215 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8216                                            DeclContext *DC, QualType &R,
8217                                            TypeSourceInfo *TInfo,
8218                                            StorageClass SC,
8219                                            bool &IsVirtualOkay) {
8220   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8221   DeclarationName Name = NameInfo.getName();
8222 
8223   FunctionDecl *NewFD = nullptr;
8224   bool isInline = D.getDeclSpec().isInlineSpecified();
8225 
8226   if (!SemaRef.getLangOpts().CPlusPlus) {
8227     // Determine whether the function was written with a
8228     // prototype. This true when:
8229     //   - there is a prototype in the declarator, or
8230     //   - the type R of the function is some kind of typedef or other non-
8231     //     attributed reference to a type name (which eventually refers to a
8232     //     function type).
8233     bool HasPrototype =
8234       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8235       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8236 
8237     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8238                                  R, TInfo, SC, isInline, HasPrototype,
8239                                  CSK_unspecified);
8240     if (D.isInvalidType())
8241       NewFD->setInvalidDecl();
8242 
8243     return NewFD;
8244   }
8245 
8246   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8247 
8248   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8249   if (ConstexprKind == CSK_constinit) {
8250     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8251                  diag::err_constexpr_wrong_decl_kind)
8252         << ConstexprKind;
8253     ConstexprKind = CSK_unspecified;
8254     D.getMutableDeclSpec().ClearConstexprSpec();
8255   }
8256 
8257   // Check that the return type is not an abstract class type.
8258   // For record types, this is done by the AbstractClassUsageDiagnoser once
8259   // the class has been completely parsed.
8260   if (!DC->isRecord() &&
8261       SemaRef.RequireNonAbstractType(
8262           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8263           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8264     D.setInvalidType();
8265 
8266   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8267     // This is a C++ constructor declaration.
8268     assert(DC->isRecord() &&
8269            "Constructors can only be declared in a member context");
8270 
8271     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8272     return CXXConstructorDecl::Create(
8273         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8274         TInfo, ExplicitSpecifier, isInline,
8275         /*isImplicitlyDeclared=*/false, ConstexprKind);
8276 
8277   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8278     // This is a C++ destructor declaration.
8279     if (DC->isRecord()) {
8280       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8281       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8282       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8283           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8284           isInline,
8285           /*isImplicitlyDeclared=*/false, ConstexprKind);
8286 
8287       // If the destructor needs an implicit exception specification, set it
8288       // now. FIXME: It'd be nice to be able to create the right type to start
8289       // with, but the type needs to reference the destructor declaration.
8290       if (SemaRef.getLangOpts().CPlusPlus11)
8291         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8292 
8293       IsVirtualOkay = true;
8294       return NewDD;
8295 
8296     } else {
8297       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8298       D.setInvalidType();
8299 
8300       // Create a FunctionDecl to satisfy the function definition parsing
8301       // code path.
8302       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8303                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8304                                   isInline,
8305                                   /*hasPrototype=*/true, ConstexprKind);
8306     }
8307 
8308   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8309     if (!DC->isRecord()) {
8310       SemaRef.Diag(D.getIdentifierLoc(),
8311            diag::err_conv_function_not_member);
8312       return nullptr;
8313     }
8314 
8315     SemaRef.CheckConversionDeclarator(D, R, SC);
8316     if (D.isInvalidType())
8317       return nullptr;
8318 
8319     IsVirtualOkay = true;
8320     return CXXConversionDecl::Create(
8321         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8322         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8323 
8324   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8325     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8326 
8327     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8328                                          ExplicitSpecifier, NameInfo, R, TInfo,
8329                                          D.getEndLoc());
8330   } else if (DC->isRecord()) {
8331     // If the name of the function is the same as the name of the record,
8332     // then this must be an invalid constructor that has a return type.
8333     // (The parser checks for a return type and makes the declarator a
8334     // constructor if it has no return type).
8335     if (Name.getAsIdentifierInfo() &&
8336         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8337       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8338         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8339         << SourceRange(D.getIdentifierLoc());
8340       return nullptr;
8341     }
8342 
8343     // This is a C++ method declaration.
8344     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8345         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8346         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8347     IsVirtualOkay = !Ret->isStatic();
8348     return Ret;
8349   } else {
8350     bool isFriend =
8351         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8352     if (!isFriend && SemaRef.CurContext->isRecord())
8353       return nullptr;
8354 
8355     // Determine whether the function was written with a
8356     // prototype. This true when:
8357     //   - we're in C++ (where every function has a prototype),
8358     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8359                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8360                                 ConstexprKind);
8361   }
8362 }
8363 
8364 enum OpenCLParamType {
8365   ValidKernelParam,
8366   PtrPtrKernelParam,
8367   PtrKernelParam,
8368   InvalidAddrSpacePtrKernelParam,
8369   InvalidKernelParam,
8370   RecordKernelParam
8371 };
8372 
8373 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8374   // Size dependent types are just typedefs to normal integer types
8375   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8376   // integers other than by their names.
8377   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8378 
8379   // Remove typedefs one by one until we reach a typedef
8380   // for a size dependent type.
8381   QualType DesugaredTy = Ty;
8382   do {
8383     ArrayRef<StringRef> Names(SizeTypeNames);
8384     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8385     if (Names.end() != Match)
8386       return true;
8387 
8388     Ty = DesugaredTy;
8389     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8390   } while (DesugaredTy != Ty);
8391 
8392   return false;
8393 }
8394 
8395 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8396   if (PT->isPointerType()) {
8397     QualType PointeeType = PT->getPointeeType();
8398     if (PointeeType->isPointerType())
8399       return PtrPtrKernelParam;
8400     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8401         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8402         PointeeType.getAddressSpace() == LangAS::Default)
8403       return InvalidAddrSpacePtrKernelParam;
8404     return PtrKernelParam;
8405   }
8406 
8407   // OpenCL v1.2 s6.9.k:
8408   // Arguments to kernel functions in a program cannot be declared with the
8409   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8410   // uintptr_t or a struct and/or union that contain fields declared to be one
8411   // of these built-in scalar types.
8412   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8413     return InvalidKernelParam;
8414 
8415   if (PT->isImageType())
8416     return PtrKernelParam;
8417 
8418   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8419     return InvalidKernelParam;
8420 
8421   // OpenCL extension spec v1.2 s9.5:
8422   // This extension adds support for half scalar and vector types as built-in
8423   // types that can be used for arithmetic operations, conversions etc.
8424   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8425     return InvalidKernelParam;
8426 
8427   if (PT->isRecordType())
8428     return RecordKernelParam;
8429 
8430   // Look into an array argument to check if it has a forbidden type.
8431   if (PT->isArrayType()) {
8432     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8433     // Call ourself to check an underlying type of an array. Since the
8434     // getPointeeOrArrayElementType returns an innermost type which is not an
8435     // array, this recursive call only happens once.
8436     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8437   }
8438 
8439   return ValidKernelParam;
8440 }
8441 
8442 static void checkIsValidOpenCLKernelParameter(
8443   Sema &S,
8444   Declarator &D,
8445   ParmVarDecl *Param,
8446   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8447   QualType PT = Param->getType();
8448 
8449   // Cache the valid types we encounter to avoid rechecking structs that are
8450   // used again
8451   if (ValidTypes.count(PT.getTypePtr()))
8452     return;
8453 
8454   switch (getOpenCLKernelParameterType(S, PT)) {
8455   case PtrPtrKernelParam:
8456     // OpenCL v1.2 s6.9.a:
8457     // A kernel function argument cannot be declared as a
8458     // pointer to a pointer type.
8459     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8460     D.setInvalidType();
8461     return;
8462 
8463   case InvalidAddrSpacePtrKernelParam:
8464     // OpenCL v1.0 s6.5:
8465     // __kernel function arguments declared to be a pointer of a type can point
8466     // to one of the following address spaces only : __global, __local or
8467     // __constant.
8468     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8469     D.setInvalidType();
8470     return;
8471 
8472     // OpenCL v1.2 s6.9.k:
8473     // Arguments to kernel functions in a program cannot be declared with the
8474     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8475     // uintptr_t or a struct and/or union that contain fields declared to be
8476     // one of these built-in scalar types.
8477 
8478   case InvalidKernelParam:
8479     // OpenCL v1.2 s6.8 n:
8480     // A kernel function argument cannot be declared
8481     // of event_t type.
8482     // Do not diagnose half type since it is diagnosed as invalid argument
8483     // type for any function elsewhere.
8484     if (!PT->isHalfType()) {
8485       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8486 
8487       // Explain what typedefs are involved.
8488       const TypedefType *Typedef = nullptr;
8489       while ((Typedef = PT->getAs<TypedefType>())) {
8490         SourceLocation Loc = Typedef->getDecl()->getLocation();
8491         // SourceLocation may be invalid for a built-in type.
8492         if (Loc.isValid())
8493           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8494         PT = Typedef->desugar();
8495       }
8496     }
8497 
8498     D.setInvalidType();
8499     return;
8500 
8501   case PtrKernelParam:
8502   case ValidKernelParam:
8503     ValidTypes.insert(PT.getTypePtr());
8504     return;
8505 
8506   case RecordKernelParam:
8507     break;
8508   }
8509 
8510   // Track nested structs we will inspect
8511   SmallVector<const Decl *, 4> VisitStack;
8512 
8513   // Track where we are in the nested structs. Items will migrate from
8514   // VisitStack to HistoryStack as we do the DFS for bad field.
8515   SmallVector<const FieldDecl *, 4> HistoryStack;
8516   HistoryStack.push_back(nullptr);
8517 
8518   // At this point we already handled everything except of a RecordType or
8519   // an ArrayType of a RecordType.
8520   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8521   const RecordType *RecTy =
8522       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8523   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8524 
8525   VisitStack.push_back(RecTy->getDecl());
8526   assert(VisitStack.back() && "First decl null?");
8527 
8528   do {
8529     const Decl *Next = VisitStack.pop_back_val();
8530     if (!Next) {
8531       assert(!HistoryStack.empty());
8532       // Found a marker, we have gone up a level
8533       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8534         ValidTypes.insert(Hist->getType().getTypePtr());
8535 
8536       continue;
8537     }
8538 
8539     // Adds everything except the original parameter declaration (which is not a
8540     // field itself) to the history stack.
8541     const RecordDecl *RD;
8542     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8543       HistoryStack.push_back(Field);
8544 
8545       QualType FieldTy = Field->getType();
8546       // Other field types (known to be valid or invalid) are handled while we
8547       // walk around RecordDecl::fields().
8548       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8549              "Unexpected type.");
8550       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8551 
8552       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8553     } else {
8554       RD = cast<RecordDecl>(Next);
8555     }
8556 
8557     // Add a null marker so we know when we've gone back up a level
8558     VisitStack.push_back(nullptr);
8559 
8560     for (const auto *FD : RD->fields()) {
8561       QualType QT = FD->getType();
8562 
8563       if (ValidTypes.count(QT.getTypePtr()))
8564         continue;
8565 
8566       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8567       if (ParamType == ValidKernelParam)
8568         continue;
8569 
8570       if (ParamType == RecordKernelParam) {
8571         VisitStack.push_back(FD);
8572         continue;
8573       }
8574 
8575       // OpenCL v1.2 s6.9.p:
8576       // Arguments to kernel functions that are declared to be a struct or union
8577       // do not allow OpenCL objects to be passed as elements of the struct or
8578       // union.
8579       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8580           ParamType == InvalidAddrSpacePtrKernelParam) {
8581         S.Diag(Param->getLocation(),
8582                diag::err_record_with_pointers_kernel_param)
8583           << PT->isUnionType()
8584           << PT;
8585       } else {
8586         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8587       }
8588 
8589       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8590           << OrigRecDecl->getDeclName();
8591 
8592       // We have an error, now let's go back up through history and show where
8593       // the offending field came from
8594       for (ArrayRef<const FieldDecl *>::const_iterator
8595                I = HistoryStack.begin() + 1,
8596                E = HistoryStack.end();
8597            I != E; ++I) {
8598         const FieldDecl *OuterField = *I;
8599         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8600           << OuterField->getType();
8601       }
8602 
8603       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8604         << QT->isPointerType()
8605         << QT;
8606       D.setInvalidType();
8607       return;
8608     }
8609   } while (!VisitStack.empty());
8610 }
8611 
8612 /// Find the DeclContext in which a tag is implicitly declared if we see an
8613 /// elaborated type specifier in the specified context, and lookup finds
8614 /// nothing.
8615 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8616   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8617     DC = DC->getParent();
8618   return DC;
8619 }
8620 
8621 /// Find the Scope in which a tag is implicitly declared if we see an
8622 /// elaborated type specifier in the specified context, and lookup finds
8623 /// nothing.
8624 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8625   while (S->isClassScope() ||
8626          (LangOpts.CPlusPlus &&
8627           S->isFunctionPrototypeScope()) ||
8628          ((S->getFlags() & Scope::DeclScope) == 0) ||
8629          (S->getEntity() && S->getEntity()->isTransparentContext()))
8630     S = S->getParent();
8631   return S;
8632 }
8633 
8634 NamedDecl*
8635 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8636                               TypeSourceInfo *TInfo, LookupResult &Previous,
8637                               MultiTemplateParamsArg TemplateParamLists,
8638                               bool &AddToScope) {
8639   QualType R = TInfo->getType();
8640 
8641   assert(R->isFunctionType());
8642 
8643   // TODO: consider using NameInfo for diagnostic.
8644   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8645   DeclarationName Name = NameInfo.getName();
8646   StorageClass SC = getFunctionStorageClass(*this, D);
8647 
8648   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8649     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8650          diag::err_invalid_thread)
8651       << DeclSpec::getSpecifierName(TSCS);
8652 
8653   if (D.isFirstDeclarationOfMember())
8654     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8655                            D.getIdentifierLoc());
8656 
8657   bool isFriend = false;
8658   FunctionTemplateDecl *FunctionTemplate = nullptr;
8659   bool isMemberSpecialization = false;
8660   bool isFunctionTemplateSpecialization = false;
8661 
8662   bool isDependentClassScopeExplicitSpecialization = false;
8663   bool HasExplicitTemplateArgs = false;
8664   TemplateArgumentListInfo TemplateArgs;
8665 
8666   bool isVirtualOkay = false;
8667 
8668   DeclContext *OriginalDC = DC;
8669   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8670 
8671   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8672                                               isVirtualOkay);
8673   if (!NewFD) return nullptr;
8674 
8675   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8676     NewFD->setTopLevelDeclInObjCContainer();
8677 
8678   // Set the lexical context. If this is a function-scope declaration, or has a
8679   // C++ scope specifier, or is the object of a friend declaration, the lexical
8680   // context will be different from the semantic context.
8681   NewFD->setLexicalDeclContext(CurContext);
8682 
8683   if (IsLocalExternDecl)
8684     NewFD->setLocalExternDecl();
8685 
8686   if (getLangOpts().CPlusPlus) {
8687     bool isInline = D.getDeclSpec().isInlineSpecified();
8688     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8689     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8690     isFriend = D.getDeclSpec().isFriendSpecified();
8691     if (isFriend && !isInline && D.isFunctionDefinition()) {
8692       // C++ [class.friend]p5
8693       //   A function can be defined in a friend declaration of a
8694       //   class . . . . Such a function is implicitly inline.
8695       NewFD->setImplicitlyInline();
8696     }
8697 
8698     // If this is a method defined in an __interface, and is not a constructor
8699     // or an overloaded operator, then set the pure flag (isVirtual will already
8700     // return true).
8701     if (const CXXRecordDecl *Parent =
8702           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8703       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8704         NewFD->setPure(true);
8705 
8706       // C++ [class.union]p2
8707       //   A union can have member functions, but not virtual functions.
8708       if (isVirtual && Parent->isUnion())
8709         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8710     }
8711 
8712     SetNestedNameSpecifier(*this, NewFD, D);
8713     isMemberSpecialization = false;
8714     isFunctionTemplateSpecialization = false;
8715     if (D.isInvalidType())
8716       NewFD->setInvalidDecl();
8717 
8718     // Match up the template parameter lists with the scope specifier, then
8719     // determine whether we have a template or a template specialization.
8720     bool Invalid = false;
8721     if (TemplateParameterList *TemplateParams =
8722             MatchTemplateParametersToScopeSpecifier(
8723                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8724                 D.getCXXScopeSpec(),
8725                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8726                     ? D.getName().TemplateId
8727                     : nullptr,
8728                 TemplateParamLists, isFriend, isMemberSpecialization,
8729                 Invalid)) {
8730       if (TemplateParams->size() > 0) {
8731         // This is a function template
8732 
8733         // Check that we can declare a template here.
8734         if (CheckTemplateDeclScope(S, TemplateParams))
8735           NewFD->setInvalidDecl();
8736 
8737         // A destructor cannot be a template.
8738         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8739           Diag(NewFD->getLocation(), diag::err_destructor_template);
8740           NewFD->setInvalidDecl();
8741         }
8742 
8743         // If we're adding a template to a dependent context, we may need to
8744         // rebuilding some of the types used within the template parameter list,
8745         // now that we know what the current instantiation is.
8746         if (DC->isDependentContext()) {
8747           ContextRAII SavedContext(*this, DC);
8748           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8749             Invalid = true;
8750         }
8751 
8752         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8753                                                         NewFD->getLocation(),
8754                                                         Name, TemplateParams,
8755                                                         NewFD);
8756         FunctionTemplate->setLexicalDeclContext(CurContext);
8757         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8758 
8759         // For source fidelity, store the other template param lists.
8760         if (TemplateParamLists.size() > 1) {
8761           NewFD->setTemplateParameterListsInfo(Context,
8762                                                TemplateParamLists.drop_back(1));
8763         }
8764       } else {
8765         // This is a function template specialization.
8766         isFunctionTemplateSpecialization = true;
8767         // For source fidelity, store all the template param lists.
8768         if (TemplateParamLists.size() > 0)
8769           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8770 
8771         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8772         if (isFriend) {
8773           // We want to remove the "template<>", found here.
8774           SourceRange RemoveRange = TemplateParams->getSourceRange();
8775 
8776           // If we remove the template<> and the name is not a
8777           // template-id, we're actually silently creating a problem:
8778           // the friend declaration will refer to an untemplated decl,
8779           // and clearly the user wants a template specialization.  So
8780           // we need to insert '<>' after the name.
8781           SourceLocation InsertLoc;
8782           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8783             InsertLoc = D.getName().getSourceRange().getEnd();
8784             InsertLoc = getLocForEndOfToken(InsertLoc);
8785           }
8786 
8787           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8788             << Name << RemoveRange
8789             << FixItHint::CreateRemoval(RemoveRange)
8790             << FixItHint::CreateInsertion(InsertLoc, "<>");
8791         }
8792       }
8793     } else {
8794       // All template param lists were matched against the scope specifier:
8795       // this is NOT (an explicit specialization of) a template.
8796       if (TemplateParamLists.size() > 0)
8797         // For source fidelity, store all the template param lists.
8798         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8799     }
8800 
8801     if (Invalid) {
8802       NewFD->setInvalidDecl();
8803       if (FunctionTemplate)
8804         FunctionTemplate->setInvalidDecl();
8805     }
8806 
8807     // C++ [dcl.fct.spec]p5:
8808     //   The virtual specifier shall only be used in declarations of
8809     //   nonstatic class member functions that appear within a
8810     //   member-specification of a class declaration; see 10.3.
8811     //
8812     if (isVirtual && !NewFD->isInvalidDecl()) {
8813       if (!isVirtualOkay) {
8814         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8815              diag::err_virtual_non_function);
8816       } else if (!CurContext->isRecord()) {
8817         // 'virtual' was specified outside of the class.
8818         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8819              diag::err_virtual_out_of_class)
8820           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8821       } else if (NewFD->getDescribedFunctionTemplate()) {
8822         // C++ [temp.mem]p3:
8823         //  A member function template shall not be virtual.
8824         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8825              diag::err_virtual_member_function_template)
8826           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8827       } else {
8828         // Okay: Add virtual to the method.
8829         NewFD->setVirtualAsWritten(true);
8830       }
8831 
8832       if (getLangOpts().CPlusPlus14 &&
8833           NewFD->getReturnType()->isUndeducedType())
8834         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8835     }
8836 
8837     if (getLangOpts().CPlusPlus14 &&
8838         (NewFD->isDependentContext() ||
8839          (isFriend && CurContext->isDependentContext())) &&
8840         NewFD->getReturnType()->isUndeducedType()) {
8841       // If the function template is referenced directly (for instance, as a
8842       // member of the current instantiation), pretend it has a dependent type.
8843       // This is not really justified by the standard, but is the only sane
8844       // thing to do.
8845       // FIXME: For a friend function, we have not marked the function as being
8846       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8847       const FunctionProtoType *FPT =
8848           NewFD->getType()->castAs<FunctionProtoType>();
8849       QualType Result =
8850           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8851       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8852                                              FPT->getExtProtoInfo()));
8853     }
8854 
8855     // C++ [dcl.fct.spec]p3:
8856     //  The inline specifier shall not appear on a block scope function
8857     //  declaration.
8858     if (isInline && !NewFD->isInvalidDecl()) {
8859       if (CurContext->isFunctionOrMethod()) {
8860         // 'inline' is not allowed on block scope function declaration.
8861         Diag(D.getDeclSpec().getInlineSpecLoc(),
8862              diag::err_inline_declaration_block_scope) << Name
8863           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8864       }
8865     }
8866 
8867     // C++ [dcl.fct.spec]p6:
8868     //  The explicit specifier shall be used only in the declaration of a
8869     //  constructor or conversion function within its class definition;
8870     //  see 12.3.1 and 12.3.2.
8871     if (hasExplicit && !NewFD->isInvalidDecl() &&
8872         !isa<CXXDeductionGuideDecl>(NewFD)) {
8873       if (!CurContext->isRecord()) {
8874         // 'explicit' was specified outside of the class.
8875         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8876              diag::err_explicit_out_of_class)
8877             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8878       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8879                  !isa<CXXConversionDecl>(NewFD)) {
8880         // 'explicit' was specified on a function that wasn't a constructor
8881         // or conversion function.
8882         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8883              diag::err_explicit_non_ctor_or_conv_function)
8884             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8885       }
8886     }
8887 
8888     if (ConstexprSpecKind ConstexprKind =
8889             D.getDeclSpec().getConstexprSpecifier()) {
8890       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8891       // are implicitly inline.
8892       NewFD->setImplicitlyInline();
8893 
8894       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8895       // be either constructors or to return a literal type. Therefore,
8896       // destructors cannot be declared constexpr.
8897       if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
8898         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8899             << ConstexprKind;
8900       }
8901     }
8902 
8903     // If __module_private__ was specified, mark the function accordingly.
8904     if (D.getDeclSpec().isModulePrivateSpecified()) {
8905       if (isFunctionTemplateSpecialization) {
8906         SourceLocation ModulePrivateLoc
8907           = D.getDeclSpec().getModulePrivateSpecLoc();
8908         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8909           << 0
8910           << FixItHint::CreateRemoval(ModulePrivateLoc);
8911       } else {
8912         NewFD->setModulePrivate();
8913         if (FunctionTemplate)
8914           FunctionTemplate->setModulePrivate();
8915       }
8916     }
8917 
8918     if (isFriend) {
8919       if (FunctionTemplate) {
8920         FunctionTemplate->setObjectOfFriendDecl();
8921         FunctionTemplate->setAccess(AS_public);
8922       }
8923       NewFD->setObjectOfFriendDecl();
8924       NewFD->setAccess(AS_public);
8925     }
8926 
8927     // If a function is defined as defaulted or deleted, mark it as such now.
8928     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8929     // definition kind to FDK_Definition.
8930     switch (D.getFunctionDefinitionKind()) {
8931       case FDK_Declaration:
8932       case FDK_Definition:
8933         break;
8934 
8935       case FDK_Defaulted:
8936         NewFD->setDefaulted();
8937         break;
8938 
8939       case FDK_Deleted:
8940         NewFD->setDeletedAsWritten();
8941         break;
8942     }
8943 
8944     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8945         D.isFunctionDefinition()) {
8946       // C++ [class.mfct]p2:
8947       //   A member function may be defined (8.4) in its class definition, in
8948       //   which case it is an inline member function (7.1.2)
8949       NewFD->setImplicitlyInline();
8950     }
8951 
8952     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8953         !CurContext->isRecord()) {
8954       // C++ [class.static]p1:
8955       //   A data or function member of a class may be declared static
8956       //   in a class definition, in which case it is a static member of
8957       //   the class.
8958 
8959       // Complain about the 'static' specifier if it's on an out-of-line
8960       // member function definition.
8961 
8962       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8963       // member function template declaration and class member template
8964       // declaration (MSVC versions before 2015), warn about this.
8965       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8966            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8967              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8968            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8969            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8970         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8971     }
8972 
8973     // C++11 [except.spec]p15:
8974     //   A deallocation function with no exception-specification is treated
8975     //   as if it were specified with noexcept(true).
8976     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8977     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8978          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8979         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8980       NewFD->setType(Context.getFunctionType(
8981           FPT->getReturnType(), FPT->getParamTypes(),
8982           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8983   }
8984 
8985   // Filter out previous declarations that don't match the scope.
8986   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8987                        D.getCXXScopeSpec().isNotEmpty() ||
8988                        isMemberSpecialization ||
8989                        isFunctionTemplateSpecialization);
8990 
8991   // Handle GNU asm-label extension (encoded as an attribute).
8992   if (Expr *E = (Expr*) D.getAsmLabel()) {
8993     // The parser guarantees this is a string.
8994     StringLiteral *SE = cast<StringLiteral>(E);
8995     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
8996                                         /*IsLiteralLabel=*/true,
8997                                         SE->getStrTokenLoc(0)));
8998   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8999     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9000       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9001     if (I != ExtnameUndeclaredIdentifiers.end()) {
9002       if (isDeclExternC(NewFD)) {
9003         NewFD->addAttr(I->second);
9004         ExtnameUndeclaredIdentifiers.erase(I);
9005       } else
9006         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9007             << /*Variable*/0 << NewFD;
9008     }
9009   }
9010 
9011   // Copy the parameter declarations from the declarator D to the function
9012   // declaration NewFD, if they are available.  First scavenge them into Params.
9013   SmallVector<ParmVarDecl*, 16> Params;
9014   unsigned FTIIdx;
9015   if (D.isFunctionDeclarator(FTIIdx)) {
9016     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9017 
9018     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9019     // function that takes no arguments, not a function that takes a
9020     // single void argument.
9021     // We let through "const void" here because Sema::GetTypeForDeclarator
9022     // already checks for that case.
9023     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9024       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9025         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9026         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9027         Param->setDeclContext(NewFD);
9028         Params.push_back(Param);
9029 
9030         if (Param->isInvalidDecl())
9031           NewFD->setInvalidDecl();
9032       }
9033     }
9034 
9035     if (!getLangOpts().CPlusPlus) {
9036       // In C, find all the tag declarations from the prototype and move them
9037       // into the function DeclContext. Remove them from the surrounding tag
9038       // injection context of the function, which is typically but not always
9039       // the TU.
9040       DeclContext *PrototypeTagContext =
9041           getTagInjectionContext(NewFD->getLexicalDeclContext());
9042       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9043         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9044 
9045         // We don't want to reparent enumerators. Look at their parent enum
9046         // instead.
9047         if (!TD) {
9048           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9049             TD = cast<EnumDecl>(ECD->getDeclContext());
9050         }
9051         if (!TD)
9052           continue;
9053         DeclContext *TagDC = TD->getLexicalDeclContext();
9054         if (!TagDC->containsDecl(TD))
9055           continue;
9056         TagDC->removeDecl(TD);
9057         TD->setDeclContext(NewFD);
9058         NewFD->addDecl(TD);
9059 
9060         // Preserve the lexical DeclContext if it is not the surrounding tag
9061         // injection context of the FD. In this example, the semantic context of
9062         // E will be f and the lexical context will be S, while both the
9063         // semantic and lexical contexts of S will be f:
9064         //   void f(struct S { enum E { a } f; } s);
9065         if (TagDC != PrototypeTagContext)
9066           TD->setLexicalDeclContext(TagDC);
9067       }
9068     }
9069   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9070     // When we're declaring a function with a typedef, typeof, etc as in the
9071     // following example, we'll need to synthesize (unnamed)
9072     // parameters for use in the declaration.
9073     //
9074     // @code
9075     // typedef void fn(int);
9076     // fn f;
9077     // @endcode
9078 
9079     // Synthesize a parameter for each argument type.
9080     for (const auto &AI : FT->param_types()) {
9081       ParmVarDecl *Param =
9082           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9083       Param->setScopeInfo(0, Params.size());
9084       Params.push_back(Param);
9085     }
9086   } else {
9087     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9088            "Should not need args for typedef of non-prototype fn");
9089   }
9090 
9091   // Finally, we know we have the right number of parameters, install them.
9092   NewFD->setParams(Params);
9093 
9094   if (D.getDeclSpec().isNoreturnSpecified())
9095     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9096                                            D.getDeclSpec().getNoreturnSpecLoc(),
9097                                            AttributeCommonInfo::AS_Keyword));
9098 
9099   // Functions returning a variably modified type violate C99 6.7.5.2p2
9100   // because all functions have linkage.
9101   if (!NewFD->isInvalidDecl() &&
9102       NewFD->getReturnType()->isVariablyModifiedType()) {
9103     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9104     NewFD->setInvalidDecl();
9105   }
9106 
9107   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9108   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9109       !NewFD->hasAttr<SectionAttr>())
9110     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9111         Context, PragmaClangTextSection.SectionName,
9112         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9113 
9114   // Apply an implicit SectionAttr if #pragma code_seg is active.
9115   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9116       !NewFD->hasAttr<SectionAttr>()) {
9117     NewFD->addAttr(SectionAttr::CreateImplicit(
9118         Context, CodeSegStack.CurrentValue->getString(),
9119         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9120         SectionAttr::Declspec_allocate));
9121     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9122                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9123                          ASTContext::PSF_Read,
9124                      NewFD))
9125       NewFD->dropAttr<SectionAttr>();
9126   }
9127 
9128   // Apply an implicit CodeSegAttr from class declspec or
9129   // apply an implicit SectionAttr from #pragma code_seg if active.
9130   if (!NewFD->hasAttr<CodeSegAttr>()) {
9131     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9132                                                                  D.isFunctionDefinition())) {
9133       NewFD->addAttr(SAttr);
9134     }
9135   }
9136 
9137   // Handle attributes.
9138   ProcessDeclAttributes(S, NewFD, D);
9139 
9140   if (getLangOpts().OpenCL) {
9141     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9142     // type declaration will generate a compilation error.
9143     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9144     if (AddressSpace != LangAS::Default) {
9145       Diag(NewFD->getLocation(),
9146            diag::err_opencl_return_value_with_address_space);
9147       NewFD->setInvalidDecl();
9148     }
9149   }
9150 
9151   if (!getLangOpts().CPlusPlus) {
9152     // Perform semantic checking on the function declaration.
9153     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9154       CheckMain(NewFD, D.getDeclSpec());
9155 
9156     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9157       CheckMSVCRTEntryPoint(NewFD);
9158 
9159     if (!NewFD->isInvalidDecl())
9160       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9161                                                   isMemberSpecialization));
9162     else if (!Previous.empty())
9163       // Recover gracefully from an invalid redeclaration.
9164       D.setRedeclaration(true);
9165     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9166             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9167            "previous declaration set still overloaded");
9168 
9169     // Diagnose no-prototype function declarations with calling conventions that
9170     // don't support variadic calls. Only do this in C and do it after merging
9171     // possibly prototyped redeclarations.
9172     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9173     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9174       CallingConv CC = FT->getExtInfo().getCC();
9175       if (!supportsVariadicCall(CC)) {
9176         // Windows system headers sometimes accidentally use stdcall without
9177         // (void) parameters, so we relax this to a warning.
9178         int DiagID =
9179             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9180         Diag(NewFD->getLocation(), DiagID)
9181             << FunctionType::getNameForCallConv(CC);
9182       }
9183     }
9184 
9185    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9186        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9187      checkNonTrivialCUnion(NewFD->getReturnType(),
9188                            NewFD->getReturnTypeSourceRange().getBegin(),
9189                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9190   } else {
9191     // C++11 [replacement.functions]p3:
9192     //  The program's definitions shall not be specified as inline.
9193     //
9194     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9195     //
9196     // Suppress the diagnostic if the function is __attribute__((used)), since
9197     // that forces an external definition to be emitted.
9198     if (D.getDeclSpec().isInlineSpecified() &&
9199         NewFD->isReplaceableGlobalAllocationFunction() &&
9200         !NewFD->hasAttr<UsedAttr>())
9201       Diag(D.getDeclSpec().getInlineSpecLoc(),
9202            diag::ext_operator_new_delete_declared_inline)
9203         << NewFD->getDeclName();
9204 
9205     // If the declarator is a template-id, translate the parser's template
9206     // argument list into our AST format.
9207     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9208       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9209       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9210       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9211       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9212                                          TemplateId->NumArgs);
9213       translateTemplateArguments(TemplateArgsPtr,
9214                                  TemplateArgs);
9215 
9216       HasExplicitTemplateArgs = true;
9217 
9218       if (NewFD->isInvalidDecl()) {
9219         HasExplicitTemplateArgs = false;
9220       } else if (FunctionTemplate) {
9221         // Function template with explicit template arguments.
9222         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9223           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9224 
9225         HasExplicitTemplateArgs = false;
9226       } else {
9227         assert((isFunctionTemplateSpecialization ||
9228                 D.getDeclSpec().isFriendSpecified()) &&
9229                "should have a 'template<>' for this decl");
9230         // "friend void foo<>(int);" is an implicit specialization decl.
9231         isFunctionTemplateSpecialization = true;
9232       }
9233     } else if (isFriend && isFunctionTemplateSpecialization) {
9234       // This combination is only possible in a recovery case;  the user
9235       // wrote something like:
9236       //   template <> friend void foo(int);
9237       // which we're recovering from as if the user had written:
9238       //   friend void foo<>(int);
9239       // Go ahead and fake up a template id.
9240       HasExplicitTemplateArgs = true;
9241       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9242       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9243     }
9244 
9245     // We do not add HD attributes to specializations here because
9246     // they may have different constexpr-ness compared to their
9247     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9248     // may end up with different effective targets. Instead, a
9249     // specialization inherits its target attributes from its template
9250     // in the CheckFunctionTemplateSpecialization() call below.
9251     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9252       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9253 
9254     // If it's a friend (and only if it's a friend), it's possible
9255     // that either the specialized function type or the specialized
9256     // template is dependent, and therefore matching will fail.  In
9257     // this case, don't check the specialization yet.
9258     bool InstantiationDependent = false;
9259     if (isFunctionTemplateSpecialization && isFriend &&
9260         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9261          TemplateSpecializationType::anyDependentTemplateArguments(
9262             TemplateArgs,
9263             InstantiationDependent))) {
9264       assert(HasExplicitTemplateArgs &&
9265              "friend function specialization without template args");
9266       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9267                                                        Previous))
9268         NewFD->setInvalidDecl();
9269     } else if (isFunctionTemplateSpecialization) {
9270       if (CurContext->isDependentContext() && CurContext->isRecord()
9271           && !isFriend) {
9272         isDependentClassScopeExplicitSpecialization = true;
9273       } else if (!NewFD->isInvalidDecl() &&
9274                  CheckFunctionTemplateSpecialization(
9275                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9276                      Previous))
9277         NewFD->setInvalidDecl();
9278 
9279       // C++ [dcl.stc]p1:
9280       //   A storage-class-specifier shall not be specified in an explicit
9281       //   specialization (14.7.3)
9282       FunctionTemplateSpecializationInfo *Info =
9283           NewFD->getTemplateSpecializationInfo();
9284       if (Info && SC != SC_None) {
9285         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9286           Diag(NewFD->getLocation(),
9287                diag::err_explicit_specialization_inconsistent_storage_class)
9288             << SC
9289             << FixItHint::CreateRemoval(
9290                                       D.getDeclSpec().getStorageClassSpecLoc());
9291 
9292         else
9293           Diag(NewFD->getLocation(),
9294                diag::ext_explicit_specialization_storage_class)
9295             << FixItHint::CreateRemoval(
9296                                       D.getDeclSpec().getStorageClassSpecLoc());
9297       }
9298     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9299       if (CheckMemberSpecialization(NewFD, Previous))
9300           NewFD->setInvalidDecl();
9301     }
9302 
9303     // Perform semantic checking on the function declaration.
9304     if (!isDependentClassScopeExplicitSpecialization) {
9305       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9306         CheckMain(NewFD, D.getDeclSpec());
9307 
9308       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9309         CheckMSVCRTEntryPoint(NewFD);
9310 
9311       if (!NewFD->isInvalidDecl())
9312         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9313                                                     isMemberSpecialization));
9314       else if (!Previous.empty())
9315         // Recover gracefully from an invalid redeclaration.
9316         D.setRedeclaration(true);
9317     }
9318 
9319     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9320             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9321            "previous declaration set still overloaded");
9322 
9323     NamedDecl *PrincipalDecl = (FunctionTemplate
9324                                 ? cast<NamedDecl>(FunctionTemplate)
9325                                 : NewFD);
9326 
9327     if (isFriend && NewFD->getPreviousDecl()) {
9328       AccessSpecifier Access = AS_public;
9329       if (!NewFD->isInvalidDecl())
9330         Access = NewFD->getPreviousDecl()->getAccess();
9331 
9332       NewFD->setAccess(Access);
9333       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9334     }
9335 
9336     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9337         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9338       PrincipalDecl->setNonMemberOperator();
9339 
9340     // If we have a function template, check the template parameter
9341     // list. This will check and merge default template arguments.
9342     if (FunctionTemplate) {
9343       FunctionTemplateDecl *PrevTemplate =
9344                                      FunctionTemplate->getPreviousDecl();
9345       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9346                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9347                                     : nullptr,
9348                             D.getDeclSpec().isFriendSpecified()
9349                               ? (D.isFunctionDefinition()
9350                                    ? TPC_FriendFunctionTemplateDefinition
9351                                    : TPC_FriendFunctionTemplate)
9352                               : (D.getCXXScopeSpec().isSet() &&
9353                                  DC && DC->isRecord() &&
9354                                  DC->isDependentContext())
9355                                   ? TPC_ClassTemplateMember
9356                                   : TPC_FunctionTemplate);
9357     }
9358 
9359     if (NewFD->isInvalidDecl()) {
9360       // Ignore all the rest of this.
9361     } else if (!D.isRedeclaration()) {
9362       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9363                                        AddToScope };
9364       // Fake up an access specifier if it's supposed to be a class member.
9365       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9366         NewFD->setAccess(AS_public);
9367 
9368       // Qualified decls generally require a previous declaration.
9369       if (D.getCXXScopeSpec().isSet()) {
9370         // ...with the major exception of templated-scope or
9371         // dependent-scope friend declarations.
9372 
9373         // TODO: we currently also suppress this check in dependent
9374         // contexts because (1) the parameter depth will be off when
9375         // matching friend templates and (2) we might actually be
9376         // selecting a friend based on a dependent factor.  But there
9377         // are situations where these conditions don't apply and we
9378         // can actually do this check immediately.
9379         //
9380         // Unless the scope is dependent, it's always an error if qualified
9381         // redeclaration lookup found nothing at all. Diagnose that now;
9382         // nothing will diagnose that error later.
9383         if (isFriend &&
9384             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9385              (!Previous.empty() && CurContext->isDependentContext()))) {
9386           // ignore these
9387         } else {
9388           // The user tried to provide an out-of-line definition for a
9389           // function that is a member of a class or namespace, but there
9390           // was no such member function declared (C++ [class.mfct]p2,
9391           // C++ [namespace.memdef]p2). For example:
9392           //
9393           // class X {
9394           //   void f() const;
9395           // };
9396           //
9397           // void X::f() { } // ill-formed
9398           //
9399           // Complain about this problem, and attempt to suggest close
9400           // matches (e.g., those that differ only in cv-qualifiers and
9401           // whether the parameter types are references).
9402 
9403           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9404                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9405             AddToScope = ExtraArgs.AddToScope;
9406             return Result;
9407           }
9408         }
9409 
9410         // Unqualified local friend declarations are required to resolve
9411         // to something.
9412       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9413         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9414                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9415           AddToScope = ExtraArgs.AddToScope;
9416           return Result;
9417         }
9418       }
9419     } else if (!D.isFunctionDefinition() &&
9420                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9421                !isFriend && !isFunctionTemplateSpecialization &&
9422                !isMemberSpecialization) {
9423       // An out-of-line member function declaration must also be a
9424       // definition (C++ [class.mfct]p2).
9425       // Note that this is not the case for explicit specializations of
9426       // function templates or member functions of class templates, per
9427       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9428       // extension for compatibility with old SWIG code which likes to
9429       // generate them.
9430       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9431         << D.getCXXScopeSpec().getRange();
9432     }
9433   }
9434 
9435   ProcessPragmaWeak(S, NewFD);
9436   checkAttributesAfterMerging(*this, *NewFD);
9437 
9438   AddKnownFunctionAttributes(NewFD);
9439 
9440   if (NewFD->hasAttr<OverloadableAttr>() &&
9441       !NewFD->getType()->getAs<FunctionProtoType>()) {
9442     Diag(NewFD->getLocation(),
9443          diag::err_attribute_overloadable_no_prototype)
9444       << NewFD;
9445 
9446     // Turn this into a variadic function with no parameters.
9447     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9448     FunctionProtoType::ExtProtoInfo EPI(
9449         Context.getDefaultCallingConvention(true, false));
9450     EPI.Variadic = true;
9451     EPI.ExtInfo = FT->getExtInfo();
9452 
9453     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9454     NewFD->setType(R);
9455   }
9456 
9457   // If there's a #pragma GCC visibility in scope, and this isn't a class
9458   // member, set the visibility of this function.
9459   if (!DC->isRecord() && NewFD->isExternallyVisible())
9460     AddPushedVisibilityAttribute(NewFD);
9461 
9462   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9463   // marking the function.
9464   AddCFAuditedAttribute(NewFD);
9465 
9466   // If this is a function definition, check if we have to apply optnone due to
9467   // a pragma.
9468   if(D.isFunctionDefinition())
9469     AddRangeBasedOptnone(NewFD);
9470 
9471   // If this is the first declaration of an extern C variable, update
9472   // the map of such variables.
9473   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9474       isIncompleteDeclExternC(*this, NewFD))
9475     RegisterLocallyScopedExternCDecl(NewFD, S);
9476 
9477   // Set this FunctionDecl's range up to the right paren.
9478   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9479 
9480   if (D.isRedeclaration() && !Previous.empty()) {
9481     NamedDecl *Prev = Previous.getRepresentativeDecl();
9482     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9483                                    isMemberSpecialization ||
9484                                        isFunctionTemplateSpecialization,
9485                                    D.isFunctionDefinition());
9486   }
9487 
9488   if (getLangOpts().CUDA) {
9489     IdentifierInfo *II = NewFD->getIdentifier();
9490     if (II && II->isStr(getCudaConfigureFuncName()) &&
9491         !NewFD->isInvalidDecl() &&
9492         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9493       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9494         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9495             << getCudaConfigureFuncName();
9496       Context.setcudaConfigureCallDecl(NewFD);
9497     }
9498 
9499     // Variadic functions, other than a *declaration* of printf, are not allowed
9500     // in device-side CUDA code, unless someone passed
9501     // -fcuda-allow-variadic-functions.
9502     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9503         (NewFD->hasAttr<CUDADeviceAttr>() ||
9504          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9505         !(II && II->isStr("printf") && NewFD->isExternC() &&
9506           !D.isFunctionDefinition())) {
9507       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9508     }
9509   }
9510 
9511   MarkUnusedFileScopedDecl(NewFD);
9512 
9513 
9514 
9515   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9516     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9517     if ((getLangOpts().OpenCLVersion >= 120)
9518         && (SC == SC_Static)) {
9519       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9520       D.setInvalidType();
9521     }
9522 
9523     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9524     if (!NewFD->getReturnType()->isVoidType()) {
9525       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9526       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9527           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9528                                 : FixItHint());
9529       D.setInvalidType();
9530     }
9531 
9532     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9533     for (auto Param : NewFD->parameters())
9534       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9535 
9536     if (getLangOpts().OpenCLCPlusPlus) {
9537       if (DC->isRecord()) {
9538         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9539         D.setInvalidType();
9540       }
9541       if (FunctionTemplate) {
9542         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9543         D.setInvalidType();
9544       }
9545     }
9546   }
9547 
9548   if (getLangOpts().CPlusPlus) {
9549     if (FunctionTemplate) {
9550       if (NewFD->isInvalidDecl())
9551         FunctionTemplate->setInvalidDecl();
9552       return FunctionTemplate;
9553     }
9554 
9555     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9556       CompleteMemberSpecialization(NewFD, Previous);
9557   }
9558 
9559   for (const ParmVarDecl *Param : NewFD->parameters()) {
9560     QualType PT = Param->getType();
9561 
9562     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9563     // types.
9564     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9565       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9566         QualType ElemTy = PipeTy->getElementType();
9567           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9568             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9569             D.setInvalidType();
9570           }
9571       }
9572     }
9573   }
9574 
9575   // Here we have an function template explicit specialization at class scope.
9576   // The actual specialization will be postponed to template instatiation
9577   // time via the ClassScopeFunctionSpecializationDecl node.
9578   if (isDependentClassScopeExplicitSpecialization) {
9579     ClassScopeFunctionSpecializationDecl *NewSpec =
9580                          ClassScopeFunctionSpecializationDecl::Create(
9581                                 Context, CurContext, NewFD->getLocation(),
9582                                 cast<CXXMethodDecl>(NewFD),
9583                                 HasExplicitTemplateArgs, TemplateArgs);
9584     CurContext->addDecl(NewSpec);
9585     AddToScope = false;
9586   }
9587 
9588   // Diagnose availability attributes. Availability cannot be used on functions
9589   // that are run during load/unload.
9590   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9591     if (NewFD->hasAttr<ConstructorAttr>()) {
9592       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9593           << 1;
9594       NewFD->dropAttr<AvailabilityAttr>();
9595     }
9596     if (NewFD->hasAttr<DestructorAttr>()) {
9597       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9598           << 2;
9599       NewFD->dropAttr<AvailabilityAttr>();
9600     }
9601   }
9602 
9603   // Diagnose no_builtin attribute on function declaration that are not a
9604   // definition.
9605   // FIXME: We should really be doing this in
9606   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9607   // the FunctionDecl and at this point of the code
9608   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9609   // because Sema::ActOnStartOfFunctionDef has not been called yet.
9610   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9611     switch (D.getFunctionDefinitionKind()) {
9612     case FDK_Defaulted:
9613     case FDK_Deleted:
9614       Diag(NBA->getLocation(),
9615            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9616           << NBA->getSpelling();
9617       break;
9618     case FDK_Declaration:
9619       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9620           << NBA->getSpelling();
9621       break;
9622     case FDK_Definition:
9623       break;
9624     }
9625 
9626   return NewFD;
9627 }
9628 
9629 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9630 /// when __declspec(code_seg) "is applied to a class, all member functions of
9631 /// the class and nested classes -- this includes compiler-generated special
9632 /// member functions -- are put in the specified segment."
9633 /// The actual behavior is a little more complicated. The Microsoft compiler
9634 /// won't check outer classes if there is an active value from #pragma code_seg.
9635 /// The CodeSeg is always applied from the direct parent but only from outer
9636 /// classes when the #pragma code_seg stack is empty. See:
9637 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9638 /// available since MS has removed the page.
9639 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9640   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9641   if (!Method)
9642     return nullptr;
9643   const CXXRecordDecl *Parent = Method->getParent();
9644   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9645     Attr *NewAttr = SAttr->clone(S.getASTContext());
9646     NewAttr->setImplicit(true);
9647     return NewAttr;
9648   }
9649 
9650   // The Microsoft compiler won't check outer classes for the CodeSeg
9651   // when the #pragma code_seg stack is active.
9652   if (S.CodeSegStack.CurrentValue)
9653    return nullptr;
9654 
9655   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9656     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9657       Attr *NewAttr = SAttr->clone(S.getASTContext());
9658       NewAttr->setImplicit(true);
9659       return NewAttr;
9660     }
9661   }
9662   return nullptr;
9663 }
9664 
9665 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9666 /// containing class. Otherwise it will return implicit SectionAttr if the
9667 /// function is a definition and there is an active value on CodeSegStack
9668 /// (from the current #pragma code-seg value).
9669 ///
9670 /// \param FD Function being declared.
9671 /// \param IsDefinition Whether it is a definition or just a declarartion.
9672 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9673 ///          nullptr if no attribute should be added.
9674 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9675                                                        bool IsDefinition) {
9676   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9677     return A;
9678   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9679       CodeSegStack.CurrentValue)
9680     return SectionAttr::CreateImplicit(
9681         getASTContext(), CodeSegStack.CurrentValue->getString(),
9682         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9683         SectionAttr::Declspec_allocate);
9684   return nullptr;
9685 }
9686 
9687 /// Determines if we can perform a correct type check for \p D as a
9688 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9689 /// best-effort check.
9690 ///
9691 /// \param NewD The new declaration.
9692 /// \param OldD The old declaration.
9693 /// \param NewT The portion of the type of the new declaration to check.
9694 /// \param OldT The portion of the type of the old declaration to check.
9695 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9696                                           QualType NewT, QualType OldT) {
9697   if (!NewD->getLexicalDeclContext()->isDependentContext())
9698     return true;
9699 
9700   // For dependently-typed local extern declarations and friends, we can't
9701   // perform a correct type check in general until instantiation:
9702   //
9703   //   int f();
9704   //   template<typename T> void g() { T f(); }
9705   //
9706   // (valid if g() is only instantiated with T = int).
9707   if (NewT->isDependentType() &&
9708       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9709     return false;
9710 
9711   // Similarly, if the previous declaration was a dependent local extern
9712   // declaration, we don't really know its type yet.
9713   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9714     return false;
9715 
9716   return true;
9717 }
9718 
9719 /// Checks if the new declaration declared in dependent context must be
9720 /// put in the same redeclaration chain as the specified declaration.
9721 ///
9722 /// \param D Declaration that is checked.
9723 /// \param PrevDecl Previous declaration found with proper lookup method for the
9724 ///                 same declaration name.
9725 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9726 ///          belongs to.
9727 ///
9728 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9729   if (!D->getLexicalDeclContext()->isDependentContext())
9730     return true;
9731 
9732   // Don't chain dependent friend function definitions until instantiation, to
9733   // permit cases like
9734   //
9735   //   void func();
9736   //   template<typename T> class C1 { friend void func() {} };
9737   //   template<typename T> class C2 { friend void func() {} };
9738   //
9739   // ... which is valid if only one of C1 and C2 is ever instantiated.
9740   //
9741   // FIXME: This need only apply to function definitions. For now, we proxy
9742   // this by checking for a file-scope function. We do not want this to apply
9743   // to friend declarations nominating member functions, because that gets in
9744   // the way of access checks.
9745   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9746     return false;
9747 
9748   auto *VD = dyn_cast<ValueDecl>(D);
9749   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9750   return !VD || !PrevVD ||
9751          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9752                                         PrevVD->getType());
9753 }
9754 
9755 /// Check the target attribute of the function for MultiVersion
9756 /// validity.
9757 ///
9758 /// Returns true if there was an error, false otherwise.
9759 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9760   const auto *TA = FD->getAttr<TargetAttr>();
9761   assert(TA && "MultiVersion Candidate requires a target attribute");
9762   ParsedTargetAttr ParseInfo = TA->parse();
9763   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9764   enum ErrType { Feature = 0, Architecture = 1 };
9765 
9766   if (!ParseInfo.Architecture.empty() &&
9767       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9768     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9769         << Architecture << ParseInfo.Architecture;
9770     return true;
9771   }
9772 
9773   for (const auto &Feat : ParseInfo.Features) {
9774     auto BareFeat = StringRef{Feat}.substr(1);
9775     if (Feat[0] == '-') {
9776       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9777           << Feature << ("no-" + BareFeat).str();
9778       return true;
9779     }
9780 
9781     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9782         !TargetInfo.isValidFeatureName(BareFeat)) {
9783       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9784           << Feature << BareFeat;
9785       return true;
9786     }
9787   }
9788   return false;
9789 }
9790 
9791 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9792                                          MultiVersionKind MVType) {
9793   for (const Attr *A : FD->attrs()) {
9794     switch (A->getKind()) {
9795     case attr::CPUDispatch:
9796     case attr::CPUSpecific:
9797       if (MVType != MultiVersionKind::CPUDispatch &&
9798           MVType != MultiVersionKind::CPUSpecific)
9799         return true;
9800       break;
9801     case attr::Target:
9802       if (MVType != MultiVersionKind::Target)
9803         return true;
9804       break;
9805     default:
9806       return true;
9807     }
9808   }
9809   return false;
9810 }
9811 
9812 bool Sema::areMultiversionVariantFunctionsCompatible(
9813     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9814     const PartialDiagnostic &NoProtoDiagID,
9815     const PartialDiagnosticAt &NoteCausedDiagIDAt,
9816     const PartialDiagnosticAt &NoSupportDiagIDAt,
9817     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9818     bool ConstexprSupported, bool CLinkageMayDiffer) {
9819   enum DoesntSupport {
9820     FuncTemplates = 0,
9821     VirtFuncs = 1,
9822     DeducedReturn = 2,
9823     Constructors = 3,
9824     Destructors = 4,
9825     DeletedFuncs = 5,
9826     DefaultedFuncs = 6,
9827     ConstexprFuncs = 7,
9828     ConstevalFuncs = 8,
9829   };
9830   enum Different {
9831     CallingConv = 0,
9832     ReturnType = 1,
9833     ConstexprSpec = 2,
9834     InlineSpec = 3,
9835     StorageClass = 4,
9836     Linkage = 5,
9837   };
9838 
9839   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
9840       !OldFD->getType()->getAs<FunctionProtoType>()) {
9841     Diag(OldFD->getLocation(), NoProtoDiagID);
9842     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
9843     return true;
9844   }
9845 
9846   if (NoProtoDiagID.getDiagID() != 0 &&
9847       !NewFD->getType()->getAs<FunctionProtoType>())
9848     return Diag(NewFD->getLocation(), NoProtoDiagID);
9849 
9850   if (!TemplatesSupported &&
9851       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9852     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9853            << FuncTemplates;
9854 
9855   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9856     if (NewCXXFD->isVirtual())
9857       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9858              << VirtFuncs;
9859 
9860     if (isa<CXXConstructorDecl>(NewCXXFD))
9861       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9862              << Constructors;
9863 
9864     if (isa<CXXDestructorDecl>(NewCXXFD))
9865       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9866              << Destructors;
9867   }
9868 
9869   if (NewFD->isDeleted())
9870     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9871            << DeletedFuncs;
9872 
9873   if (NewFD->isDefaulted())
9874     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9875            << DefaultedFuncs;
9876 
9877   if (!ConstexprSupported && NewFD->isConstexpr())
9878     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9879            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9880 
9881   QualType NewQType = Context.getCanonicalType(NewFD->getType());
9882   const auto *NewType = cast<FunctionType>(NewQType);
9883   QualType NewReturnType = NewType->getReturnType();
9884 
9885   if (NewReturnType->isUndeducedType())
9886     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
9887            << DeducedReturn;
9888 
9889   // Ensure the return type is identical.
9890   if (OldFD) {
9891     QualType OldQType = Context.getCanonicalType(OldFD->getType());
9892     const auto *OldType = cast<FunctionType>(OldQType);
9893     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9894     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9895 
9896     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9897       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
9898 
9899     QualType OldReturnType = OldType->getReturnType();
9900 
9901     if (OldReturnType != NewReturnType)
9902       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
9903 
9904     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9905       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
9906 
9907     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9908       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
9909 
9910     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9911       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
9912 
9913     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
9914       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
9915 
9916     if (CheckEquivalentExceptionSpec(
9917             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9918             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9919       return true;
9920   }
9921   return false;
9922 }
9923 
9924 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9925                                              const FunctionDecl *NewFD,
9926                                              bool CausesMV,
9927                                              MultiVersionKind MVType) {
9928   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9929     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9930     if (OldFD)
9931       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9932     return true;
9933   }
9934 
9935   bool IsCPUSpecificCPUDispatchMVType =
9936       MVType == MultiVersionKind::CPUDispatch ||
9937       MVType == MultiVersionKind::CPUSpecific;
9938 
9939   // For now, disallow all other attributes.  These should be opt-in, but
9940   // an analysis of all of them is a future FIXME.
9941   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9942     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9943         << IsCPUSpecificCPUDispatchMVType;
9944     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9945     return true;
9946   }
9947 
9948   if (HasNonMultiVersionAttributes(NewFD, MVType))
9949     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9950            << IsCPUSpecificCPUDispatchMVType;
9951 
9952   // Only allow transition to MultiVersion if it hasn't been used.
9953   if (OldFD && CausesMV && OldFD->isUsed(false))
9954     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9955 
9956   return S.areMultiversionVariantFunctionsCompatible(
9957       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
9958       PartialDiagnosticAt(NewFD->getLocation(),
9959                           S.PDiag(diag::note_multiversioning_caused_here)),
9960       PartialDiagnosticAt(NewFD->getLocation(),
9961                           S.PDiag(diag::err_multiversion_doesnt_support)
9962                               << IsCPUSpecificCPUDispatchMVType),
9963       PartialDiagnosticAt(NewFD->getLocation(),
9964                           S.PDiag(diag::err_multiversion_diff)),
9965       /*TemplatesSupported=*/false,
9966       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
9967       /*CLinkageMayDiffer=*/false);
9968 }
9969 
9970 /// Check the validity of a multiversion function declaration that is the
9971 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9972 ///
9973 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9974 ///
9975 /// Returns true if there was an error, false otherwise.
9976 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9977                                            MultiVersionKind MVType,
9978                                            const TargetAttr *TA) {
9979   assert(MVType != MultiVersionKind::None &&
9980          "Function lacks multiversion attribute");
9981 
9982   // Target only causes MV if it is default, otherwise this is a normal
9983   // function.
9984   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9985     return false;
9986 
9987   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9988     FD->setInvalidDecl();
9989     return true;
9990   }
9991 
9992   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9993     FD->setInvalidDecl();
9994     return true;
9995   }
9996 
9997   FD->setIsMultiVersion();
9998   return false;
9999 }
10000 
10001 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10002   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10003     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10004       return true;
10005   }
10006 
10007   return false;
10008 }
10009 
10010 static bool CheckTargetCausesMultiVersioning(
10011     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10012     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10013     LookupResult &Previous) {
10014   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10015   ParsedTargetAttr NewParsed = NewTA->parse();
10016   // Sort order doesn't matter, it just needs to be consistent.
10017   llvm::sort(NewParsed.Features);
10018 
10019   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10020   // to change, this is a simple redeclaration.
10021   if (!NewTA->isDefaultVersion() &&
10022       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10023     return false;
10024 
10025   // Otherwise, this decl causes MultiVersioning.
10026   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10027     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10028     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10029     NewFD->setInvalidDecl();
10030     return true;
10031   }
10032 
10033   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10034                                        MultiVersionKind::Target)) {
10035     NewFD->setInvalidDecl();
10036     return true;
10037   }
10038 
10039   if (CheckMultiVersionValue(S, NewFD)) {
10040     NewFD->setInvalidDecl();
10041     return true;
10042   }
10043 
10044   // If this is 'default', permit the forward declaration.
10045   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10046     Redeclaration = true;
10047     OldDecl = OldFD;
10048     OldFD->setIsMultiVersion();
10049     NewFD->setIsMultiVersion();
10050     return false;
10051   }
10052 
10053   if (CheckMultiVersionValue(S, OldFD)) {
10054     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10055     NewFD->setInvalidDecl();
10056     return true;
10057   }
10058 
10059   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10060 
10061   if (OldParsed == NewParsed) {
10062     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10063     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10064     NewFD->setInvalidDecl();
10065     return true;
10066   }
10067 
10068   for (const auto *FD : OldFD->redecls()) {
10069     const auto *CurTA = FD->getAttr<TargetAttr>();
10070     // We allow forward declarations before ANY multiversioning attributes, but
10071     // nothing after the fact.
10072     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10073         (!CurTA || CurTA->isInherited())) {
10074       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10075           << 0;
10076       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10077       NewFD->setInvalidDecl();
10078       return true;
10079     }
10080   }
10081 
10082   OldFD->setIsMultiVersion();
10083   NewFD->setIsMultiVersion();
10084   Redeclaration = false;
10085   MergeTypeWithPrevious = false;
10086   OldDecl = nullptr;
10087   Previous.clear();
10088   return false;
10089 }
10090 
10091 /// Check the validity of a new function declaration being added to an existing
10092 /// multiversioned declaration collection.
10093 static bool CheckMultiVersionAdditionalDecl(
10094     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10095     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10096     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10097     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10098     LookupResult &Previous) {
10099 
10100   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10101   // Disallow mixing of multiversioning types.
10102   if ((OldMVType == MultiVersionKind::Target &&
10103        NewMVType != MultiVersionKind::Target) ||
10104       (NewMVType == MultiVersionKind::Target &&
10105        OldMVType != MultiVersionKind::Target)) {
10106     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10107     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10108     NewFD->setInvalidDecl();
10109     return true;
10110   }
10111 
10112   ParsedTargetAttr NewParsed;
10113   if (NewTA) {
10114     NewParsed = NewTA->parse();
10115     llvm::sort(NewParsed.Features);
10116   }
10117 
10118   bool UseMemberUsingDeclRules =
10119       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10120 
10121   // Next, check ALL non-overloads to see if this is a redeclaration of a
10122   // previous member of the MultiVersion set.
10123   for (NamedDecl *ND : Previous) {
10124     FunctionDecl *CurFD = ND->getAsFunction();
10125     if (!CurFD)
10126       continue;
10127     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10128       continue;
10129 
10130     if (NewMVType == MultiVersionKind::Target) {
10131       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10132       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10133         NewFD->setIsMultiVersion();
10134         Redeclaration = true;
10135         OldDecl = ND;
10136         return false;
10137       }
10138 
10139       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10140       if (CurParsed == NewParsed) {
10141         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10142         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10143         NewFD->setInvalidDecl();
10144         return true;
10145       }
10146     } else {
10147       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10148       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10149       // Handle CPUDispatch/CPUSpecific versions.
10150       // Only 1 CPUDispatch function is allowed, this will make it go through
10151       // the redeclaration errors.
10152       if (NewMVType == MultiVersionKind::CPUDispatch &&
10153           CurFD->hasAttr<CPUDispatchAttr>()) {
10154         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10155             std::equal(
10156                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10157                 NewCPUDisp->cpus_begin(),
10158                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10159                   return Cur->getName() == New->getName();
10160                 })) {
10161           NewFD->setIsMultiVersion();
10162           Redeclaration = true;
10163           OldDecl = ND;
10164           return false;
10165         }
10166 
10167         // If the declarations don't match, this is an error condition.
10168         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10169         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10170         NewFD->setInvalidDecl();
10171         return true;
10172       }
10173       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10174 
10175         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10176             std::equal(
10177                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10178                 NewCPUSpec->cpus_begin(),
10179                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10180                   return Cur->getName() == New->getName();
10181                 })) {
10182           NewFD->setIsMultiVersion();
10183           Redeclaration = true;
10184           OldDecl = ND;
10185           return false;
10186         }
10187 
10188         // Only 1 version of CPUSpecific is allowed for each CPU.
10189         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10190           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10191             if (CurII == NewII) {
10192               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10193                   << NewII;
10194               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10195               NewFD->setInvalidDecl();
10196               return true;
10197             }
10198           }
10199         }
10200       }
10201       // If the two decls aren't the same MVType, there is no possible error
10202       // condition.
10203     }
10204   }
10205 
10206   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10207   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10208   // handled in the attribute adding step.
10209   if (NewMVType == MultiVersionKind::Target &&
10210       CheckMultiVersionValue(S, NewFD)) {
10211     NewFD->setInvalidDecl();
10212     return true;
10213   }
10214 
10215   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10216                                        !OldFD->isMultiVersion(), NewMVType)) {
10217     NewFD->setInvalidDecl();
10218     return true;
10219   }
10220 
10221   // Permit forward declarations in the case where these two are compatible.
10222   if (!OldFD->isMultiVersion()) {
10223     OldFD->setIsMultiVersion();
10224     NewFD->setIsMultiVersion();
10225     Redeclaration = true;
10226     OldDecl = OldFD;
10227     return false;
10228   }
10229 
10230   NewFD->setIsMultiVersion();
10231   Redeclaration = false;
10232   MergeTypeWithPrevious = false;
10233   OldDecl = nullptr;
10234   Previous.clear();
10235   return false;
10236 }
10237 
10238 
10239 /// Check the validity of a mulitversion function declaration.
10240 /// Also sets the multiversion'ness' of the function itself.
10241 ///
10242 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10243 ///
10244 /// Returns true if there was an error, false otherwise.
10245 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10246                                       bool &Redeclaration, NamedDecl *&OldDecl,
10247                                       bool &MergeTypeWithPrevious,
10248                                       LookupResult &Previous) {
10249   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10250   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10251   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10252 
10253   // Mixing Multiversioning types is prohibited.
10254   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10255       (NewCPUDisp && NewCPUSpec)) {
10256     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10257     NewFD->setInvalidDecl();
10258     return true;
10259   }
10260 
10261   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10262 
10263   // Main isn't allowed to become a multiversion function, however it IS
10264   // permitted to have 'main' be marked with the 'target' optimization hint.
10265   if (NewFD->isMain()) {
10266     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10267         MVType == MultiVersionKind::CPUDispatch ||
10268         MVType == MultiVersionKind::CPUSpecific) {
10269       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10270       NewFD->setInvalidDecl();
10271       return true;
10272     }
10273     return false;
10274   }
10275 
10276   if (!OldDecl || !OldDecl->getAsFunction() ||
10277       OldDecl->getDeclContext()->getRedeclContext() !=
10278           NewFD->getDeclContext()->getRedeclContext()) {
10279     // If there's no previous declaration, AND this isn't attempting to cause
10280     // multiversioning, this isn't an error condition.
10281     if (MVType == MultiVersionKind::None)
10282       return false;
10283     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10284   }
10285 
10286   FunctionDecl *OldFD = OldDecl->getAsFunction();
10287 
10288   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10289     return false;
10290 
10291   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10292     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10293         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10294     NewFD->setInvalidDecl();
10295     return true;
10296   }
10297 
10298   // Handle the target potentially causes multiversioning case.
10299   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10300     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10301                                             Redeclaration, OldDecl,
10302                                             MergeTypeWithPrevious, Previous);
10303 
10304   // At this point, we have a multiversion function decl (in OldFD) AND an
10305   // appropriate attribute in the current function decl.  Resolve that these are
10306   // still compatible with previous declarations.
10307   return CheckMultiVersionAdditionalDecl(
10308       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10309       OldDecl, MergeTypeWithPrevious, Previous);
10310 }
10311 
10312 /// Perform semantic checking of a new function declaration.
10313 ///
10314 /// Performs semantic analysis of the new function declaration
10315 /// NewFD. This routine performs all semantic checking that does not
10316 /// require the actual declarator involved in the declaration, and is
10317 /// used both for the declaration of functions as they are parsed
10318 /// (called via ActOnDeclarator) and for the declaration of functions
10319 /// that have been instantiated via C++ template instantiation (called
10320 /// via InstantiateDecl).
10321 ///
10322 /// \param IsMemberSpecialization whether this new function declaration is
10323 /// a member specialization (that replaces any definition provided by the
10324 /// previous declaration).
10325 ///
10326 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10327 ///
10328 /// \returns true if the function declaration is a redeclaration.
10329 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10330                                     LookupResult &Previous,
10331                                     bool IsMemberSpecialization) {
10332   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10333          "Variably modified return types are not handled here");
10334 
10335   // Determine whether the type of this function should be merged with
10336   // a previous visible declaration. This never happens for functions in C++,
10337   // and always happens in C if the previous declaration was visible.
10338   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10339                                !Previous.isShadowed();
10340 
10341   bool Redeclaration = false;
10342   NamedDecl *OldDecl = nullptr;
10343   bool MayNeedOverloadableChecks = false;
10344 
10345   // Merge or overload the declaration with an existing declaration of
10346   // the same name, if appropriate.
10347   if (!Previous.empty()) {
10348     // Determine whether NewFD is an overload of PrevDecl or
10349     // a declaration that requires merging. If it's an overload,
10350     // there's no more work to do here; we'll just add the new
10351     // function to the scope.
10352     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10353       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10354       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10355         Redeclaration = true;
10356         OldDecl = Candidate;
10357       }
10358     } else {
10359       MayNeedOverloadableChecks = true;
10360       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10361                             /*NewIsUsingDecl*/ false)) {
10362       case Ovl_Match:
10363         Redeclaration = true;
10364         break;
10365 
10366       case Ovl_NonFunction:
10367         Redeclaration = true;
10368         break;
10369 
10370       case Ovl_Overload:
10371         Redeclaration = false;
10372         break;
10373       }
10374     }
10375   }
10376 
10377   // Check for a previous extern "C" declaration with this name.
10378   if (!Redeclaration &&
10379       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10380     if (!Previous.empty()) {
10381       // This is an extern "C" declaration with the same name as a previous
10382       // declaration, and thus redeclares that entity...
10383       Redeclaration = true;
10384       OldDecl = Previous.getFoundDecl();
10385       MergeTypeWithPrevious = false;
10386 
10387       // ... except in the presence of __attribute__((overloadable)).
10388       if (OldDecl->hasAttr<OverloadableAttr>() ||
10389           NewFD->hasAttr<OverloadableAttr>()) {
10390         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10391           MayNeedOverloadableChecks = true;
10392           Redeclaration = false;
10393           OldDecl = nullptr;
10394         }
10395       }
10396     }
10397   }
10398 
10399   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10400                                 MergeTypeWithPrevious, Previous))
10401     return Redeclaration;
10402 
10403   // C++11 [dcl.constexpr]p8:
10404   //   A constexpr specifier for a non-static member function that is not
10405   //   a constructor declares that member function to be const.
10406   //
10407   // This needs to be delayed until we know whether this is an out-of-line
10408   // definition of a static member function.
10409   //
10410   // This rule is not present in C++1y, so we produce a backwards
10411   // compatibility warning whenever it happens in C++11.
10412   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10413   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10414       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10415       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10416     CXXMethodDecl *OldMD = nullptr;
10417     if (OldDecl)
10418       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10419     if (!OldMD || !OldMD->isStatic()) {
10420       const FunctionProtoType *FPT =
10421         MD->getType()->castAs<FunctionProtoType>();
10422       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10423       EPI.TypeQuals.addConst();
10424       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10425                                           FPT->getParamTypes(), EPI));
10426 
10427       // Warn that we did this, if we're not performing template instantiation.
10428       // In that case, we'll have warned already when the template was defined.
10429       if (!inTemplateInstantiation()) {
10430         SourceLocation AddConstLoc;
10431         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10432                 .IgnoreParens().getAs<FunctionTypeLoc>())
10433           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10434 
10435         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10436           << FixItHint::CreateInsertion(AddConstLoc, " const");
10437       }
10438     }
10439   }
10440 
10441   if (Redeclaration) {
10442     // NewFD and OldDecl represent declarations that need to be
10443     // merged.
10444     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10445       NewFD->setInvalidDecl();
10446       return Redeclaration;
10447     }
10448 
10449     Previous.clear();
10450     Previous.addDecl(OldDecl);
10451 
10452     if (FunctionTemplateDecl *OldTemplateDecl =
10453             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10454       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10455       FunctionTemplateDecl *NewTemplateDecl
10456         = NewFD->getDescribedFunctionTemplate();
10457       assert(NewTemplateDecl && "Template/non-template mismatch");
10458 
10459       // The call to MergeFunctionDecl above may have created some state in
10460       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10461       // can add it as a redeclaration.
10462       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10463 
10464       NewFD->setPreviousDeclaration(OldFD);
10465       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10466       if (NewFD->isCXXClassMember()) {
10467         NewFD->setAccess(OldTemplateDecl->getAccess());
10468         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10469       }
10470 
10471       // If this is an explicit specialization of a member that is a function
10472       // template, mark it as a member specialization.
10473       if (IsMemberSpecialization &&
10474           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10475         NewTemplateDecl->setMemberSpecialization();
10476         assert(OldTemplateDecl->isMemberSpecialization());
10477         // Explicit specializations of a member template do not inherit deleted
10478         // status from the parent member template that they are specializing.
10479         if (OldFD->isDeleted()) {
10480           // FIXME: This assert will not hold in the presence of modules.
10481           assert(OldFD->getCanonicalDecl() == OldFD);
10482           // FIXME: We need an update record for this AST mutation.
10483           OldFD->setDeletedAsWritten(false);
10484         }
10485       }
10486 
10487     } else {
10488       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10489         auto *OldFD = cast<FunctionDecl>(OldDecl);
10490         // This needs to happen first so that 'inline' propagates.
10491         NewFD->setPreviousDeclaration(OldFD);
10492         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10493         if (NewFD->isCXXClassMember())
10494           NewFD->setAccess(OldFD->getAccess());
10495       }
10496     }
10497   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10498              !NewFD->getAttr<OverloadableAttr>()) {
10499     assert((Previous.empty() ||
10500             llvm::any_of(Previous,
10501                          [](const NamedDecl *ND) {
10502                            return ND->hasAttr<OverloadableAttr>();
10503                          })) &&
10504            "Non-redecls shouldn't happen without overloadable present");
10505 
10506     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10507       const auto *FD = dyn_cast<FunctionDecl>(ND);
10508       return FD && !FD->hasAttr<OverloadableAttr>();
10509     });
10510 
10511     if (OtherUnmarkedIter != Previous.end()) {
10512       Diag(NewFD->getLocation(),
10513            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10514       Diag((*OtherUnmarkedIter)->getLocation(),
10515            diag::note_attribute_overloadable_prev_overload)
10516           << false;
10517 
10518       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10519     }
10520   }
10521 
10522   // Semantic checking for this function declaration (in isolation).
10523 
10524   if (getLangOpts().CPlusPlus) {
10525     // C++-specific checks.
10526     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10527       CheckConstructor(Constructor);
10528     } else if (CXXDestructorDecl *Destructor =
10529                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10530       CXXRecordDecl *Record = Destructor->getParent();
10531       QualType ClassType = Context.getTypeDeclType(Record);
10532 
10533       // FIXME: Shouldn't we be able to perform this check even when the class
10534       // type is dependent? Both gcc and edg can handle that.
10535       if (!ClassType->isDependentType()) {
10536         DeclarationName Name
10537           = Context.DeclarationNames.getCXXDestructorName(
10538                                         Context.getCanonicalType(ClassType));
10539         if (NewFD->getDeclName() != Name) {
10540           Diag(NewFD->getLocation(), diag::err_destructor_name);
10541           NewFD->setInvalidDecl();
10542           return Redeclaration;
10543         }
10544       }
10545     } else if (CXXConversionDecl *Conversion
10546                = dyn_cast<CXXConversionDecl>(NewFD)) {
10547       ActOnConversionDeclarator(Conversion);
10548     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10549       if (auto *TD = Guide->getDescribedFunctionTemplate())
10550         CheckDeductionGuideTemplate(TD);
10551 
10552       // A deduction guide is not on the list of entities that can be
10553       // explicitly specialized.
10554       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10555         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10556             << /*explicit specialization*/ 1;
10557     }
10558 
10559     // Find any virtual functions that this function overrides.
10560     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10561       if (!Method->isFunctionTemplateSpecialization() &&
10562           !Method->getDescribedFunctionTemplate() &&
10563           Method->isCanonicalDecl()) {
10564         if (AddOverriddenMethods(Method->getParent(), Method)) {
10565           // If the function was marked as "static", we have a problem.
10566           if (NewFD->getStorageClass() == SC_Static) {
10567             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10568           }
10569         }
10570       }
10571 
10572       if (Method->isStatic())
10573         checkThisInStaticMemberFunctionType(Method);
10574     }
10575 
10576     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10577     if (NewFD->isOverloadedOperator() &&
10578         CheckOverloadedOperatorDeclaration(NewFD)) {
10579       NewFD->setInvalidDecl();
10580       return Redeclaration;
10581     }
10582 
10583     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10584     if (NewFD->getLiteralIdentifier() &&
10585         CheckLiteralOperatorDeclaration(NewFD)) {
10586       NewFD->setInvalidDecl();
10587       return Redeclaration;
10588     }
10589 
10590     // In C++, check default arguments now that we have merged decls. Unless
10591     // the lexical context is the class, because in this case this is done
10592     // during delayed parsing anyway.
10593     if (!CurContext->isRecord())
10594       CheckCXXDefaultArguments(NewFD);
10595 
10596     // If this function declares a builtin function, check the type of this
10597     // declaration against the expected type for the builtin.
10598     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10599       ASTContext::GetBuiltinTypeError Error;
10600       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10601       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10602       // If the type of the builtin differs only in its exception
10603       // specification, that's OK.
10604       // FIXME: If the types do differ in this way, it would be better to
10605       // retain the 'noexcept' form of the type.
10606       if (!T.isNull() &&
10607           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10608                                                             NewFD->getType()))
10609         // The type of this function differs from the type of the builtin,
10610         // so forget about the builtin entirely.
10611         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10612     }
10613 
10614     // If this function is declared as being extern "C", then check to see if
10615     // the function returns a UDT (class, struct, or union type) that is not C
10616     // compatible, and if it does, warn the user.
10617     // But, issue any diagnostic on the first declaration only.
10618     if (Previous.empty() && NewFD->isExternC()) {
10619       QualType R = NewFD->getReturnType();
10620       if (R->isIncompleteType() && !R->isVoidType())
10621         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10622             << NewFD << R;
10623       else if (!R.isPODType(Context) && !R->isVoidType() &&
10624                !R->isObjCObjectPointerType())
10625         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10626     }
10627 
10628     // C++1z [dcl.fct]p6:
10629     //   [...] whether the function has a non-throwing exception-specification
10630     //   [is] part of the function type
10631     //
10632     // This results in an ABI break between C++14 and C++17 for functions whose
10633     // declared type includes an exception-specification in a parameter or
10634     // return type. (Exception specifications on the function itself are OK in
10635     // most cases, and exception specifications are not permitted in most other
10636     // contexts where they could make it into a mangling.)
10637     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10638       auto HasNoexcept = [&](QualType T) -> bool {
10639         // Strip off declarator chunks that could be between us and a function
10640         // type. We don't need to look far, exception specifications are very
10641         // restricted prior to C++17.
10642         if (auto *RT = T->getAs<ReferenceType>())
10643           T = RT->getPointeeType();
10644         else if (T->isAnyPointerType())
10645           T = T->getPointeeType();
10646         else if (auto *MPT = T->getAs<MemberPointerType>())
10647           T = MPT->getPointeeType();
10648         if (auto *FPT = T->getAs<FunctionProtoType>())
10649           if (FPT->isNothrow())
10650             return true;
10651         return false;
10652       };
10653 
10654       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10655       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10656       for (QualType T : FPT->param_types())
10657         AnyNoexcept |= HasNoexcept(T);
10658       if (AnyNoexcept)
10659         Diag(NewFD->getLocation(),
10660              diag::warn_cxx17_compat_exception_spec_in_signature)
10661             << NewFD;
10662     }
10663 
10664     if (!Redeclaration && LangOpts.CUDA)
10665       checkCUDATargetOverload(NewFD, Previous);
10666   }
10667   return Redeclaration;
10668 }
10669 
10670 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10671   // C++11 [basic.start.main]p3:
10672   //   A program that [...] declares main to be inline, static or
10673   //   constexpr is ill-formed.
10674   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10675   //   appear in a declaration of main.
10676   // static main is not an error under C99, but we should warn about it.
10677   // We accept _Noreturn main as an extension.
10678   if (FD->getStorageClass() == SC_Static)
10679     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10680          ? diag::err_static_main : diag::warn_static_main)
10681       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10682   if (FD->isInlineSpecified())
10683     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10684       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10685   if (DS.isNoreturnSpecified()) {
10686     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10687     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10688     Diag(NoreturnLoc, diag::ext_noreturn_main);
10689     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10690       << FixItHint::CreateRemoval(NoreturnRange);
10691   }
10692   if (FD->isConstexpr()) {
10693     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10694         << FD->isConsteval()
10695         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10696     FD->setConstexprKind(CSK_unspecified);
10697   }
10698 
10699   if (getLangOpts().OpenCL) {
10700     Diag(FD->getLocation(), diag::err_opencl_no_main)
10701         << FD->hasAttr<OpenCLKernelAttr>();
10702     FD->setInvalidDecl();
10703     return;
10704   }
10705 
10706   QualType T = FD->getType();
10707   assert(T->isFunctionType() && "function decl is not of function type");
10708   const FunctionType* FT = T->castAs<FunctionType>();
10709 
10710   // Set default calling convention for main()
10711   if (FT->getCallConv() != CC_C) {
10712     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10713     FD->setType(QualType(FT, 0));
10714     T = Context.getCanonicalType(FD->getType());
10715   }
10716 
10717   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10718     // In C with GNU extensions we allow main() to have non-integer return
10719     // type, but we should warn about the extension, and we disable the
10720     // implicit-return-zero rule.
10721 
10722     // GCC in C mode accepts qualified 'int'.
10723     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10724       FD->setHasImplicitReturnZero(true);
10725     else {
10726       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10727       SourceRange RTRange = FD->getReturnTypeSourceRange();
10728       if (RTRange.isValid())
10729         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10730             << FixItHint::CreateReplacement(RTRange, "int");
10731     }
10732   } else {
10733     // In C and C++, main magically returns 0 if you fall off the end;
10734     // set the flag which tells us that.
10735     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10736 
10737     // All the standards say that main() should return 'int'.
10738     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10739       FD->setHasImplicitReturnZero(true);
10740     else {
10741       // Otherwise, this is just a flat-out error.
10742       SourceRange RTRange = FD->getReturnTypeSourceRange();
10743       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10744           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10745                                 : FixItHint());
10746       FD->setInvalidDecl(true);
10747     }
10748   }
10749 
10750   // Treat protoless main() as nullary.
10751   if (isa<FunctionNoProtoType>(FT)) return;
10752 
10753   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10754   unsigned nparams = FTP->getNumParams();
10755   assert(FD->getNumParams() == nparams);
10756 
10757   bool HasExtraParameters = (nparams > 3);
10758 
10759   if (FTP->isVariadic()) {
10760     Diag(FD->getLocation(), diag::ext_variadic_main);
10761     // FIXME: if we had information about the location of the ellipsis, we
10762     // could add a FixIt hint to remove it as a parameter.
10763   }
10764 
10765   // Darwin passes an undocumented fourth argument of type char**.  If
10766   // other platforms start sprouting these, the logic below will start
10767   // getting shifty.
10768   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10769     HasExtraParameters = false;
10770 
10771   if (HasExtraParameters) {
10772     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10773     FD->setInvalidDecl(true);
10774     nparams = 3;
10775   }
10776 
10777   // FIXME: a lot of the following diagnostics would be improved
10778   // if we had some location information about types.
10779 
10780   QualType CharPP =
10781     Context.getPointerType(Context.getPointerType(Context.CharTy));
10782   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10783 
10784   for (unsigned i = 0; i < nparams; ++i) {
10785     QualType AT = FTP->getParamType(i);
10786 
10787     bool mismatch = true;
10788 
10789     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10790       mismatch = false;
10791     else if (Expected[i] == CharPP) {
10792       // As an extension, the following forms are okay:
10793       //   char const **
10794       //   char const * const *
10795       //   char * const *
10796 
10797       QualifierCollector qs;
10798       const PointerType* PT;
10799       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10800           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10801           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10802                               Context.CharTy)) {
10803         qs.removeConst();
10804         mismatch = !qs.empty();
10805       }
10806     }
10807 
10808     if (mismatch) {
10809       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10810       // TODO: suggest replacing given type with expected type
10811       FD->setInvalidDecl(true);
10812     }
10813   }
10814 
10815   if (nparams == 1 && !FD->isInvalidDecl()) {
10816     Diag(FD->getLocation(), diag::warn_main_one_arg);
10817   }
10818 
10819   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10820     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10821     FD->setInvalidDecl();
10822   }
10823 }
10824 
10825 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10826   QualType T = FD->getType();
10827   assert(T->isFunctionType() && "function decl is not of function type");
10828   const FunctionType *FT = T->castAs<FunctionType>();
10829 
10830   // Set an implicit return of 'zero' if the function can return some integral,
10831   // enumeration, pointer or nullptr type.
10832   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10833       FT->getReturnType()->isAnyPointerType() ||
10834       FT->getReturnType()->isNullPtrType())
10835     // DllMain is exempt because a return value of zero means it failed.
10836     if (FD->getName() != "DllMain")
10837       FD->setHasImplicitReturnZero(true);
10838 
10839   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10840     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10841     FD->setInvalidDecl();
10842   }
10843 }
10844 
10845 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10846   // FIXME: Need strict checking.  In C89, we need to check for
10847   // any assignment, increment, decrement, function-calls, or
10848   // commas outside of a sizeof.  In C99, it's the same list,
10849   // except that the aforementioned are allowed in unevaluated
10850   // expressions.  Everything else falls under the
10851   // "may accept other forms of constant expressions" exception.
10852   // (We never end up here for C++, so the constant expression
10853   // rules there don't matter.)
10854   const Expr *Culprit;
10855   if (Init->isConstantInitializer(Context, false, &Culprit))
10856     return false;
10857   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10858     << Culprit->getSourceRange();
10859   return true;
10860 }
10861 
10862 namespace {
10863   // Visits an initialization expression to see if OrigDecl is evaluated in
10864   // its own initialization and throws a warning if it does.
10865   class SelfReferenceChecker
10866       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10867     Sema &S;
10868     Decl *OrigDecl;
10869     bool isRecordType;
10870     bool isPODType;
10871     bool isReferenceType;
10872 
10873     bool isInitList;
10874     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10875 
10876   public:
10877     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10878 
10879     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10880                                                     S(S), OrigDecl(OrigDecl) {
10881       isPODType = false;
10882       isRecordType = false;
10883       isReferenceType = false;
10884       isInitList = false;
10885       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10886         isPODType = VD->getType().isPODType(S.Context);
10887         isRecordType = VD->getType()->isRecordType();
10888         isReferenceType = VD->getType()->isReferenceType();
10889       }
10890     }
10891 
10892     // For most expressions, just call the visitor.  For initializer lists,
10893     // track the index of the field being initialized since fields are
10894     // initialized in order allowing use of previously initialized fields.
10895     void CheckExpr(Expr *E) {
10896       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10897       if (!InitList) {
10898         Visit(E);
10899         return;
10900       }
10901 
10902       // Track and increment the index here.
10903       isInitList = true;
10904       InitFieldIndex.push_back(0);
10905       for (auto Child : InitList->children()) {
10906         CheckExpr(cast<Expr>(Child));
10907         ++InitFieldIndex.back();
10908       }
10909       InitFieldIndex.pop_back();
10910     }
10911 
10912     // Returns true if MemberExpr is checked and no further checking is needed.
10913     // Returns false if additional checking is required.
10914     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10915       llvm::SmallVector<FieldDecl*, 4> Fields;
10916       Expr *Base = E;
10917       bool ReferenceField = false;
10918 
10919       // Get the field members used.
10920       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10921         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10922         if (!FD)
10923           return false;
10924         Fields.push_back(FD);
10925         if (FD->getType()->isReferenceType())
10926           ReferenceField = true;
10927         Base = ME->getBase()->IgnoreParenImpCasts();
10928       }
10929 
10930       // Keep checking only if the base Decl is the same.
10931       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10932       if (!DRE || DRE->getDecl() != OrigDecl)
10933         return false;
10934 
10935       // A reference field can be bound to an unininitialized field.
10936       if (CheckReference && !ReferenceField)
10937         return true;
10938 
10939       // Convert FieldDecls to their index number.
10940       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10941       for (const FieldDecl *I : llvm::reverse(Fields))
10942         UsedFieldIndex.push_back(I->getFieldIndex());
10943 
10944       // See if a warning is needed by checking the first difference in index
10945       // numbers.  If field being used has index less than the field being
10946       // initialized, then the use is safe.
10947       for (auto UsedIter = UsedFieldIndex.begin(),
10948                 UsedEnd = UsedFieldIndex.end(),
10949                 OrigIter = InitFieldIndex.begin(),
10950                 OrigEnd = InitFieldIndex.end();
10951            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10952         if (*UsedIter < *OrigIter)
10953           return true;
10954         if (*UsedIter > *OrigIter)
10955           break;
10956       }
10957 
10958       // TODO: Add a different warning which will print the field names.
10959       HandleDeclRefExpr(DRE);
10960       return true;
10961     }
10962 
10963     // For most expressions, the cast is directly above the DeclRefExpr.
10964     // For conditional operators, the cast can be outside the conditional
10965     // operator if both expressions are DeclRefExpr's.
10966     void HandleValue(Expr *E) {
10967       E = E->IgnoreParens();
10968       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10969         HandleDeclRefExpr(DRE);
10970         return;
10971       }
10972 
10973       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10974         Visit(CO->getCond());
10975         HandleValue(CO->getTrueExpr());
10976         HandleValue(CO->getFalseExpr());
10977         return;
10978       }
10979 
10980       if (BinaryConditionalOperator *BCO =
10981               dyn_cast<BinaryConditionalOperator>(E)) {
10982         Visit(BCO->getCond());
10983         HandleValue(BCO->getFalseExpr());
10984         return;
10985       }
10986 
10987       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10988         HandleValue(OVE->getSourceExpr());
10989         return;
10990       }
10991 
10992       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10993         if (BO->getOpcode() == BO_Comma) {
10994           Visit(BO->getLHS());
10995           HandleValue(BO->getRHS());
10996           return;
10997         }
10998       }
10999 
11000       if (isa<MemberExpr>(E)) {
11001         if (isInitList) {
11002           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11003                                       false /*CheckReference*/))
11004             return;
11005         }
11006 
11007         Expr *Base = E->IgnoreParenImpCasts();
11008         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11009           // Check for static member variables and don't warn on them.
11010           if (!isa<FieldDecl>(ME->getMemberDecl()))
11011             return;
11012           Base = ME->getBase()->IgnoreParenImpCasts();
11013         }
11014         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11015           HandleDeclRefExpr(DRE);
11016         return;
11017       }
11018 
11019       Visit(E);
11020     }
11021 
11022     // Reference types not handled in HandleValue are handled here since all
11023     // uses of references are bad, not just r-value uses.
11024     void VisitDeclRefExpr(DeclRefExpr *E) {
11025       if (isReferenceType)
11026         HandleDeclRefExpr(E);
11027     }
11028 
11029     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11030       if (E->getCastKind() == CK_LValueToRValue) {
11031         HandleValue(E->getSubExpr());
11032         return;
11033       }
11034 
11035       Inherited::VisitImplicitCastExpr(E);
11036     }
11037 
11038     void VisitMemberExpr(MemberExpr *E) {
11039       if (isInitList) {
11040         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11041           return;
11042       }
11043 
11044       // Don't warn on arrays since they can be treated as pointers.
11045       if (E->getType()->canDecayToPointerType()) return;
11046 
11047       // Warn when a non-static method call is followed by non-static member
11048       // field accesses, which is followed by a DeclRefExpr.
11049       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11050       bool Warn = (MD && !MD->isStatic());
11051       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11052       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11053         if (!isa<FieldDecl>(ME->getMemberDecl()))
11054           Warn = false;
11055         Base = ME->getBase()->IgnoreParenImpCasts();
11056       }
11057 
11058       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11059         if (Warn)
11060           HandleDeclRefExpr(DRE);
11061         return;
11062       }
11063 
11064       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11065       // Visit that expression.
11066       Visit(Base);
11067     }
11068 
11069     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11070       Expr *Callee = E->getCallee();
11071 
11072       if (isa<UnresolvedLookupExpr>(Callee))
11073         return Inherited::VisitCXXOperatorCallExpr(E);
11074 
11075       Visit(Callee);
11076       for (auto Arg: E->arguments())
11077         HandleValue(Arg->IgnoreParenImpCasts());
11078     }
11079 
11080     void VisitUnaryOperator(UnaryOperator *E) {
11081       // For POD record types, addresses of its own members are well-defined.
11082       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11083           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11084         if (!isPODType)
11085           HandleValue(E->getSubExpr());
11086         return;
11087       }
11088 
11089       if (E->isIncrementDecrementOp()) {
11090         HandleValue(E->getSubExpr());
11091         return;
11092       }
11093 
11094       Inherited::VisitUnaryOperator(E);
11095     }
11096 
11097     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11098 
11099     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11100       if (E->getConstructor()->isCopyConstructor()) {
11101         Expr *ArgExpr = E->getArg(0);
11102         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11103           if (ILE->getNumInits() == 1)
11104             ArgExpr = ILE->getInit(0);
11105         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11106           if (ICE->getCastKind() == CK_NoOp)
11107             ArgExpr = ICE->getSubExpr();
11108         HandleValue(ArgExpr);
11109         return;
11110       }
11111       Inherited::VisitCXXConstructExpr(E);
11112     }
11113 
11114     void VisitCallExpr(CallExpr *E) {
11115       // Treat std::move as a use.
11116       if (E->isCallToStdMove()) {
11117         HandleValue(E->getArg(0));
11118         return;
11119       }
11120 
11121       Inherited::VisitCallExpr(E);
11122     }
11123 
11124     void VisitBinaryOperator(BinaryOperator *E) {
11125       if (E->isCompoundAssignmentOp()) {
11126         HandleValue(E->getLHS());
11127         Visit(E->getRHS());
11128         return;
11129       }
11130 
11131       Inherited::VisitBinaryOperator(E);
11132     }
11133 
11134     // A custom visitor for BinaryConditionalOperator is needed because the
11135     // regular visitor would check the condition and true expression separately
11136     // but both point to the same place giving duplicate diagnostics.
11137     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11138       Visit(E->getCond());
11139       Visit(E->getFalseExpr());
11140     }
11141 
11142     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11143       Decl* ReferenceDecl = DRE->getDecl();
11144       if (OrigDecl != ReferenceDecl) return;
11145       unsigned diag;
11146       if (isReferenceType) {
11147         diag = diag::warn_uninit_self_reference_in_reference_init;
11148       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11149         diag = diag::warn_static_self_reference_in_init;
11150       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11151                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11152                  DRE->getDecl()->getType()->isRecordType()) {
11153         diag = diag::warn_uninit_self_reference_in_init;
11154       } else {
11155         // Local variables will be handled by the CFG analysis.
11156         return;
11157       }
11158 
11159       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11160                             S.PDiag(diag)
11161                                 << DRE->getDecl() << OrigDecl->getLocation()
11162                                 << DRE->getSourceRange());
11163     }
11164   };
11165 
11166   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11167   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11168                                  bool DirectInit) {
11169     // Parameters arguments are occassionially constructed with itself,
11170     // for instance, in recursive functions.  Skip them.
11171     if (isa<ParmVarDecl>(OrigDecl))
11172       return;
11173 
11174     E = E->IgnoreParens();
11175 
11176     // Skip checking T a = a where T is not a record or reference type.
11177     // Doing so is a way to silence uninitialized warnings.
11178     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11179       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11180         if (ICE->getCastKind() == CK_LValueToRValue)
11181           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11182             if (DRE->getDecl() == OrigDecl)
11183               return;
11184 
11185     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11186   }
11187 } // end anonymous namespace
11188 
11189 namespace {
11190   // Simple wrapper to add the name of a variable or (if no variable is
11191   // available) a DeclarationName into a diagnostic.
11192   struct VarDeclOrName {
11193     VarDecl *VDecl;
11194     DeclarationName Name;
11195 
11196     friend const Sema::SemaDiagnosticBuilder &
11197     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11198       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11199     }
11200   };
11201 } // end anonymous namespace
11202 
11203 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11204                                             DeclarationName Name, QualType Type,
11205                                             TypeSourceInfo *TSI,
11206                                             SourceRange Range, bool DirectInit,
11207                                             Expr *Init) {
11208   bool IsInitCapture = !VDecl;
11209   assert((!VDecl || !VDecl->isInitCapture()) &&
11210          "init captures are expected to be deduced prior to initialization");
11211 
11212   VarDeclOrName VN{VDecl, Name};
11213 
11214   DeducedType *Deduced = Type->getContainedDeducedType();
11215   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11216 
11217   // C++11 [dcl.spec.auto]p3
11218   if (!Init) {
11219     assert(VDecl && "no init for init capture deduction?");
11220 
11221     // Except for class argument deduction, and then for an initializing
11222     // declaration only, i.e. no static at class scope or extern.
11223     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11224         VDecl->hasExternalStorage() ||
11225         VDecl->isStaticDataMember()) {
11226       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11227         << VDecl->getDeclName() << Type;
11228       return QualType();
11229     }
11230   }
11231 
11232   ArrayRef<Expr*> DeduceInits;
11233   if (Init)
11234     DeduceInits = Init;
11235 
11236   if (DirectInit) {
11237     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11238       DeduceInits = PL->exprs();
11239   }
11240 
11241   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11242     assert(VDecl && "non-auto type for init capture deduction?");
11243     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11244     InitializationKind Kind = InitializationKind::CreateForInit(
11245         VDecl->getLocation(), DirectInit, Init);
11246     // FIXME: Initialization should not be taking a mutable list of inits.
11247     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11248     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11249                                                        InitsCopy);
11250   }
11251 
11252   if (DirectInit) {
11253     if (auto *IL = dyn_cast<InitListExpr>(Init))
11254       DeduceInits = IL->inits();
11255   }
11256 
11257   // Deduction only works if we have exactly one source expression.
11258   if (DeduceInits.empty()) {
11259     // It isn't possible to write this directly, but it is possible to
11260     // end up in this situation with "auto x(some_pack...);"
11261     Diag(Init->getBeginLoc(), IsInitCapture
11262                                   ? diag::err_init_capture_no_expression
11263                                   : diag::err_auto_var_init_no_expression)
11264         << VN << Type << Range;
11265     return QualType();
11266   }
11267 
11268   if (DeduceInits.size() > 1) {
11269     Diag(DeduceInits[1]->getBeginLoc(),
11270          IsInitCapture ? diag::err_init_capture_multiple_expressions
11271                        : diag::err_auto_var_init_multiple_expressions)
11272         << VN << Type << Range;
11273     return QualType();
11274   }
11275 
11276   Expr *DeduceInit = DeduceInits[0];
11277   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11278     Diag(Init->getBeginLoc(), IsInitCapture
11279                                   ? diag::err_init_capture_paren_braces
11280                                   : diag::err_auto_var_init_paren_braces)
11281         << isa<InitListExpr>(Init) << VN << Type << Range;
11282     return QualType();
11283   }
11284 
11285   // Expressions default to 'id' when we're in a debugger.
11286   bool DefaultedAnyToId = false;
11287   if (getLangOpts().DebuggerCastResultToId &&
11288       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11289     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11290     if (Result.isInvalid()) {
11291       return QualType();
11292     }
11293     Init = Result.get();
11294     DefaultedAnyToId = true;
11295   }
11296 
11297   // C++ [dcl.decomp]p1:
11298   //   If the assignment-expression [...] has array type A and no ref-qualifier
11299   //   is present, e has type cv A
11300   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11301       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11302       DeduceInit->getType()->isConstantArrayType())
11303     return Context.getQualifiedType(DeduceInit->getType(),
11304                                     Type.getQualifiers());
11305 
11306   QualType DeducedType;
11307   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11308     if (!IsInitCapture)
11309       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11310     else if (isa<InitListExpr>(Init))
11311       Diag(Range.getBegin(),
11312            diag::err_init_capture_deduction_failure_from_init_list)
11313           << VN
11314           << (DeduceInit->getType().isNull() ? TSI->getType()
11315                                              : DeduceInit->getType())
11316           << DeduceInit->getSourceRange();
11317     else
11318       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11319           << VN << TSI->getType()
11320           << (DeduceInit->getType().isNull() ? TSI->getType()
11321                                              : DeduceInit->getType())
11322           << DeduceInit->getSourceRange();
11323   }
11324 
11325   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11326   // 'id' instead of a specific object type prevents most of our usual
11327   // checks.
11328   // We only want to warn outside of template instantiations, though:
11329   // inside a template, the 'id' could have come from a parameter.
11330   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11331       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11332     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11333     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11334   }
11335 
11336   return DeducedType;
11337 }
11338 
11339 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11340                                          Expr *Init) {
11341   QualType DeducedType = deduceVarTypeFromInitializer(
11342       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11343       VDecl->getSourceRange(), DirectInit, Init);
11344   if (DeducedType.isNull()) {
11345     VDecl->setInvalidDecl();
11346     return true;
11347   }
11348 
11349   VDecl->setType(DeducedType);
11350   assert(VDecl->isLinkageValid());
11351 
11352   // In ARC, infer lifetime.
11353   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11354     VDecl->setInvalidDecl();
11355 
11356   if (getLangOpts().OpenCL)
11357     deduceOpenCLAddressSpace(VDecl);
11358 
11359   // If this is a redeclaration, check that the type we just deduced matches
11360   // the previously declared type.
11361   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11362     // We never need to merge the type, because we cannot form an incomplete
11363     // array of auto, nor deduce such a type.
11364     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11365   }
11366 
11367   // Check the deduced type is valid for a variable declaration.
11368   CheckVariableDeclarationType(VDecl);
11369   return VDecl->isInvalidDecl();
11370 }
11371 
11372 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11373                                               SourceLocation Loc) {
11374   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11375     Init = CE->getSubExpr();
11376 
11377   QualType InitType = Init->getType();
11378   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11379           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11380          "shouldn't be called if type doesn't have a non-trivial C struct");
11381   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11382     for (auto I : ILE->inits()) {
11383       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11384           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11385         continue;
11386       SourceLocation SL = I->getExprLoc();
11387       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11388     }
11389     return;
11390   }
11391 
11392   if (isa<ImplicitValueInitExpr>(Init)) {
11393     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11394       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11395                             NTCUK_Init);
11396   } else {
11397     // Assume all other explicit initializers involving copying some existing
11398     // object.
11399     // TODO: ignore any explicit initializers where we can guarantee
11400     // copy-elision.
11401     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11402       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11403   }
11404 }
11405 
11406 namespace {
11407 
11408 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11409   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11410   // in the source code or implicitly by the compiler if it is in a union
11411   // defined in a system header and has non-trivial ObjC ownership
11412   // qualifications. We don't want those fields to participate in determining
11413   // whether the containing union is non-trivial.
11414   return FD->hasAttr<UnavailableAttr>();
11415 }
11416 
11417 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11418     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11419                                     void> {
11420   using Super =
11421       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11422                                     void>;
11423 
11424   DiagNonTrivalCUnionDefaultInitializeVisitor(
11425       QualType OrigTy, SourceLocation OrigLoc,
11426       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11427       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11428 
11429   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11430                      const FieldDecl *FD, bool InNonTrivialUnion) {
11431     if (const auto *AT = S.Context.getAsArrayType(QT))
11432       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11433                                      InNonTrivialUnion);
11434     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11435   }
11436 
11437   void visitARCStrong(QualType QT, const FieldDecl *FD,
11438                       bool InNonTrivialUnion) {
11439     if (InNonTrivialUnion)
11440       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11441           << 1 << 0 << QT << FD->getName();
11442   }
11443 
11444   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11445     if (InNonTrivialUnion)
11446       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11447           << 1 << 0 << QT << FD->getName();
11448   }
11449 
11450   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11451     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11452     if (RD->isUnion()) {
11453       if (OrigLoc.isValid()) {
11454         bool IsUnion = false;
11455         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11456           IsUnion = OrigRD->isUnion();
11457         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11458             << 0 << OrigTy << IsUnion << UseContext;
11459         // Reset OrigLoc so that this diagnostic is emitted only once.
11460         OrigLoc = SourceLocation();
11461       }
11462       InNonTrivialUnion = true;
11463     }
11464 
11465     if (InNonTrivialUnion)
11466       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11467           << 0 << 0 << QT.getUnqualifiedType() << "";
11468 
11469     for (const FieldDecl *FD : RD->fields())
11470       if (!shouldIgnoreForRecordTriviality(FD))
11471         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11472   }
11473 
11474   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11475 
11476   // The non-trivial C union type or the struct/union type that contains a
11477   // non-trivial C union.
11478   QualType OrigTy;
11479   SourceLocation OrigLoc;
11480   Sema::NonTrivialCUnionContext UseContext;
11481   Sema &S;
11482 };
11483 
11484 struct DiagNonTrivalCUnionDestructedTypeVisitor
11485     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11486   using Super =
11487       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11488 
11489   DiagNonTrivalCUnionDestructedTypeVisitor(
11490       QualType OrigTy, SourceLocation OrigLoc,
11491       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11492       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11493 
11494   void visitWithKind(QualType::DestructionKind DK, QualType QT,
11495                      const FieldDecl *FD, bool InNonTrivialUnion) {
11496     if (const auto *AT = S.Context.getAsArrayType(QT))
11497       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11498                                      InNonTrivialUnion);
11499     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11500   }
11501 
11502   void visitARCStrong(QualType QT, const FieldDecl *FD,
11503                       bool InNonTrivialUnion) {
11504     if (InNonTrivialUnion)
11505       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11506           << 1 << 1 << QT << FD->getName();
11507   }
11508 
11509   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11510     if (InNonTrivialUnion)
11511       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11512           << 1 << 1 << QT << FD->getName();
11513   }
11514 
11515   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11516     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11517     if (RD->isUnion()) {
11518       if (OrigLoc.isValid()) {
11519         bool IsUnion = false;
11520         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11521           IsUnion = OrigRD->isUnion();
11522         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11523             << 1 << OrigTy << IsUnion << UseContext;
11524         // Reset OrigLoc so that this diagnostic is emitted only once.
11525         OrigLoc = SourceLocation();
11526       }
11527       InNonTrivialUnion = true;
11528     }
11529 
11530     if (InNonTrivialUnion)
11531       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11532           << 0 << 1 << QT.getUnqualifiedType() << "";
11533 
11534     for (const FieldDecl *FD : RD->fields())
11535       if (!shouldIgnoreForRecordTriviality(FD))
11536         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11537   }
11538 
11539   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11540   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11541                           bool InNonTrivialUnion) {}
11542 
11543   // The non-trivial C union type or the struct/union type that contains a
11544   // non-trivial C union.
11545   QualType OrigTy;
11546   SourceLocation OrigLoc;
11547   Sema::NonTrivialCUnionContext UseContext;
11548   Sema &S;
11549 };
11550 
11551 struct DiagNonTrivalCUnionCopyVisitor
11552     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11553   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11554 
11555   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11556                                  Sema::NonTrivialCUnionContext UseContext,
11557                                  Sema &S)
11558       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11559 
11560   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11561                      const FieldDecl *FD, bool InNonTrivialUnion) {
11562     if (const auto *AT = S.Context.getAsArrayType(QT))
11563       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11564                                      InNonTrivialUnion);
11565     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11566   }
11567 
11568   void visitARCStrong(QualType QT, const FieldDecl *FD,
11569                       bool InNonTrivialUnion) {
11570     if (InNonTrivialUnion)
11571       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11572           << 1 << 2 << QT << FD->getName();
11573   }
11574 
11575   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11576     if (InNonTrivialUnion)
11577       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11578           << 1 << 2 << QT << FD->getName();
11579   }
11580 
11581   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11582     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11583     if (RD->isUnion()) {
11584       if (OrigLoc.isValid()) {
11585         bool IsUnion = false;
11586         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11587           IsUnion = OrigRD->isUnion();
11588         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11589             << 2 << OrigTy << IsUnion << UseContext;
11590         // Reset OrigLoc so that this diagnostic is emitted only once.
11591         OrigLoc = SourceLocation();
11592       }
11593       InNonTrivialUnion = true;
11594     }
11595 
11596     if (InNonTrivialUnion)
11597       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11598           << 0 << 2 << QT.getUnqualifiedType() << "";
11599 
11600     for (const FieldDecl *FD : RD->fields())
11601       if (!shouldIgnoreForRecordTriviality(FD))
11602         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11603   }
11604 
11605   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11606                 const FieldDecl *FD, bool InNonTrivialUnion) {}
11607   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11608   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11609                             bool InNonTrivialUnion) {}
11610 
11611   // The non-trivial C union type or the struct/union type that contains a
11612   // non-trivial C union.
11613   QualType OrigTy;
11614   SourceLocation OrigLoc;
11615   Sema::NonTrivialCUnionContext UseContext;
11616   Sema &S;
11617 };
11618 
11619 } // namespace
11620 
11621 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11622                                  NonTrivialCUnionContext UseContext,
11623                                  unsigned NonTrivialKind) {
11624   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11625           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
11626           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
11627          "shouldn't be called if type doesn't have a non-trivial C union");
11628 
11629   if ((NonTrivialKind & NTCUK_Init) &&
11630       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11631     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11632         .visit(QT, nullptr, false);
11633   if ((NonTrivialKind & NTCUK_Destruct) &&
11634       QT.hasNonTrivialToPrimitiveDestructCUnion())
11635     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11636         .visit(QT, nullptr, false);
11637   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11638     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11639         .visit(QT, nullptr, false);
11640 }
11641 
11642 /// AddInitializerToDecl - Adds the initializer Init to the
11643 /// declaration dcl. If DirectInit is true, this is C++ direct
11644 /// initialization rather than copy initialization.
11645 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11646   // If there is no declaration, there was an error parsing it.  Just ignore
11647   // the initializer.
11648   if (!RealDecl || RealDecl->isInvalidDecl()) {
11649     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11650     return;
11651   }
11652 
11653   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11654     // Pure-specifiers are handled in ActOnPureSpecifier.
11655     Diag(Method->getLocation(), diag::err_member_function_initialization)
11656       << Method->getDeclName() << Init->getSourceRange();
11657     Method->setInvalidDecl();
11658     return;
11659   }
11660 
11661   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11662   if (!VDecl) {
11663     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11664     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11665     RealDecl->setInvalidDecl();
11666     return;
11667   }
11668 
11669   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11670   if (VDecl->getType()->isUndeducedType()) {
11671     // Attempt typo correction early so that the type of the init expression can
11672     // be deduced based on the chosen correction if the original init contains a
11673     // TypoExpr.
11674     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11675     if (!Res.isUsable()) {
11676       RealDecl->setInvalidDecl();
11677       return;
11678     }
11679     Init = Res.get();
11680 
11681     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11682       return;
11683   }
11684 
11685   // dllimport cannot be used on variable definitions.
11686   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11687     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11688     VDecl->setInvalidDecl();
11689     return;
11690   }
11691 
11692   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11693     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11694     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11695     VDecl->setInvalidDecl();
11696     return;
11697   }
11698 
11699   if (!VDecl->getType()->isDependentType()) {
11700     // A definition must end up with a complete type, which means it must be
11701     // complete with the restriction that an array type might be completed by
11702     // the initializer; note that later code assumes this restriction.
11703     QualType BaseDeclType = VDecl->getType();
11704     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11705       BaseDeclType = Array->getElementType();
11706     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11707                             diag::err_typecheck_decl_incomplete_type)) {
11708       RealDecl->setInvalidDecl();
11709       return;
11710     }
11711 
11712     // The variable can not have an abstract class type.
11713     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11714                                diag::err_abstract_type_in_decl,
11715                                AbstractVariableType))
11716       VDecl->setInvalidDecl();
11717   }
11718 
11719   // If adding the initializer will turn this declaration into a definition,
11720   // and we already have a definition for this variable, diagnose or otherwise
11721   // handle the situation.
11722   VarDecl *Def;
11723   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11724       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11725       !VDecl->isThisDeclarationADemotedDefinition() &&
11726       checkVarDeclRedefinition(Def, VDecl))
11727     return;
11728 
11729   if (getLangOpts().CPlusPlus) {
11730     // C++ [class.static.data]p4
11731     //   If a static data member is of const integral or const
11732     //   enumeration type, its declaration in the class definition can
11733     //   specify a constant-initializer which shall be an integral
11734     //   constant expression (5.19). In that case, the member can appear
11735     //   in integral constant expressions. The member shall still be
11736     //   defined in a namespace scope if it is used in the program and the
11737     //   namespace scope definition shall not contain an initializer.
11738     //
11739     // We already performed a redefinition check above, but for static
11740     // data members we also need to check whether there was an in-class
11741     // declaration with an initializer.
11742     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11743       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11744           << VDecl->getDeclName();
11745       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11746            diag::note_previous_initializer)
11747           << 0;
11748       return;
11749     }
11750 
11751     if (VDecl->hasLocalStorage())
11752       setFunctionHasBranchProtectedScope();
11753 
11754     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11755       VDecl->setInvalidDecl();
11756       return;
11757     }
11758   }
11759 
11760   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11761   // a kernel function cannot be initialized."
11762   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11763     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11764     VDecl->setInvalidDecl();
11765     return;
11766   }
11767 
11768   // Get the decls type and save a reference for later, since
11769   // CheckInitializerTypes may change it.
11770   QualType DclT = VDecl->getType(), SavT = DclT;
11771 
11772   // Expressions default to 'id' when we're in a debugger
11773   // and we are assigning it to a variable of Objective-C pointer type.
11774   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11775       Init->getType() == Context.UnknownAnyTy) {
11776     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11777     if (Result.isInvalid()) {
11778       VDecl->setInvalidDecl();
11779       return;
11780     }
11781     Init = Result.get();
11782   }
11783 
11784   // Perform the initialization.
11785   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11786   if (!VDecl->isInvalidDecl()) {
11787     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11788     InitializationKind Kind = InitializationKind::CreateForInit(
11789         VDecl->getLocation(), DirectInit, Init);
11790 
11791     MultiExprArg Args = Init;
11792     if (CXXDirectInit)
11793       Args = MultiExprArg(CXXDirectInit->getExprs(),
11794                           CXXDirectInit->getNumExprs());
11795 
11796     // Try to correct any TypoExprs in the initialization arguments.
11797     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11798       ExprResult Res = CorrectDelayedTyposInExpr(
11799           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11800             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11801             return Init.Failed() ? ExprError() : E;
11802           });
11803       if (Res.isInvalid()) {
11804         VDecl->setInvalidDecl();
11805       } else if (Res.get() != Args[Idx]) {
11806         Args[Idx] = Res.get();
11807       }
11808     }
11809     if (VDecl->isInvalidDecl())
11810       return;
11811 
11812     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11813                                    /*TopLevelOfInitList=*/false,
11814                                    /*TreatUnavailableAsInvalid=*/false);
11815     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11816     if (Result.isInvalid()) {
11817       VDecl->setInvalidDecl();
11818       return;
11819     }
11820 
11821     Init = Result.getAs<Expr>();
11822   }
11823 
11824   // Check for self-references within variable initializers.
11825   // Variables declared within a function/method body (except for references)
11826   // are handled by a dataflow analysis.
11827   // This is undefined behavior in C++, but valid in C.
11828   if (getLangOpts().CPlusPlus) {
11829     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11830         VDecl->getType()->isReferenceType()) {
11831       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11832     }
11833   }
11834 
11835   // If the type changed, it means we had an incomplete type that was
11836   // completed by the initializer. For example:
11837   //   int ary[] = { 1, 3, 5 };
11838   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11839   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11840     VDecl->setType(DclT);
11841 
11842   if (!VDecl->isInvalidDecl()) {
11843     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11844 
11845     if (VDecl->hasAttr<BlocksAttr>())
11846       checkRetainCycles(VDecl, Init);
11847 
11848     // It is safe to assign a weak reference into a strong variable.
11849     // Although this code can still have problems:
11850     //   id x = self.weakProp;
11851     //   id y = self.weakProp;
11852     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11853     // paths through the function. This should be revisited if
11854     // -Wrepeated-use-of-weak is made flow-sensitive.
11855     if (FunctionScopeInfo *FSI = getCurFunction())
11856       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11857            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11858           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11859                            Init->getBeginLoc()))
11860         FSI->markSafeWeakUse(Init);
11861   }
11862 
11863   // The initialization is usually a full-expression.
11864   //
11865   // FIXME: If this is a braced initialization of an aggregate, it is not
11866   // an expression, and each individual field initializer is a separate
11867   // full-expression. For instance, in:
11868   //
11869   //   struct Temp { ~Temp(); };
11870   //   struct S { S(Temp); };
11871   //   struct T { S a, b; } t = { Temp(), Temp() }
11872   //
11873   // we should destroy the first Temp before constructing the second.
11874   ExprResult Result =
11875       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11876                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11877   if (Result.isInvalid()) {
11878     VDecl->setInvalidDecl();
11879     return;
11880   }
11881   Init = Result.get();
11882 
11883   // Attach the initializer to the decl.
11884   VDecl->setInit(Init);
11885 
11886   if (VDecl->isLocalVarDecl()) {
11887     // Don't check the initializer if the declaration is malformed.
11888     if (VDecl->isInvalidDecl()) {
11889       // do nothing
11890 
11891     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11892     // This is true even in C++ for OpenCL.
11893     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11894       CheckForConstantInitializer(Init, DclT);
11895 
11896     // Otherwise, C++ does not restrict the initializer.
11897     } else if (getLangOpts().CPlusPlus) {
11898       // do nothing
11899 
11900     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11901     // static storage duration shall be constant expressions or string literals.
11902     } else if (VDecl->getStorageClass() == SC_Static) {
11903       CheckForConstantInitializer(Init, DclT);
11904 
11905     // C89 is stricter than C99 for aggregate initializers.
11906     // C89 6.5.7p3: All the expressions [...] in an initializer list
11907     // for an object that has aggregate or union type shall be
11908     // constant expressions.
11909     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11910                isa<InitListExpr>(Init)) {
11911       const Expr *Culprit;
11912       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11913         Diag(Culprit->getExprLoc(),
11914              diag::ext_aggregate_init_not_constant)
11915           << Culprit->getSourceRange();
11916       }
11917     }
11918 
11919     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11920       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11921         if (VDecl->hasLocalStorage())
11922           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11923   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11924              VDecl->getLexicalDeclContext()->isRecord()) {
11925     // This is an in-class initialization for a static data member, e.g.,
11926     //
11927     // struct S {
11928     //   static const int value = 17;
11929     // };
11930 
11931     // C++ [class.mem]p4:
11932     //   A member-declarator can contain a constant-initializer only
11933     //   if it declares a static member (9.4) of const integral or
11934     //   const enumeration type, see 9.4.2.
11935     //
11936     // C++11 [class.static.data]p3:
11937     //   If a non-volatile non-inline const static data member is of integral
11938     //   or enumeration type, its declaration in the class definition can
11939     //   specify a brace-or-equal-initializer in which every initializer-clause
11940     //   that is an assignment-expression is a constant expression. A static
11941     //   data member of literal type can be declared in the class definition
11942     //   with the constexpr specifier; if so, its declaration shall specify a
11943     //   brace-or-equal-initializer in which every initializer-clause that is
11944     //   an assignment-expression is a constant expression.
11945 
11946     // Do nothing on dependent types.
11947     if (DclT->isDependentType()) {
11948 
11949     // Allow any 'static constexpr' members, whether or not they are of literal
11950     // type. We separately check that every constexpr variable is of literal
11951     // type.
11952     } else if (VDecl->isConstexpr()) {
11953 
11954     // Require constness.
11955     } else if (!DclT.isConstQualified()) {
11956       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11957         << Init->getSourceRange();
11958       VDecl->setInvalidDecl();
11959 
11960     // We allow integer constant expressions in all cases.
11961     } else if (DclT->isIntegralOrEnumerationType()) {
11962       // Check whether the expression is a constant expression.
11963       SourceLocation Loc;
11964       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11965         // In C++11, a non-constexpr const static data member with an
11966         // in-class initializer cannot be volatile.
11967         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11968       else if (Init->isValueDependent())
11969         ; // Nothing to check.
11970       else if (Init->isIntegerConstantExpr(Context, &Loc))
11971         ; // Ok, it's an ICE!
11972       else if (Init->getType()->isScopedEnumeralType() &&
11973                Init->isCXX11ConstantExpr(Context))
11974         ; // Ok, it is a scoped-enum constant expression.
11975       else if (Init->isEvaluatable(Context)) {
11976         // If we can constant fold the initializer through heroics, accept it,
11977         // but report this as a use of an extension for -pedantic.
11978         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11979           << Init->getSourceRange();
11980       } else {
11981         // Otherwise, this is some crazy unknown case.  Report the issue at the
11982         // location provided by the isIntegerConstantExpr failed check.
11983         Diag(Loc, diag::err_in_class_initializer_non_constant)
11984           << Init->getSourceRange();
11985         VDecl->setInvalidDecl();
11986       }
11987 
11988     // We allow foldable floating-point constants as an extension.
11989     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11990       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11991       // it anyway and provide a fixit to add the 'constexpr'.
11992       if (getLangOpts().CPlusPlus11) {
11993         Diag(VDecl->getLocation(),
11994              diag::ext_in_class_initializer_float_type_cxx11)
11995             << DclT << Init->getSourceRange();
11996         Diag(VDecl->getBeginLoc(),
11997              diag::note_in_class_initializer_float_type_cxx11)
11998             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11999       } else {
12000         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12001           << DclT << Init->getSourceRange();
12002 
12003         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12004           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12005             << Init->getSourceRange();
12006           VDecl->setInvalidDecl();
12007         }
12008       }
12009 
12010     // Suggest adding 'constexpr' in C++11 for literal types.
12011     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12012       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12013           << DclT << Init->getSourceRange()
12014           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12015       VDecl->setConstexpr(true);
12016 
12017     } else {
12018       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12019         << DclT << Init->getSourceRange();
12020       VDecl->setInvalidDecl();
12021     }
12022   } else if (VDecl->isFileVarDecl()) {
12023     // In C, extern is typically used to avoid tentative definitions when
12024     // declaring variables in headers, but adding an intializer makes it a
12025     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12026     // In C++, extern is often used to give implictly static const variables
12027     // external linkage, so don't warn in that case. If selectany is present,
12028     // this might be header code intended for C and C++ inclusion, so apply the
12029     // C++ rules.
12030     if (VDecl->getStorageClass() == SC_Extern &&
12031         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12032          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12033         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12034         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12035       Diag(VDecl->getLocation(), diag::warn_extern_init);
12036 
12037     // In Microsoft C++ mode, a const variable defined in namespace scope has
12038     // external linkage by default if the variable is declared with
12039     // __declspec(dllexport).
12040     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12041         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12042         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12043       VDecl->setStorageClass(SC_Extern);
12044 
12045     // C99 6.7.8p4. All file scoped initializers need to be constant.
12046     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12047       CheckForConstantInitializer(Init, DclT);
12048   }
12049 
12050   QualType InitType = Init->getType();
12051   if (!InitType.isNull() &&
12052       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12053        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12054     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12055 
12056   // We will represent direct-initialization similarly to copy-initialization:
12057   //    int x(1);  -as-> int x = 1;
12058   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12059   //
12060   // Clients that want to distinguish between the two forms, can check for
12061   // direct initializer using VarDecl::getInitStyle().
12062   // A major benefit is that clients that don't particularly care about which
12063   // exactly form was it (like the CodeGen) can handle both cases without
12064   // special case code.
12065 
12066   // C++ 8.5p11:
12067   // The form of initialization (using parentheses or '=') is generally
12068   // insignificant, but does matter when the entity being initialized has a
12069   // class type.
12070   if (CXXDirectInit) {
12071     assert(DirectInit && "Call-style initializer must be direct init.");
12072     VDecl->setInitStyle(VarDecl::CallInit);
12073   } else if (DirectInit) {
12074     // This must be list-initialization. No other way is direct-initialization.
12075     VDecl->setInitStyle(VarDecl::ListInit);
12076   }
12077 
12078   CheckCompleteVariableDeclaration(VDecl);
12079 }
12080 
12081 /// ActOnInitializerError - Given that there was an error parsing an
12082 /// initializer for the given declaration, try to return to some form
12083 /// of sanity.
12084 void Sema::ActOnInitializerError(Decl *D) {
12085   // Our main concern here is re-establishing invariants like "a
12086   // variable's type is either dependent or complete".
12087   if (!D || D->isInvalidDecl()) return;
12088 
12089   VarDecl *VD = dyn_cast<VarDecl>(D);
12090   if (!VD) return;
12091 
12092   // Bindings are not usable if we can't make sense of the initializer.
12093   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12094     for (auto *BD : DD->bindings())
12095       BD->setInvalidDecl();
12096 
12097   // Auto types are meaningless if we can't make sense of the initializer.
12098   if (ParsingInitForAutoVars.count(D)) {
12099     D->setInvalidDecl();
12100     return;
12101   }
12102 
12103   QualType Ty = VD->getType();
12104   if (Ty->isDependentType()) return;
12105 
12106   // Require a complete type.
12107   if (RequireCompleteType(VD->getLocation(),
12108                           Context.getBaseElementType(Ty),
12109                           diag::err_typecheck_decl_incomplete_type)) {
12110     VD->setInvalidDecl();
12111     return;
12112   }
12113 
12114   // Require a non-abstract type.
12115   if (RequireNonAbstractType(VD->getLocation(), Ty,
12116                              diag::err_abstract_type_in_decl,
12117                              AbstractVariableType)) {
12118     VD->setInvalidDecl();
12119     return;
12120   }
12121 
12122   // Don't bother complaining about constructors or destructors,
12123   // though.
12124 }
12125 
12126 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12127   // If there is no declaration, there was an error parsing it. Just ignore it.
12128   if (!RealDecl)
12129     return;
12130 
12131   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12132     QualType Type = Var->getType();
12133 
12134     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12135     if (isa<DecompositionDecl>(RealDecl)) {
12136       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12137       Var->setInvalidDecl();
12138       return;
12139     }
12140 
12141     if (Type->isUndeducedType() &&
12142         DeduceVariableDeclarationType(Var, false, nullptr))
12143       return;
12144 
12145     // C++11 [class.static.data]p3: A static data member can be declared with
12146     // the constexpr specifier; if so, its declaration shall specify
12147     // a brace-or-equal-initializer.
12148     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12149     // the definition of a variable [...] or the declaration of a static data
12150     // member.
12151     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12152         !Var->isThisDeclarationADemotedDefinition()) {
12153       if (Var->isStaticDataMember()) {
12154         // C++1z removes the relevant rule; the in-class declaration is always
12155         // a definition there.
12156         if (!getLangOpts().CPlusPlus17 &&
12157             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12158           Diag(Var->getLocation(),
12159                diag::err_constexpr_static_mem_var_requires_init)
12160             << Var->getDeclName();
12161           Var->setInvalidDecl();
12162           return;
12163         }
12164       } else {
12165         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12166         Var->setInvalidDecl();
12167         return;
12168       }
12169     }
12170 
12171     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12172     // be initialized.
12173     if (!Var->isInvalidDecl() &&
12174         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12175         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12176       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12177       Var->setInvalidDecl();
12178       return;
12179     }
12180 
12181     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12182     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12183         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12184       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12185                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12186 
12187 
12188     switch (DefKind) {
12189     case VarDecl::Definition:
12190       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12191         break;
12192 
12193       // We have an out-of-line definition of a static data member
12194       // that has an in-class initializer, so we type-check this like
12195       // a declaration.
12196       //
12197       LLVM_FALLTHROUGH;
12198 
12199     case VarDecl::DeclarationOnly:
12200       // It's only a declaration.
12201 
12202       // Block scope. C99 6.7p7: If an identifier for an object is
12203       // declared with no linkage (C99 6.2.2p6), the type for the
12204       // object shall be complete.
12205       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12206           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12207           RequireCompleteType(Var->getLocation(), Type,
12208                               diag::err_typecheck_decl_incomplete_type))
12209         Var->setInvalidDecl();
12210 
12211       // Make sure that the type is not abstract.
12212       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12213           RequireNonAbstractType(Var->getLocation(), Type,
12214                                  diag::err_abstract_type_in_decl,
12215                                  AbstractVariableType))
12216         Var->setInvalidDecl();
12217       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12218           Var->getStorageClass() == SC_PrivateExtern) {
12219         Diag(Var->getLocation(), diag::warn_private_extern);
12220         Diag(Var->getLocation(), diag::note_private_extern);
12221       }
12222 
12223       if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12224           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12225         ExternalDeclarations.push_back(Var);
12226 
12227       return;
12228 
12229     case VarDecl::TentativeDefinition:
12230       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12231       // object that has file scope without an initializer, and without a
12232       // storage-class specifier or with the storage-class specifier "static",
12233       // constitutes a tentative definition. Note: A tentative definition with
12234       // external linkage is valid (C99 6.2.2p5).
12235       if (!Var->isInvalidDecl()) {
12236         if (const IncompleteArrayType *ArrayT
12237                                     = Context.getAsIncompleteArrayType(Type)) {
12238           if (RequireCompleteType(Var->getLocation(),
12239                                   ArrayT->getElementType(),
12240                                   diag::err_illegal_decl_array_incomplete_type))
12241             Var->setInvalidDecl();
12242         } else if (Var->getStorageClass() == SC_Static) {
12243           // C99 6.9.2p3: If the declaration of an identifier for an object is
12244           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12245           // declared type shall not be an incomplete type.
12246           // NOTE: code such as the following
12247           //     static struct s;
12248           //     struct s { int a; };
12249           // is accepted by gcc. Hence here we issue a warning instead of
12250           // an error and we do not invalidate the static declaration.
12251           // NOTE: to avoid multiple warnings, only check the first declaration.
12252           if (Var->isFirstDecl())
12253             RequireCompleteType(Var->getLocation(), Type,
12254                                 diag::ext_typecheck_decl_incomplete_type);
12255         }
12256       }
12257 
12258       // Record the tentative definition; we're done.
12259       if (!Var->isInvalidDecl())
12260         TentativeDefinitions.push_back(Var);
12261       return;
12262     }
12263 
12264     // Provide a specific diagnostic for uninitialized variable
12265     // definitions with incomplete array type.
12266     if (Type->isIncompleteArrayType()) {
12267       Diag(Var->getLocation(),
12268            diag::err_typecheck_incomplete_array_needs_initializer);
12269       Var->setInvalidDecl();
12270       return;
12271     }
12272 
12273     // Provide a specific diagnostic for uninitialized variable
12274     // definitions with reference type.
12275     if (Type->isReferenceType()) {
12276       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12277         << Var->getDeclName()
12278         << SourceRange(Var->getLocation(), Var->getLocation());
12279       Var->setInvalidDecl();
12280       return;
12281     }
12282 
12283     // Do not attempt to type-check the default initializer for a
12284     // variable with dependent type.
12285     if (Type->isDependentType())
12286       return;
12287 
12288     if (Var->isInvalidDecl())
12289       return;
12290 
12291     if (!Var->hasAttr<AliasAttr>()) {
12292       if (RequireCompleteType(Var->getLocation(),
12293                               Context.getBaseElementType(Type),
12294                               diag::err_typecheck_decl_incomplete_type)) {
12295         Var->setInvalidDecl();
12296         return;
12297       }
12298     } else {
12299       return;
12300     }
12301 
12302     // The variable can not have an abstract class type.
12303     if (RequireNonAbstractType(Var->getLocation(), Type,
12304                                diag::err_abstract_type_in_decl,
12305                                AbstractVariableType)) {
12306       Var->setInvalidDecl();
12307       return;
12308     }
12309 
12310     // Check for jumps past the implicit initializer.  C++0x
12311     // clarifies that this applies to a "variable with automatic
12312     // storage duration", not a "local variable".
12313     // C++11 [stmt.dcl]p3
12314     //   A program that jumps from a point where a variable with automatic
12315     //   storage duration is not in scope to a point where it is in scope is
12316     //   ill-formed unless the variable has scalar type, class type with a
12317     //   trivial default constructor and a trivial destructor, a cv-qualified
12318     //   version of one of these types, or an array of one of the preceding
12319     //   types and is declared without an initializer.
12320     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12321       if (const RecordType *Record
12322             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12323         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12324         // Mark the function (if we're in one) for further checking even if the
12325         // looser rules of C++11 do not require such checks, so that we can
12326         // diagnose incompatibilities with C++98.
12327         if (!CXXRecord->isPOD())
12328           setFunctionHasBranchProtectedScope();
12329       }
12330     }
12331     // In OpenCL, we can't initialize objects in the __local address space,
12332     // even implicitly, so don't synthesize an implicit initializer.
12333     if (getLangOpts().OpenCL &&
12334         Var->getType().getAddressSpace() == LangAS::opencl_local)
12335       return;
12336     // C++03 [dcl.init]p9:
12337     //   If no initializer is specified for an object, and the
12338     //   object is of (possibly cv-qualified) non-POD class type (or
12339     //   array thereof), the object shall be default-initialized; if
12340     //   the object is of const-qualified type, the underlying class
12341     //   type shall have a user-declared default
12342     //   constructor. Otherwise, if no initializer is specified for
12343     //   a non- static object, the object and its subobjects, if
12344     //   any, have an indeterminate initial value); if the object
12345     //   or any of its subobjects are of const-qualified type, the
12346     //   program is ill-formed.
12347     // C++0x [dcl.init]p11:
12348     //   If no initializer is specified for an object, the object is
12349     //   default-initialized; [...].
12350     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12351     InitializationKind Kind
12352       = InitializationKind::CreateDefault(Var->getLocation());
12353 
12354     InitializationSequence InitSeq(*this, Entity, Kind, None);
12355     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12356     if (Init.isInvalid())
12357       Var->setInvalidDecl();
12358     else if (Init.get()) {
12359       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12360       // This is important for template substitution.
12361       Var->setInitStyle(VarDecl::CallInit);
12362     }
12363 
12364     CheckCompleteVariableDeclaration(Var);
12365   }
12366 }
12367 
12368 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12369   // If there is no declaration, there was an error parsing it. Ignore it.
12370   if (!D)
12371     return;
12372 
12373   VarDecl *VD = dyn_cast<VarDecl>(D);
12374   if (!VD) {
12375     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12376     D->setInvalidDecl();
12377     return;
12378   }
12379 
12380   VD->setCXXForRangeDecl(true);
12381 
12382   // for-range-declaration cannot be given a storage class specifier.
12383   int Error = -1;
12384   switch (VD->getStorageClass()) {
12385   case SC_None:
12386     break;
12387   case SC_Extern:
12388     Error = 0;
12389     break;
12390   case SC_Static:
12391     Error = 1;
12392     break;
12393   case SC_PrivateExtern:
12394     Error = 2;
12395     break;
12396   case SC_Auto:
12397     Error = 3;
12398     break;
12399   case SC_Register:
12400     Error = 4;
12401     break;
12402   }
12403   if (Error != -1) {
12404     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12405       << VD->getDeclName() << Error;
12406     D->setInvalidDecl();
12407   }
12408 }
12409 
12410 StmtResult
12411 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12412                                  IdentifierInfo *Ident,
12413                                  ParsedAttributes &Attrs,
12414                                  SourceLocation AttrEnd) {
12415   // C++1y [stmt.iter]p1:
12416   //   A range-based for statement of the form
12417   //      for ( for-range-identifier : for-range-initializer ) statement
12418   //   is equivalent to
12419   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
12420   DeclSpec DS(Attrs.getPool().getFactory());
12421 
12422   const char *PrevSpec;
12423   unsigned DiagID;
12424   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12425                      getPrintingPolicy());
12426 
12427   Declarator D(DS, DeclaratorContext::ForContext);
12428   D.SetIdentifier(Ident, IdentLoc);
12429   D.takeAttributes(Attrs, AttrEnd);
12430 
12431   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12432                 IdentLoc);
12433   Decl *Var = ActOnDeclarator(S, D);
12434   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12435   FinalizeDeclaration(Var);
12436   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12437                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
12438 }
12439 
12440 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12441   if (var->isInvalidDecl()) return;
12442 
12443   if (getLangOpts().OpenCL) {
12444     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12445     // initialiser
12446     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12447         !var->hasInit()) {
12448       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12449           << 1 /*Init*/;
12450       var->setInvalidDecl();
12451       return;
12452     }
12453   }
12454 
12455   // In Objective-C, don't allow jumps past the implicit initialization of a
12456   // local retaining variable.
12457   if (getLangOpts().ObjC &&
12458       var->hasLocalStorage()) {
12459     switch (var->getType().getObjCLifetime()) {
12460     case Qualifiers::OCL_None:
12461     case Qualifiers::OCL_ExplicitNone:
12462     case Qualifiers::OCL_Autoreleasing:
12463       break;
12464 
12465     case Qualifiers::OCL_Weak:
12466     case Qualifiers::OCL_Strong:
12467       setFunctionHasBranchProtectedScope();
12468       break;
12469     }
12470   }
12471 
12472   if (var->hasLocalStorage() &&
12473       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12474     setFunctionHasBranchProtectedScope();
12475 
12476   // Warn about externally-visible variables being defined without a
12477   // prior declaration.  We only want to do this for global
12478   // declarations, but we also specifically need to avoid doing it for
12479   // class members because the linkage of an anonymous class can
12480   // change if it's later given a typedef name.
12481   if (var->isThisDeclarationADefinition() &&
12482       var->getDeclContext()->getRedeclContext()->isFileContext() &&
12483       var->isExternallyVisible() && var->hasLinkage() &&
12484       !var->isInline() && !var->getDescribedVarTemplate() &&
12485       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12486       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12487                                   var->getLocation())) {
12488     // Find a previous declaration that's not a definition.
12489     VarDecl *prev = var->getPreviousDecl();
12490     while (prev && prev->isThisDeclarationADefinition())
12491       prev = prev->getPreviousDecl();
12492 
12493     if (!prev) {
12494       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12495       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12496           << /* variable */ 0;
12497     }
12498   }
12499 
12500   // Cache the result of checking for constant initialization.
12501   Optional<bool> CacheHasConstInit;
12502   const Expr *CacheCulprit = nullptr;
12503   auto checkConstInit = [&]() mutable {
12504     if (!CacheHasConstInit)
12505       CacheHasConstInit = var->getInit()->isConstantInitializer(
12506             Context, var->getType()->isReferenceType(), &CacheCulprit);
12507     return *CacheHasConstInit;
12508   };
12509 
12510   if (var->getTLSKind() == VarDecl::TLS_Static) {
12511     if (var->getType().isDestructedType()) {
12512       // GNU C++98 edits for __thread, [basic.start.term]p3:
12513       //   The type of an object with thread storage duration shall not
12514       //   have a non-trivial destructor.
12515       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12516       if (getLangOpts().CPlusPlus11)
12517         Diag(var->getLocation(), diag::note_use_thread_local);
12518     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12519       if (!checkConstInit()) {
12520         // GNU C++98 edits for __thread, [basic.start.init]p4:
12521         //   An object of thread storage duration shall not require dynamic
12522         //   initialization.
12523         // FIXME: Need strict checking here.
12524         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12525           << CacheCulprit->getSourceRange();
12526         if (getLangOpts().CPlusPlus11)
12527           Diag(var->getLocation(), diag::note_use_thread_local);
12528       }
12529     }
12530   }
12531 
12532   // Apply section attributes and pragmas to global variables.
12533   bool GlobalStorage = var->hasGlobalStorage();
12534   if (GlobalStorage && var->isThisDeclarationADefinition() &&
12535       !inTemplateInstantiation()) {
12536     PragmaStack<StringLiteral *> *Stack = nullptr;
12537     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
12538     if (var->getType().isConstQualified())
12539       Stack = &ConstSegStack;
12540     else if (!var->getInit()) {
12541       Stack = &BSSSegStack;
12542       SectionFlags |= ASTContext::PSF_Write;
12543     } else {
12544       Stack = &DataSegStack;
12545       SectionFlags |= ASTContext::PSF_Write;
12546     }
12547     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
12548       var->addAttr(SectionAttr::CreateImplicit(
12549           Context, Stack->CurrentValue->getString(),
12550           Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
12551           SectionAttr::Declspec_allocate));
12552     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
12553       if (UnifySection(SA->getName(), SectionFlags, var))
12554         var->dropAttr<SectionAttr>();
12555 
12556     // Apply the init_seg attribute if this has an initializer.  If the
12557     // initializer turns out to not be dynamic, we'll end up ignoring this
12558     // attribute.
12559     if (CurInitSeg && var->getInit())
12560       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12561                                                CurInitSegLoc,
12562                                                AttributeCommonInfo::AS_Pragma));
12563   }
12564 
12565   // All the following checks are C++ only.
12566   if (!getLangOpts().CPlusPlus) {
12567       // If this variable must be emitted, add it as an initializer for the
12568       // current module.
12569      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12570        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12571      return;
12572   }
12573 
12574   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12575     CheckCompleteDecompositionDeclaration(DD);
12576 
12577   QualType type = var->getType();
12578   if (type->isDependentType()) return;
12579 
12580   if (var->hasAttr<BlocksAttr>())
12581     getCurFunction()->addByrefBlockVar(var);
12582 
12583   Expr *Init = var->getInit();
12584   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12585   QualType baseType = Context.getBaseElementType(type);
12586 
12587   if (Init && !Init->isValueDependent()) {
12588     if (var->isConstexpr()) {
12589       SmallVector<PartialDiagnosticAt, 8> Notes;
12590       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12591         SourceLocation DiagLoc = var->getLocation();
12592         // If the note doesn't add any useful information other than a source
12593         // location, fold it into the primary diagnostic.
12594         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12595               diag::note_invalid_subexpr_in_const_expr) {
12596           DiagLoc = Notes[0].first;
12597           Notes.clear();
12598         }
12599         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12600           << var << Init->getSourceRange();
12601         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12602           Diag(Notes[I].first, Notes[I].second);
12603       }
12604     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12605       // Check whether the initializer of a const variable of integral or
12606       // enumeration type is an ICE now, since we can't tell whether it was
12607       // initialized by a constant expression if we check later.
12608       var->checkInitIsICE();
12609     }
12610 
12611     // Don't emit further diagnostics about constexpr globals since they
12612     // were just diagnosed.
12613     if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12614       // FIXME: Need strict checking in C++03 here.
12615       bool DiagErr = getLangOpts().CPlusPlus11
12616           ? !var->checkInitIsICE() : !checkConstInit();
12617       if (DiagErr) {
12618         auto *Attr = var->getAttr<ConstInitAttr>();
12619         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12620           << Init->getSourceRange();
12621         Diag(Attr->getLocation(),
12622              diag::note_declared_required_constant_init_here)
12623             << Attr->getRange() << Attr->isConstinit();
12624         if (getLangOpts().CPlusPlus11) {
12625           APValue Value;
12626           SmallVector<PartialDiagnosticAt, 8> Notes;
12627           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12628           for (auto &it : Notes)
12629             Diag(it.first, it.second);
12630         } else {
12631           Diag(CacheCulprit->getExprLoc(),
12632                diag::note_invalid_subexpr_in_const_expr)
12633               << CacheCulprit->getSourceRange();
12634         }
12635       }
12636     }
12637     else if (!var->isConstexpr() && IsGlobal &&
12638              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12639                                     var->getLocation())) {
12640       // Warn about globals which don't have a constant initializer.  Don't
12641       // warn about globals with a non-trivial destructor because we already
12642       // warned about them.
12643       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12644       if (!(RD && !RD->hasTrivialDestructor())) {
12645         if (!checkConstInit())
12646           Diag(var->getLocation(), diag::warn_global_constructor)
12647             << Init->getSourceRange();
12648       }
12649     }
12650   }
12651 
12652   // Require the destructor.
12653   if (const RecordType *recordType = baseType->getAs<RecordType>())
12654     FinalizeVarWithDestructor(var, recordType);
12655 
12656   // If this variable must be emitted, add it as an initializer for the current
12657   // module.
12658   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12659     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12660 }
12661 
12662 /// Determines if a variable's alignment is dependent.
12663 static bool hasDependentAlignment(VarDecl *VD) {
12664   if (VD->getType()->isDependentType())
12665     return true;
12666   for (auto *I : VD->specific_attrs<AlignedAttr>())
12667     if (I->isAlignmentDependent())
12668       return true;
12669   return false;
12670 }
12671 
12672 /// Check if VD needs to be dllexport/dllimport due to being in a
12673 /// dllexport/import function.
12674 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12675   assert(VD->isStaticLocal());
12676 
12677   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12678 
12679   // Find outermost function when VD is in lambda function.
12680   while (FD && !getDLLAttr(FD) &&
12681          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12682          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12683     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12684   }
12685 
12686   if (!FD)
12687     return;
12688 
12689   // Static locals inherit dll attributes from their function.
12690   if (Attr *A = getDLLAttr(FD)) {
12691     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12692     NewAttr->setInherited(true);
12693     VD->addAttr(NewAttr);
12694   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12695     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
12696     NewAttr->setInherited(true);
12697     VD->addAttr(NewAttr);
12698 
12699     // Export this function to enforce exporting this static variable even
12700     // if it is not used in this compilation unit.
12701     if (!FD->hasAttr<DLLExportAttr>())
12702       FD->addAttr(NewAttr);
12703 
12704   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12705     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
12706     NewAttr->setInherited(true);
12707     VD->addAttr(NewAttr);
12708   }
12709 }
12710 
12711 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12712 /// any semantic actions necessary after any initializer has been attached.
12713 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12714   // Note that we are no longer parsing the initializer for this declaration.
12715   ParsingInitForAutoVars.erase(ThisDecl);
12716 
12717   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12718   if (!VD)
12719     return;
12720 
12721   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12722   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12723       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12724     if (PragmaClangBSSSection.Valid)
12725       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
12726           Context, PragmaClangBSSSection.SectionName,
12727           PragmaClangBSSSection.PragmaLocation,
12728           AttributeCommonInfo::AS_Pragma));
12729     if (PragmaClangDataSection.Valid)
12730       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
12731           Context, PragmaClangDataSection.SectionName,
12732           PragmaClangDataSection.PragmaLocation,
12733           AttributeCommonInfo::AS_Pragma));
12734     if (PragmaClangRodataSection.Valid)
12735       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
12736           Context, PragmaClangRodataSection.SectionName,
12737           PragmaClangRodataSection.PragmaLocation,
12738           AttributeCommonInfo::AS_Pragma));
12739     if (PragmaClangRelroSection.Valid)
12740       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
12741           Context, PragmaClangRelroSection.SectionName,
12742           PragmaClangRelroSection.PragmaLocation,
12743           AttributeCommonInfo::AS_Pragma));
12744   }
12745 
12746   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12747     for (auto *BD : DD->bindings()) {
12748       FinalizeDeclaration(BD);
12749     }
12750   }
12751 
12752   checkAttributesAfterMerging(*this, *VD);
12753 
12754   // Perform TLS alignment check here after attributes attached to the variable
12755   // which may affect the alignment have been processed. Only perform the check
12756   // if the target has a maximum TLS alignment (zero means no constraints).
12757   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12758     // Protect the check so that it's not performed on dependent types and
12759     // dependent alignments (we can't determine the alignment in that case).
12760     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12761         !VD->isInvalidDecl()) {
12762       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12763       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12764         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12765           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12766           << (unsigned)MaxAlignChars.getQuantity();
12767       }
12768     }
12769   }
12770 
12771   if (VD->isStaticLocal()) {
12772     CheckStaticLocalForDllExport(VD);
12773 
12774     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12775       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12776       // function, only __shared__ variables or variables without any device
12777       // memory qualifiers may be declared with static storage class.
12778       // Note: It is unclear how a function-scope non-const static variable
12779       // without device memory qualifier is implemented, therefore only static
12780       // const variable without device memory qualifier is allowed.
12781       [&]() {
12782         if (!getLangOpts().CUDA)
12783           return;
12784         if (VD->hasAttr<CUDASharedAttr>())
12785           return;
12786         if (VD->getType().isConstQualified() &&
12787             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12788           return;
12789         if (CUDADiagIfDeviceCode(VD->getLocation(),
12790                                  diag::err_device_static_local_var)
12791             << CurrentCUDATarget())
12792           VD->setInvalidDecl();
12793       }();
12794     }
12795   }
12796 
12797   // Perform check for initializers of device-side global variables.
12798   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12799   // 7.5). We must also apply the same checks to all __shared__
12800   // variables whether they are local or not. CUDA also allows
12801   // constant initializers for __constant__ and __device__ variables.
12802   if (getLangOpts().CUDA)
12803     checkAllowedCUDAInitializer(VD);
12804 
12805   // Grab the dllimport or dllexport attribute off of the VarDecl.
12806   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12807 
12808   // Imported static data members cannot be defined out-of-line.
12809   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12810     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12811         VD->isThisDeclarationADefinition()) {
12812       // We allow definitions of dllimport class template static data members
12813       // with a warning.
12814       CXXRecordDecl *Context =
12815         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12816       bool IsClassTemplateMember =
12817           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12818           Context->getDescribedClassTemplate();
12819 
12820       Diag(VD->getLocation(),
12821            IsClassTemplateMember
12822                ? diag::warn_attribute_dllimport_static_field_definition
12823                : diag::err_attribute_dllimport_static_field_definition);
12824       Diag(IA->getLocation(), diag::note_attribute);
12825       if (!IsClassTemplateMember)
12826         VD->setInvalidDecl();
12827     }
12828   }
12829 
12830   // dllimport/dllexport variables cannot be thread local, their TLS index
12831   // isn't exported with the variable.
12832   if (DLLAttr && VD->getTLSKind()) {
12833     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12834     if (F && getDLLAttr(F)) {
12835       assert(VD->isStaticLocal());
12836       // But if this is a static local in a dlimport/dllexport function, the
12837       // function will never be inlined, which means the var would never be
12838       // imported, so having it marked import/export is safe.
12839     } else {
12840       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12841                                                                     << DLLAttr;
12842       VD->setInvalidDecl();
12843     }
12844   }
12845 
12846   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12847     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12848       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12849       VD->dropAttr<UsedAttr>();
12850     }
12851   }
12852 
12853   const DeclContext *DC = VD->getDeclContext();
12854   // If there's a #pragma GCC visibility in scope, and this isn't a class
12855   // member, set the visibility of this variable.
12856   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12857     AddPushedVisibilityAttribute(VD);
12858 
12859   // FIXME: Warn on unused var template partial specializations.
12860   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12861     MarkUnusedFileScopedDecl(VD);
12862 
12863   // Now we have parsed the initializer and can update the table of magic
12864   // tag values.
12865   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12866       !VD->getType()->isIntegralOrEnumerationType())
12867     return;
12868 
12869   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12870     const Expr *MagicValueExpr = VD->getInit();
12871     if (!MagicValueExpr) {
12872       continue;
12873     }
12874     llvm::APSInt MagicValueInt;
12875     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12876       Diag(I->getRange().getBegin(),
12877            diag::err_type_tag_for_datatype_not_ice)
12878         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12879       continue;
12880     }
12881     if (MagicValueInt.getActiveBits() > 64) {
12882       Diag(I->getRange().getBegin(),
12883            diag::err_type_tag_for_datatype_too_large)
12884         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12885       continue;
12886     }
12887     uint64_t MagicValue = MagicValueInt.getZExtValue();
12888     RegisterTypeTagForDatatype(I->getArgumentKind(),
12889                                MagicValue,
12890                                I->getMatchingCType(),
12891                                I->getLayoutCompatible(),
12892                                I->getMustBeNull());
12893   }
12894 }
12895 
12896 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12897   auto *VD = dyn_cast<VarDecl>(DD);
12898   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12899 }
12900 
12901 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12902                                                    ArrayRef<Decl *> Group) {
12903   SmallVector<Decl*, 8> Decls;
12904 
12905   if (DS.isTypeSpecOwned())
12906     Decls.push_back(DS.getRepAsDecl());
12907 
12908   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12909   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12910   bool DiagnosedMultipleDecomps = false;
12911   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12912   bool DiagnosedNonDeducedAuto = false;
12913 
12914   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12915     if (Decl *D = Group[i]) {
12916       // For declarators, there are some additional syntactic-ish checks we need
12917       // to perform.
12918       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12919         if (!FirstDeclaratorInGroup)
12920           FirstDeclaratorInGroup = DD;
12921         if (!FirstDecompDeclaratorInGroup)
12922           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12923         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12924             !hasDeducedAuto(DD))
12925           FirstNonDeducedAutoInGroup = DD;
12926 
12927         if (FirstDeclaratorInGroup != DD) {
12928           // A decomposition declaration cannot be combined with any other
12929           // declaration in the same group.
12930           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12931             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12932                  diag::err_decomp_decl_not_alone)
12933                 << FirstDeclaratorInGroup->getSourceRange()
12934                 << DD->getSourceRange();
12935             DiagnosedMultipleDecomps = true;
12936           }
12937 
12938           // A declarator that uses 'auto' in any way other than to declare a
12939           // variable with a deduced type cannot be combined with any other
12940           // declarator in the same group.
12941           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12942             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12943                  diag::err_auto_non_deduced_not_alone)
12944                 << FirstNonDeducedAutoInGroup->getType()
12945                        ->hasAutoForTrailingReturnType()
12946                 << FirstDeclaratorInGroup->getSourceRange()
12947                 << DD->getSourceRange();
12948             DiagnosedNonDeducedAuto = true;
12949           }
12950         }
12951       }
12952 
12953       Decls.push_back(D);
12954     }
12955   }
12956 
12957   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12958     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12959       handleTagNumbering(Tag, S);
12960       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12961           getLangOpts().CPlusPlus)
12962         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12963     }
12964   }
12965 
12966   return BuildDeclaratorGroup(Decls);
12967 }
12968 
12969 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12970 /// group, performing any necessary semantic checking.
12971 Sema::DeclGroupPtrTy
12972 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12973   // C++14 [dcl.spec.auto]p7: (DR1347)
12974   //   If the type that replaces the placeholder type is not the same in each
12975   //   deduction, the program is ill-formed.
12976   if (Group.size() > 1) {
12977     QualType Deduced;
12978     VarDecl *DeducedDecl = nullptr;
12979     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12980       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12981       if (!D || D->isInvalidDecl())
12982         break;
12983       DeducedType *DT = D->getType()->getContainedDeducedType();
12984       if (!DT || DT->getDeducedType().isNull())
12985         continue;
12986       if (Deduced.isNull()) {
12987         Deduced = DT->getDeducedType();
12988         DeducedDecl = D;
12989       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12990         auto *AT = dyn_cast<AutoType>(DT);
12991         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12992              diag::err_auto_different_deductions)
12993           << (AT ? (unsigned)AT->getKeyword() : 3)
12994           << Deduced << DeducedDecl->getDeclName()
12995           << DT->getDeducedType() << D->getDeclName()
12996           << DeducedDecl->getInit()->getSourceRange()
12997           << D->getInit()->getSourceRange();
12998         D->setInvalidDecl();
12999         break;
13000       }
13001     }
13002   }
13003 
13004   ActOnDocumentableDecls(Group);
13005 
13006   return DeclGroupPtrTy::make(
13007       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13008 }
13009 
13010 void Sema::ActOnDocumentableDecl(Decl *D) {
13011   ActOnDocumentableDecls(D);
13012 }
13013 
13014 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13015   // Don't parse the comment if Doxygen diagnostics are ignored.
13016   if (Group.empty() || !Group[0])
13017     return;
13018 
13019   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13020                       Group[0]->getLocation()) &&
13021       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13022                       Group[0]->getLocation()))
13023     return;
13024 
13025   if (Group.size() >= 2) {
13026     // This is a decl group.  Normally it will contain only declarations
13027     // produced from declarator list.  But in case we have any definitions or
13028     // additional declaration references:
13029     //   'typedef struct S {} S;'
13030     //   'typedef struct S *S;'
13031     //   'struct S *pS;'
13032     // FinalizeDeclaratorGroup adds these as separate declarations.
13033     Decl *MaybeTagDecl = Group[0];
13034     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13035       Group = Group.slice(1);
13036     }
13037   }
13038 
13039   // FIMXE: We assume every Decl in the group is in the same file.
13040   // This is false when preprocessor constructs the group from decls in
13041   // different files (e. g. macros or #include).
13042   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13043 }
13044 
13045 /// Common checks for a parameter-declaration that should apply to both function
13046 /// parameters and non-type template parameters.
13047 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13048   // Check that there are no default arguments inside the type of this
13049   // parameter.
13050   if (getLangOpts().CPlusPlus)
13051     CheckExtraCXXDefaultArguments(D);
13052 
13053   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13054   if (D.getCXXScopeSpec().isSet()) {
13055     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13056       << D.getCXXScopeSpec().getRange();
13057   }
13058 
13059   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13060   // simple identifier except [...irrelevant cases...].
13061   switch (D.getName().getKind()) {
13062   case UnqualifiedIdKind::IK_Identifier:
13063     break;
13064 
13065   case UnqualifiedIdKind::IK_OperatorFunctionId:
13066   case UnqualifiedIdKind::IK_ConversionFunctionId:
13067   case UnqualifiedIdKind::IK_LiteralOperatorId:
13068   case UnqualifiedIdKind::IK_ConstructorName:
13069   case UnqualifiedIdKind::IK_DestructorName:
13070   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13071   case UnqualifiedIdKind::IK_DeductionGuideName:
13072     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13073       << GetNameForDeclarator(D).getName();
13074     break;
13075 
13076   case UnqualifiedIdKind::IK_TemplateId:
13077   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13078     // GetNameForDeclarator would not produce a useful name in this case.
13079     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13080     break;
13081   }
13082 }
13083 
13084 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13085 /// to introduce parameters into function prototype scope.
13086 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13087   const DeclSpec &DS = D.getDeclSpec();
13088 
13089   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13090 
13091   // C++03 [dcl.stc]p2 also permits 'auto'.
13092   StorageClass SC = SC_None;
13093   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13094     SC = SC_Register;
13095     // In C++11, the 'register' storage class specifier is deprecated.
13096     // In C++17, it is not allowed, but we tolerate it as an extension.
13097     if (getLangOpts().CPlusPlus11) {
13098       Diag(DS.getStorageClassSpecLoc(),
13099            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13100                                      : diag::warn_deprecated_register)
13101         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13102     }
13103   } else if (getLangOpts().CPlusPlus &&
13104              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13105     SC = SC_Auto;
13106   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13107     Diag(DS.getStorageClassSpecLoc(),
13108          diag::err_invalid_storage_class_in_func_decl);
13109     D.getMutableDeclSpec().ClearStorageClassSpecs();
13110   }
13111 
13112   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13113     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13114       << DeclSpec::getSpecifierName(TSCS);
13115   if (DS.isInlineSpecified())
13116     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13117         << getLangOpts().CPlusPlus17;
13118   if (DS.hasConstexprSpecifier())
13119     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13120         << 0 << D.getDeclSpec().getConstexprSpecifier();
13121 
13122   DiagnoseFunctionSpecifiers(DS);
13123 
13124   CheckFunctionOrTemplateParamDeclarator(S, D);
13125 
13126   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13127   QualType parmDeclType = TInfo->getType();
13128 
13129   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13130   IdentifierInfo *II = D.getIdentifier();
13131   if (II) {
13132     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13133                    ForVisibleRedeclaration);
13134     LookupName(R, S);
13135     if (R.isSingleResult()) {
13136       NamedDecl *PrevDecl = R.getFoundDecl();
13137       if (PrevDecl->isTemplateParameter()) {
13138         // Maybe we will complain about the shadowed template parameter.
13139         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13140         // Just pretend that we didn't see the previous declaration.
13141         PrevDecl = nullptr;
13142       } else if (S->isDeclScope(PrevDecl)) {
13143         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13144         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13145 
13146         // Recover by removing the name
13147         II = nullptr;
13148         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13149         D.setInvalidType(true);
13150       }
13151     }
13152   }
13153 
13154   // Temporarily put parameter variables in the translation unit, not
13155   // the enclosing context.  This prevents them from accidentally
13156   // looking like class members in C++.
13157   ParmVarDecl *New =
13158       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13159                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13160 
13161   if (D.isInvalidType())
13162     New->setInvalidDecl();
13163 
13164   assert(S->isFunctionPrototypeScope());
13165   assert(S->getFunctionPrototypeDepth() >= 1);
13166   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13167                     S->getNextFunctionPrototypeIndex());
13168 
13169   // Add the parameter declaration into this scope.
13170   S->AddDecl(New);
13171   if (II)
13172     IdResolver.AddDecl(New);
13173 
13174   ProcessDeclAttributes(S, New, D);
13175 
13176   if (D.getDeclSpec().isModulePrivateSpecified())
13177     Diag(New->getLocation(), diag::err_module_private_local)
13178       << 1 << New->getDeclName()
13179       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13180       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13181 
13182   if (New->hasAttr<BlocksAttr>()) {
13183     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13184   }
13185 
13186   if (getLangOpts().OpenCL)
13187     deduceOpenCLAddressSpace(New);
13188 
13189   return New;
13190 }
13191 
13192 /// Synthesizes a variable for a parameter arising from a
13193 /// typedef.
13194 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13195                                               SourceLocation Loc,
13196                                               QualType T) {
13197   /* FIXME: setting StartLoc == Loc.
13198      Would it be worth to modify callers so as to provide proper source
13199      location for the unnamed parameters, embedding the parameter's type? */
13200   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13201                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13202                                            SC_None, nullptr);
13203   Param->setImplicit();
13204   return Param;
13205 }
13206 
13207 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13208   // Don't diagnose unused-parameter errors in template instantiations; we
13209   // will already have done so in the template itself.
13210   if (inTemplateInstantiation())
13211     return;
13212 
13213   for (const ParmVarDecl *Parameter : Parameters) {
13214     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13215         !Parameter->hasAttr<UnusedAttr>()) {
13216       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13217         << Parameter->getDeclName();
13218     }
13219   }
13220 }
13221 
13222 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13223     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13224   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13225     return;
13226 
13227   // Warn if the return value is pass-by-value and larger than the specified
13228   // threshold.
13229   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13230     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13231     if (Size > LangOpts.NumLargeByValueCopy)
13232       Diag(D->getLocation(), diag::warn_return_value_size)
13233           << D->getDeclName() << Size;
13234   }
13235 
13236   // Warn if any parameter is pass-by-value and larger than the specified
13237   // threshold.
13238   for (const ParmVarDecl *Parameter : Parameters) {
13239     QualType T = Parameter->getType();
13240     if (T->isDependentType() || !T.isPODType(Context))
13241       continue;
13242     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13243     if (Size > LangOpts.NumLargeByValueCopy)
13244       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13245           << Parameter->getDeclName() << Size;
13246   }
13247 }
13248 
13249 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13250                                   SourceLocation NameLoc, IdentifierInfo *Name,
13251                                   QualType T, TypeSourceInfo *TSInfo,
13252                                   StorageClass SC) {
13253   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13254   if (getLangOpts().ObjCAutoRefCount &&
13255       T.getObjCLifetime() == Qualifiers::OCL_None &&
13256       T->isObjCLifetimeType()) {
13257 
13258     Qualifiers::ObjCLifetime lifetime;
13259 
13260     // Special cases for arrays:
13261     //   - if it's const, use __unsafe_unretained
13262     //   - otherwise, it's an error
13263     if (T->isArrayType()) {
13264       if (!T.isConstQualified()) {
13265         if (DelayedDiagnostics.shouldDelayDiagnostics())
13266           DelayedDiagnostics.add(
13267               sema::DelayedDiagnostic::makeForbiddenType(
13268               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13269         else
13270           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13271               << TSInfo->getTypeLoc().getSourceRange();
13272       }
13273       lifetime = Qualifiers::OCL_ExplicitNone;
13274     } else {
13275       lifetime = T->getObjCARCImplicitLifetime();
13276     }
13277     T = Context.getLifetimeQualifiedType(T, lifetime);
13278   }
13279 
13280   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13281                                          Context.getAdjustedParameterType(T),
13282                                          TSInfo, SC, nullptr);
13283 
13284   // Make a note if we created a new pack in the scope of a lambda, so that
13285   // we know that references to that pack must also be expanded within the
13286   // lambda scope.
13287   if (New->isParameterPack())
13288     if (auto *LSI = getEnclosingLambda())
13289       LSI->LocalPacks.push_back(New);
13290 
13291   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13292       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13293     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13294                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13295 
13296   // Parameters can not be abstract class types.
13297   // For record types, this is done by the AbstractClassUsageDiagnoser once
13298   // the class has been completely parsed.
13299   if (!CurContext->isRecord() &&
13300       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13301                              AbstractParamType))
13302     New->setInvalidDecl();
13303 
13304   // Parameter declarators cannot be interface types. All ObjC objects are
13305   // passed by reference.
13306   if (T->isObjCObjectType()) {
13307     SourceLocation TypeEndLoc =
13308         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13309     Diag(NameLoc,
13310          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13311       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13312     T = Context.getObjCObjectPointerType(T);
13313     New->setType(T);
13314   }
13315 
13316   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13317   // duration shall not be qualified by an address-space qualifier."
13318   // Since all parameters have automatic store duration, they can not have
13319   // an address space.
13320   if (T.getAddressSpace() != LangAS::Default &&
13321       // OpenCL allows function arguments declared to be an array of a type
13322       // to be qualified with an address space.
13323       !(getLangOpts().OpenCL &&
13324         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13325     Diag(NameLoc, diag::err_arg_with_address_space);
13326     New->setInvalidDecl();
13327   }
13328 
13329   return New;
13330 }
13331 
13332 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13333                                            SourceLocation LocAfterDecls) {
13334   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13335 
13336   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13337   // for a K&R function.
13338   if (!FTI.hasPrototype) {
13339     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13340       --i;
13341       if (FTI.Params[i].Param == nullptr) {
13342         SmallString<256> Code;
13343         llvm::raw_svector_ostream(Code)
13344             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13345         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13346             << FTI.Params[i].Ident
13347             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13348 
13349         // Implicitly declare the argument as type 'int' for lack of a better
13350         // type.
13351         AttributeFactory attrs;
13352         DeclSpec DS(attrs);
13353         const char* PrevSpec; // unused
13354         unsigned DiagID; // unused
13355         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13356                            DiagID, Context.getPrintingPolicy());
13357         // Use the identifier location for the type source range.
13358         DS.SetRangeStart(FTI.Params[i].IdentLoc);
13359         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13360         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13361         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13362         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13363       }
13364     }
13365   }
13366 }
13367 
13368 Decl *
13369 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13370                               MultiTemplateParamsArg TemplateParameterLists,
13371                               SkipBodyInfo *SkipBody) {
13372   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
13373   assert(D.isFunctionDeclarator() && "Not a function declarator!");
13374   Scope *ParentScope = FnBodyScope->getParent();
13375 
13376   D.setFunctionDefinitionKind(FDK_Definition);
13377   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13378   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13379 }
13380 
13381 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13382   Consumer.HandleInlineFunctionDefinition(D);
13383 }
13384 
13385 static bool
13386 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13387                                 const FunctionDecl *&PossiblePrototype) {
13388   // Don't warn about invalid declarations.
13389   if (FD->isInvalidDecl())
13390     return false;
13391 
13392   // Or declarations that aren't global.
13393   if (!FD->isGlobal())
13394     return false;
13395 
13396   // Don't warn about C++ member functions.
13397   if (isa<CXXMethodDecl>(FD))
13398     return false;
13399 
13400   // Don't warn about 'main'.
13401   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13402     if (IdentifierInfo *II = FD->getIdentifier())
13403       if (II->isStr("main"))
13404         return false;
13405 
13406   // Don't warn about inline functions.
13407   if (FD->isInlined())
13408     return false;
13409 
13410   // Don't warn about function templates.
13411   if (FD->getDescribedFunctionTemplate())
13412     return false;
13413 
13414   // Don't warn about function template specializations.
13415   if (FD->isFunctionTemplateSpecialization())
13416     return false;
13417 
13418   // Don't warn for OpenCL kernels.
13419   if (FD->hasAttr<OpenCLKernelAttr>())
13420     return false;
13421 
13422   // Don't warn on explicitly deleted functions.
13423   if (FD->isDeleted())
13424     return false;
13425 
13426   for (const FunctionDecl *Prev = FD->getPreviousDecl();
13427        Prev; Prev = Prev->getPreviousDecl()) {
13428     // Ignore any declarations that occur in function or method
13429     // scope, because they aren't visible from the header.
13430     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13431       continue;
13432 
13433     PossiblePrototype = Prev;
13434     return Prev->getType()->isFunctionNoProtoType();
13435   }
13436 
13437   return true;
13438 }
13439 
13440 void
13441 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13442                                    const FunctionDecl *EffectiveDefinition,
13443                                    SkipBodyInfo *SkipBody) {
13444   const FunctionDecl *Definition = EffectiveDefinition;
13445   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13446     // If this is a friend function defined in a class template, it does not
13447     // have a body until it is used, nevertheless it is a definition, see
13448     // [temp.inst]p2:
13449     //
13450     // ... for the purpose of determining whether an instantiated redeclaration
13451     // is valid according to [basic.def.odr] and [class.mem], a declaration that
13452     // corresponds to a definition in the template is considered to be a
13453     // definition.
13454     //
13455     // The following code must produce redefinition error:
13456     //
13457     //     template<typename T> struct C20 { friend void func_20() {} };
13458     //     C20<int> c20i;
13459     //     void func_20() {}
13460     //
13461     for (auto I : FD->redecls()) {
13462       if (I != FD && !I->isInvalidDecl() &&
13463           I->getFriendObjectKind() != Decl::FOK_None) {
13464         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13465           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13466             // A merged copy of the same function, instantiated as a member of
13467             // the same class, is OK.
13468             if (declaresSameEntity(OrigFD, Original) &&
13469                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13470                                    cast<Decl>(FD->getLexicalDeclContext())))
13471               continue;
13472           }
13473 
13474           if (Original->isThisDeclarationADefinition()) {
13475             Definition = I;
13476             break;
13477           }
13478         }
13479       }
13480     }
13481   }
13482 
13483   if (!Definition)
13484     // Similar to friend functions a friend function template may be a
13485     // definition and do not have a body if it is instantiated in a class
13486     // template.
13487     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13488       for (auto I : FTD->redecls()) {
13489         auto D = cast<FunctionTemplateDecl>(I);
13490         if (D != FTD) {
13491           assert(!D->isThisDeclarationADefinition() &&
13492                  "More than one definition in redeclaration chain");
13493           if (D->getFriendObjectKind() != Decl::FOK_None)
13494             if (FunctionTemplateDecl *FT =
13495                                        D->getInstantiatedFromMemberTemplate()) {
13496               if (FT->isThisDeclarationADefinition()) {
13497                 Definition = D->getTemplatedDecl();
13498                 break;
13499               }
13500             }
13501         }
13502       }
13503     }
13504 
13505   if (!Definition)
13506     return;
13507 
13508   if (canRedefineFunction(Definition, getLangOpts()))
13509     return;
13510 
13511   // Don't emit an error when this is redefinition of a typo-corrected
13512   // definition.
13513   if (TypoCorrectedFunctionDefinitions.count(Definition))
13514     return;
13515 
13516   // If we don't have a visible definition of the function, and it's inline or
13517   // a template, skip the new definition.
13518   if (SkipBody && !hasVisibleDefinition(Definition) &&
13519       (Definition->getFormalLinkage() == InternalLinkage ||
13520        Definition->isInlined() ||
13521        Definition->getDescribedFunctionTemplate() ||
13522        Definition->getNumTemplateParameterLists())) {
13523     SkipBody->ShouldSkip = true;
13524     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13525     if (auto *TD = Definition->getDescribedFunctionTemplate())
13526       makeMergedDefinitionVisible(TD);
13527     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13528     return;
13529   }
13530 
13531   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13532       Definition->getStorageClass() == SC_Extern)
13533     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13534         << FD->getDeclName() << getLangOpts().CPlusPlus;
13535   else
13536     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
13537 
13538   Diag(Definition->getLocation(), diag::note_previous_definition);
13539   FD->setInvalidDecl();
13540 }
13541 
13542 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13543                                    Sema &S) {
13544   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13545 
13546   LambdaScopeInfo *LSI = S.PushLambdaScope();
13547   LSI->CallOperator = CallOperator;
13548   LSI->Lambda = LambdaClass;
13549   LSI->ReturnType = CallOperator->getReturnType();
13550   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13551 
13552   if (LCD == LCD_None)
13553     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13554   else if (LCD == LCD_ByCopy)
13555     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13556   else if (LCD == LCD_ByRef)
13557     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13558   DeclarationNameInfo DNI = CallOperator->getNameInfo();
13559 
13560   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13561   LSI->Mutable = !CallOperator->isConst();
13562 
13563   // Add the captures to the LSI so they can be noted as already
13564   // captured within tryCaptureVar.
13565   auto I = LambdaClass->field_begin();
13566   for (const auto &C : LambdaClass->captures()) {
13567     if (C.capturesVariable()) {
13568       VarDecl *VD = C.getCapturedVar();
13569       if (VD->isInitCapture())
13570         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13571       QualType CaptureType = VD->getType();
13572       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13573       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13574           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13575           /*EllipsisLoc*/C.isPackExpansion()
13576                          ? C.getEllipsisLoc() : SourceLocation(),
13577           CaptureType, /*Invalid*/false);
13578 
13579     } else if (C.capturesThis()) {
13580       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13581                           C.getCaptureKind() == LCK_StarThis);
13582     } else {
13583       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13584                              I->getType());
13585     }
13586     ++I;
13587   }
13588 }
13589 
13590 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13591                                     SkipBodyInfo *SkipBody) {
13592   if (!D) {
13593     // Parsing the function declaration failed in some way. Push on a fake scope
13594     // anyway so we can try to parse the function body.
13595     PushFunctionScope();
13596     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13597     return D;
13598   }
13599 
13600   FunctionDecl *FD = nullptr;
13601 
13602   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13603     FD = FunTmpl->getTemplatedDecl();
13604   else
13605     FD = cast<FunctionDecl>(D);
13606 
13607   // Do not push if it is a lambda because one is already pushed when building
13608   // the lambda in ActOnStartOfLambdaDefinition().
13609   if (!isLambdaCallOperator(FD))
13610     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13611 
13612   // Check for defining attributes before the check for redefinition.
13613   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13614     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13615     FD->dropAttr<AliasAttr>();
13616     FD->setInvalidDecl();
13617   }
13618   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13619     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13620     FD->dropAttr<IFuncAttr>();
13621     FD->setInvalidDecl();
13622   }
13623 
13624   // See if this is a redefinition. If 'will have body' is already set, then
13625   // these checks were already performed when it was set.
13626   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13627     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13628 
13629     // If we're skipping the body, we're done. Don't enter the scope.
13630     if (SkipBody && SkipBody->ShouldSkip)
13631       return D;
13632   }
13633 
13634   // Mark this function as "will have a body eventually".  This lets users to
13635   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13636   // this function.
13637   FD->setWillHaveBody();
13638 
13639   // If we are instantiating a generic lambda call operator, push
13640   // a LambdaScopeInfo onto the function stack.  But use the information
13641   // that's already been calculated (ActOnLambdaExpr) to prime the current
13642   // LambdaScopeInfo.
13643   // When the template operator is being specialized, the LambdaScopeInfo,
13644   // has to be properly restored so that tryCaptureVariable doesn't try
13645   // and capture any new variables. In addition when calculating potential
13646   // captures during transformation of nested lambdas, it is necessary to
13647   // have the LSI properly restored.
13648   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13649     assert(inTemplateInstantiation() &&
13650            "There should be an active template instantiation on the stack "
13651            "when instantiating a generic lambda!");
13652     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13653   } else {
13654     // Enter a new function scope
13655     PushFunctionScope();
13656   }
13657 
13658   // Builtin functions cannot be defined.
13659   if (unsigned BuiltinID = FD->getBuiltinID()) {
13660     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13661         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13662       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13663       FD->setInvalidDecl();
13664     }
13665   }
13666 
13667   // The return type of a function definition must be complete
13668   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13669   QualType ResultType = FD->getReturnType();
13670   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13671       !FD->isInvalidDecl() &&
13672       RequireCompleteType(FD->getLocation(), ResultType,
13673                           diag::err_func_def_incomplete_result))
13674     FD->setInvalidDecl();
13675 
13676   if (FnBodyScope)
13677     PushDeclContext(FnBodyScope, FD);
13678 
13679   // Check the validity of our function parameters
13680   CheckParmsForFunctionDef(FD->parameters(),
13681                            /*CheckParameterNames=*/true);
13682 
13683   // Add non-parameter declarations already in the function to the current
13684   // scope.
13685   if (FnBodyScope) {
13686     for (Decl *NPD : FD->decls()) {
13687       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13688       if (!NonParmDecl)
13689         continue;
13690       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13691              "parameters should not be in newly created FD yet");
13692 
13693       // If the decl has a name, make it accessible in the current scope.
13694       if (NonParmDecl->getDeclName())
13695         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13696 
13697       // Similarly, dive into enums and fish their constants out, making them
13698       // accessible in this scope.
13699       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13700         for (auto *EI : ED->enumerators())
13701           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13702       }
13703     }
13704   }
13705 
13706   // Introduce our parameters into the function scope
13707   for (auto Param : FD->parameters()) {
13708     Param->setOwningFunction(FD);
13709 
13710     // If this has an identifier, add it to the scope stack.
13711     if (Param->getIdentifier() && FnBodyScope) {
13712       CheckShadow(FnBodyScope, Param);
13713 
13714       PushOnScopeChains(Param, FnBodyScope);
13715     }
13716   }
13717 
13718   // Ensure that the function's exception specification is instantiated.
13719   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13720     ResolveExceptionSpec(D->getLocation(), FPT);
13721 
13722   // dllimport cannot be applied to non-inline function definitions.
13723   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13724       !FD->isTemplateInstantiation()) {
13725     assert(!FD->hasAttr<DLLExportAttr>());
13726     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13727     FD->setInvalidDecl();
13728     return D;
13729   }
13730   // We want to attach documentation to original Decl (which might be
13731   // a function template).
13732   ActOnDocumentableDecl(D);
13733   if (getCurLexicalContext()->isObjCContainer() &&
13734       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13735       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13736     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13737 
13738   return D;
13739 }
13740 
13741 /// Given the set of return statements within a function body,
13742 /// compute the variables that are subject to the named return value
13743 /// optimization.
13744 ///
13745 /// Each of the variables that is subject to the named return value
13746 /// optimization will be marked as NRVO variables in the AST, and any
13747 /// return statement that has a marked NRVO variable as its NRVO candidate can
13748 /// use the named return value optimization.
13749 ///
13750 /// This function applies a very simplistic algorithm for NRVO: if every return
13751 /// statement in the scope of a variable has the same NRVO candidate, that
13752 /// candidate is an NRVO variable.
13753 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13754   ReturnStmt **Returns = Scope->Returns.data();
13755 
13756   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13757     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13758       if (!NRVOCandidate->isNRVOVariable())
13759         Returns[I]->setNRVOCandidate(nullptr);
13760     }
13761   }
13762 }
13763 
13764 bool Sema::canDelayFunctionBody(const Declarator &D) {
13765   // We can't delay parsing the body of a constexpr function template (yet).
13766   if (D.getDeclSpec().hasConstexprSpecifier())
13767     return false;
13768 
13769   // We can't delay parsing the body of a function template with a deduced
13770   // return type (yet).
13771   if (D.getDeclSpec().hasAutoTypeSpec()) {
13772     // If the placeholder introduces a non-deduced trailing return type,
13773     // we can still delay parsing it.
13774     if (D.getNumTypeObjects()) {
13775       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13776       if (Outer.Kind == DeclaratorChunk::Function &&
13777           Outer.Fun.hasTrailingReturnType()) {
13778         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13779         return Ty.isNull() || !Ty->isUndeducedType();
13780       }
13781     }
13782     return false;
13783   }
13784 
13785   return true;
13786 }
13787 
13788 bool Sema::canSkipFunctionBody(Decl *D) {
13789   // We cannot skip the body of a function (or function template) which is
13790   // constexpr, since we may need to evaluate its body in order to parse the
13791   // rest of the file.
13792   // We cannot skip the body of a function with an undeduced return type,
13793   // because any callers of that function need to know the type.
13794   if (const FunctionDecl *FD = D->getAsFunction()) {
13795     if (FD->isConstexpr())
13796       return false;
13797     // We can't simply call Type::isUndeducedType here, because inside template
13798     // auto can be deduced to a dependent type, which is not considered
13799     // "undeduced".
13800     if (FD->getReturnType()->getContainedDeducedType())
13801       return false;
13802   }
13803   return Consumer.shouldSkipFunctionBody(D);
13804 }
13805 
13806 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13807   if (!Decl)
13808     return nullptr;
13809   if (FunctionDecl *FD = Decl->getAsFunction())
13810     FD->setHasSkippedBody();
13811   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13812     MD->setHasSkippedBody();
13813   return Decl;
13814 }
13815 
13816 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13817   return ActOnFinishFunctionBody(D, BodyArg, false);
13818 }
13819 
13820 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13821 /// body.
13822 class ExitFunctionBodyRAII {
13823 public:
13824   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13825   ~ExitFunctionBodyRAII() {
13826     if (!IsLambda)
13827       S.PopExpressionEvaluationContext();
13828   }
13829 
13830 private:
13831   Sema &S;
13832   bool IsLambda = false;
13833 };
13834 
13835 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13836   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13837 
13838   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13839     if (EscapeInfo.count(BD))
13840       return EscapeInfo[BD];
13841 
13842     bool R = false;
13843     const BlockDecl *CurBD = BD;
13844 
13845     do {
13846       R = !CurBD->doesNotEscape();
13847       if (R)
13848         break;
13849       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13850     } while (CurBD);
13851 
13852     return EscapeInfo[BD] = R;
13853   };
13854 
13855   // If the location where 'self' is implicitly retained is inside a escaping
13856   // block, emit a diagnostic.
13857   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13858        S.ImplicitlyRetainedSelfLocs)
13859     if (IsOrNestedInEscapingBlock(P.second))
13860       S.Diag(P.first, diag::warn_implicitly_retains_self)
13861           << FixItHint::CreateInsertion(P.first, "self->");
13862 }
13863 
13864 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13865                                     bool IsInstantiation) {
13866   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13867 
13868   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13869   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13870 
13871   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13872     CheckCompletedCoroutineBody(FD, Body);
13873 
13874   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13875   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13876   // meant to pop the context added in ActOnStartOfFunctionDef().
13877   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13878 
13879   if (FD) {
13880     FD->setBody(Body);
13881     FD->setWillHaveBody(false);
13882 
13883     if (getLangOpts().CPlusPlus14) {
13884       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13885           FD->getReturnType()->isUndeducedType()) {
13886         // If the function has a deduced result type but contains no 'return'
13887         // statements, the result type as written must be exactly 'auto', and
13888         // the deduced result type is 'void'.
13889         if (!FD->getReturnType()->getAs<AutoType>()) {
13890           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13891               << FD->getReturnType();
13892           FD->setInvalidDecl();
13893         } else {
13894           // Substitute 'void' for the 'auto' in the type.
13895           TypeLoc ResultType = getReturnTypeLoc(FD);
13896           Context.adjustDeducedFunctionResultType(
13897               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13898         }
13899       }
13900     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13901       // In C++11, we don't use 'auto' deduction rules for lambda call
13902       // operators because we don't support return type deduction.
13903       auto *LSI = getCurLambda();
13904       if (LSI->HasImplicitReturnType) {
13905         deduceClosureReturnType(*LSI);
13906 
13907         // C++11 [expr.prim.lambda]p4:
13908         //   [...] if there are no return statements in the compound-statement
13909         //   [the deduced type is] the type void
13910         QualType RetType =
13911             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13912 
13913         // Update the return type to the deduced type.
13914         const FunctionProtoType *Proto =
13915             FD->getType()->getAs<FunctionProtoType>();
13916         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13917                                             Proto->getExtProtoInfo()));
13918       }
13919     }
13920 
13921     // If the function implicitly returns zero (like 'main') or is naked,
13922     // don't complain about missing return statements.
13923     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13924       WP.disableCheckFallThrough();
13925 
13926     // MSVC permits the use of pure specifier (=0) on function definition,
13927     // defined at class scope, warn about this non-standard construct.
13928     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13929       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13930 
13931     if (!FD->isInvalidDecl()) {
13932       // Don't diagnose unused parameters of defaulted or deleted functions.
13933       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13934         DiagnoseUnusedParameters(FD->parameters());
13935       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13936                                              FD->getReturnType(), FD);
13937 
13938       // If this is a structor, we need a vtable.
13939       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13940         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13941       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13942         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13943 
13944       // Try to apply the named return value optimization. We have to check
13945       // if we can do this here because lambdas keep return statements around
13946       // to deduce an implicit return type.
13947       if (FD->getReturnType()->isRecordType() &&
13948           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13949         computeNRVO(Body, getCurFunction());
13950     }
13951 
13952     // GNU warning -Wmissing-prototypes:
13953     //   Warn if a global function is defined without a previous
13954     //   prototype declaration. This warning is issued even if the
13955     //   definition itself provides a prototype. The aim is to detect
13956     //   global functions that fail to be declared in header files.
13957     const FunctionDecl *PossiblePrototype = nullptr;
13958     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13959       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13960 
13961       if (PossiblePrototype) {
13962         // We found a declaration that is not a prototype,
13963         // but that could be a zero-parameter prototype
13964         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13965           TypeLoc TL = TI->getTypeLoc();
13966           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13967             Diag(PossiblePrototype->getLocation(),
13968                  diag::note_declaration_not_a_prototype)
13969                 << (FD->getNumParams() != 0)
13970                 << (FD->getNumParams() == 0
13971                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13972                         : FixItHint{});
13973         }
13974       } else {
13975         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13976             << /* function */ 1
13977             << (FD->getStorageClass() == SC_None
13978                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13979                                                  "static ")
13980                     : FixItHint{});
13981       }
13982 
13983       // GNU warning -Wstrict-prototypes
13984       //   Warn if K&R function is defined without a previous declaration.
13985       //   This warning is issued only if the definition itself does not provide
13986       //   a prototype. Only K&R definitions do not provide a prototype.
13987       //   An empty list in a function declarator that is part of a definition
13988       //   of that function specifies that the function has no parameters
13989       //   (C99 6.7.5.3p14)
13990       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13991           !LangOpts.CPlusPlus) {
13992         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13993         TypeLoc TL = TI->getTypeLoc();
13994         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13995         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13996       }
13997     }
13998 
13999     // Warn on CPUDispatch with an actual body.
14000     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14001       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14002         if (!CmpndBody->body_empty())
14003           Diag(CmpndBody->body_front()->getBeginLoc(),
14004                diag::warn_dispatch_body_ignored);
14005 
14006     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14007       const CXXMethodDecl *KeyFunction;
14008       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14009           MD->isVirtual() &&
14010           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14011           MD == KeyFunction->getCanonicalDecl()) {
14012         // Update the key-function state if necessary for this ABI.
14013         if (FD->isInlined() &&
14014             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14015           Context.setNonKeyFunction(MD);
14016 
14017           // If the newly-chosen key function is already defined, then we
14018           // need to mark the vtable as used retroactively.
14019           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14020           const FunctionDecl *Definition;
14021           if (KeyFunction && KeyFunction->isDefined(Definition))
14022             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14023         } else {
14024           // We just defined they key function; mark the vtable as used.
14025           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14026         }
14027       }
14028     }
14029 
14030     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14031            "Function parsing confused");
14032   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14033     assert(MD == getCurMethodDecl() && "Method parsing confused");
14034     MD->setBody(Body);
14035     if (!MD->isInvalidDecl()) {
14036       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14037                                              MD->getReturnType(), MD);
14038 
14039       if (Body)
14040         computeNRVO(Body, getCurFunction());
14041     }
14042     if (getCurFunction()->ObjCShouldCallSuper) {
14043       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14044           << MD->getSelector().getAsString();
14045       getCurFunction()->ObjCShouldCallSuper = false;
14046     }
14047     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14048       const ObjCMethodDecl *InitMethod = nullptr;
14049       bool isDesignated =
14050           MD->isDesignatedInitializerForTheInterface(&InitMethod);
14051       assert(isDesignated && InitMethod);
14052       (void)isDesignated;
14053 
14054       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14055         auto IFace = MD->getClassInterface();
14056         if (!IFace)
14057           return false;
14058         auto SuperD = IFace->getSuperClass();
14059         if (!SuperD)
14060           return false;
14061         return SuperD->getIdentifier() ==
14062             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14063       };
14064       // Don't issue this warning for unavailable inits or direct subclasses
14065       // of NSObject.
14066       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14067         Diag(MD->getLocation(),
14068              diag::warn_objc_designated_init_missing_super_call);
14069         Diag(InitMethod->getLocation(),
14070              diag::note_objc_designated_init_marked_here);
14071       }
14072       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14073     }
14074     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14075       // Don't issue this warning for unavaialable inits.
14076       if (!MD->isUnavailable())
14077         Diag(MD->getLocation(),
14078              diag::warn_objc_secondary_init_missing_init_call);
14079       getCurFunction()->ObjCWarnForNoInitDelegation = false;
14080     }
14081 
14082     diagnoseImplicitlyRetainedSelf(*this);
14083   } else {
14084     // Parsing the function declaration failed in some way. Pop the fake scope
14085     // we pushed on.
14086     PopFunctionScopeInfo(ActivePolicy, dcl);
14087     return nullptr;
14088   }
14089 
14090   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14091     DiagnoseUnguardedAvailabilityViolations(dcl);
14092 
14093   assert(!getCurFunction()->ObjCShouldCallSuper &&
14094          "This should only be set for ObjC methods, which should have been "
14095          "handled in the block above.");
14096 
14097   // Verify and clean out per-function state.
14098   if (Body && (!FD || !FD->isDefaulted())) {
14099     // C++ constructors that have function-try-blocks can't have return
14100     // statements in the handlers of that block. (C++ [except.handle]p14)
14101     // Verify this.
14102     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14103       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14104 
14105     // Verify that gotos and switch cases don't jump into scopes illegally.
14106     if (getCurFunction()->NeedsScopeChecking() &&
14107         !PP.isCodeCompletionEnabled())
14108       DiagnoseInvalidJumps(Body);
14109 
14110     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14111       if (!Destructor->getParent()->isDependentType())
14112         CheckDestructor(Destructor);
14113 
14114       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14115                                              Destructor->getParent());
14116     }
14117 
14118     // If any errors have occurred, clear out any temporaries that may have
14119     // been leftover. This ensures that these temporaries won't be picked up for
14120     // deletion in some later function.
14121     if (getDiagnostics().hasErrorOccurred() ||
14122         getDiagnostics().getSuppressAllDiagnostics()) {
14123       DiscardCleanupsInEvaluationContext();
14124     }
14125     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14126         !isa<FunctionTemplateDecl>(dcl)) {
14127       // Since the body is valid, issue any analysis-based warnings that are
14128       // enabled.
14129       ActivePolicy = &WP;
14130     }
14131 
14132     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14133         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14134       FD->setInvalidDecl();
14135 
14136     if (FD && FD->hasAttr<NakedAttr>()) {
14137       for (const Stmt *S : Body->children()) {
14138         // Allow local register variables without initializer as they don't
14139         // require prologue.
14140         bool RegisterVariables = false;
14141         if (auto *DS = dyn_cast<DeclStmt>(S)) {
14142           for (const auto *Decl : DS->decls()) {
14143             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14144               RegisterVariables =
14145                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14146               if (!RegisterVariables)
14147                 break;
14148             }
14149           }
14150         }
14151         if (RegisterVariables)
14152           continue;
14153         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14154           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14155           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14156           FD->setInvalidDecl();
14157           break;
14158         }
14159       }
14160     }
14161 
14162     assert(ExprCleanupObjects.size() ==
14163                ExprEvalContexts.back().NumCleanupObjects &&
14164            "Leftover temporaries in function");
14165     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
14166     assert(MaybeODRUseExprs.empty() &&
14167            "Leftover expressions for odr-use checking");
14168   }
14169 
14170   if (!IsInstantiation)
14171     PopDeclContext();
14172 
14173   PopFunctionScopeInfo(ActivePolicy, dcl);
14174   // If any errors have occurred, clear out any temporaries that may have
14175   // been leftover. This ensures that these temporaries won't be picked up for
14176   // deletion in some later function.
14177   if (getDiagnostics().hasErrorOccurred()) {
14178     DiscardCleanupsInEvaluationContext();
14179   }
14180 
14181   return dcl;
14182 }
14183 
14184 /// When we finish delayed parsing of an attribute, we must attach it to the
14185 /// relevant Decl.
14186 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14187                                        ParsedAttributes &Attrs) {
14188   // Always attach attributes to the underlying decl.
14189   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14190     D = TD->getTemplatedDecl();
14191   ProcessDeclAttributeList(S, D, Attrs);
14192 
14193   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14194     if (Method->isStatic())
14195       checkThisInStaticMemberFunctionAttributes(Method);
14196 }
14197 
14198 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14199 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14200 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14201                                           IdentifierInfo &II, Scope *S) {
14202   // Find the scope in which the identifier is injected and the corresponding
14203   // DeclContext.
14204   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14205   // In that case, we inject the declaration into the translation unit scope
14206   // instead.
14207   Scope *BlockScope = S;
14208   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14209     BlockScope = BlockScope->getParent();
14210 
14211   Scope *ContextScope = BlockScope;
14212   while (!ContextScope->getEntity())
14213     ContextScope = ContextScope->getParent();
14214   ContextRAII SavedContext(*this, ContextScope->getEntity());
14215 
14216   // Before we produce a declaration for an implicitly defined
14217   // function, see whether there was a locally-scoped declaration of
14218   // this name as a function or variable. If so, use that
14219   // (non-visible) declaration, and complain about it.
14220   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14221   if (ExternCPrev) {
14222     // We still need to inject the function into the enclosing block scope so
14223     // that later (non-call) uses can see it.
14224     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14225 
14226     // C89 footnote 38:
14227     //   If in fact it is not defined as having type "function returning int",
14228     //   the behavior is undefined.
14229     if (!isa<FunctionDecl>(ExternCPrev) ||
14230         !Context.typesAreCompatible(
14231             cast<FunctionDecl>(ExternCPrev)->getType(),
14232             Context.getFunctionNoProtoType(Context.IntTy))) {
14233       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14234           << ExternCPrev << !getLangOpts().C99;
14235       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14236       return ExternCPrev;
14237     }
14238   }
14239 
14240   // Extension in C99.  Legal in C90, but warn about it.
14241   unsigned diag_id;
14242   if (II.getName().startswith("__builtin_"))
14243     diag_id = diag::warn_builtin_unknown;
14244   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14245   else if (getLangOpts().OpenCL)
14246     diag_id = diag::err_opencl_implicit_function_decl;
14247   else if (getLangOpts().C99)
14248     diag_id = diag::ext_implicit_function_decl;
14249   else
14250     diag_id = diag::warn_implicit_function_decl;
14251   Diag(Loc, diag_id) << &II;
14252 
14253   // If we found a prior declaration of this function, don't bother building
14254   // another one. We've already pushed that one into scope, so there's nothing
14255   // more to do.
14256   if (ExternCPrev)
14257     return ExternCPrev;
14258 
14259   // Because typo correction is expensive, only do it if the implicit
14260   // function declaration is going to be treated as an error.
14261   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14262     TypoCorrection Corrected;
14263     DeclFilterCCC<FunctionDecl> CCC{};
14264     if (S && (Corrected =
14265                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14266                               S, nullptr, CCC, CTK_NonError)))
14267       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14268                    /*ErrorRecovery*/false);
14269   }
14270 
14271   // Set a Declarator for the implicit definition: int foo();
14272   const char *Dummy;
14273   AttributeFactory attrFactory;
14274   DeclSpec DS(attrFactory);
14275   unsigned DiagID;
14276   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14277                                   Context.getPrintingPolicy());
14278   (void)Error; // Silence warning.
14279   assert(!Error && "Error setting up implicit decl!");
14280   SourceLocation NoLoc;
14281   Declarator D(DS, DeclaratorContext::BlockContext);
14282   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14283                                              /*IsAmbiguous=*/false,
14284                                              /*LParenLoc=*/NoLoc,
14285                                              /*Params=*/nullptr,
14286                                              /*NumParams=*/0,
14287                                              /*EllipsisLoc=*/NoLoc,
14288                                              /*RParenLoc=*/NoLoc,
14289                                              /*RefQualifierIsLvalueRef=*/true,
14290                                              /*RefQualifierLoc=*/NoLoc,
14291                                              /*MutableLoc=*/NoLoc, EST_None,
14292                                              /*ESpecRange=*/SourceRange(),
14293                                              /*Exceptions=*/nullptr,
14294                                              /*ExceptionRanges=*/nullptr,
14295                                              /*NumExceptions=*/0,
14296                                              /*NoexceptExpr=*/nullptr,
14297                                              /*ExceptionSpecTokens=*/nullptr,
14298                                              /*DeclsInPrototype=*/None, Loc,
14299                                              Loc, D),
14300                 std::move(DS.getAttributes()), SourceLocation());
14301   D.SetIdentifier(&II, Loc);
14302 
14303   // Insert this function into the enclosing block scope.
14304   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14305   FD->setImplicit();
14306 
14307   AddKnownFunctionAttributes(FD);
14308 
14309   return FD;
14310 }
14311 
14312 /// Adds any function attributes that we know a priori based on
14313 /// the declaration of this function.
14314 ///
14315 /// These attributes can apply both to implicitly-declared builtins
14316 /// (like __builtin___printf_chk) or to library-declared functions
14317 /// like NSLog or printf.
14318 ///
14319 /// We need to check for duplicate attributes both here and where user-written
14320 /// attributes are applied to declarations.
14321 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14322   if (FD->isInvalidDecl())
14323     return;
14324 
14325   // If this is a built-in function, map its builtin attributes to
14326   // actual attributes.
14327   if (unsigned BuiltinID = FD->getBuiltinID()) {
14328     // Handle printf-formatting attributes.
14329     unsigned FormatIdx;
14330     bool HasVAListArg;
14331     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14332       if (!FD->hasAttr<FormatAttr>()) {
14333         const char *fmt = "printf";
14334         unsigned int NumParams = FD->getNumParams();
14335         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14336             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14337           fmt = "NSString";
14338         FD->addAttr(FormatAttr::CreateImplicit(Context,
14339                                                &Context.Idents.get(fmt),
14340                                                FormatIdx+1,
14341                                                HasVAListArg ? 0 : FormatIdx+2,
14342                                                FD->getLocation()));
14343       }
14344     }
14345     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14346                                              HasVAListArg)) {
14347      if (!FD->hasAttr<FormatAttr>())
14348        FD->addAttr(FormatAttr::CreateImplicit(Context,
14349                                               &Context.Idents.get("scanf"),
14350                                               FormatIdx+1,
14351                                               HasVAListArg ? 0 : FormatIdx+2,
14352                                               FD->getLocation()));
14353     }
14354 
14355     // Handle automatically recognized callbacks.
14356     SmallVector<int, 4> Encoding;
14357     if (!FD->hasAttr<CallbackAttr>() &&
14358         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14359       FD->addAttr(CallbackAttr::CreateImplicit(
14360           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14361 
14362     // Mark const if we don't care about errno and that is the only thing
14363     // preventing the function from being const. This allows IRgen to use LLVM
14364     // intrinsics for such functions.
14365     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14366         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14367       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14368 
14369     // We make "fma" on some platforms const because we know it does not set
14370     // errno in those environments even though it could set errno based on the
14371     // C standard.
14372     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14373     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14374         !FD->hasAttr<ConstAttr>()) {
14375       switch (BuiltinID) {
14376       case Builtin::BI__builtin_fma:
14377       case Builtin::BI__builtin_fmaf:
14378       case Builtin::BI__builtin_fmal:
14379       case Builtin::BIfma:
14380       case Builtin::BIfmaf:
14381       case Builtin::BIfmal:
14382         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14383         break;
14384       default:
14385         break;
14386       }
14387     }
14388 
14389     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14390         !FD->hasAttr<ReturnsTwiceAttr>())
14391       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14392                                          FD->getLocation()));
14393     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14394       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14395     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14396       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14397     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14398       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14399     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14400         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14401       // Add the appropriate attribute, depending on the CUDA compilation mode
14402       // and which target the builtin belongs to. For example, during host
14403       // compilation, aux builtins are __device__, while the rest are __host__.
14404       if (getLangOpts().CUDAIsDevice !=
14405           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14406         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14407       else
14408         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14409     }
14410   }
14411 
14412   // If C++ exceptions are enabled but we are told extern "C" functions cannot
14413   // throw, add an implicit nothrow attribute to any extern "C" function we come
14414   // across.
14415   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14416       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14417     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14418     if (!FPT || FPT->getExceptionSpecType() == EST_None)
14419       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14420   }
14421 
14422   IdentifierInfo *Name = FD->getIdentifier();
14423   if (!Name)
14424     return;
14425   if ((!getLangOpts().CPlusPlus &&
14426        FD->getDeclContext()->isTranslationUnit()) ||
14427       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14428        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14429        LinkageSpecDecl::lang_c)) {
14430     // Okay: this could be a libc/libm/Objective-C function we know
14431     // about.
14432   } else
14433     return;
14434 
14435   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14436     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14437     // target-specific builtins, perhaps?
14438     if (!FD->hasAttr<FormatAttr>())
14439       FD->addAttr(FormatAttr::CreateImplicit(Context,
14440                                              &Context.Idents.get("printf"), 2,
14441                                              Name->isStr("vasprintf") ? 0 : 3,
14442                                              FD->getLocation()));
14443   }
14444 
14445   if (Name->isStr("__CFStringMakeConstantString")) {
14446     // We already have a __builtin___CFStringMakeConstantString,
14447     // but builds that use -fno-constant-cfstrings don't go through that.
14448     if (!FD->hasAttr<FormatArgAttr>())
14449       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14450                                                 FD->getLocation()));
14451   }
14452 }
14453 
14454 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14455                                     TypeSourceInfo *TInfo) {
14456   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
14457   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
14458 
14459   if (!TInfo) {
14460     assert(D.isInvalidType() && "no declarator info for valid type");
14461     TInfo = Context.getTrivialTypeSourceInfo(T);
14462   }
14463 
14464   // Scope manipulation handled by caller.
14465   TypedefDecl *NewTD =
14466       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14467                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14468 
14469   // Bail out immediately if we have an invalid declaration.
14470   if (D.isInvalidType()) {
14471     NewTD->setInvalidDecl();
14472     return NewTD;
14473   }
14474 
14475   if (D.getDeclSpec().isModulePrivateSpecified()) {
14476     if (CurContext->isFunctionOrMethod())
14477       Diag(NewTD->getLocation(), diag::err_module_private_local)
14478         << 2 << NewTD->getDeclName()
14479         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14480         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14481     else
14482       NewTD->setModulePrivate();
14483   }
14484 
14485   // C++ [dcl.typedef]p8:
14486   //   If the typedef declaration defines an unnamed class (or
14487   //   enum), the first typedef-name declared by the declaration
14488   //   to be that class type (or enum type) is used to denote the
14489   //   class type (or enum type) for linkage purposes only.
14490   // We need to check whether the type was declared in the declaration.
14491   switch (D.getDeclSpec().getTypeSpecType()) {
14492   case TST_enum:
14493   case TST_struct:
14494   case TST_interface:
14495   case TST_union:
14496   case TST_class: {
14497     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14498     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14499     break;
14500   }
14501 
14502   default:
14503     break;
14504   }
14505 
14506   return NewTD;
14507 }
14508 
14509 /// Check that this is a valid underlying type for an enum declaration.
14510 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
14511   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
14512   QualType T = TI->getType();
14513 
14514   if (T->isDependentType())
14515     return false;
14516 
14517   if (const BuiltinType *BT = T->getAs<BuiltinType>())
14518     if (BT->isInteger())
14519       return false;
14520 
14521   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
14522   return true;
14523 }
14524 
14525 /// Check whether this is a valid redeclaration of a previous enumeration.
14526 /// \return true if the redeclaration was invalid.
14527 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
14528                                   QualType EnumUnderlyingTy, bool IsFixed,
14529                                   const EnumDecl *Prev) {
14530   if (IsScoped != Prev->isScoped()) {
14531     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
14532       << Prev->isScoped();
14533     Diag(Prev->getLocation(), diag::note_previous_declaration);
14534     return true;
14535   }
14536 
14537   if (IsFixed && Prev->isFixed()) {
14538     if (!EnumUnderlyingTy->isDependentType() &&
14539         !Prev->getIntegerType()->isDependentType() &&
14540         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
14541                                         Prev->getIntegerType())) {
14542       // TODO: Highlight the underlying type of the redeclaration.
14543       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
14544         << EnumUnderlyingTy << Prev->getIntegerType();
14545       Diag(Prev->getLocation(), diag::note_previous_declaration)
14546           << Prev->getIntegerTypeRange();
14547       return true;
14548     }
14549   } else if (IsFixed != Prev->isFixed()) {
14550     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
14551       << Prev->isFixed();
14552     Diag(Prev->getLocation(), diag::note_previous_declaration);
14553     return true;
14554   }
14555 
14556   return false;
14557 }
14558 
14559 /// Get diagnostic %select index for tag kind for
14560 /// redeclaration diagnostic message.
14561 /// WARNING: Indexes apply to particular diagnostics only!
14562 ///
14563 /// \returns diagnostic %select index.
14564 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
14565   switch (Tag) {
14566   case TTK_Struct: return 0;
14567   case TTK_Interface: return 1;
14568   case TTK_Class:  return 2;
14569   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
14570   }
14571 }
14572 
14573 /// Determine if tag kind is a class-key compatible with
14574 /// class for redeclaration (class, struct, or __interface).
14575 ///
14576 /// \returns true iff the tag kind is compatible.
14577 static bool isClassCompatTagKind(TagTypeKind Tag)
14578 {
14579   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
14580 }
14581 
14582 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14583                                              TagTypeKind TTK) {
14584   if (isa<TypedefDecl>(PrevDecl))
14585     return NTK_Typedef;
14586   else if (isa<TypeAliasDecl>(PrevDecl))
14587     return NTK_TypeAlias;
14588   else if (isa<ClassTemplateDecl>(PrevDecl))
14589     return NTK_Template;
14590   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14591     return NTK_TypeAliasTemplate;
14592   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14593     return NTK_TemplateTemplateArgument;
14594   switch (TTK) {
14595   case TTK_Struct:
14596   case TTK_Interface:
14597   case TTK_Class:
14598     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14599   case TTK_Union:
14600     return NTK_NonUnion;
14601   case TTK_Enum:
14602     return NTK_NonEnum;
14603   }
14604   llvm_unreachable("invalid TTK");
14605 }
14606 
14607 /// Determine whether a tag with a given kind is acceptable
14608 /// as a redeclaration of the given tag declaration.
14609 ///
14610 /// \returns true if the new tag kind is acceptable, false otherwise.
14611 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14612                                         TagTypeKind NewTag, bool isDefinition,
14613                                         SourceLocation NewTagLoc,
14614                                         const IdentifierInfo *Name) {
14615   // C++ [dcl.type.elab]p3:
14616   //   The class-key or enum keyword present in the
14617   //   elaborated-type-specifier shall agree in kind with the
14618   //   declaration to which the name in the elaborated-type-specifier
14619   //   refers. This rule also applies to the form of
14620   //   elaborated-type-specifier that declares a class-name or
14621   //   friend class since it can be construed as referring to the
14622   //   definition of the class. Thus, in any
14623   //   elaborated-type-specifier, the enum keyword shall be used to
14624   //   refer to an enumeration (7.2), the union class-key shall be
14625   //   used to refer to a union (clause 9), and either the class or
14626   //   struct class-key shall be used to refer to a class (clause 9)
14627   //   declared using the class or struct class-key.
14628   TagTypeKind OldTag = Previous->getTagKind();
14629   if (OldTag != NewTag &&
14630       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14631     return false;
14632 
14633   // Tags are compatible, but we might still want to warn on mismatched tags.
14634   // Non-class tags can't be mismatched at this point.
14635   if (!isClassCompatTagKind(NewTag))
14636     return true;
14637 
14638   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14639   // by our warning analysis. We don't want to warn about mismatches with (eg)
14640   // declarations in system headers that are designed to be specialized, but if
14641   // a user asks us to warn, we should warn if their code contains mismatched
14642   // declarations.
14643   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14644     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14645                                       Loc);
14646   };
14647   if (IsIgnoredLoc(NewTagLoc))
14648     return true;
14649 
14650   auto IsIgnored = [&](const TagDecl *Tag) {
14651     return IsIgnoredLoc(Tag->getLocation());
14652   };
14653   while (IsIgnored(Previous)) {
14654     Previous = Previous->getPreviousDecl();
14655     if (!Previous)
14656       return true;
14657     OldTag = Previous->getTagKind();
14658   }
14659 
14660   bool isTemplate = false;
14661   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14662     isTemplate = Record->getDescribedClassTemplate();
14663 
14664   if (inTemplateInstantiation()) {
14665     if (OldTag != NewTag) {
14666       // In a template instantiation, do not offer fix-its for tag mismatches
14667       // since they usually mess up the template instead of fixing the problem.
14668       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14669         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14670         << getRedeclDiagFromTagKind(OldTag);
14671       // FIXME: Note previous location?
14672     }
14673     return true;
14674   }
14675 
14676   if (isDefinition) {
14677     // On definitions, check all previous tags and issue a fix-it for each
14678     // one that doesn't match the current tag.
14679     if (Previous->getDefinition()) {
14680       // Don't suggest fix-its for redefinitions.
14681       return true;
14682     }
14683 
14684     bool previousMismatch = false;
14685     for (const TagDecl *I : Previous->redecls()) {
14686       if (I->getTagKind() != NewTag) {
14687         // Ignore previous declarations for which the warning was disabled.
14688         if (IsIgnored(I))
14689           continue;
14690 
14691         if (!previousMismatch) {
14692           previousMismatch = true;
14693           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14694             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14695             << getRedeclDiagFromTagKind(I->getTagKind());
14696         }
14697         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14698           << getRedeclDiagFromTagKind(NewTag)
14699           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14700                TypeWithKeyword::getTagTypeKindName(NewTag));
14701       }
14702     }
14703     return true;
14704   }
14705 
14706   // Identify the prevailing tag kind: this is the kind of the definition (if
14707   // there is a non-ignored definition), or otherwise the kind of the prior
14708   // (non-ignored) declaration.
14709   const TagDecl *PrevDef = Previous->getDefinition();
14710   if (PrevDef && IsIgnored(PrevDef))
14711     PrevDef = nullptr;
14712   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14713   if (Redecl->getTagKind() != NewTag) {
14714     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14715       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14716       << getRedeclDiagFromTagKind(OldTag);
14717     Diag(Redecl->getLocation(), diag::note_previous_use);
14718 
14719     // If there is a previous definition, suggest a fix-it.
14720     if (PrevDef) {
14721       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14722         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14723         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14724              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14725     }
14726   }
14727 
14728   return true;
14729 }
14730 
14731 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14732 /// from an outer enclosing namespace or file scope inside a friend declaration.
14733 /// This should provide the commented out code in the following snippet:
14734 ///   namespace N {
14735 ///     struct X;
14736 ///     namespace M {
14737 ///       struct Y { friend struct /*N::*/ X; };
14738 ///     }
14739 ///   }
14740 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14741                                          SourceLocation NameLoc) {
14742   // While the decl is in a namespace, do repeated lookup of that name and see
14743   // if we get the same namespace back.  If we do not, continue until
14744   // translation unit scope, at which point we have a fully qualified NNS.
14745   SmallVector<IdentifierInfo *, 4> Namespaces;
14746   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14747   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14748     // This tag should be declared in a namespace, which can only be enclosed by
14749     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14750     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14751     if (!Namespace || Namespace->isAnonymousNamespace())
14752       return FixItHint();
14753     IdentifierInfo *II = Namespace->getIdentifier();
14754     Namespaces.push_back(II);
14755     NamedDecl *Lookup = SemaRef.LookupSingleName(
14756         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14757     if (Lookup == Namespace)
14758       break;
14759   }
14760 
14761   // Once we have all the namespaces, reverse them to go outermost first, and
14762   // build an NNS.
14763   SmallString<64> Insertion;
14764   llvm::raw_svector_ostream OS(Insertion);
14765   if (DC->isTranslationUnit())
14766     OS << "::";
14767   std::reverse(Namespaces.begin(), Namespaces.end());
14768   for (auto *II : Namespaces)
14769     OS << II->getName() << "::";
14770   return FixItHint::CreateInsertion(NameLoc, Insertion);
14771 }
14772 
14773 /// Determine whether a tag originally declared in context \p OldDC can
14774 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14775 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14776 /// using-declaration).
14777 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14778                                          DeclContext *NewDC) {
14779   OldDC = OldDC->getRedeclContext();
14780   NewDC = NewDC->getRedeclContext();
14781 
14782   if (OldDC->Equals(NewDC))
14783     return true;
14784 
14785   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14786   // encloses the other).
14787   if (S.getLangOpts().MSVCCompat &&
14788       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14789     return true;
14790 
14791   return false;
14792 }
14793 
14794 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14795 /// former case, Name will be non-null.  In the later case, Name will be null.
14796 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14797 /// reference/declaration/definition of a tag.
14798 ///
14799 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14800 /// trailing-type-specifier) other than one in an alias-declaration.
14801 ///
14802 /// \param SkipBody If non-null, will be set to indicate if the caller should
14803 /// skip the definition of this tag and treat it as if it were a declaration.
14804 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14805                      SourceLocation KWLoc, CXXScopeSpec &SS,
14806                      IdentifierInfo *Name, SourceLocation NameLoc,
14807                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14808                      SourceLocation ModulePrivateLoc,
14809                      MultiTemplateParamsArg TemplateParameterLists,
14810                      bool &OwnedDecl, bool &IsDependent,
14811                      SourceLocation ScopedEnumKWLoc,
14812                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14813                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14814                      SkipBodyInfo *SkipBody) {
14815   // If this is not a definition, it must have a name.
14816   IdentifierInfo *OrigName = Name;
14817   assert((Name != nullptr || TUK == TUK_Definition) &&
14818          "Nameless record must be a definition!");
14819   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14820 
14821   OwnedDecl = false;
14822   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14823   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14824 
14825   // FIXME: Check member specializations more carefully.
14826   bool isMemberSpecialization = false;
14827   bool Invalid = false;
14828 
14829   // We only need to do this matching if we have template parameters
14830   // or a scope specifier, which also conveniently avoids this work
14831   // for non-C++ cases.
14832   if (TemplateParameterLists.size() > 0 ||
14833       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14834     if (TemplateParameterList *TemplateParams =
14835             MatchTemplateParametersToScopeSpecifier(
14836                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14837                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14838       if (Kind == TTK_Enum) {
14839         Diag(KWLoc, diag::err_enum_template);
14840         return nullptr;
14841       }
14842 
14843       if (TemplateParams->size() > 0) {
14844         // This is a declaration or definition of a class template (which may
14845         // be a member of another template).
14846 
14847         if (Invalid)
14848           return nullptr;
14849 
14850         OwnedDecl = false;
14851         DeclResult Result = CheckClassTemplate(
14852             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14853             AS, ModulePrivateLoc,
14854             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14855             TemplateParameterLists.data(), SkipBody);
14856         return Result.get();
14857       } else {
14858         // The "template<>" header is extraneous.
14859         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14860           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14861         isMemberSpecialization = true;
14862       }
14863     }
14864   }
14865 
14866   // Figure out the underlying type if this a enum declaration. We need to do
14867   // this early, because it's needed to detect if this is an incompatible
14868   // redeclaration.
14869   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14870   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14871 
14872   if (Kind == TTK_Enum) {
14873     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14874       // No underlying type explicitly specified, or we failed to parse the
14875       // type, default to int.
14876       EnumUnderlying = Context.IntTy.getTypePtr();
14877     } else if (UnderlyingType.get()) {
14878       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14879       // integral type; any cv-qualification is ignored.
14880       TypeSourceInfo *TI = nullptr;
14881       GetTypeFromParser(UnderlyingType.get(), &TI);
14882       EnumUnderlying = TI;
14883 
14884       if (CheckEnumUnderlyingType(TI))
14885         // Recover by falling back to int.
14886         EnumUnderlying = Context.IntTy.getTypePtr();
14887 
14888       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14889                                           UPPC_FixedUnderlyingType))
14890         EnumUnderlying = Context.IntTy.getTypePtr();
14891 
14892     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
14893       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14894       // of 'int'. However, if this is an unfixed forward declaration, don't set
14895       // the underlying type unless the user enables -fms-compatibility. This
14896       // makes unfixed forward declared enums incomplete and is more conforming.
14897       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14898         EnumUnderlying = Context.IntTy.getTypePtr();
14899     }
14900   }
14901 
14902   DeclContext *SearchDC = CurContext;
14903   DeclContext *DC = CurContext;
14904   bool isStdBadAlloc = false;
14905   bool isStdAlignValT = false;
14906 
14907   RedeclarationKind Redecl = forRedeclarationInCurContext();
14908   if (TUK == TUK_Friend || TUK == TUK_Reference)
14909     Redecl = NotForRedeclaration;
14910 
14911   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14912   /// implemented asks for structural equivalence checking, the returned decl
14913   /// here is passed back to the parser, allowing the tag body to be parsed.
14914   auto createTagFromNewDecl = [&]() -> TagDecl * {
14915     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14916     // If there is an identifier, use the location of the identifier as the
14917     // location of the decl, otherwise use the location of the struct/union
14918     // keyword.
14919     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14920     TagDecl *New = nullptr;
14921 
14922     if (Kind == TTK_Enum) {
14923       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14924                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14925       // If this is an undefined enum, bail.
14926       if (TUK != TUK_Definition && !Invalid)
14927         return nullptr;
14928       if (EnumUnderlying) {
14929         EnumDecl *ED = cast<EnumDecl>(New);
14930         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14931           ED->setIntegerTypeSourceInfo(TI);
14932         else
14933           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14934         ED->setPromotionType(ED->getIntegerType());
14935       }
14936     } else { // struct/union
14937       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14938                                nullptr);
14939     }
14940 
14941     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14942       // Add alignment attributes if necessary; these attributes are checked
14943       // when the ASTContext lays out the structure.
14944       //
14945       // It is important for implementing the correct semantics that this
14946       // happen here (in ActOnTag). The #pragma pack stack is
14947       // maintained as a result of parser callbacks which can occur at
14948       // many points during the parsing of a struct declaration (because
14949       // the #pragma tokens are effectively skipped over during the
14950       // parsing of the struct).
14951       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14952         AddAlignmentAttributesForRecord(RD);
14953         AddMsStructLayoutForRecord(RD);
14954       }
14955     }
14956     New->setLexicalDeclContext(CurContext);
14957     return New;
14958   };
14959 
14960   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14961   if (Name && SS.isNotEmpty()) {
14962     // We have a nested-name tag ('struct foo::bar').
14963 
14964     // Check for invalid 'foo::'.
14965     if (SS.isInvalid()) {
14966       Name = nullptr;
14967       goto CreateNewDecl;
14968     }
14969 
14970     // If this is a friend or a reference to a class in a dependent
14971     // context, don't try to make a decl for it.
14972     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14973       DC = computeDeclContext(SS, false);
14974       if (!DC) {
14975         IsDependent = true;
14976         return nullptr;
14977       }
14978     } else {
14979       DC = computeDeclContext(SS, true);
14980       if (!DC) {
14981         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14982           << SS.getRange();
14983         return nullptr;
14984       }
14985     }
14986 
14987     if (RequireCompleteDeclContext(SS, DC))
14988       return nullptr;
14989 
14990     SearchDC = DC;
14991     // Look-up name inside 'foo::'.
14992     LookupQualifiedName(Previous, DC);
14993 
14994     if (Previous.isAmbiguous())
14995       return nullptr;
14996 
14997     if (Previous.empty()) {
14998       // Name lookup did not find anything. However, if the
14999       // nested-name-specifier refers to the current instantiation,
15000       // and that current instantiation has any dependent base
15001       // classes, we might find something at instantiation time: treat
15002       // this as a dependent elaborated-type-specifier.
15003       // But this only makes any sense for reference-like lookups.
15004       if (Previous.wasNotFoundInCurrentInstantiation() &&
15005           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15006         IsDependent = true;
15007         return nullptr;
15008       }
15009 
15010       // A tag 'foo::bar' must already exist.
15011       Diag(NameLoc, diag::err_not_tag_in_scope)
15012         << Kind << Name << DC << SS.getRange();
15013       Name = nullptr;
15014       Invalid = true;
15015       goto CreateNewDecl;
15016     }
15017   } else if (Name) {
15018     // C++14 [class.mem]p14:
15019     //   If T is the name of a class, then each of the following shall have a
15020     //   name different from T:
15021     //    -- every member of class T that is itself a type
15022     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15023         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15024       return nullptr;
15025 
15026     // If this is a named struct, check to see if there was a previous forward
15027     // declaration or definition.
15028     // FIXME: We're looking into outer scopes here, even when we
15029     // shouldn't be. Doing so can result in ambiguities that we
15030     // shouldn't be diagnosing.
15031     LookupName(Previous, S);
15032 
15033     // When declaring or defining a tag, ignore ambiguities introduced
15034     // by types using'ed into this scope.
15035     if (Previous.isAmbiguous() &&
15036         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15037       LookupResult::Filter F = Previous.makeFilter();
15038       while (F.hasNext()) {
15039         NamedDecl *ND = F.next();
15040         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15041                 SearchDC->getRedeclContext()))
15042           F.erase();
15043       }
15044       F.done();
15045     }
15046 
15047     // C++11 [namespace.memdef]p3:
15048     //   If the name in a friend declaration is neither qualified nor
15049     //   a template-id and the declaration is a function or an
15050     //   elaborated-type-specifier, the lookup to determine whether
15051     //   the entity has been previously declared shall not consider
15052     //   any scopes outside the innermost enclosing namespace.
15053     //
15054     // MSVC doesn't implement the above rule for types, so a friend tag
15055     // declaration may be a redeclaration of a type declared in an enclosing
15056     // scope.  They do implement this rule for friend functions.
15057     //
15058     // Does it matter that this should be by scope instead of by
15059     // semantic context?
15060     if (!Previous.empty() && TUK == TUK_Friend) {
15061       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15062       LookupResult::Filter F = Previous.makeFilter();
15063       bool FriendSawTagOutsideEnclosingNamespace = false;
15064       while (F.hasNext()) {
15065         NamedDecl *ND = F.next();
15066         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15067         if (DC->isFileContext() &&
15068             !EnclosingNS->Encloses(ND->getDeclContext())) {
15069           if (getLangOpts().MSVCCompat)
15070             FriendSawTagOutsideEnclosingNamespace = true;
15071           else
15072             F.erase();
15073         }
15074       }
15075       F.done();
15076 
15077       // Diagnose this MSVC extension in the easy case where lookup would have
15078       // unambiguously found something outside the enclosing namespace.
15079       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15080         NamedDecl *ND = Previous.getFoundDecl();
15081         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15082             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15083       }
15084     }
15085 
15086     // Note:  there used to be some attempt at recovery here.
15087     if (Previous.isAmbiguous())
15088       return nullptr;
15089 
15090     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15091       // FIXME: This makes sure that we ignore the contexts associated
15092       // with C structs, unions, and enums when looking for a matching
15093       // tag declaration or definition. See the similar lookup tweak
15094       // in Sema::LookupName; is there a better way to deal with this?
15095       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15096         SearchDC = SearchDC->getParent();
15097     }
15098   }
15099 
15100   if (Previous.isSingleResult() &&
15101       Previous.getFoundDecl()->isTemplateParameter()) {
15102     // Maybe we will complain about the shadowed template parameter.
15103     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15104     // Just pretend that we didn't see the previous declaration.
15105     Previous.clear();
15106   }
15107 
15108   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15109       DC->Equals(getStdNamespace())) {
15110     if (Name->isStr("bad_alloc")) {
15111       // This is a declaration of or a reference to "std::bad_alloc".
15112       isStdBadAlloc = true;
15113 
15114       // If std::bad_alloc has been implicitly declared (but made invisible to
15115       // name lookup), fill in this implicit declaration as the previous
15116       // declaration, so that the declarations get chained appropriately.
15117       if (Previous.empty() && StdBadAlloc)
15118         Previous.addDecl(getStdBadAlloc());
15119     } else if (Name->isStr("align_val_t")) {
15120       isStdAlignValT = true;
15121       if (Previous.empty() && StdAlignValT)
15122         Previous.addDecl(getStdAlignValT());
15123     }
15124   }
15125 
15126   // If we didn't find a previous declaration, and this is a reference
15127   // (or friend reference), move to the correct scope.  In C++, we
15128   // also need to do a redeclaration lookup there, just in case
15129   // there's a shadow friend decl.
15130   if (Name && Previous.empty() &&
15131       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15132     if (Invalid) goto CreateNewDecl;
15133     assert(SS.isEmpty());
15134 
15135     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15136       // C++ [basic.scope.pdecl]p5:
15137       //   -- for an elaborated-type-specifier of the form
15138       //
15139       //          class-key identifier
15140       //
15141       //      if the elaborated-type-specifier is used in the
15142       //      decl-specifier-seq or parameter-declaration-clause of a
15143       //      function defined in namespace scope, the identifier is
15144       //      declared as a class-name in the namespace that contains
15145       //      the declaration; otherwise, except as a friend
15146       //      declaration, the identifier is declared in the smallest
15147       //      non-class, non-function-prototype scope that contains the
15148       //      declaration.
15149       //
15150       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15151       // C structs and unions.
15152       //
15153       // It is an error in C++ to declare (rather than define) an enum
15154       // type, including via an elaborated type specifier.  We'll
15155       // diagnose that later; for now, declare the enum in the same
15156       // scope as we would have picked for any other tag type.
15157       //
15158       // GNU C also supports this behavior as part of its incomplete
15159       // enum types extension, while GNU C++ does not.
15160       //
15161       // Find the context where we'll be declaring the tag.
15162       // FIXME: We would like to maintain the current DeclContext as the
15163       // lexical context,
15164       SearchDC = getTagInjectionContext(SearchDC);
15165 
15166       // Find the scope where we'll be declaring the tag.
15167       S = getTagInjectionScope(S, getLangOpts());
15168     } else {
15169       assert(TUK == TUK_Friend);
15170       // C++ [namespace.memdef]p3:
15171       //   If a friend declaration in a non-local class first declares a
15172       //   class or function, the friend class or function is a member of
15173       //   the innermost enclosing namespace.
15174       SearchDC = SearchDC->getEnclosingNamespaceContext();
15175     }
15176 
15177     // In C++, we need to do a redeclaration lookup to properly
15178     // diagnose some problems.
15179     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15180     // hidden declaration so that we don't get ambiguity errors when using a
15181     // type declared by an elaborated-type-specifier.  In C that is not correct
15182     // and we should instead merge compatible types found by lookup.
15183     if (getLangOpts().CPlusPlus) {
15184       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15185       LookupQualifiedName(Previous, SearchDC);
15186     } else {
15187       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15188       LookupName(Previous, S);
15189     }
15190   }
15191 
15192   // If we have a known previous declaration to use, then use it.
15193   if (Previous.empty() && SkipBody && SkipBody->Previous)
15194     Previous.addDecl(SkipBody->Previous);
15195 
15196   if (!Previous.empty()) {
15197     NamedDecl *PrevDecl = Previous.getFoundDecl();
15198     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15199 
15200     // It's okay to have a tag decl in the same scope as a typedef
15201     // which hides a tag decl in the same scope.  Finding this
15202     // insanity with a redeclaration lookup can only actually happen
15203     // in C++.
15204     //
15205     // This is also okay for elaborated-type-specifiers, which is
15206     // technically forbidden by the current standard but which is
15207     // okay according to the likely resolution of an open issue;
15208     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15209     if (getLangOpts().CPlusPlus) {
15210       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15211         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15212           TagDecl *Tag = TT->getDecl();
15213           if (Tag->getDeclName() == Name &&
15214               Tag->getDeclContext()->getRedeclContext()
15215                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
15216             PrevDecl = Tag;
15217             Previous.clear();
15218             Previous.addDecl(Tag);
15219             Previous.resolveKind();
15220           }
15221         }
15222       }
15223     }
15224 
15225     // If this is a redeclaration of a using shadow declaration, it must
15226     // declare a tag in the same context. In MSVC mode, we allow a
15227     // redefinition if either context is within the other.
15228     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15229       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15230       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15231           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15232           !(OldTag && isAcceptableTagRedeclContext(
15233                           *this, OldTag->getDeclContext(), SearchDC))) {
15234         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15235         Diag(Shadow->getTargetDecl()->getLocation(),
15236              diag::note_using_decl_target);
15237         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15238             << 0;
15239         // Recover by ignoring the old declaration.
15240         Previous.clear();
15241         goto CreateNewDecl;
15242       }
15243     }
15244 
15245     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15246       // If this is a use of a previous tag, or if the tag is already declared
15247       // in the same scope (so that the definition/declaration completes or
15248       // rementions the tag), reuse the decl.
15249       if (TUK == TUK_Reference || TUK == TUK_Friend ||
15250           isDeclInScope(DirectPrevDecl, SearchDC, S,
15251                         SS.isNotEmpty() || isMemberSpecialization)) {
15252         // Make sure that this wasn't declared as an enum and now used as a
15253         // struct or something similar.
15254         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15255                                           TUK == TUK_Definition, KWLoc,
15256                                           Name)) {
15257           bool SafeToContinue
15258             = (PrevTagDecl->getTagKind() != TTK_Enum &&
15259                Kind != TTK_Enum);
15260           if (SafeToContinue)
15261             Diag(KWLoc, diag::err_use_with_wrong_tag)
15262               << Name
15263               << FixItHint::CreateReplacement(SourceRange(KWLoc),
15264                                               PrevTagDecl->getKindName());
15265           else
15266             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15267           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15268 
15269           if (SafeToContinue)
15270             Kind = PrevTagDecl->getTagKind();
15271           else {
15272             // Recover by making this an anonymous redefinition.
15273             Name = nullptr;
15274             Previous.clear();
15275             Invalid = true;
15276           }
15277         }
15278 
15279         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15280           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15281 
15282           // If this is an elaborated-type-specifier for a scoped enumeration,
15283           // the 'class' keyword is not necessary and not permitted.
15284           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15285             if (ScopedEnum)
15286               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
15287                 << PrevEnum->isScoped()
15288                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
15289             return PrevTagDecl;
15290           }
15291 
15292           QualType EnumUnderlyingTy;
15293           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15294             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15295           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15296             EnumUnderlyingTy = QualType(T, 0);
15297 
15298           // All conflicts with previous declarations are recovered by
15299           // returning the previous declaration, unless this is a definition,
15300           // in which case we want the caller to bail out.
15301           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15302                                      ScopedEnum, EnumUnderlyingTy,
15303                                      IsFixed, PrevEnum))
15304             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15305         }
15306 
15307         // C++11 [class.mem]p1:
15308         //   A member shall not be declared twice in the member-specification,
15309         //   except that a nested class or member class template can be declared
15310         //   and then later defined.
15311         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15312             S->isDeclScope(PrevDecl)) {
15313           Diag(NameLoc, diag::ext_member_redeclared);
15314           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15315         }
15316 
15317         if (!Invalid) {
15318           // If this is a use, just return the declaration we found, unless
15319           // we have attributes.
15320           if (TUK == TUK_Reference || TUK == TUK_Friend) {
15321             if (!Attrs.empty()) {
15322               // FIXME: Diagnose these attributes. For now, we create a new
15323               // declaration to hold them.
15324             } else if (TUK == TUK_Reference &&
15325                        (PrevTagDecl->getFriendObjectKind() ==
15326                             Decl::FOK_Undeclared ||
15327                         PrevDecl->getOwningModule() != getCurrentModule()) &&
15328                        SS.isEmpty()) {
15329               // This declaration is a reference to an existing entity, but
15330               // has different visibility from that entity: it either makes
15331               // a friend visible or it makes a type visible in a new module.
15332               // In either case, create a new declaration. We only do this if
15333               // the declaration would have meant the same thing if no prior
15334               // declaration were found, that is, if it was found in the same
15335               // scope where we would have injected a declaration.
15336               if (!getTagInjectionContext(CurContext)->getRedeclContext()
15337                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15338                 return PrevTagDecl;
15339               // This is in the injected scope, create a new declaration in
15340               // that scope.
15341               S = getTagInjectionScope(S, getLangOpts());
15342             } else {
15343               return PrevTagDecl;
15344             }
15345           }
15346 
15347           // Diagnose attempts to redefine a tag.
15348           if (TUK == TUK_Definition) {
15349             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15350               // If we're defining a specialization and the previous definition
15351               // is from an implicit instantiation, don't emit an error
15352               // here; we'll catch this in the general case below.
15353               bool IsExplicitSpecializationAfterInstantiation = false;
15354               if (isMemberSpecialization) {
15355                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15356                   IsExplicitSpecializationAfterInstantiation =
15357                     RD->getTemplateSpecializationKind() !=
15358                     TSK_ExplicitSpecialization;
15359                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15360                   IsExplicitSpecializationAfterInstantiation =
15361                     ED->getTemplateSpecializationKind() !=
15362                     TSK_ExplicitSpecialization;
15363               }
15364 
15365               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15366               // not keep more that one definition around (merge them). However,
15367               // ensure the decl passes the structural compatibility check in
15368               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15369               NamedDecl *Hidden = nullptr;
15370               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15371                 // There is a definition of this tag, but it is not visible. We
15372                 // explicitly make use of C++'s one definition rule here, and
15373                 // assume that this definition is identical to the hidden one
15374                 // we already have. Make the existing definition visible and
15375                 // use it in place of this one.
15376                 if (!getLangOpts().CPlusPlus) {
15377                   // Postpone making the old definition visible until after we
15378                   // complete parsing the new one and do the structural
15379                   // comparison.
15380                   SkipBody->CheckSameAsPrevious = true;
15381                   SkipBody->New = createTagFromNewDecl();
15382                   SkipBody->Previous = Def;
15383                   return Def;
15384                 } else {
15385                   SkipBody->ShouldSkip = true;
15386                   SkipBody->Previous = Def;
15387                   makeMergedDefinitionVisible(Hidden);
15388                   // Carry on and handle it like a normal definition. We'll
15389                   // skip starting the definitiion later.
15390                 }
15391               } else if (!IsExplicitSpecializationAfterInstantiation) {
15392                 // A redeclaration in function prototype scope in C isn't
15393                 // visible elsewhere, so merely issue a warning.
15394                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15395                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15396                 else
15397                   Diag(NameLoc, diag::err_redefinition) << Name;
15398                 notePreviousDefinition(Def,
15399                                        NameLoc.isValid() ? NameLoc : KWLoc);
15400                 // If this is a redefinition, recover by making this
15401                 // struct be anonymous, which will make any later
15402                 // references get the previous definition.
15403                 Name = nullptr;
15404                 Previous.clear();
15405                 Invalid = true;
15406               }
15407             } else {
15408               // If the type is currently being defined, complain
15409               // about a nested redefinition.
15410               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15411               if (TD->isBeingDefined()) {
15412                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15413                 Diag(PrevTagDecl->getLocation(),
15414                      diag::note_previous_definition);
15415                 Name = nullptr;
15416                 Previous.clear();
15417                 Invalid = true;
15418               }
15419             }
15420 
15421             // Okay, this is definition of a previously declared or referenced
15422             // tag. We're going to create a new Decl for it.
15423           }
15424 
15425           // Okay, we're going to make a redeclaration.  If this is some kind
15426           // of reference, make sure we build the redeclaration in the same DC
15427           // as the original, and ignore the current access specifier.
15428           if (TUK == TUK_Friend || TUK == TUK_Reference) {
15429             SearchDC = PrevTagDecl->getDeclContext();
15430             AS = AS_none;
15431           }
15432         }
15433         // If we get here we have (another) forward declaration or we
15434         // have a definition.  Just create a new decl.
15435 
15436       } else {
15437         // If we get here, this is a definition of a new tag type in a nested
15438         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15439         // new decl/type.  We set PrevDecl to NULL so that the entities
15440         // have distinct types.
15441         Previous.clear();
15442       }
15443       // If we get here, we're going to create a new Decl. If PrevDecl
15444       // is non-NULL, it's a definition of the tag declared by
15445       // PrevDecl. If it's NULL, we have a new definition.
15446 
15447     // Otherwise, PrevDecl is not a tag, but was found with tag
15448     // lookup.  This is only actually possible in C++, where a few
15449     // things like templates still live in the tag namespace.
15450     } else {
15451       // Use a better diagnostic if an elaborated-type-specifier
15452       // found the wrong kind of type on the first
15453       // (non-redeclaration) lookup.
15454       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15455           !Previous.isForRedeclaration()) {
15456         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15457         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15458                                                        << Kind;
15459         Diag(PrevDecl->getLocation(), diag::note_declared_at);
15460         Invalid = true;
15461 
15462       // Otherwise, only diagnose if the declaration is in scope.
15463       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15464                                 SS.isNotEmpty() || isMemberSpecialization)) {
15465         // do nothing
15466 
15467       // Diagnose implicit declarations introduced by elaborated types.
15468       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15469         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15470         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15471         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15472         Invalid = true;
15473 
15474       // Otherwise it's a declaration.  Call out a particularly common
15475       // case here.
15476       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15477         unsigned Kind = 0;
15478         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15479         Diag(NameLoc, diag::err_tag_definition_of_typedef)
15480           << Name << Kind << TND->getUnderlyingType();
15481         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15482         Invalid = true;
15483 
15484       // Otherwise, diagnose.
15485       } else {
15486         // The tag name clashes with something else in the target scope,
15487         // issue an error and recover by making this tag be anonymous.
15488         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15489         notePreviousDefinition(PrevDecl, NameLoc);
15490         Name = nullptr;
15491         Invalid = true;
15492       }
15493 
15494       // The existing declaration isn't relevant to us; we're in a
15495       // new scope, so clear out the previous declaration.
15496       Previous.clear();
15497     }
15498   }
15499 
15500 CreateNewDecl:
15501 
15502   TagDecl *PrevDecl = nullptr;
15503   if (Previous.isSingleResult())
15504     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
15505 
15506   // If there is an identifier, use the location of the identifier as the
15507   // location of the decl, otherwise use the location of the struct/union
15508   // keyword.
15509   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15510 
15511   // Otherwise, create a new declaration. If there is a previous
15512   // declaration of the same entity, the two will be linked via
15513   // PrevDecl.
15514   TagDecl *New;
15515 
15516   if (Kind == TTK_Enum) {
15517     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15518     // enum X { A, B, C } D;    D should chain to X.
15519     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
15520                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
15521                            ScopedEnumUsesClassTag, IsFixed);
15522 
15523     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
15524       StdAlignValT = cast<EnumDecl>(New);
15525 
15526     // If this is an undefined enum, warn.
15527     if (TUK != TUK_Definition && !Invalid) {
15528       TagDecl *Def;
15529       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
15530         // C++0x: 7.2p2: opaque-enum-declaration.
15531         // Conflicts are diagnosed above. Do nothing.
15532       }
15533       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
15534         Diag(Loc, diag::ext_forward_ref_enum_def)
15535           << New;
15536         Diag(Def->getLocation(), diag::note_previous_definition);
15537       } else {
15538         unsigned DiagID = diag::ext_forward_ref_enum;
15539         if (getLangOpts().MSVCCompat)
15540           DiagID = diag::ext_ms_forward_ref_enum;
15541         else if (getLangOpts().CPlusPlus)
15542           DiagID = diag::err_forward_ref_enum;
15543         Diag(Loc, DiagID);
15544       }
15545     }
15546 
15547     if (EnumUnderlying) {
15548       EnumDecl *ED = cast<EnumDecl>(New);
15549       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15550         ED->setIntegerTypeSourceInfo(TI);
15551       else
15552         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
15553       ED->setPromotionType(ED->getIntegerType());
15554       assert(ED->isComplete() && "enum with type should be complete");
15555     }
15556   } else {
15557     // struct/union/class
15558 
15559     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
15560     // struct X { int A; } D;    D should chain to X.
15561     if (getLangOpts().CPlusPlus) {
15562       // FIXME: Look for a way to use RecordDecl for simple structs.
15563       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15564                                   cast_or_null<CXXRecordDecl>(PrevDecl));
15565 
15566       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
15567         StdBadAlloc = cast<CXXRecordDecl>(New);
15568     } else
15569       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15570                                cast_or_null<RecordDecl>(PrevDecl));
15571   }
15572 
15573   // C++11 [dcl.type]p3:
15574   //   A type-specifier-seq shall not define a class or enumeration [...].
15575   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
15576       TUK == TUK_Definition) {
15577     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
15578       << Context.getTagDeclType(New);
15579     Invalid = true;
15580   }
15581 
15582   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15583       DC->getDeclKind() == Decl::Enum) {
15584     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15585       << Context.getTagDeclType(New);
15586     Invalid = true;
15587   }
15588 
15589   // Maybe add qualifier info.
15590   if (SS.isNotEmpty()) {
15591     if (SS.isSet()) {
15592       // If this is either a declaration or a definition, check the
15593       // nested-name-specifier against the current context.
15594       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15595           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15596                                        isMemberSpecialization))
15597         Invalid = true;
15598 
15599       New->setQualifierInfo(SS.getWithLocInContext(Context));
15600       if (TemplateParameterLists.size() > 0) {
15601         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15602       }
15603     }
15604     else
15605       Invalid = true;
15606   }
15607 
15608   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15609     // Add alignment attributes if necessary; these attributes are checked when
15610     // the ASTContext lays out the structure.
15611     //
15612     // It is important for implementing the correct semantics that this
15613     // happen here (in ActOnTag). The #pragma pack stack is
15614     // maintained as a result of parser callbacks which can occur at
15615     // many points during the parsing of a struct declaration (because
15616     // the #pragma tokens are effectively skipped over during the
15617     // parsing of the struct).
15618     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15619       AddAlignmentAttributesForRecord(RD);
15620       AddMsStructLayoutForRecord(RD);
15621     }
15622   }
15623 
15624   if (ModulePrivateLoc.isValid()) {
15625     if (isMemberSpecialization)
15626       Diag(New->getLocation(), diag::err_module_private_specialization)
15627         << 2
15628         << FixItHint::CreateRemoval(ModulePrivateLoc);
15629     // __module_private__ does not apply to local classes. However, we only
15630     // diagnose this as an error when the declaration specifiers are
15631     // freestanding. Here, we just ignore the __module_private__.
15632     else if (!SearchDC->isFunctionOrMethod())
15633       New->setModulePrivate();
15634   }
15635 
15636   // If this is a specialization of a member class (of a class template),
15637   // check the specialization.
15638   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15639     Invalid = true;
15640 
15641   // If we're declaring or defining a tag in function prototype scope in C,
15642   // note that this type can only be used within the function and add it to
15643   // the list of decls to inject into the function definition scope.
15644   if ((Name || Kind == TTK_Enum) &&
15645       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15646     if (getLangOpts().CPlusPlus) {
15647       // C++ [dcl.fct]p6:
15648       //   Types shall not be defined in return or parameter types.
15649       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15650         Diag(Loc, diag::err_type_defined_in_param_type)
15651             << Name;
15652         Invalid = true;
15653       }
15654     } else if (!PrevDecl) {
15655       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15656     }
15657   }
15658 
15659   if (Invalid)
15660     New->setInvalidDecl();
15661 
15662   // Set the lexical context. If the tag has a C++ scope specifier, the
15663   // lexical context will be different from the semantic context.
15664   New->setLexicalDeclContext(CurContext);
15665 
15666   // Mark this as a friend decl if applicable.
15667   // In Microsoft mode, a friend declaration also acts as a forward
15668   // declaration so we always pass true to setObjectOfFriendDecl to make
15669   // the tag name visible.
15670   if (TUK == TUK_Friend)
15671     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15672 
15673   // Set the access specifier.
15674   if (!Invalid && SearchDC->isRecord())
15675     SetMemberAccessSpecifier(New, PrevDecl, AS);
15676 
15677   if (PrevDecl)
15678     CheckRedeclarationModuleOwnership(New, PrevDecl);
15679 
15680   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15681     New->startDefinition();
15682 
15683   ProcessDeclAttributeList(S, New, Attrs);
15684   AddPragmaAttributes(S, New);
15685 
15686   // If this has an identifier, add it to the scope stack.
15687   if (TUK == TUK_Friend) {
15688     // We might be replacing an existing declaration in the lookup tables;
15689     // if so, borrow its access specifier.
15690     if (PrevDecl)
15691       New->setAccess(PrevDecl->getAccess());
15692 
15693     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15694     DC->makeDeclVisibleInContext(New);
15695     if (Name) // can be null along some error paths
15696       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15697         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15698   } else if (Name) {
15699     S = getNonFieldDeclScope(S);
15700     PushOnScopeChains(New, S, true);
15701   } else {
15702     CurContext->addDecl(New);
15703   }
15704 
15705   // If this is the C FILE type, notify the AST context.
15706   if (IdentifierInfo *II = New->getIdentifier())
15707     if (!New->isInvalidDecl() &&
15708         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15709         II->isStr("FILE"))
15710       Context.setFILEDecl(New);
15711 
15712   if (PrevDecl)
15713     mergeDeclAttributes(New, PrevDecl);
15714 
15715   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
15716     inferGslOwnerPointerAttribute(CXXRD);
15717 
15718   // If there's a #pragma GCC visibility in scope, set the visibility of this
15719   // record.
15720   AddPushedVisibilityAttribute(New);
15721 
15722   if (isMemberSpecialization && !New->isInvalidDecl())
15723     CompleteMemberSpecialization(New, Previous);
15724 
15725   OwnedDecl = true;
15726   // In C++, don't return an invalid declaration. We can't recover well from
15727   // the cases where we make the type anonymous.
15728   if (Invalid && getLangOpts().CPlusPlus) {
15729     if (New->isBeingDefined())
15730       if (auto RD = dyn_cast<RecordDecl>(New))
15731         RD->completeDefinition();
15732     return nullptr;
15733   } else if (SkipBody && SkipBody->ShouldSkip) {
15734     return SkipBody->Previous;
15735   } else {
15736     return New;
15737   }
15738 }
15739 
15740 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15741   AdjustDeclIfTemplate(TagD);
15742   TagDecl *Tag = cast<TagDecl>(TagD);
15743 
15744   // Enter the tag context.
15745   PushDeclContext(S, Tag);
15746 
15747   ActOnDocumentableDecl(TagD);
15748 
15749   // If there's a #pragma GCC visibility in scope, set the visibility of this
15750   // record.
15751   AddPushedVisibilityAttribute(Tag);
15752 }
15753 
15754 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15755                                     SkipBodyInfo &SkipBody) {
15756   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15757     return false;
15758 
15759   // Make the previous decl visible.
15760   makeMergedDefinitionVisible(SkipBody.Previous);
15761   return true;
15762 }
15763 
15764 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15765   assert(isa<ObjCContainerDecl>(IDecl) &&
15766          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15767   DeclContext *OCD = cast<DeclContext>(IDecl);
15768   assert(getContainingDC(OCD) == CurContext &&
15769       "The next DeclContext should be lexically contained in the current one.");
15770   CurContext = OCD;
15771   return IDecl;
15772 }
15773 
15774 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15775                                            SourceLocation FinalLoc,
15776                                            bool IsFinalSpelledSealed,
15777                                            SourceLocation LBraceLoc) {
15778   AdjustDeclIfTemplate(TagD);
15779   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15780 
15781   FieldCollector->StartClass();
15782 
15783   if (!Record->getIdentifier())
15784     return;
15785 
15786   if (FinalLoc.isValid())
15787     Record->addAttr(FinalAttr::Create(
15788         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
15789         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
15790 
15791   // C++ [class]p2:
15792   //   [...] The class-name is also inserted into the scope of the
15793   //   class itself; this is known as the injected-class-name. For
15794   //   purposes of access checking, the injected-class-name is treated
15795   //   as if it were a public member name.
15796   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15797       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15798       Record->getLocation(), Record->getIdentifier(),
15799       /*PrevDecl=*/nullptr,
15800       /*DelayTypeCreation=*/true);
15801   Context.getTypeDeclType(InjectedClassName, Record);
15802   InjectedClassName->setImplicit();
15803   InjectedClassName->setAccess(AS_public);
15804   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15805       InjectedClassName->setDescribedClassTemplate(Template);
15806   PushOnScopeChains(InjectedClassName, S);
15807   assert(InjectedClassName->isInjectedClassName() &&
15808          "Broken injected-class-name");
15809 }
15810 
15811 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15812                                     SourceRange BraceRange) {
15813   AdjustDeclIfTemplate(TagD);
15814   TagDecl *Tag = cast<TagDecl>(TagD);
15815   Tag->setBraceRange(BraceRange);
15816 
15817   // Make sure we "complete" the definition even it is invalid.
15818   if (Tag->isBeingDefined()) {
15819     assert(Tag->isInvalidDecl() && "We should already have completed it");
15820     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15821       RD->completeDefinition();
15822   }
15823 
15824   if (isa<CXXRecordDecl>(Tag)) {
15825     FieldCollector->FinishClass();
15826   }
15827 
15828   // Exit this scope of this tag's definition.
15829   PopDeclContext();
15830 
15831   if (getCurLexicalContext()->isObjCContainer() &&
15832       Tag->getDeclContext()->isFileContext())
15833     Tag->setTopLevelDeclInObjCContainer();
15834 
15835   // Notify the consumer that we've defined a tag.
15836   if (!Tag->isInvalidDecl())
15837     Consumer.HandleTagDeclDefinition(Tag);
15838 }
15839 
15840 void Sema::ActOnObjCContainerFinishDefinition() {
15841   // Exit this scope of this interface definition.
15842   PopDeclContext();
15843 }
15844 
15845 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15846   assert(DC == CurContext && "Mismatch of container contexts");
15847   OriginalLexicalContext = DC;
15848   ActOnObjCContainerFinishDefinition();
15849 }
15850 
15851 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15852   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15853   OriginalLexicalContext = nullptr;
15854 }
15855 
15856 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15857   AdjustDeclIfTemplate(TagD);
15858   TagDecl *Tag = cast<TagDecl>(TagD);
15859   Tag->setInvalidDecl();
15860 
15861   // Make sure we "complete" the definition even it is invalid.
15862   if (Tag->isBeingDefined()) {
15863     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15864       RD->completeDefinition();
15865   }
15866 
15867   // We're undoing ActOnTagStartDefinition here, not
15868   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15869   // the FieldCollector.
15870 
15871   PopDeclContext();
15872 }
15873 
15874 // Note that FieldName may be null for anonymous bitfields.
15875 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15876                                 IdentifierInfo *FieldName,
15877                                 QualType FieldTy, bool IsMsStruct,
15878                                 Expr *BitWidth, bool *ZeroWidth) {
15879   // Default to true; that shouldn't confuse checks for emptiness
15880   if (ZeroWidth)
15881     *ZeroWidth = true;
15882 
15883   // C99 6.7.2.1p4 - verify the field type.
15884   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15885   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15886     // Handle incomplete types with specific error.
15887     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15888       return ExprError();
15889     if (FieldName)
15890       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15891         << FieldName << FieldTy << BitWidth->getSourceRange();
15892     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15893       << FieldTy << BitWidth->getSourceRange();
15894   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15895                                              UPPC_BitFieldWidth))
15896     return ExprError();
15897 
15898   // If the bit-width is type- or value-dependent, don't try to check
15899   // it now.
15900   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15901     return BitWidth;
15902 
15903   llvm::APSInt Value;
15904   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15905   if (ICE.isInvalid())
15906     return ICE;
15907   BitWidth = ICE.get();
15908 
15909   if (Value != 0 && ZeroWidth)
15910     *ZeroWidth = false;
15911 
15912   // Zero-width bitfield is ok for anonymous field.
15913   if (Value == 0 && FieldName)
15914     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15915 
15916   if (Value.isSigned() && Value.isNegative()) {
15917     if (FieldName)
15918       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15919                << FieldName << Value.toString(10);
15920     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15921       << Value.toString(10);
15922   }
15923 
15924   if (!FieldTy->isDependentType()) {
15925     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15926     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15927     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15928 
15929     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15930     // ABI.
15931     bool CStdConstraintViolation =
15932         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15933     bool MSBitfieldViolation =
15934         Value.ugt(TypeStorageSize) &&
15935         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15936     if (CStdConstraintViolation || MSBitfieldViolation) {
15937       unsigned DiagWidth =
15938           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15939       if (FieldName)
15940         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15941                << FieldName << (unsigned)Value.getZExtValue()
15942                << !CStdConstraintViolation << DiagWidth;
15943 
15944       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15945              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15946              << DiagWidth;
15947     }
15948 
15949     // Warn on types where the user might conceivably expect to get all
15950     // specified bits as value bits: that's all integral types other than
15951     // 'bool'.
15952     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15953       if (FieldName)
15954         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15955             << FieldName << (unsigned)Value.getZExtValue()
15956             << (unsigned)TypeWidth;
15957       else
15958         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15959             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15960     }
15961   }
15962 
15963   return BitWidth;
15964 }
15965 
15966 /// ActOnField - Each field of a C struct/union is passed into this in order
15967 /// to create a FieldDecl object for it.
15968 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15969                        Declarator &D, Expr *BitfieldWidth) {
15970   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15971                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15972                                /*InitStyle=*/ICIS_NoInit, AS_public);
15973   return Res;
15974 }
15975 
15976 /// HandleField - Analyze a field of a C struct or a C++ data member.
15977 ///
15978 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15979                              SourceLocation DeclStart,
15980                              Declarator &D, Expr *BitWidth,
15981                              InClassInitStyle InitStyle,
15982                              AccessSpecifier AS) {
15983   if (D.isDecompositionDeclarator()) {
15984     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15985     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15986       << Decomp.getSourceRange();
15987     return nullptr;
15988   }
15989 
15990   IdentifierInfo *II = D.getIdentifier();
15991   SourceLocation Loc = DeclStart;
15992   if (II) Loc = D.getIdentifierLoc();
15993 
15994   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15995   QualType T = TInfo->getType();
15996   if (getLangOpts().CPlusPlus) {
15997     CheckExtraCXXDefaultArguments(D);
15998 
15999     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16000                                         UPPC_DataMemberType)) {
16001       D.setInvalidType();
16002       T = Context.IntTy;
16003       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16004     }
16005   }
16006 
16007   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16008 
16009   if (D.getDeclSpec().isInlineSpecified())
16010     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16011         << getLangOpts().CPlusPlus17;
16012   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16013     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16014          diag::err_invalid_thread)
16015       << DeclSpec::getSpecifierName(TSCS);
16016 
16017   // Check to see if this name was declared as a member previously
16018   NamedDecl *PrevDecl = nullptr;
16019   LookupResult Previous(*this, II, Loc, LookupMemberName,
16020                         ForVisibleRedeclaration);
16021   LookupName(Previous, S);
16022   switch (Previous.getResultKind()) {
16023     case LookupResult::Found:
16024     case LookupResult::FoundUnresolvedValue:
16025       PrevDecl = Previous.getAsSingle<NamedDecl>();
16026       break;
16027 
16028     case LookupResult::FoundOverloaded:
16029       PrevDecl = Previous.getRepresentativeDecl();
16030       break;
16031 
16032     case LookupResult::NotFound:
16033     case LookupResult::NotFoundInCurrentInstantiation:
16034     case LookupResult::Ambiguous:
16035       break;
16036   }
16037   Previous.suppressDiagnostics();
16038 
16039   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16040     // Maybe we will complain about the shadowed template parameter.
16041     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16042     // Just pretend that we didn't see the previous declaration.
16043     PrevDecl = nullptr;
16044   }
16045 
16046   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16047     PrevDecl = nullptr;
16048 
16049   bool Mutable
16050     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16051   SourceLocation TSSL = D.getBeginLoc();
16052   FieldDecl *NewFD
16053     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16054                      TSSL, AS, PrevDecl, &D);
16055 
16056   if (NewFD->isInvalidDecl())
16057     Record->setInvalidDecl();
16058 
16059   if (D.getDeclSpec().isModulePrivateSpecified())
16060     NewFD->setModulePrivate();
16061 
16062   if (NewFD->isInvalidDecl() && PrevDecl) {
16063     // Don't introduce NewFD into scope; there's already something
16064     // with the same name in the same scope.
16065   } else if (II) {
16066     PushOnScopeChains(NewFD, S);
16067   } else
16068     Record->addDecl(NewFD);
16069 
16070   return NewFD;
16071 }
16072 
16073 /// Build a new FieldDecl and check its well-formedness.
16074 ///
16075 /// This routine builds a new FieldDecl given the fields name, type,
16076 /// record, etc. \p PrevDecl should refer to any previous declaration
16077 /// with the same name and in the same scope as the field to be
16078 /// created.
16079 ///
16080 /// \returns a new FieldDecl.
16081 ///
16082 /// \todo The Declarator argument is a hack. It will be removed once
16083 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16084                                 TypeSourceInfo *TInfo,
16085                                 RecordDecl *Record, SourceLocation Loc,
16086                                 bool Mutable, Expr *BitWidth,
16087                                 InClassInitStyle InitStyle,
16088                                 SourceLocation TSSL,
16089                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16090                                 Declarator *D) {
16091   IdentifierInfo *II = Name.getAsIdentifierInfo();
16092   bool InvalidDecl = false;
16093   if (D) InvalidDecl = D->isInvalidType();
16094 
16095   // If we receive a broken type, recover by assuming 'int' and
16096   // marking this declaration as invalid.
16097   if (T.isNull()) {
16098     InvalidDecl = true;
16099     T = Context.IntTy;
16100   }
16101 
16102   QualType EltTy = Context.getBaseElementType(T);
16103   if (!EltTy->isDependentType()) {
16104     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
16105       // Fields of incomplete type force their record to be invalid.
16106       Record->setInvalidDecl();
16107       InvalidDecl = true;
16108     } else {
16109       NamedDecl *Def;
16110       EltTy->isIncompleteType(&Def);
16111       if (Def && Def->isInvalidDecl()) {
16112         Record->setInvalidDecl();
16113         InvalidDecl = true;
16114       }
16115     }
16116   }
16117 
16118   // TR 18037 does not allow fields to be declared with address space
16119   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16120       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16121     Diag(Loc, diag::err_field_with_address_space);
16122     Record->setInvalidDecl();
16123     InvalidDecl = true;
16124   }
16125 
16126   if (LangOpts.OpenCL) {
16127     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16128     // used as structure or union field: image, sampler, event or block types.
16129     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16130         T->isBlockPointerType()) {
16131       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16132       Record->setInvalidDecl();
16133       InvalidDecl = true;
16134     }
16135     // OpenCL v1.2 s6.9.c: bitfields are not supported.
16136     if (BitWidth) {
16137       Diag(Loc, diag::err_opencl_bitfields);
16138       InvalidDecl = true;
16139     }
16140   }
16141 
16142   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16143   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16144       T.hasQualifiers()) {
16145     InvalidDecl = true;
16146     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16147   }
16148 
16149   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16150   // than a variably modified type.
16151   if (!InvalidDecl && T->isVariablyModifiedType()) {
16152     bool SizeIsNegative;
16153     llvm::APSInt Oversized;
16154 
16155     TypeSourceInfo *FixedTInfo =
16156       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16157                                                     SizeIsNegative,
16158                                                     Oversized);
16159     if (FixedTInfo) {
16160       Diag(Loc, diag::warn_illegal_constant_array_size);
16161       TInfo = FixedTInfo;
16162       T = FixedTInfo->getType();
16163     } else {
16164       if (SizeIsNegative)
16165         Diag(Loc, diag::err_typecheck_negative_array_size);
16166       else if (Oversized.getBoolValue())
16167         Diag(Loc, diag::err_array_too_large)
16168           << Oversized.toString(10);
16169       else
16170         Diag(Loc, diag::err_typecheck_field_variable_size);
16171       InvalidDecl = true;
16172     }
16173   }
16174 
16175   // Fields can not have abstract class types
16176   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16177                                              diag::err_abstract_type_in_decl,
16178                                              AbstractFieldType))
16179     InvalidDecl = true;
16180 
16181   bool ZeroWidth = false;
16182   if (InvalidDecl)
16183     BitWidth = nullptr;
16184   // If this is declared as a bit-field, check the bit-field.
16185   if (BitWidth) {
16186     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16187                               &ZeroWidth).get();
16188     if (!BitWidth) {
16189       InvalidDecl = true;
16190       BitWidth = nullptr;
16191       ZeroWidth = false;
16192     }
16193   }
16194 
16195   // Check that 'mutable' is consistent with the type of the declaration.
16196   if (!InvalidDecl && Mutable) {
16197     unsigned DiagID = 0;
16198     if (T->isReferenceType())
16199       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16200                                         : diag::err_mutable_reference;
16201     else if (T.isConstQualified())
16202       DiagID = diag::err_mutable_const;
16203 
16204     if (DiagID) {
16205       SourceLocation ErrLoc = Loc;
16206       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16207         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16208       Diag(ErrLoc, DiagID);
16209       if (DiagID != diag::ext_mutable_reference) {
16210         Mutable = false;
16211         InvalidDecl = true;
16212       }
16213     }
16214   }
16215 
16216   // C++11 [class.union]p8 (DR1460):
16217   //   At most one variant member of a union may have a
16218   //   brace-or-equal-initializer.
16219   if (InitStyle != ICIS_NoInit)
16220     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16221 
16222   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16223                                        BitWidth, Mutable, InitStyle);
16224   if (InvalidDecl)
16225     NewFD->setInvalidDecl();
16226 
16227   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16228     Diag(Loc, diag::err_duplicate_member) << II;
16229     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16230     NewFD->setInvalidDecl();
16231   }
16232 
16233   if (!InvalidDecl && getLangOpts().CPlusPlus) {
16234     if (Record->isUnion()) {
16235       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16236         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16237         if (RDecl->getDefinition()) {
16238           // C++ [class.union]p1: An object of a class with a non-trivial
16239           // constructor, a non-trivial copy constructor, a non-trivial
16240           // destructor, or a non-trivial copy assignment operator
16241           // cannot be a member of a union, nor can an array of such
16242           // objects.
16243           if (CheckNontrivialField(NewFD))
16244             NewFD->setInvalidDecl();
16245         }
16246       }
16247 
16248       // C++ [class.union]p1: If a union contains a member of reference type,
16249       // the program is ill-formed, except when compiling with MSVC extensions
16250       // enabled.
16251       if (EltTy->isReferenceType()) {
16252         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16253                                     diag::ext_union_member_of_reference_type :
16254                                     diag::err_union_member_of_reference_type)
16255           << NewFD->getDeclName() << EltTy;
16256         if (!getLangOpts().MicrosoftExt)
16257           NewFD->setInvalidDecl();
16258       }
16259     }
16260   }
16261 
16262   // FIXME: We need to pass in the attributes given an AST
16263   // representation, not a parser representation.
16264   if (D) {
16265     // FIXME: The current scope is almost... but not entirely... correct here.
16266     ProcessDeclAttributes(getCurScope(), NewFD, *D);
16267 
16268     if (NewFD->hasAttrs())
16269       CheckAlignasUnderalignment(NewFD);
16270   }
16271 
16272   // In auto-retain/release, infer strong retension for fields of
16273   // retainable type.
16274   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16275     NewFD->setInvalidDecl();
16276 
16277   if (T.isObjCGCWeak())
16278     Diag(Loc, diag::warn_attribute_weak_on_field);
16279 
16280   NewFD->setAccess(AS);
16281   return NewFD;
16282 }
16283 
16284 bool Sema::CheckNontrivialField(FieldDecl *FD) {
16285   assert(FD);
16286   assert(getLangOpts().CPlusPlus && "valid check only for C++");
16287 
16288   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16289     return false;
16290 
16291   QualType EltTy = Context.getBaseElementType(FD->getType());
16292   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16293     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16294     if (RDecl->getDefinition()) {
16295       // We check for copy constructors before constructors
16296       // because otherwise we'll never get complaints about
16297       // copy constructors.
16298 
16299       CXXSpecialMember member = CXXInvalid;
16300       // We're required to check for any non-trivial constructors. Since the
16301       // implicit default constructor is suppressed if there are any
16302       // user-declared constructors, we just need to check that there is a
16303       // trivial default constructor and a trivial copy constructor. (We don't
16304       // worry about move constructors here, since this is a C++98 check.)
16305       if (RDecl->hasNonTrivialCopyConstructor())
16306         member = CXXCopyConstructor;
16307       else if (!RDecl->hasTrivialDefaultConstructor())
16308         member = CXXDefaultConstructor;
16309       else if (RDecl->hasNonTrivialCopyAssignment())
16310         member = CXXCopyAssignment;
16311       else if (RDecl->hasNonTrivialDestructor())
16312         member = CXXDestructor;
16313 
16314       if (member != CXXInvalid) {
16315         if (!getLangOpts().CPlusPlus11 &&
16316             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16317           // Objective-C++ ARC: it is an error to have a non-trivial field of
16318           // a union. However, system headers in Objective-C programs
16319           // occasionally have Objective-C lifetime objects within unions,
16320           // and rather than cause the program to fail, we make those
16321           // members unavailable.
16322           SourceLocation Loc = FD->getLocation();
16323           if (getSourceManager().isInSystemHeader(Loc)) {
16324             if (!FD->hasAttr<UnavailableAttr>())
16325               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16326                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16327             return false;
16328           }
16329         }
16330 
16331         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16332                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16333                diag::err_illegal_union_or_anon_struct_member)
16334           << FD->getParent()->isUnion() << FD->getDeclName() << member;
16335         DiagnoseNontrivial(RDecl, member);
16336         return !getLangOpts().CPlusPlus11;
16337       }
16338     }
16339   }
16340 
16341   return false;
16342 }
16343 
16344 /// TranslateIvarVisibility - Translate visibility from a token ID to an
16345 ///  AST enum value.
16346 static ObjCIvarDecl::AccessControl
16347 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16348   switch (ivarVisibility) {
16349   default: llvm_unreachable("Unknown visitibility kind");
16350   case tok::objc_private: return ObjCIvarDecl::Private;
16351   case tok::objc_public: return ObjCIvarDecl::Public;
16352   case tok::objc_protected: return ObjCIvarDecl::Protected;
16353   case tok::objc_package: return ObjCIvarDecl::Package;
16354   }
16355 }
16356 
16357 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
16358 /// in order to create an IvarDecl object for it.
16359 Decl *Sema::ActOnIvar(Scope *S,
16360                                 SourceLocation DeclStart,
16361                                 Declarator &D, Expr *BitfieldWidth,
16362                                 tok::ObjCKeywordKind Visibility) {
16363 
16364   IdentifierInfo *II = D.getIdentifier();
16365   Expr *BitWidth = (Expr*)BitfieldWidth;
16366   SourceLocation Loc = DeclStart;
16367   if (II) Loc = D.getIdentifierLoc();
16368 
16369   // FIXME: Unnamed fields can be handled in various different ways, for
16370   // example, unnamed unions inject all members into the struct namespace!
16371 
16372   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16373   QualType T = TInfo->getType();
16374 
16375   if (BitWidth) {
16376     // 6.7.2.1p3, 6.7.2.1p4
16377     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16378     if (!BitWidth)
16379       D.setInvalidType();
16380   } else {
16381     // Not a bitfield.
16382 
16383     // validate II.
16384 
16385   }
16386   if (T->isReferenceType()) {
16387     Diag(Loc, diag::err_ivar_reference_type);
16388     D.setInvalidType();
16389   }
16390   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16391   // than a variably modified type.
16392   else if (T->isVariablyModifiedType()) {
16393     Diag(Loc, diag::err_typecheck_ivar_variable_size);
16394     D.setInvalidType();
16395   }
16396 
16397   // Get the visibility (access control) for this ivar.
16398   ObjCIvarDecl::AccessControl ac =
16399     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16400                                         : ObjCIvarDecl::None;
16401   // Must set ivar's DeclContext to its enclosing interface.
16402   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16403   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16404     return nullptr;
16405   ObjCContainerDecl *EnclosingContext;
16406   if (ObjCImplementationDecl *IMPDecl =
16407       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16408     if (LangOpts.ObjCRuntime.isFragile()) {
16409     // Case of ivar declared in an implementation. Context is that of its class.
16410       EnclosingContext = IMPDecl->getClassInterface();
16411       assert(EnclosingContext && "Implementation has no class interface!");
16412     }
16413     else
16414       EnclosingContext = EnclosingDecl;
16415   } else {
16416     if (ObjCCategoryDecl *CDecl =
16417         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16418       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16419         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16420         return nullptr;
16421       }
16422     }
16423     EnclosingContext = EnclosingDecl;
16424   }
16425 
16426   // Construct the decl.
16427   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16428                                              DeclStart, Loc, II, T,
16429                                              TInfo, ac, (Expr *)BitfieldWidth);
16430 
16431   if (II) {
16432     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16433                                            ForVisibleRedeclaration);
16434     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16435         && !isa<TagDecl>(PrevDecl)) {
16436       Diag(Loc, diag::err_duplicate_member) << II;
16437       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16438       NewID->setInvalidDecl();
16439     }
16440   }
16441 
16442   // Process attributes attached to the ivar.
16443   ProcessDeclAttributes(S, NewID, D);
16444 
16445   if (D.isInvalidType())
16446     NewID->setInvalidDecl();
16447 
16448   // In ARC, infer 'retaining' for ivars of retainable type.
16449   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16450     NewID->setInvalidDecl();
16451 
16452   if (D.getDeclSpec().isModulePrivateSpecified())
16453     NewID->setModulePrivate();
16454 
16455   if (II) {
16456     // FIXME: When interfaces are DeclContexts, we'll need to add
16457     // these to the interface.
16458     S->AddDecl(NewID);
16459     IdResolver.AddDecl(NewID);
16460   }
16461 
16462   if (LangOpts.ObjCRuntime.isNonFragile() &&
16463       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16464     Diag(Loc, diag::warn_ivars_in_interface);
16465 
16466   return NewID;
16467 }
16468 
16469 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16470 /// class and class extensions. For every class \@interface and class
16471 /// extension \@interface, if the last ivar is a bitfield of any type,
16472 /// then add an implicit `char :0` ivar to the end of that interface.
16473 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16474                              SmallVectorImpl<Decl *> &AllIvarDecls) {
16475   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16476     return;
16477 
16478   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16479   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16480 
16481   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16482     return;
16483   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16484   if (!ID) {
16485     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16486       if (!CD->IsClassExtension())
16487         return;
16488     }
16489     // No need to add this to end of @implementation.
16490     else
16491       return;
16492   }
16493   // All conditions are met. Add a new bitfield to the tail end of ivars.
16494   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16495   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16496 
16497   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
16498                               DeclLoc, DeclLoc, nullptr,
16499                               Context.CharTy,
16500                               Context.getTrivialTypeSourceInfo(Context.CharTy,
16501                                                                DeclLoc),
16502                               ObjCIvarDecl::Private, BW,
16503                               true);
16504   AllIvarDecls.push_back(Ivar);
16505 }
16506 
16507 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
16508                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
16509                        SourceLocation RBrac,
16510                        const ParsedAttributesView &Attrs) {
16511   assert(EnclosingDecl && "missing record or interface decl");
16512 
16513   // If this is an Objective-C @implementation or category and we have
16514   // new fields here we should reset the layout of the interface since
16515   // it will now change.
16516   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
16517     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
16518     switch (DC->getKind()) {
16519     default: break;
16520     case Decl::ObjCCategory:
16521       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
16522       break;
16523     case Decl::ObjCImplementation:
16524       Context.
16525         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
16526       break;
16527     }
16528   }
16529 
16530   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
16531   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
16532 
16533   // Start counting up the number of named members; make sure to include
16534   // members of anonymous structs and unions in the total.
16535   unsigned NumNamedMembers = 0;
16536   if (Record) {
16537     for (const auto *I : Record->decls()) {
16538       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
16539         if (IFD->getDeclName())
16540           ++NumNamedMembers;
16541     }
16542   }
16543 
16544   // Verify that all the fields are okay.
16545   SmallVector<FieldDecl*, 32> RecFields;
16546 
16547   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
16548        i != end; ++i) {
16549     FieldDecl *FD = cast<FieldDecl>(*i);
16550 
16551     // Get the type for the field.
16552     const Type *FDTy = FD->getType().getTypePtr();
16553 
16554     if (!FD->isAnonymousStructOrUnion()) {
16555       // Remember all fields written by the user.
16556       RecFields.push_back(FD);
16557     }
16558 
16559     // If the field is already invalid for some reason, don't emit more
16560     // diagnostics about it.
16561     if (FD->isInvalidDecl()) {
16562       EnclosingDecl->setInvalidDecl();
16563       continue;
16564     }
16565 
16566     // C99 6.7.2.1p2:
16567     //   A structure or union shall not contain a member with
16568     //   incomplete or function type (hence, a structure shall not
16569     //   contain an instance of itself, but may contain a pointer to
16570     //   an instance of itself), except that the last member of a
16571     //   structure with more than one named member may have incomplete
16572     //   array type; such a structure (and any union containing,
16573     //   possibly recursively, a member that is such a structure)
16574     //   shall not be a member of a structure or an element of an
16575     //   array.
16576     bool IsLastField = (i + 1 == Fields.end());
16577     if (FDTy->isFunctionType()) {
16578       // Field declared as a function.
16579       Diag(FD->getLocation(), diag::err_field_declared_as_function)
16580         << FD->getDeclName();
16581       FD->setInvalidDecl();
16582       EnclosingDecl->setInvalidDecl();
16583       continue;
16584     } else if (FDTy->isIncompleteArrayType() &&
16585                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16586       if (Record) {
16587         // Flexible array member.
16588         // Microsoft and g++ is more permissive regarding flexible array.
16589         // It will accept flexible array in union and also
16590         // as the sole element of a struct/class.
16591         unsigned DiagID = 0;
16592         if (!Record->isUnion() && !IsLastField) {
16593           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16594             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16595           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16596           FD->setInvalidDecl();
16597           EnclosingDecl->setInvalidDecl();
16598           continue;
16599         } else if (Record->isUnion())
16600           DiagID = getLangOpts().MicrosoftExt
16601                        ? diag::ext_flexible_array_union_ms
16602                        : getLangOpts().CPlusPlus
16603                              ? diag::ext_flexible_array_union_gnu
16604                              : diag::err_flexible_array_union;
16605         else if (NumNamedMembers < 1)
16606           DiagID = getLangOpts().MicrosoftExt
16607                        ? diag::ext_flexible_array_empty_aggregate_ms
16608                        : getLangOpts().CPlusPlus
16609                              ? diag::ext_flexible_array_empty_aggregate_gnu
16610                              : diag::err_flexible_array_empty_aggregate;
16611 
16612         if (DiagID)
16613           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16614                                           << Record->getTagKind();
16615         // While the layout of types that contain virtual bases is not specified
16616         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16617         // virtual bases after the derived members.  This would make a flexible
16618         // array member declared at the end of an object not adjacent to the end
16619         // of the type.
16620         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16621           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16622               << FD->getDeclName() << Record->getTagKind();
16623         if (!getLangOpts().C99)
16624           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16625             << FD->getDeclName() << Record->getTagKind();
16626 
16627         // If the element type has a non-trivial destructor, we would not
16628         // implicitly destroy the elements, so disallow it for now.
16629         //
16630         // FIXME: GCC allows this. We should probably either implicitly delete
16631         // the destructor of the containing class, or just allow this.
16632         QualType BaseElem = Context.getBaseElementType(FD->getType());
16633         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16634           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16635             << FD->getDeclName() << FD->getType();
16636           FD->setInvalidDecl();
16637           EnclosingDecl->setInvalidDecl();
16638           continue;
16639         }
16640         // Okay, we have a legal flexible array member at the end of the struct.
16641         Record->setHasFlexibleArrayMember(true);
16642       } else {
16643         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16644         // unless they are followed by another ivar. That check is done
16645         // elsewhere, after synthesized ivars are known.
16646       }
16647     } else if (!FDTy->isDependentType() &&
16648                RequireCompleteType(FD->getLocation(), FD->getType(),
16649                                    diag::err_field_incomplete)) {
16650       // Incomplete type
16651       FD->setInvalidDecl();
16652       EnclosingDecl->setInvalidDecl();
16653       continue;
16654     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16655       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16656         // A type which contains a flexible array member is considered to be a
16657         // flexible array member.
16658         Record->setHasFlexibleArrayMember(true);
16659         if (!Record->isUnion()) {
16660           // If this is a struct/class and this is not the last element, reject
16661           // it.  Note that GCC supports variable sized arrays in the middle of
16662           // structures.
16663           if (!IsLastField)
16664             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16665               << FD->getDeclName() << FD->getType();
16666           else {
16667             // We support flexible arrays at the end of structs in
16668             // other structs as an extension.
16669             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16670               << FD->getDeclName();
16671           }
16672         }
16673       }
16674       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16675           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16676                                  diag::err_abstract_type_in_decl,
16677                                  AbstractIvarType)) {
16678         // Ivars can not have abstract class types
16679         FD->setInvalidDecl();
16680       }
16681       if (Record && FDTTy->getDecl()->hasObjectMember())
16682         Record->setHasObjectMember(true);
16683       if (Record && FDTTy->getDecl()->hasVolatileMember())
16684         Record->setHasVolatileMember(true);
16685     } else if (FDTy->isObjCObjectType()) {
16686       /// A field cannot be an Objective-c object
16687       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16688         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16689       QualType T = Context.getObjCObjectPointerType(FD->getType());
16690       FD->setType(T);
16691     } else if (Record && Record->isUnion() &&
16692                FD->getType().hasNonTrivialObjCLifetime() &&
16693                getSourceManager().isInSystemHeader(FD->getLocation()) &&
16694                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
16695                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
16696                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
16697       // For backward compatibility, fields of C unions declared in system
16698       // headers that have non-trivial ObjC ownership qualifications are marked
16699       // as unavailable unless the qualifier is explicit and __strong. This can
16700       // break ABI compatibility between programs compiled with ARC and MRR, but
16701       // is a better option than rejecting programs using those unions under
16702       // ARC.
16703       FD->addAttr(UnavailableAttr::CreateImplicit(
16704           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
16705           FD->getLocation()));
16706     } else if (getLangOpts().ObjC &&
16707                getLangOpts().getGC() != LangOptions::NonGC &&
16708                Record && !Record->hasObjectMember()) {
16709       if (FD->getType()->isObjCObjectPointerType() ||
16710           FD->getType().isObjCGCStrong())
16711         Record->setHasObjectMember(true);
16712       else if (Context.getAsArrayType(FD->getType())) {
16713         QualType BaseType = Context.getBaseElementType(FD->getType());
16714         if (BaseType->isRecordType() &&
16715             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
16716           Record->setHasObjectMember(true);
16717         else if (BaseType->isObjCObjectPointerType() ||
16718                  BaseType.isObjCGCStrong())
16719                Record->setHasObjectMember(true);
16720       }
16721     }
16722 
16723     if (Record && !getLangOpts().CPlusPlus &&
16724         !shouldIgnoreForRecordTriviality(FD)) {
16725       QualType FT = FD->getType();
16726       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
16727         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16728         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
16729             Record->isUnion())
16730           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
16731       }
16732       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16733       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
16734         Record->setNonTrivialToPrimitiveCopy(true);
16735         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
16736           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
16737       }
16738       if (FT.isDestructedType()) {
16739         Record->setNonTrivialToPrimitiveDestroy(true);
16740         Record->setParamDestroyedInCallee(true);
16741         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
16742           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
16743       }
16744 
16745       if (const auto *RT = FT->getAs<RecordType>()) {
16746         if (RT->getDecl()->getArgPassingRestrictions() ==
16747             RecordDecl::APK_CanNeverPassInRegs)
16748           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16749       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16750         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16751     }
16752 
16753     if (Record && FD->getType().isVolatileQualified())
16754       Record->setHasVolatileMember(true);
16755     // Keep track of the number of named members.
16756     if (FD->getIdentifier())
16757       ++NumNamedMembers;
16758   }
16759 
16760   // Okay, we successfully defined 'Record'.
16761   if (Record) {
16762     bool Completed = false;
16763     if (CXXRecord) {
16764       if (!CXXRecord->isInvalidDecl()) {
16765         // Set access bits correctly on the directly-declared conversions.
16766         for (CXXRecordDecl::conversion_iterator
16767                I = CXXRecord->conversion_begin(),
16768                E = CXXRecord->conversion_end(); I != E; ++I)
16769           I.setAccess((*I)->getAccess());
16770       }
16771 
16772       if (!CXXRecord->isDependentType()) {
16773         // Add any implicitly-declared members to this class.
16774         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16775 
16776         if (!CXXRecord->isInvalidDecl()) {
16777           // If we have virtual base classes, we may end up finding multiple
16778           // final overriders for a given virtual function. Check for this
16779           // problem now.
16780           if (CXXRecord->getNumVBases()) {
16781             CXXFinalOverriderMap FinalOverriders;
16782             CXXRecord->getFinalOverriders(FinalOverriders);
16783 
16784             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16785                                              MEnd = FinalOverriders.end();
16786                  M != MEnd; ++M) {
16787               for (OverridingMethods::iterator SO = M->second.begin(),
16788                                             SOEnd = M->second.end();
16789                    SO != SOEnd; ++SO) {
16790                 assert(SO->second.size() > 0 &&
16791                        "Virtual function without overriding functions?");
16792                 if (SO->second.size() == 1)
16793                   continue;
16794 
16795                 // C++ [class.virtual]p2:
16796                 //   In a derived class, if a virtual member function of a base
16797                 //   class subobject has more than one final overrider the
16798                 //   program is ill-formed.
16799                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16800                   << (const NamedDecl *)M->first << Record;
16801                 Diag(M->first->getLocation(),
16802                      diag::note_overridden_virtual_function);
16803                 for (OverridingMethods::overriding_iterator
16804                           OM = SO->second.begin(),
16805                        OMEnd = SO->second.end();
16806                      OM != OMEnd; ++OM)
16807                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16808                     << (const NamedDecl *)M->first << OM->Method->getParent();
16809 
16810                 Record->setInvalidDecl();
16811               }
16812             }
16813             CXXRecord->completeDefinition(&FinalOverriders);
16814             Completed = true;
16815           }
16816         }
16817       }
16818     }
16819 
16820     if (!Completed)
16821       Record->completeDefinition();
16822 
16823     // Handle attributes before checking the layout.
16824     ProcessDeclAttributeList(S, Record, Attrs);
16825 
16826     // We may have deferred checking for a deleted destructor. Check now.
16827     if (CXXRecord) {
16828       auto *Dtor = CXXRecord->getDestructor();
16829       if (Dtor && Dtor->isImplicit() &&
16830           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16831         CXXRecord->setImplicitDestructorIsDeleted();
16832         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16833       }
16834     }
16835 
16836     if (Record->hasAttrs()) {
16837       CheckAlignasUnderalignment(Record);
16838 
16839       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16840         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16841                                            IA->getRange(), IA->getBestCase(),
16842                                            IA->getInheritanceModel());
16843     }
16844 
16845     // Check if the structure/union declaration is a type that can have zero
16846     // size in C. For C this is a language extension, for C++ it may cause
16847     // compatibility problems.
16848     bool CheckForZeroSize;
16849     if (!getLangOpts().CPlusPlus) {
16850       CheckForZeroSize = true;
16851     } else {
16852       // For C++ filter out types that cannot be referenced in C code.
16853       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16854       CheckForZeroSize =
16855           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16856           !CXXRecord->isDependentType() &&
16857           CXXRecord->isCLike();
16858     }
16859     if (CheckForZeroSize) {
16860       bool ZeroSize = true;
16861       bool IsEmpty = true;
16862       unsigned NonBitFields = 0;
16863       for (RecordDecl::field_iterator I = Record->field_begin(),
16864                                       E = Record->field_end();
16865            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16866         IsEmpty = false;
16867         if (I->isUnnamedBitfield()) {
16868           if (!I->isZeroLengthBitField(Context))
16869             ZeroSize = false;
16870         } else {
16871           ++NonBitFields;
16872           QualType FieldType = I->getType();
16873           if (FieldType->isIncompleteType() ||
16874               !Context.getTypeSizeInChars(FieldType).isZero())
16875             ZeroSize = false;
16876         }
16877       }
16878 
16879       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16880       // allowed in C++, but warn if its declaration is inside
16881       // extern "C" block.
16882       if (ZeroSize) {
16883         Diag(RecLoc, getLangOpts().CPlusPlus ?
16884                          diag::warn_zero_size_struct_union_in_extern_c :
16885                          diag::warn_zero_size_struct_union_compat)
16886           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16887       }
16888 
16889       // Structs without named members are extension in C (C99 6.7.2.1p7),
16890       // but are accepted by GCC.
16891       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16892         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16893                                diag::ext_no_named_members_in_struct_union)
16894           << Record->isUnion();
16895       }
16896     }
16897   } else {
16898     ObjCIvarDecl **ClsFields =
16899       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16900     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16901       ID->setEndOfDefinitionLoc(RBrac);
16902       // Add ivar's to class's DeclContext.
16903       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16904         ClsFields[i]->setLexicalDeclContext(ID);
16905         ID->addDecl(ClsFields[i]);
16906       }
16907       // Must enforce the rule that ivars in the base classes may not be
16908       // duplicates.
16909       if (ID->getSuperClass())
16910         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16911     } else if (ObjCImplementationDecl *IMPDecl =
16912                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16913       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16914       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16915         // Ivar declared in @implementation never belongs to the implementation.
16916         // Only it is in implementation's lexical context.
16917         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16918       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16919       IMPDecl->setIvarLBraceLoc(LBrac);
16920       IMPDecl->setIvarRBraceLoc(RBrac);
16921     } else if (ObjCCategoryDecl *CDecl =
16922                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16923       // case of ivars in class extension; all other cases have been
16924       // reported as errors elsewhere.
16925       // FIXME. Class extension does not have a LocEnd field.
16926       // CDecl->setLocEnd(RBrac);
16927       // Add ivar's to class extension's DeclContext.
16928       // Diagnose redeclaration of private ivars.
16929       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16930       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16931         if (IDecl) {
16932           if (const ObjCIvarDecl *ClsIvar =
16933               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16934             Diag(ClsFields[i]->getLocation(),
16935                  diag::err_duplicate_ivar_declaration);
16936             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16937             continue;
16938           }
16939           for (const auto *Ext : IDecl->known_extensions()) {
16940             if (const ObjCIvarDecl *ClsExtIvar
16941                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16942               Diag(ClsFields[i]->getLocation(),
16943                    diag::err_duplicate_ivar_declaration);
16944               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16945               continue;
16946             }
16947           }
16948         }
16949         ClsFields[i]->setLexicalDeclContext(CDecl);
16950         CDecl->addDecl(ClsFields[i]);
16951       }
16952       CDecl->setIvarLBraceLoc(LBrac);
16953       CDecl->setIvarRBraceLoc(RBrac);
16954     }
16955   }
16956 }
16957 
16958 /// Determine whether the given integral value is representable within
16959 /// the given type T.
16960 static bool isRepresentableIntegerValue(ASTContext &Context,
16961                                         llvm::APSInt &Value,
16962                                         QualType T) {
16963   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16964          "Integral type required!");
16965   unsigned BitWidth = Context.getIntWidth(T);
16966 
16967   if (Value.isUnsigned() || Value.isNonNegative()) {
16968     if (T->isSignedIntegerOrEnumerationType())
16969       --BitWidth;
16970     return Value.getActiveBits() <= BitWidth;
16971   }
16972   return Value.getMinSignedBits() <= BitWidth;
16973 }
16974 
16975 // Given an integral type, return the next larger integral type
16976 // (or a NULL type of no such type exists).
16977 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16978   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16979   // enum checking below.
16980   assert((T->isIntegralType(Context) ||
16981          T->isEnumeralType()) && "Integral type required!");
16982   const unsigned NumTypes = 4;
16983   QualType SignedIntegralTypes[NumTypes] = {
16984     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16985   };
16986   QualType UnsignedIntegralTypes[NumTypes] = {
16987     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16988     Context.UnsignedLongLongTy
16989   };
16990 
16991   unsigned BitWidth = Context.getTypeSize(T);
16992   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16993                                                         : UnsignedIntegralTypes;
16994   for (unsigned I = 0; I != NumTypes; ++I)
16995     if (Context.getTypeSize(Types[I]) > BitWidth)
16996       return Types[I];
16997 
16998   return QualType();
16999 }
17000 
17001 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17002                                           EnumConstantDecl *LastEnumConst,
17003                                           SourceLocation IdLoc,
17004                                           IdentifierInfo *Id,
17005                                           Expr *Val) {
17006   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17007   llvm::APSInt EnumVal(IntWidth);
17008   QualType EltTy;
17009 
17010   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17011     Val = nullptr;
17012 
17013   if (Val)
17014     Val = DefaultLvalueConversion(Val).get();
17015 
17016   if (Val) {
17017     if (Enum->isDependentType() || Val->isTypeDependent())
17018       EltTy = Context.DependentTy;
17019     else {
17020       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17021         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17022         // constant-expression in the enumerator-definition shall be a converted
17023         // constant expression of the underlying type.
17024         EltTy = Enum->getIntegerType();
17025         ExprResult Converted =
17026           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17027                                            CCEK_Enumerator);
17028         if (Converted.isInvalid())
17029           Val = nullptr;
17030         else
17031           Val = Converted.get();
17032       } else if (!Val->isValueDependent() &&
17033                  !(Val = VerifyIntegerConstantExpression(Val,
17034                                                          &EnumVal).get())) {
17035         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17036       } else {
17037         if (Enum->isComplete()) {
17038           EltTy = Enum->getIntegerType();
17039 
17040           // In Obj-C and Microsoft mode, require the enumeration value to be
17041           // representable in the underlying type of the enumeration. In C++11,
17042           // we perform a non-narrowing conversion as part of converted constant
17043           // expression checking.
17044           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17045             if (Context.getTargetInfo()
17046                     .getTriple()
17047                     .isWindowsMSVCEnvironment()) {
17048               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17049             } else {
17050               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17051             }
17052           }
17053 
17054           // Cast to the underlying type.
17055           Val = ImpCastExprToType(Val, EltTy,
17056                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17057                                                          : CK_IntegralCast)
17058                     .get();
17059         } else if (getLangOpts().CPlusPlus) {
17060           // C++11 [dcl.enum]p5:
17061           //   If the underlying type is not fixed, the type of each enumerator
17062           //   is the type of its initializing value:
17063           //     - If an initializer is specified for an enumerator, the
17064           //       initializing value has the same type as the expression.
17065           EltTy = Val->getType();
17066         } else {
17067           // C99 6.7.2.2p2:
17068           //   The expression that defines the value of an enumeration constant
17069           //   shall be an integer constant expression that has a value
17070           //   representable as an int.
17071 
17072           // Complain if the value is not representable in an int.
17073           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17074             Diag(IdLoc, diag::ext_enum_value_not_int)
17075               << EnumVal.toString(10) << Val->getSourceRange()
17076               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17077           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17078             // Force the type of the expression to 'int'.
17079             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17080           }
17081           EltTy = Val->getType();
17082         }
17083       }
17084     }
17085   }
17086 
17087   if (!Val) {
17088     if (Enum->isDependentType())
17089       EltTy = Context.DependentTy;
17090     else if (!LastEnumConst) {
17091       // C++0x [dcl.enum]p5:
17092       //   If the underlying type is not fixed, the type of each enumerator
17093       //   is the type of its initializing value:
17094       //     - If no initializer is specified for the first enumerator, the
17095       //       initializing value has an unspecified integral type.
17096       //
17097       // GCC uses 'int' for its unspecified integral type, as does
17098       // C99 6.7.2.2p3.
17099       if (Enum->isFixed()) {
17100         EltTy = Enum->getIntegerType();
17101       }
17102       else {
17103         EltTy = Context.IntTy;
17104       }
17105     } else {
17106       // Assign the last value + 1.
17107       EnumVal = LastEnumConst->getInitVal();
17108       ++EnumVal;
17109       EltTy = LastEnumConst->getType();
17110 
17111       // Check for overflow on increment.
17112       if (EnumVal < LastEnumConst->getInitVal()) {
17113         // C++0x [dcl.enum]p5:
17114         //   If the underlying type is not fixed, the type of each enumerator
17115         //   is the type of its initializing value:
17116         //
17117         //     - Otherwise the type of the initializing value is the same as
17118         //       the type of the initializing value of the preceding enumerator
17119         //       unless the incremented value is not representable in that type,
17120         //       in which case the type is an unspecified integral type
17121         //       sufficient to contain the incremented value. If no such type
17122         //       exists, the program is ill-formed.
17123         QualType T = getNextLargerIntegralType(Context, EltTy);
17124         if (T.isNull() || Enum->isFixed()) {
17125           // There is no integral type larger enough to represent this
17126           // value. Complain, then allow the value to wrap around.
17127           EnumVal = LastEnumConst->getInitVal();
17128           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17129           ++EnumVal;
17130           if (Enum->isFixed())
17131             // When the underlying type is fixed, this is ill-formed.
17132             Diag(IdLoc, diag::err_enumerator_wrapped)
17133               << EnumVal.toString(10)
17134               << EltTy;
17135           else
17136             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17137               << EnumVal.toString(10);
17138         } else {
17139           EltTy = T;
17140         }
17141 
17142         // Retrieve the last enumerator's value, extent that type to the
17143         // type that is supposed to be large enough to represent the incremented
17144         // value, then increment.
17145         EnumVal = LastEnumConst->getInitVal();
17146         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17147         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17148         ++EnumVal;
17149 
17150         // If we're not in C++, diagnose the overflow of enumerator values,
17151         // which in C99 means that the enumerator value is not representable in
17152         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17153         // permits enumerator values that are representable in some larger
17154         // integral type.
17155         if (!getLangOpts().CPlusPlus && !T.isNull())
17156           Diag(IdLoc, diag::warn_enum_value_overflow);
17157       } else if (!getLangOpts().CPlusPlus &&
17158                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17159         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17160         Diag(IdLoc, diag::ext_enum_value_not_int)
17161           << EnumVal.toString(10) << 1;
17162       }
17163     }
17164   }
17165 
17166   if (!EltTy->isDependentType()) {
17167     // Make the enumerator value match the signedness and size of the
17168     // enumerator's type.
17169     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17170     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17171   }
17172 
17173   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17174                                   Val, EnumVal);
17175 }
17176 
17177 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17178                                                 SourceLocation IILoc) {
17179   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17180       !getLangOpts().CPlusPlus)
17181     return SkipBodyInfo();
17182 
17183   // We have an anonymous enum definition. Look up the first enumerator to
17184   // determine if we should merge the definition with an existing one and
17185   // skip the body.
17186   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17187                                          forRedeclarationInCurContext());
17188   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17189   if (!PrevECD)
17190     return SkipBodyInfo();
17191 
17192   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17193   NamedDecl *Hidden;
17194   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17195     SkipBodyInfo Skip;
17196     Skip.Previous = Hidden;
17197     return Skip;
17198   }
17199 
17200   return SkipBodyInfo();
17201 }
17202 
17203 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17204                               SourceLocation IdLoc, IdentifierInfo *Id,
17205                               const ParsedAttributesView &Attrs,
17206                               SourceLocation EqualLoc, Expr *Val) {
17207   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17208   EnumConstantDecl *LastEnumConst =
17209     cast_or_null<EnumConstantDecl>(lastEnumConst);
17210 
17211   // The scope passed in may not be a decl scope.  Zip up the scope tree until
17212   // we find one that is.
17213   S = getNonFieldDeclScope(S);
17214 
17215   // Verify that there isn't already something declared with this name in this
17216   // scope.
17217   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17218   LookupName(R, S);
17219   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17220 
17221   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17222     // Maybe we will complain about the shadowed template parameter.
17223     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17224     // Just pretend that we didn't see the previous declaration.
17225     PrevDecl = nullptr;
17226   }
17227 
17228   // C++ [class.mem]p15:
17229   // If T is the name of a class, then each of the following shall have a name
17230   // different from T:
17231   // - every enumerator of every member of class T that is an unscoped
17232   // enumerated type
17233   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17234     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17235                             DeclarationNameInfo(Id, IdLoc));
17236 
17237   EnumConstantDecl *New =
17238     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17239   if (!New)
17240     return nullptr;
17241 
17242   if (PrevDecl) {
17243     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17244       // Check for other kinds of shadowing not already handled.
17245       CheckShadow(New, PrevDecl, R);
17246     }
17247 
17248     // When in C++, we may get a TagDecl with the same name; in this case the
17249     // enum constant will 'hide' the tag.
17250     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
17251            "Received TagDecl when not in C++!");
17252     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17253       if (isa<EnumConstantDecl>(PrevDecl))
17254         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17255       else
17256         Diag(IdLoc, diag::err_redefinition) << Id;
17257       notePreviousDefinition(PrevDecl, IdLoc);
17258       return nullptr;
17259     }
17260   }
17261 
17262   // Process attributes.
17263   ProcessDeclAttributeList(S, New, Attrs);
17264   AddPragmaAttributes(S, New);
17265 
17266   // Register this decl in the current scope stack.
17267   New->setAccess(TheEnumDecl->getAccess());
17268   PushOnScopeChains(New, S);
17269 
17270   ActOnDocumentableDecl(New);
17271 
17272   return New;
17273 }
17274 
17275 // Returns true when the enum initial expression does not trigger the
17276 // duplicate enum warning.  A few common cases are exempted as follows:
17277 // Element2 = Element1
17278 // Element2 = Element1 + 1
17279 // Element2 = Element1 - 1
17280 // Where Element2 and Element1 are from the same enum.
17281 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17282   Expr *InitExpr = ECD->getInitExpr();
17283   if (!InitExpr)
17284     return true;
17285   InitExpr = InitExpr->IgnoreImpCasts();
17286 
17287   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17288     if (!BO->isAdditiveOp())
17289       return true;
17290     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17291     if (!IL)
17292       return true;
17293     if (IL->getValue() != 1)
17294       return true;
17295 
17296     InitExpr = BO->getLHS();
17297   }
17298 
17299   // This checks if the elements are from the same enum.
17300   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17301   if (!DRE)
17302     return true;
17303 
17304   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17305   if (!EnumConstant)
17306     return true;
17307 
17308   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17309       Enum)
17310     return true;
17311 
17312   return false;
17313 }
17314 
17315 // Emits a warning when an element is implicitly set a value that
17316 // a previous element has already been set to.
17317 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17318                                         EnumDecl *Enum, QualType EnumType) {
17319   // Avoid anonymous enums
17320   if (!Enum->getIdentifier())
17321     return;
17322 
17323   // Only check for small enums.
17324   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17325     return;
17326 
17327   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17328     return;
17329 
17330   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17331   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17332 
17333   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17334   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17335 
17336   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
17337   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17338     llvm::APSInt Val = D->getInitVal();
17339     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17340   };
17341 
17342   DuplicatesVector DupVector;
17343   ValueToVectorMap EnumMap;
17344 
17345   // Populate the EnumMap with all values represented by enum constants without
17346   // an initializer.
17347   for (auto *Element : Elements) {
17348     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17349 
17350     // Null EnumConstantDecl means a previous diagnostic has been emitted for
17351     // this constant.  Skip this enum since it may be ill-formed.
17352     if (!ECD) {
17353       return;
17354     }
17355 
17356     // Constants with initalizers are handled in the next loop.
17357     if (ECD->getInitExpr())
17358       continue;
17359 
17360     // Duplicate values are handled in the next loop.
17361     EnumMap.insert({EnumConstantToKey(ECD), ECD});
17362   }
17363 
17364   if (EnumMap.size() == 0)
17365     return;
17366 
17367   // Create vectors for any values that has duplicates.
17368   for (auto *Element : Elements) {
17369     // The last loop returned if any constant was null.
17370     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17371     if (!ValidDuplicateEnum(ECD, Enum))
17372       continue;
17373 
17374     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17375     if (Iter == EnumMap.end())
17376       continue;
17377 
17378     DeclOrVector& Entry = Iter->second;
17379     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17380       // Ensure constants are different.
17381       if (D == ECD)
17382         continue;
17383 
17384       // Create new vector and push values onto it.
17385       auto Vec = std::make_unique<ECDVector>();
17386       Vec->push_back(D);
17387       Vec->push_back(ECD);
17388 
17389       // Update entry to point to the duplicates vector.
17390       Entry = Vec.get();
17391 
17392       // Store the vector somewhere we can consult later for quick emission of
17393       // diagnostics.
17394       DupVector.emplace_back(std::move(Vec));
17395       continue;
17396     }
17397 
17398     ECDVector *Vec = Entry.get<ECDVector*>();
17399     // Make sure constants are not added more than once.
17400     if (*Vec->begin() == ECD)
17401       continue;
17402 
17403     Vec->push_back(ECD);
17404   }
17405 
17406   // Emit diagnostics.
17407   for (const auto &Vec : DupVector) {
17408     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
17409 
17410     // Emit warning for one enum constant.
17411     auto *FirstECD = Vec->front();
17412     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17413       << FirstECD << FirstECD->getInitVal().toString(10)
17414       << FirstECD->getSourceRange();
17415 
17416     // Emit one note for each of the remaining enum constants with
17417     // the same value.
17418     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17419       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17420         << ECD << ECD->getInitVal().toString(10)
17421         << ECD->getSourceRange();
17422   }
17423 }
17424 
17425 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17426                              bool AllowMask) const {
17427   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
17428   assert(ED->isCompleteDefinition() && "expected enum definition");
17429 
17430   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17431   llvm::APInt &FlagBits = R.first->second;
17432 
17433   if (R.second) {
17434     for (auto *E : ED->enumerators()) {
17435       const auto &EVal = E->getInitVal();
17436       // Only single-bit enumerators introduce new flag values.
17437       if (EVal.isPowerOf2())
17438         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17439     }
17440   }
17441 
17442   // A value is in a flag enum if either its bits are a subset of the enum's
17443   // flag bits (the first condition) or we are allowing masks and the same is
17444   // true of its complement (the second condition). When masks are allowed, we
17445   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17446   //
17447   // While it's true that any value could be used as a mask, the assumption is
17448   // that a mask will have all of the insignificant bits set. Anything else is
17449   // likely a logic error.
17450   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17451   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17452 }
17453 
17454 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17455                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17456                          const ParsedAttributesView &Attrs) {
17457   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17458   QualType EnumType = Context.getTypeDeclType(Enum);
17459 
17460   ProcessDeclAttributeList(S, Enum, Attrs);
17461 
17462   if (Enum->isDependentType()) {
17463     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17464       EnumConstantDecl *ECD =
17465         cast_or_null<EnumConstantDecl>(Elements[i]);
17466       if (!ECD) continue;
17467 
17468       ECD->setType(EnumType);
17469     }
17470 
17471     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17472     return;
17473   }
17474 
17475   // TODO: If the result value doesn't fit in an int, it must be a long or long
17476   // long value.  ISO C does not support this, but GCC does as an extension,
17477   // emit a warning.
17478   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17479   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17480   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17481 
17482   // Verify that all the values are okay, compute the size of the values, and
17483   // reverse the list.
17484   unsigned NumNegativeBits = 0;
17485   unsigned NumPositiveBits = 0;
17486 
17487   // Keep track of whether all elements have type int.
17488   bool AllElementsInt = true;
17489 
17490   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17491     EnumConstantDecl *ECD =
17492       cast_or_null<EnumConstantDecl>(Elements[i]);
17493     if (!ECD) continue;  // Already issued a diagnostic.
17494 
17495     const llvm::APSInt &InitVal = ECD->getInitVal();
17496 
17497     // Keep track of the size of positive and negative values.
17498     if (InitVal.isUnsigned() || InitVal.isNonNegative())
17499       NumPositiveBits = std::max(NumPositiveBits,
17500                                  (unsigned)InitVal.getActiveBits());
17501     else
17502       NumNegativeBits = std::max(NumNegativeBits,
17503                                  (unsigned)InitVal.getMinSignedBits());
17504 
17505     // Keep track of whether every enum element has type int (very common).
17506     if (AllElementsInt)
17507       AllElementsInt = ECD->getType() == Context.IntTy;
17508   }
17509 
17510   // Figure out the type that should be used for this enum.
17511   QualType BestType;
17512   unsigned BestWidth;
17513 
17514   // C++0x N3000 [conv.prom]p3:
17515   //   An rvalue of an unscoped enumeration type whose underlying
17516   //   type is not fixed can be converted to an rvalue of the first
17517   //   of the following types that can represent all the values of
17518   //   the enumeration: int, unsigned int, long int, unsigned long
17519   //   int, long long int, or unsigned long long int.
17520   // C99 6.4.4.3p2:
17521   //   An identifier declared as an enumeration constant has type int.
17522   // The C99 rule is modified by a gcc extension
17523   QualType BestPromotionType;
17524 
17525   bool Packed = Enum->hasAttr<PackedAttr>();
17526   // -fshort-enums is the equivalent to specifying the packed attribute on all
17527   // enum definitions.
17528   if (LangOpts.ShortEnums)
17529     Packed = true;
17530 
17531   // If the enum already has a type because it is fixed or dictated by the
17532   // target, promote that type instead of analyzing the enumerators.
17533   if (Enum->isComplete()) {
17534     BestType = Enum->getIntegerType();
17535     if (BestType->isPromotableIntegerType())
17536       BestPromotionType = Context.getPromotedIntegerType(BestType);
17537     else
17538       BestPromotionType = BestType;
17539 
17540     BestWidth = Context.getIntWidth(BestType);
17541   }
17542   else if (NumNegativeBits) {
17543     // If there is a negative value, figure out the smallest integer type (of
17544     // int/long/longlong) that fits.
17545     // If it's packed, check also if it fits a char or a short.
17546     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
17547       BestType = Context.SignedCharTy;
17548       BestWidth = CharWidth;
17549     } else if (Packed && NumNegativeBits <= ShortWidth &&
17550                NumPositiveBits < ShortWidth) {
17551       BestType = Context.ShortTy;
17552       BestWidth = ShortWidth;
17553     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
17554       BestType = Context.IntTy;
17555       BestWidth = IntWidth;
17556     } else {
17557       BestWidth = Context.getTargetInfo().getLongWidth();
17558 
17559       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
17560         BestType = Context.LongTy;
17561       } else {
17562         BestWidth = Context.getTargetInfo().getLongLongWidth();
17563 
17564         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
17565           Diag(Enum->getLocation(), diag::ext_enum_too_large);
17566         BestType = Context.LongLongTy;
17567       }
17568     }
17569     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
17570   } else {
17571     // If there is no negative value, figure out the smallest type that fits
17572     // all of the enumerator values.
17573     // If it's packed, check also if it fits a char or a short.
17574     if (Packed && NumPositiveBits <= CharWidth) {
17575       BestType = Context.UnsignedCharTy;
17576       BestPromotionType = Context.IntTy;
17577       BestWidth = CharWidth;
17578     } else if (Packed && NumPositiveBits <= ShortWidth) {
17579       BestType = Context.UnsignedShortTy;
17580       BestPromotionType = Context.IntTy;
17581       BestWidth = ShortWidth;
17582     } else if (NumPositiveBits <= IntWidth) {
17583       BestType = Context.UnsignedIntTy;
17584       BestWidth = IntWidth;
17585       BestPromotionType
17586         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17587                            ? Context.UnsignedIntTy : Context.IntTy;
17588     } else if (NumPositiveBits <=
17589                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17590       BestType = Context.UnsignedLongTy;
17591       BestPromotionType
17592         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17593                            ? Context.UnsignedLongTy : Context.LongTy;
17594     } else {
17595       BestWidth = Context.getTargetInfo().getLongLongWidth();
17596       assert(NumPositiveBits <= BestWidth &&
17597              "How could an initializer get larger than ULL?");
17598       BestType = Context.UnsignedLongLongTy;
17599       BestPromotionType
17600         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17601                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17602     }
17603   }
17604 
17605   // Loop over all of the enumerator constants, changing their types to match
17606   // the type of the enum if needed.
17607   for (auto *D : Elements) {
17608     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17609     if (!ECD) continue;  // Already issued a diagnostic.
17610 
17611     // Standard C says the enumerators have int type, but we allow, as an
17612     // extension, the enumerators to be larger than int size.  If each
17613     // enumerator value fits in an int, type it as an int, otherwise type it the
17614     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17615     // that X has type 'int', not 'unsigned'.
17616 
17617     // Determine whether the value fits into an int.
17618     llvm::APSInt InitVal = ECD->getInitVal();
17619 
17620     // If it fits into an integer type, force it.  Otherwise force it to match
17621     // the enum decl type.
17622     QualType NewTy;
17623     unsigned NewWidth;
17624     bool NewSign;
17625     if (!getLangOpts().CPlusPlus &&
17626         !Enum->isFixed() &&
17627         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17628       NewTy = Context.IntTy;
17629       NewWidth = IntWidth;
17630       NewSign = true;
17631     } else if (ECD->getType() == BestType) {
17632       // Already the right type!
17633       if (getLangOpts().CPlusPlus)
17634         // C++ [dcl.enum]p4: Following the closing brace of an
17635         // enum-specifier, each enumerator has the type of its
17636         // enumeration.
17637         ECD->setType(EnumType);
17638       continue;
17639     } else {
17640       NewTy = BestType;
17641       NewWidth = BestWidth;
17642       NewSign = BestType->isSignedIntegerOrEnumerationType();
17643     }
17644 
17645     // Adjust the APSInt value.
17646     InitVal = InitVal.extOrTrunc(NewWidth);
17647     InitVal.setIsSigned(NewSign);
17648     ECD->setInitVal(InitVal);
17649 
17650     // Adjust the Expr initializer and type.
17651     if (ECD->getInitExpr() &&
17652         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17653       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17654                                                 CK_IntegralCast,
17655                                                 ECD->getInitExpr(),
17656                                                 /*base paths*/ nullptr,
17657                                                 VK_RValue));
17658     if (getLangOpts().CPlusPlus)
17659       // C++ [dcl.enum]p4: Following the closing brace of an
17660       // enum-specifier, each enumerator has the type of its
17661       // enumeration.
17662       ECD->setType(EnumType);
17663     else
17664       ECD->setType(NewTy);
17665   }
17666 
17667   Enum->completeDefinition(BestType, BestPromotionType,
17668                            NumPositiveBits, NumNegativeBits);
17669 
17670   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17671 
17672   if (Enum->isClosedFlag()) {
17673     for (Decl *D : Elements) {
17674       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17675       if (!ECD) continue;  // Already issued a diagnostic.
17676 
17677       llvm::APSInt InitVal = ECD->getInitVal();
17678       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17679           !IsValueInFlagEnum(Enum, InitVal, true))
17680         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17681           << ECD << Enum;
17682     }
17683   }
17684 
17685   // Now that the enum type is defined, ensure it's not been underaligned.
17686   if (Enum->hasAttrs())
17687     CheckAlignasUnderalignment(Enum);
17688 }
17689 
17690 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17691                                   SourceLocation StartLoc,
17692                                   SourceLocation EndLoc) {
17693   StringLiteral *AsmString = cast<StringLiteral>(expr);
17694 
17695   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17696                                                    AsmString, StartLoc,
17697                                                    EndLoc);
17698   CurContext->addDecl(New);
17699   return New;
17700 }
17701 
17702 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17703                                       IdentifierInfo* AliasName,
17704                                       SourceLocation PragmaLoc,
17705                                       SourceLocation NameLoc,
17706                                       SourceLocation AliasNameLoc) {
17707   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17708                                          LookupOrdinaryName);
17709   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
17710                            AttributeCommonInfo::AS_Pragma);
17711   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
17712       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
17713 
17714   // If a declaration that:
17715   // 1) declares a function or a variable
17716   // 2) has external linkage
17717   // already exists, add a label attribute to it.
17718   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17719     if (isDeclExternC(PrevDecl))
17720       PrevDecl->addAttr(Attr);
17721     else
17722       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17723           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17724   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17725   } else
17726     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17727 }
17728 
17729 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17730                              SourceLocation PragmaLoc,
17731                              SourceLocation NameLoc) {
17732   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17733 
17734   if (PrevDecl) {
17735     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
17736   } else {
17737     (void)WeakUndeclaredIdentifiers.insert(
17738       std::pair<IdentifierInfo*,WeakInfo>
17739         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17740   }
17741 }
17742 
17743 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17744                                 IdentifierInfo* AliasName,
17745                                 SourceLocation PragmaLoc,
17746                                 SourceLocation NameLoc,
17747                                 SourceLocation AliasNameLoc) {
17748   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17749                                     LookupOrdinaryName);
17750   WeakInfo W = WeakInfo(Name, NameLoc);
17751 
17752   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17753     if (!PrevDecl->hasAttr<AliasAttr>())
17754       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17755         DeclApplyPragmaWeak(TUScope, ND, W);
17756   } else {
17757     (void)WeakUndeclaredIdentifiers.insert(
17758       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17759   }
17760 }
17761 
17762 Decl *Sema::getObjCDeclContext() const {
17763   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17764 }
17765 
17766 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
17767   // Templates are emitted when they're instantiated.
17768   if (FD->isDependentContext())
17769     return FunctionEmissionStatus::TemplateDiscarded;
17770 
17771   FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
17772   if (LangOpts.OpenMPIsDevice) {
17773     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17774         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17775     if (DevTy.hasValue()) {
17776       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
17777         OMPES = FunctionEmissionStatus::OMPDiscarded;
17778       else if (DeviceKnownEmittedFns.count(FD) > 0)
17779         OMPES = FunctionEmissionStatus::Emitted;
17780     }
17781   } else if (LangOpts.OpenMP) {
17782     // In OpenMP 4.5 all the functions are host functions.
17783     if (LangOpts.OpenMP <= 45) {
17784       OMPES = FunctionEmissionStatus::Emitted;
17785     } else {
17786       Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17787           OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
17788       // In OpenMP 5.0 or above, DevTy may be changed later by
17789       // #pragma omp declare target to(*) device_type(*). Therefore DevTy
17790       // having no value does not imply host. The emission status will be
17791       // checked again at the end of compilation unit.
17792       if (DevTy.hasValue()) {
17793         if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
17794           OMPES = FunctionEmissionStatus::OMPDiscarded;
17795         } else if (DeviceKnownEmittedFns.count(FD) > 0) {
17796           OMPES = FunctionEmissionStatus::Emitted;
17797         }
17798       }
17799     }
17800   }
17801   if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
17802       (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
17803     return OMPES;
17804 
17805   if (LangOpts.CUDA) {
17806     // When compiling for device, host functions are never emitted.  Similarly,
17807     // when compiling for host, device and global functions are never emitted.
17808     // (Technically, we do emit a host-side stub for global functions, but this
17809     // doesn't count for our purposes here.)
17810     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
17811     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
17812       return FunctionEmissionStatus::CUDADiscarded;
17813     if (!LangOpts.CUDAIsDevice &&
17814         (T == Sema::CFT_Device || T == Sema::CFT_Global))
17815       return FunctionEmissionStatus::CUDADiscarded;
17816 
17817     // Check whether this function is externally visible -- if so, it's
17818     // known-emitted.
17819     //
17820     // We have to check the GVA linkage of the function's *definition* -- if we
17821     // only have a declaration, we don't know whether or not the function will
17822     // be emitted, because (say) the definition could include "inline".
17823     FunctionDecl *Def = FD->getDefinition();
17824 
17825     if (Def &&
17826         !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
17827         && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
17828       return FunctionEmissionStatus::Emitted;
17829   }
17830 
17831   // Otherwise, the function is known-emitted if it's in our set of
17832   // known-emitted functions.
17833   return (DeviceKnownEmittedFns.count(FD) > 0)
17834              ? FunctionEmissionStatus::Emitted
17835              : FunctionEmissionStatus::Unknown;
17836 }
17837 
17838 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
17839   // Host-side references to a __global__ function refer to the stub, so the
17840   // function itself is never emitted and therefore should not be marked.
17841   // If we have host fn calls kernel fn calls host+device, the HD function
17842   // does not get instantiated on the host. We model this by omitting at the
17843   // call to the kernel from the callgraph. This ensures that, when compiling
17844   // for host, only HD functions actually called from the host get marked as
17845   // known-emitted.
17846   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
17847          IdentifyCUDATarget(Callee) == CFT_Global;
17848 }
17849