1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaInternal.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 
50 using namespace clang;
51 using namespace sema;
52 
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
54   if (OwnedType) {
55     Decl *Group[2] = { OwnedType, Ptr };
56     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57   }
58 
59   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60 }
61 
62 namespace {
63 
64 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
65  public:
66    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
67                         bool AllowTemplates = false,
68                         bool AllowNonTemplates = true)
69        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
71      WantExpressionKeywords = false;
72      WantCXXNamedCasts = false;
73      WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       if (!AllowInvalidDecl && ND->isInvalidDecl())
79         return false;
80 
81       if (getAsTypeTemplateDecl(ND))
82         return AllowTemplates;
83 
84       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
85       if (!IsType)
86         return false;
87 
88       if (AllowNonTemplates)
89         return true;
90 
91       // An injected-class-name of a class template (specialization) is valid
92       // as a template or as a non-template.
93       if (AllowTemplates) {
94         auto *RD = dyn_cast<CXXRecordDecl>(ND);
95         if (!RD || !RD->isInjectedClassName())
96           return false;
97         RD = cast<CXXRecordDecl>(RD->getDeclContext());
98         return RD->getDescribedClassTemplate() ||
99                isa<ClassTemplateSpecializationDecl>(RD);
100       }
101 
102       return false;
103     }
104 
105     return !WantClassName && candidate.isKeyword();
106   }
107 
108   std::unique_ptr<CorrectionCandidateCallback> clone() override {
109     return llvm::make_unique<TypeNameValidatorCCC>(*this);
110   }
111 
112  private:
113   bool AllowInvalidDecl;
114   bool WantClassName;
115   bool AllowTemplates;
116   bool AllowNonTemplates;
117 };
118 
119 } // end anonymous namespace
120 
121 /// Determine whether the token kind starts a simple-type-specifier.
122 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
123   switch (Kind) {
124   // FIXME: Take into account the current language when deciding whether a
125   // token kind is a valid type specifier
126   case tok::kw_short:
127   case tok::kw_long:
128   case tok::kw___int64:
129   case tok::kw___int128:
130   case tok::kw_signed:
131   case tok::kw_unsigned:
132   case tok::kw_void:
133   case tok::kw_char:
134   case tok::kw_int:
135   case tok::kw_half:
136   case tok::kw_float:
137   case tok::kw_double:
138   case tok::kw__Float16:
139   case tok::kw___float128:
140   case tok::kw_wchar_t:
141   case tok::kw_bool:
142   case tok::kw___underlying_type:
143   case tok::kw___auto_type:
144     return true;
145 
146   case tok::annot_typename:
147   case tok::kw_char16_t:
148   case tok::kw_char32_t:
149   case tok::kw_typeof:
150   case tok::annot_decltype:
151   case tok::kw_decltype:
152     return getLangOpts().CPlusPlus;
153 
154   case tok::kw_char8_t:
155     return getLangOpts().Char8;
156 
157   default:
158     break;
159   }
160 
161   return false;
162 }
163 
164 namespace {
165 enum class UnqualifiedTypeNameLookupResult {
166   NotFound,
167   FoundNonType,
168   FoundType
169 };
170 } // end anonymous namespace
171 
172 /// Tries to perform unqualified lookup of the type decls in bases for
173 /// dependent class.
174 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
175 /// type decl, \a FoundType if only type decls are found.
176 static UnqualifiedTypeNameLookupResult
177 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
178                                 SourceLocation NameLoc,
179                                 const CXXRecordDecl *RD) {
180   if (!RD->hasDefinition())
181     return UnqualifiedTypeNameLookupResult::NotFound;
182   // Look for type decls in base classes.
183   UnqualifiedTypeNameLookupResult FoundTypeDecl =
184       UnqualifiedTypeNameLookupResult::NotFound;
185   for (const auto &Base : RD->bases()) {
186     const CXXRecordDecl *BaseRD = nullptr;
187     if (auto *BaseTT = Base.getType()->getAs<TagType>())
188       BaseRD = BaseTT->getAsCXXRecordDecl();
189     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
190       // Look for type decls in dependent base classes that have known primary
191       // templates.
192       if (!TST || !TST->isDependentType())
193         continue;
194       auto *TD = TST->getTemplateName().getAsTemplateDecl();
195       if (!TD)
196         continue;
197       if (auto *BasePrimaryTemplate =
198           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
199         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
200           BaseRD = BasePrimaryTemplate;
201         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
202           if (const ClassTemplatePartialSpecializationDecl *PS =
203                   CTD->findPartialSpecialization(Base.getType()))
204             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
205               BaseRD = PS;
206         }
207       }
208     }
209     if (BaseRD) {
210       for (NamedDecl *ND : BaseRD->lookup(&II)) {
211         if (!isa<TypeDecl>(ND))
212           return UnqualifiedTypeNameLookupResult::FoundNonType;
213         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214       }
215       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
216         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
217         case UnqualifiedTypeNameLookupResult::FoundNonType:
218           return UnqualifiedTypeNameLookupResult::FoundNonType;
219         case UnqualifiedTypeNameLookupResult::FoundType:
220           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
221           break;
222         case UnqualifiedTypeNameLookupResult::NotFound:
223           break;
224         }
225       }
226     }
227   }
228 
229   return FoundTypeDecl;
230 }
231 
232 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
233                                                       const IdentifierInfo &II,
234                                                       SourceLocation NameLoc) {
235   // Lookup in the parent class template context, if any.
236   const CXXRecordDecl *RD = nullptr;
237   UnqualifiedTypeNameLookupResult FoundTypeDecl =
238       UnqualifiedTypeNameLookupResult::NotFound;
239   for (DeclContext *DC = S.CurContext;
240        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
241        DC = DC->getParent()) {
242     // Look for type decls in dependent base classes that have known primary
243     // templates.
244     RD = dyn_cast<CXXRecordDecl>(DC);
245     if (RD && RD->getDescribedClassTemplate())
246       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
247   }
248   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
249     return nullptr;
250 
251   // We found some types in dependent base classes.  Recover as if the user
252   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
253   // lookup during template instantiation.
254   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
255 
256   ASTContext &Context = S.Context;
257   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
258                                           cast<Type>(Context.getRecordType(RD)));
259   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
260 
261   CXXScopeSpec SS;
262   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
263 
264   TypeLocBuilder Builder;
265   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
266   DepTL.setNameLoc(NameLoc);
267   DepTL.setElaboratedKeywordLoc(SourceLocation());
268   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
269   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
270 }
271 
272 /// If the identifier refers to a type name within this scope,
273 /// return the declaration of that type.
274 ///
275 /// This routine performs ordinary name lookup of the identifier II
276 /// within the given scope, with optional C++ scope specifier SS, to
277 /// determine whether the name refers to a type. If so, returns an
278 /// opaque pointer (actually a QualType) corresponding to that
279 /// type. Otherwise, returns NULL.
280 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
281                              Scope *S, CXXScopeSpec *SS,
282                              bool isClassName, bool HasTrailingDot,
283                              ParsedType ObjectTypePtr,
284                              bool IsCtorOrDtorName,
285                              bool WantNontrivialTypeSourceInfo,
286                              bool IsClassTemplateDeductionContext,
287                              IdentifierInfo **CorrectedII) {
288   // FIXME: Consider allowing this outside C++1z mode as an extension.
289   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
290                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
291                               !isClassName && !HasTrailingDot;
292 
293   // Determine where we will perform name lookup.
294   DeclContext *LookupCtx = nullptr;
295   if (ObjectTypePtr) {
296     QualType ObjectType = ObjectTypePtr.get();
297     if (ObjectType->isRecordType())
298       LookupCtx = computeDeclContext(ObjectType);
299   } else if (SS && SS->isNotEmpty()) {
300     LookupCtx = computeDeclContext(*SS, false);
301 
302     if (!LookupCtx) {
303       if (isDependentScopeSpecifier(*SS)) {
304         // C++ [temp.res]p3:
305         //   A qualified-id that refers to a type and in which the
306         //   nested-name-specifier depends on a template-parameter (14.6.2)
307         //   shall be prefixed by the keyword typename to indicate that the
308         //   qualified-id denotes a type, forming an
309         //   elaborated-type-specifier (7.1.5.3).
310         //
311         // We therefore do not perform any name lookup if the result would
312         // refer to a member of an unknown specialization.
313         if (!isClassName && !IsCtorOrDtorName)
314           return nullptr;
315 
316         // We know from the grammar that this name refers to a type,
317         // so build a dependent node to describe the type.
318         if (WantNontrivialTypeSourceInfo)
319           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
320 
321         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
322         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
323                                        II, NameLoc);
324         return ParsedType::make(T);
325       }
326 
327       return nullptr;
328     }
329 
330     if (!LookupCtx->isDependentContext() &&
331         RequireCompleteDeclContext(*SS, LookupCtx))
332       return nullptr;
333   }
334 
335   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
336   // lookup for class-names.
337   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
338                                       LookupOrdinaryName;
339   LookupResult Result(*this, &II, NameLoc, Kind);
340   if (LookupCtx) {
341     // Perform "qualified" name lookup into the declaration context we
342     // computed, which is either the type of the base of a member access
343     // expression or the declaration context associated with a prior
344     // nested-name-specifier.
345     LookupQualifiedName(Result, LookupCtx);
346 
347     if (ObjectTypePtr && Result.empty()) {
348       // C++ [basic.lookup.classref]p3:
349       //   If the unqualified-id is ~type-name, the type-name is looked up
350       //   in the context of the entire postfix-expression. If the type T of
351       //   the object expression is of a class type C, the type-name is also
352       //   looked up in the scope of class C. At least one of the lookups shall
353       //   find a name that refers to (possibly cv-qualified) T.
354       LookupName(Result, S);
355     }
356   } else {
357     // Perform unqualified name lookup.
358     LookupName(Result, S);
359 
360     // For unqualified lookup in a class template in MSVC mode, look into
361     // dependent base classes where the primary class template is known.
362     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
363       if (ParsedType TypeInBase =
364               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
365         return TypeInBase;
366     }
367   }
368 
369   NamedDecl *IIDecl = nullptr;
370   switch (Result.getResultKind()) {
371   case LookupResult::NotFound:
372   case LookupResult::NotFoundInCurrentInstantiation:
373     if (CorrectedII) {
374       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
375                                AllowDeducedTemplate);
376       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
377                                               S, SS, CCC, CTK_ErrorRecovery);
378       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
379       TemplateTy Template;
380       bool MemberOfUnknownSpecialization;
381       UnqualifiedId TemplateName;
382       TemplateName.setIdentifier(NewII, NameLoc);
383       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
384       CXXScopeSpec NewSS, *NewSSPtr = SS;
385       if (SS && NNS) {
386         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
387         NewSSPtr = &NewSS;
388       }
389       if (Correction && (NNS || NewII != &II) &&
390           // Ignore a correction to a template type as the to-be-corrected
391           // identifier is not a template (typo correction for template names
392           // is handled elsewhere).
393           !(getLangOpts().CPlusPlus && NewSSPtr &&
394             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
395                            Template, MemberOfUnknownSpecialization))) {
396         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
397                                     isClassName, HasTrailingDot, ObjectTypePtr,
398                                     IsCtorOrDtorName,
399                                     WantNontrivialTypeSourceInfo,
400                                     IsClassTemplateDeductionContext);
401         if (Ty) {
402           diagnoseTypo(Correction,
403                        PDiag(diag::err_unknown_type_or_class_name_suggest)
404                          << Result.getLookupName() << isClassName);
405           if (SS && NNS)
406             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
407           *CorrectedII = NewII;
408           return Ty;
409         }
410       }
411     }
412     // If typo correction failed or was not performed, fall through
413     LLVM_FALLTHROUGH;
414   case LookupResult::FoundOverloaded:
415   case LookupResult::FoundUnresolvedValue:
416     Result.suppressDiagnostics();
417     return nullptr;
418 
419   case LookupResult::Ambiguous:
420     // Recover from type-hiding ambiguities by hiding the type.  We'll
421     // do the lookup again when looking for an object, and we can
422     // diagnose the error then.  If we don't do this, then the error
423     // about hiding the type will be immediately followed by an error
424     // that only makes sense if the identifier was treated like a type.
425     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
426       Result.suppressDiagnostics();
427       return nullptr;
428     }
429 
430     // Look to see if we have a type anywhere in the list of results.
431     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
432          Res != ResEnd; ++Res) {
433       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
434           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
435         if (!IIDecl ||
436             (*Res)->getLocation().getRawEncoding() <
437               IIDecl->getLocation().getRawEncoding())
438           IIDecl = *Res;
439       }
440     }
441 
442     if (!IIDecl) {
443       // None of the entities we found is a type, so there is no way
444       // to even assume that the result is a type. In this case, don't
445       // complain about the ambiguity. The parser will either try to
446       // perform this lookup again (e.g., as an object name), which
447       // will produce the ambiguity, or will complain that it expected
448       // a type name.
449       Result.suppressDiagnostics();
450       return nullptr;
451     }
452 
453     // We found a type within the ambiguous lookup; diagnose the
454     // ambiguity and then return that type. This might be the right
455     // answer, or it might not be, but it suppresses any attempt to
456     // perform the name lookup again.
457     break;
458 
459   case LookupResult::Found:
460     IIDecl = Result.getFoundDecl();
461     break;
462   }
463 
464   assert(IIDecl && "Didn't find decl");
465 
466   QualType T;
467   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
468     // C++ [class.qual]p2: A lookup that would find the injected-class-name
469     // instead names the constructors of the class, except when naming a class.
470     // This is ill-formed when we're not actually forming a ctor or dtor name.
471     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
472     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
473     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
474         FoundRD->isInjectedClassName() &&
475         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
476       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
477           << &II << /*Type*/1;
478 
479     DiagnoseUseOfDecl(IIDecl, NameLoc);
480 
481     T = Context.getTypeDeclType(TD);
482     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
483   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
484     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
485     if (!HasTrailingDot)
486       T = Context.getObjCInterfaceType(IDecl);
487   } else if (AllowDeducedTemplate) {
488     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
489       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
490                                                        QualType(), false);
491   }
492 
493   if (T.isNull()) {
494     // If it's not plausibly a type, suppress diagnostics.
495     Result.suppressDiagnostics();
496     return nullptr;
497   }
498 
499   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
500   // constructor or destructor name (in such a case, the scope specifier
501   // will be attached to the enclosing Expr or Decl node).
502   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
503       !isa<ObjCInterfaceDecl>(IIDecl)) {
504     if (WantNontrivialTypeSourceInfo) {
505       // Construct a type with type-source information.
506       TypeLocBuilder Builder;
507       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
508 
509       T = getElaboratedType(ETK_None, *SS, T);
510       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
511       ElabTL.setElaboratedKeywordLoc(SourceLocation());
512       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
513       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
514     } else {
515       T = getElaboratedType(ETK_None, *SS, T);
516     }
517   }
518 
519   return ParsedType::make(T);
520 }
521 
522 // Builds a fake NNS for the given decl context.
523 static NestedNameSpecifier *
524 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
525   for (;; DC = DC->getLookupParent()) {
526     DC = DC->getPrimaryContext();
527     auto *ND = dyn_cast<NamespaceDecl>(DC);
528     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
529       return NestedNameSpecifier::Create(Context, nullptr, ND);
530     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
531       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
532                                          RD->getTypeForDecl());
533     else if (isa<TranslationUnitDecl>(DC))
534       return NestedNameSpecifier::GlobalSpecifier(Context);
535   }
536   llvm_unreachable("something isn't in TU scope?");
537 }
538 
539 /// Find the parent class with dependent bases of the innermost enclosing method
540 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
541 /// up allowing unqualified dependent type names at class-level, which MSVC
542 /// correctly rejects.
543 static const CXXRecordDecl *
544 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
545   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
546     DC = DC->getPrimaryContext();
547     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
548       if (MD->getParent()->hasAnyDependentBases())
549         return MD->getParent();
550   }
551   return nullptr;
552 }
553 
554 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
555                                           SourceLocation NameLoc,
556                                           bool IsTemplateTypeArg) {
557   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
558 
559   NestedNameSpecifier *NNS = nullptr;
560   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
561     // If we weren't able to parse a default template argument, delay lookup
562     // until instantiation time by making a non-dependent DependentTypeName. We
563     // pretend we saw a NestedNameSpecifier referring to the current scope, and
564     // lookup is retried.
565     // FIXME: This hurts our diagnostic quality, since we get errors like "no
566     // type named 'Foo' in 'current_namespace'" when the user didn't write any
567     // name specifiers.
568     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
569     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
570   } else if (const CXXRecordDecl *RD =
571                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
572     // Build a DependentNameType that will perform lookup into RD at
573     // instantiation time.
574     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
575                                       RD->getTypeForDecl());
576 
577     // Diagnose that this identifier was undeclared, and retry the lookup during
578     // template instantiation.
579     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
580                                                                       << RD;
581   } else {
582     // This is not a situation that we should recover from.
583     return ParsedType();
584   }
585 
586   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
587 
588   // Build type location information.  We synthesized the qualifier, so we have
589   // to build a fake NestedNameSpecifierLoc.
590   NestedNameSpecifierLocBuilder NNSLocBuilder;
591   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
592   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
593 
594   TypeLocBuilder Builder;
595   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
596   DepTL.setNameLoc(NameLoc);
597   DepTL.setElaboratedKeywordLoc(SourceLocation());
598   DepTL.setQualifierLoc(QualifierLoc);
599   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
600 }
601 
602 /// isTagName() - This method is called *for error recovery purposes only*
603 /// to determine if the specified name is a valid tag name ("struct foo").  If
604 /// so, this returns the TST for the tag corresponding to it (TST_enum,
605 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
606 /// cases in C where the user forgot to specify the tag.
607 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
608   // Do a tag name lookup in this scope.
609   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
610   LookupName(R, S, false);
611   R.suppressDiagnostics();
612   if (R.getResultKind() == LookupResult::Found)
613     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
614       switch (TD->getTagKind()) {
615       case TTK_Struct: return DeclSpec::TST_struct;
616       case TTK_Interface: return DeclSpec::TST_interface;
617       case TTK_Union:  return DeclSpec::TST_union;
618       case TTK_Class:  return DeclSpec::TST_class;
619       case TTK_Enum:   return DeclSpec::TST_enum;
620       }
621     }
622 
623   return DeclSpec::TST_unspecified;
624 }
625 
626 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
627 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
628 /// then downgrade the missing typename error to a warning.
629 /// This is needed for MSVC compatibility; Example:
630 /// @code
631 /// template<class T> class A {
632 /// public:
633 ///   typedef int TYPE;
634 /// };
635 /// template<class T> class B : public A<T> {
636 /// public:
637 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
638 /// };
639 /// @endcode
640 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
641   if (CurContext->isRecord()) {
642     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
643       return true;
644 
645     const Type *Ty = SS->getScopeRep()->getAsType();
646 
647     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
648     for (const auto &Base : RD->bases())
649       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
650         return true;
651     return S->isFunctionPrototypeScope();
652   }
653   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
654 }
655 
656 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
657                                    SourceLocation IILoc,
658                                    Scope *S,
659                                    CXXScopeSpec *SS,
660                                    ParsedType &SuggestedType,
661                                    bool IsTemplateName) {
662   // Don't report typename errors for editor placeholders.
663   if (II->isEditorPlaceholder())
664     return;
665   // We don't have anything to suggest (yet).
666   SuggestedType = nullptr;
667 
668   // There may have been a typo in the name of the type. Look up typo
669   // results, in case we have something that we can suggest.
670   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
671                            /*AllowTemplates=*/IsTemplateName,
672                            /*AllowNonTemplates=*/!IsTemplateName);
673   if (TypoCorrection Corrected =
674           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
675                       CCC, CTK_ErrorRecovery)) {
676     // FIXME: Support error recovery for the template-name case.
677     bool CanRecover = !IsTemplateName;
678     if (Corrected.isKeyword()) {
679       // We corrected to a keyword.
680       diagnoseTypo(Corrected,
681                    PDiag(IsTemplateName ? diag::err_no_template_suggest
682                                         : diag::err_unknown_typename_suggest)
683                        << II);
684       II = Corrected.getCorrectionAsIdentifierInfo();
685     } else {
686       // We found a similarly-named type or interface; suggest that.
687       if (!SS || !SS->isSet()) {
688         diagnoseTypo(Corrected,
689                      PDiag(IsTemplateName ? diag::err_no_template_suggest
690                                           : diag::err_unknown_typename_suggest)
691                          << II, CanRecover);
692       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
693         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
694         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
695                                 II->getName().equals(CorrectedStr);
696         diagnoseTypo(Corrected,
697                      PDiag(IsTemplateName
698                                ? diag::err_no_member_template_suggest
699                                : diag::err_unknown_nested_typename_suggest)
700                          << II << DC << DroppedSpecifier << SS->getRange(),
701                      CanRecover);
702       } else {
703         llvm_unreachable("could not have corrected a typo here");
704       }
705 
706       if (!CanRecover)
707         return;
708 
709       CXXScopeSpec tmpSS;
710       if (Corrected.getCorrectionSpecifier())
711         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
712                           SourceRange(IILoc));
713       // FIXME: Support class template argument deduction here.
714       SuggestedType =
715           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
716                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
717                       /*IsCtorOrDtorName=*/false,
718                       /*WantNontrivialTypeSourceInfo=*/true);
719     }
720     return;
721   }
722 
723   if (getLangOpts().CPlusPlus && !IsTemplateName) {
724     // See if II is a class template that the user forgot to pass arguments to.
725     UnqualifiedId Name;
726     Name.setIdentifier(II, IILoc);
727     CXXScopeSpec EmptySS;
728     TemplateTy TemplateResult;
729     bool MemberOfUnknownSpecialization;
730     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
731                        Name, nullptr, true, TemplateResult,
732                        MemberOfUnknownSpecialization) == TNK_Type_template) {
733       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
734       return;
735     }
736   }
737 
738   // FIXME: Should we move the logic that tries to recover from a missing tag
739   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740 
741   if (!SS || (!SS->isSet() && !SS->isInvalid()))
742     Diag(IILoc, IsTemplateName ? diag::err_no_template
743                                : diag::err_unknown_typename)
744         << II;
745   else if (DeclContext *DC = computeDeclContext(*SS, false))
746     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747                                : diag::err_typename_nested_not_found)
748         << II << DC << SS->getRange();
749   else if (isDependentScopeSpecifier(*SS)) {
750     unsigned DiagID = diag::err_typename_missing;
751     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752       DiagID = diag::ext_typename_missing;
753 
754     Diag(SS->getRange().getBegin(), DiagID)
755       << SS->getScopeRep() << II->getName()
756       << SourceRange(SS->getRange().getBegin(), IILoc)
757       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758     SuggestedType = ActOnTypenameType(S, SourceLocation(),
759                                       *SS, *II, IILoc).get();
760   } else {
761     assert(SS && SS->isInvalid() &&
762            "Invalid scope specifier has already been diagnosed");
763   }
764 }
765 
766 /// Determine whether the given result set contains either a type name
767 /// or
768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770                        NextToken.is(tok::less);
771 
772   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774       return true;
775 
776     if (CheckTemplate && isa<TemplateDecl>(*I))
777       return true;
778   }
779 
780   return false;
781 }
782 
783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784                                     Scope *S, CXXScopeSpec &SS,
785                                     IdentifierInfo *&Name,
786                                     SourceLocation NameLoc) {
787   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788   SemaRef.LookupParsedName(R, S, &SS);
789   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790     StringRef FixItTagName;
791     switch (Tag->getTagKind()) {
792       case TTK_Class:
793         FixItTagName = "class ";
794         break;
795 
796       case TTK_Enum:
797         FixItTagName = "enum ";
798         break;
799 
800       case TTK_Struct:
801         FixItTagName = "struct ";
802         break;
803 
804       case TTK_Interface:
805         FixItTagName = "__interface ";
806         break;
807 
808       case TTK_Union:
809         FixItTagName = "union ";
810         break;
811     }
812 
813     StringRef TagName = FixItTagName.drop_back();
814     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817 
818     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819          I != IEnd; ++I)
820       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821         << Name << TagName;
822 
823     // Replace lookup results with just the tag decl.
824     Result.clear(Sema::LookupTagName);
825     SemaRef.LookupParsedName(Result, S, &SS);
826     return true;
827   }
828 
829   return false;
830 }
831 
832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
834                                   QualType T, SourceLocation NameLoc) {
835   ASTContext &Context = S.Context;
836 
837   TypeLocBuilder Builder;
838   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839 
840   T = S.getElaboratedType(ETK_None, SS, T);
841   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842   ElabTL.setElaboratedKeywordLoc(SourceLocation());
843   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845 }
846 
847 Sema::NameClassification
848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
849                    SourceLocation NameLoc, const Token &NextToken,
850                    bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
851   DeclarationNameInfo NameInfo(Name, NameLoc);
852   ObjCMethodDecl *CurMethod = getCurMethodDecl();
853 
854   if (NextToken.is(tok::coloncolon)) {
855     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
856     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
857   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858              isCurrentClassName(*Name, S, &SS)) {
859     // Per [class.qual]p2, this names the constructors of SS, not the
860     // injected-class-name. We don't have a classification for that.
861     // There's not much point caching this result, since the parser
862     // will reject it later.
863     return NameClassification::Unknown();
864   }
865 
866   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
867   LookupParsedName(Result, S, &SS, !CurMethod);
868 
869   // For unqualified lookup in a class template in MSVC mode, look into
870   // dependent base classes where the primary class template is known.
871   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872     if (ParsedType TypeInBase =
873             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
874       return TypeInBase;
875   }
876 
877   // Perform lookup for Objective-C instance variables (including automatically
878   // synthesized instance variables), if we're in an Objective-C method.
879   // FIXME: This lookup really, really needs to be folded in to the normal
880   // unqualified lookup mechanism.
881   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
882     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
883     if (E.get() || E.isInvalid())
884       return E;
885   }
886 
887   bool SecondTry = false;
888   bool IsFilteredTemplateName = false;
889 
890 Corrected:
891   switch (Result.getResultKind()) {
892   case LookupResult::NotFound:
893     // If an unqualified-id is followed by a '(', then we have a function
894     // call.
895     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896       // In C++, this is an ADL-only call.
897       // FIXME: Reference?
898       if (getLangOpts().CPlusPlus)
899         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
900 
901       // C90 6.3.2.2:
902       //   If the expression that precedes the parenthesized argument list in a
903       //   function call consists solely of an identifier, and if no
904       //   declaration is visible for this identifier, the identifier is
905       //   implicitly declared exactly as if, in the innermost block containing
906       //   the function call, the declaration
907       //
908       //     extern int identifier ();
909       //
910       //   appeared.
911       //
912       // We also allow this in C99 as an extension.
913       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
914         Result.addDecl(D);
915         Result.resolveKind();
916         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
917       }
918     }
919 
920     if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
921       // In C++20 onwards, this could be an ADL-only call to a function
922       // template, and we're required to assume that this is a template name.
923       //
924       // FIXME: Find a way to still do typo correction in this case.
925       TemplateName Template =
926           Context.getAssumedTemplateName(NameInfo.getName());
927       return NameClassification::UndeclaredTemplate(Template);
928     }
929 
930     // In C, we first see whether there is a tag type by the same name, in
931     // which case it's likely that the user just forgot to write "enum",
932     // "struct", or "union".
933     if (!getLangOpts().CPlusPlus && !SecondTry &&
934         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
935       break;
936     }
937 
938     // Perform typo correction to determine if there is another name that is
939     // close to this name.
940     if (!SecondTry && CCC) {
941       SecondTry = true;
942       if (TypoCorrection Corrected =
943               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
944                           &SS, *CCC, CTK_ErrorRecovery)) {
945         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
946         unsigned QualifiedDiag = diag::err_no_member_suggest;
947 
948         NamedDecl *FirstDecl = Corrected.getFoundDecl();
949         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
950         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
951             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
952           UnqualifiedDiag = diag::err_no_template_suggest;
953           QualifiedDiag = diag::err_no_member_template_suggest;
954         } else if (UnderlyingFirstDecl &&
955                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
956                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
957                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
958           UnqualifiedDiag = diag::err_unknown_typename_suggest;
959           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
960         }
961 
962         if (SS.isEmpty()) {
963           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
964         } else {// FIXME: is this even reachable? Test it.
965           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
966           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
967                                   Name->getName().equals(CorrectedStr);
968           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
969                                     << Name << computeDeclContext(SS, false)
970                                     << DroppedSpecifier << SS.getRange());
971         }
972 
973         // Update the name, so that the caller has the new name.
974         Name = Corrected.getCorrectionAsIdentifierInfo();
975 
976         // Typo correction corrected to a keyword.
977         if (Corrected.isKeyword())
978           return Name;
979 
980         // Also update the LookupResult...
981         // FIXME: This should probably go away at some point
982         Result.clear();
983         Result.setLookupName(Corrected.getCorrection());
984         if (FirstDecl)
985           Result.addDecl(FirstDecl);
986 
987         // If we found an Objective-C instance variable, let
988         // LookupInObjCMethod build the appropriate expression to
989         // reference the ivar.
990         // FIXME: This is a gross hack.
991         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
992           Result.clear();
993           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
994           return E;
995         }
996 
997         goto Corrected;
998       }
999     }
1000 
1001     // We failed to correct; just fall through and let the parser deal with it.
1002     Result.suppressDiagnostics();
1003     return NameClassification::Unknown();
1004 
1005   case LookupResult::NotFoundInCurrentInstantiation: {
1006     // We performed name lookup into the current instantiation, and there were
1007     // dependent bases, so we treat this result the same way as any other
1008     // dependent nested-name-specifier.
1009 
1010     // C++ [temp.res]p2:
1011     //   A name used in a template declaration or definition and that is
1012     //   dependent on a template-parameter is assumed not to name a type
1013     //   unless the applicable name lookup finds a type name or the name is
1014     //   qualified by the keyword typename.
1015     //
1016     // FIXME: If the next token is '<', we might want to ask the parser to
1017     // perform some heroics to see if we actually have a
1018     // template-argument-list, which would indicate a missing 'template'
1019     // keyword here.
1020     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1021                                       NameInfo, IsAddressOfOperand,
1022                                       /*TemplateArgs=*/nullptr);
1023   }
1024 
1025   case LookupResult::Found:
1026   case LookupResult::FoundOverloaded:
1027   case LookupResult::FoundUnresolvedValue:
1028     break;
1029 
1030   case LookupResult::Ambiguous:
1031     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1032         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1033                                       /*AllowDependent=*/false)) {
1034       // C++ [temp.local]p3:
1035       //   A lookup that finds an injected-class-name (10.2) can result in an
1036       //   ambiguity in certain cases (for example, if it is found in more than
1037       //   one base class). If all of the injected-class-names that are found
1038       //   refer to specializations of the same class template, and if the name
1039       //   is followed by a template-argument-list, the reference refers to the
1040       //   class template itself and not a specialization thereof, and is not
1041       //   ambiguous.
1042       //
1043       // This filtering can make an ambiguous result into an unambiguous one,
1044       // so try again after filtering out template names.
1045       FilterAcceptableTemplateNames(Result);
1046       if (!Result.isAmbiguous()) {
1047         IsFilteredTemplateName = true;
1048         break;
1049       }
1050     }
1051 
1052     // Diagnose the ambiguity and return an error.
1053     return NameClassification::Error();
1054   }
1055 
1056   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1057       (IsFilteredTemplateName ||
1058        hasAnyAcceptableTemplateNames(
1059            Result, /*AllowFunctionTemplates=*/true,
1060            /*AllowDependent=*/false,
1061            /*AllowNonTemplateFunctions*/ !SS.isSet() &&
1062                getLangOpts().CPlusPlus2a))) {
1063     // C++ [temp.names]p3:
1064     //   After name lookup (3.4) finds that a name is a template-name or that
1065     //   an operator-function-id or a literal- operator-id refers to a set of
1066     //   overloaded functions any member of which is a function template if
1067     //   this is followed by a <, the < is always taken as the delimiter of a
1068     //   template-argument-list and never as the less-than operator.
1069     // C++2a [temp.names]p2:
1070     //   A name is also considered to refer to a template if it is an
1071     //   unqualified-id followed by a < and name lookup finds either one
1072     //   or more functions or finds nothing.
1073     if (!IsFilteredTemplateName)
1074       FilterAcceptableTemplateNames(Result);
1075 
1076     bool IsFunctionTemplate;
1077     bool IsVarTemplate;
1078     TemplateName Template;
1079     if (Result.end() - Result.begin() > 1) {
1080       IsFunctionTemplate = true;
1081       Template = Context.getOverloadedTemplateName(Result.begin(),
1082                                                    Result.end());
1083     } else if (!Result.empty()) {
1084       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1085           *Result.begin(), /*AllowFunctionTemplates=*/true,
1086           /*AllowDependent=*/false));
1087       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1088       IsVarTemplate = isa<VarTemplateDecl>(TD);
1089 
1090       if (SS.isSet() && !SS.isInvalid())
1091         Template =
1092             Context.getQualifiedTemplateName(SS.getScopeRep(),
1093                                              /*TemplateKeyword=*/false, TD);
1094       else
1095         Template = TemplateName(TD);
1096     } else {
1097       // All results were non-template functions. This is a function template
1098       // name.
1099       IsFunctionTemplate = true;
1100       Template = Context.getAssumedTemplateName(NameInfo.getName());
1101     }
1102 
1103     if (IsFunctionTemplate) {
1104       // Function templates always go through overload resolution, at which
1105       // point we'll perform the various checks (e.g., accessibility) we need
1106       // to based on which function we selected.
1107       Result.suppressDiagnostics();
1108 
1109       return NameClassification::FunctionTemplate(Template);
1110     }
1111 
1112     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1113                          : NameClassification::TypeTemplate(Template);
1114   }
1115 
1116   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1117   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1118     DiagnoseUseOfDecl(Type, NameLoc);
1119     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1120     QualType T = Context.getTypeDeclType(Type);
1121     if (SS.isNotEmpty())
1122       return buildNestedType(*this, SS, T, NameLoc);
1123     return ParsedType::make(T);
1124   }
1125 
1126   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1127   if (!Class) {
1128     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1129     if (ObjCCompatibleAliasDecl *Alias =
1130             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1131       Class = Alias->getClassInterface();
1132   }
1133 
1134   if (Class) {
1135     DiagnoseUseOfDecl(Class, NameLoc);
1136 
1137     if (NextToken.is(tok::period)) {
1138       // Interface. <something> is parsed as a property reference expression.
1139       // Just return "unknown" as a fall-through for now.
1140       Result.suppressDiagnostics();
1141       return NameClassification::Unknown();
1142     }
1143 
1144     QualType T = Context.getObjCInterfaceType(Class);
1145     return ParsedType::make(T);
1146   }
1147 
1148   // We can have a type template here if we're classifying a template argument.
1149   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1150       !isa<VarTemplateDecl>(FirstDecl))
1151     return NameClassification::TypeTemplate(
1152         TemplateName(cast<TemplateDecl>(FirstDecl)));
1153 
1154   // Check for a tag type hidden by a non-type decl in a few cases where it
1155   // seems likely a type is wanted instead of the non-type that was found.
1156   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1157   if ((NextToken.is(tok::identifier) ||
1158        (NextIsOp &&
1159         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1160       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1161     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1162     DiagnoseUseOfDecl(Type, NameLoc);
1163     QualType T = Context.getTypeDeclType(Type);
1164     if (SS.isNotEmpty())
1165       return buildNestedType(*this, SS, T, NameLoc);
1166     return ParsedType::make(T);
1167   }
1168 
1169   if (FirstDecl->isCXXClassMember())
1170     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1171                                            nullptr, S);
1172 
1173   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1174   return BuildDeclarationNameExpr(SS, Result, ADL);
1175 }
1176 
1177 Sema::TemplateNameKindForDiagnostics
1178 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1179   auto *TD = Name.getAsTemplateDecl();
1180   if (!TD)
1181     return TemplateNameKindForDiagnostics::DependentTemplate;
1182   if (isa<ClassTemplateDecl>(TD))
1183     return TemplateNameKindForDiagnostics::ClassTemplate;
1184   if (isa<FunctionTemplateDecl>(TD))
1185     return TemplateNameKindForDiagnostics::FunctionTemplate;
1186   if (isa<VarTemplateDecl>(TD))
1187     return TemplateNameKindForDiagnostics::VarTemplate;
1188   if (isa<TypeAliasTemplateDecl>(TD))
1189     return TemplateNameKindForDiagnostics::AliasTemplate;
1190   if (isa<TemplateTemplateParmDecl>(TD))
1191     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1192   if (isa<ConceptDecl>(TD))
1193     return TemplateNameKindForDiagnostics::Concept;
1194   return TemplateNameKindForDiagnostics::DependentTemplate;
1195 }
1196 
1197 // Determines the context to return to after temporarily entering a
1198 // context.  This depends in an unnecessarily complicated way on the
1199 // exact ordering of callbacks from the parser.
1200 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1201 
1202   // Functions defined inline within classes aren't parsed until we've
1203   // finished parsing the top-level class, so the top-level class is
1204   // the context we'll need to return to.
1205   // A Lambda call operator whose parent is a class must not be treated
1206   // as an inline member function.  A Lambda can be used legally
1207   // either as an in-class member initializer or a default argument.  These
1208   // are parsed once the class has been marked complete and so the containing
1209   // context would be the nested class (when the lambda is defined in one);
1210   // If the class is not complete, then the lambda is being used in an
1211   // ill-formed fashion (such as to specify the width of a bit-field, or
1212   // in an array-bound) - in which case we still want to return the
1213   // lexically containing DC (which could be a nested class).
1214   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1215     DC = DC->getLexicalParent();
1216 
1217     // A function not defined within a class will always return to its
1218     // lexical context.
1219     if (!isa<CXXRecordDecl>(DC))
1220       return DC;
1221 
1222     // A C++ inline method/friend is parsed *after* the topmost class
1223     // it was declared in is fully parsed ("complete");  the topmost
1224     // class is the context we need to return to.
1225     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1226       DC = RD;
1227 
1228     // Return the declaration context of the topmost class the inline method is
1229     // declared in.
1230     return DC;
1231   }
1232 
1233   return DC->getLexicalParent();
1234 }
1235 
1236 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1237   assert(getContainingDC(DC) == CurContext &&
1238       "The next DeclContext should be lexically contained in the current one.");
1239   CurContext = DC;
1240   S->setEntity(DC);
1241 }
1242 
1243 void Sema::PopDeclContext() {
1244   assert(CurContext && "DeclContext imbalance!");
1245 
1246   CurContext = getContainingDC(CurContext);
1247   assert(CurContext && "Popped translation unit!");
1248 }
1249 
1250 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1251                                                                     Decl *D) {
1252   // Unlike PushDeclContext, the context to which we return is not necessarily
1253   // the containing DC of TD, because the new context will be some pre-existing
1254   // TagDecl definition instead of a fresh one.
1255   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1256   CurContext = cast<TagDecl>(D)->getDefinition();
1257   assert(CurContext && "skipping definition of undefined tag");
1258   // Start lookups from the parent of the current context; we don't want to look
1259   // into the pre-existing complete definition.
1260   S->setEntity(CurContext->getLookupParent());
1261   return Result;
1262 }
1263 
1264 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1265   CurContext = static_cast<decltype(CurContext)>(Context);
1266 }
1267 
1268 /// EnterDeclaratorContext - Used when we must lookup names in the context
1269 /// of a declarator's nested name specifier.
1270 ///
1271 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1272   // C++0x [basic.lookup.unqual]p13:
1273   //   A name used in the definition of a static data member of class
1274   //   X (after the qualified-id of the static member) is looked up as
1275   //   if the name was used in a member function of X.
1276   // C++0x [basic.lookup.unqual]p14:
1277   //   If a variable member of a namespace is defined outside of the
1278   //   scope of its namespace then any name used in the definition of
1279   //   the variable member (after the declarator-id) is looked up as
1280   //   if the definition of the variable member occurred in its
1281   //   namespace.
1282   // Both of these imply that we should push a scope whose context
1283   // is the semantic context of the declaration.  We can't use
1284   // PushDeclContext here because that context is not necessarily
1285   // lexically contained in the current context.  Fortunately,
1286   // the containing scope should have the appropriate information.
1287 
1288   assert(!S->getEntity() && "scope already has entity");
1289 
1290 #ifndef NDEBUG
1291   Scope *Ancestor = S->getParent();
1292   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1293   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1294 #endif
1295 
1296   CurContext = DC;
1297   S->setEntity(DC);
1298 }
1299 
1300 void Sema::ExitDeclaratorContext(Scope *S) {
1301   assert(S->getEntity() == CurContext && "Context imbalance!");
1302 
1303   // Switch back to the lexical context.  The safety of this is
1304   // enforced by an assert in EnterDeclaratorContext.
1305   Scope *Ancestor = S->getParent();
1306   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1307   CurContext = Ancestor->getEntity();
1308 
1309   // We don't need to do anything with the scope, which is going to
1310   // disappear.
1311 }
1312 
1313 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1314   // We assume that the caller has already called
1315   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1316   FunctionDecl *FD = D->getAsFunction();
1317   if (!FD)
1318     return;
1319 
1320   // Same implementation as PushDeclContext, but enters the context
1321   // from the lexical parent, rather than the top-level class.
1322   assert(CurContext == FD->getLexicalParent() &&
1323     "The next DeclContext should be lexically contained in the current one.");
1324   CurContext = FD;
1325   S->setEntity(CurContext);
1326 
1327   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1328     ParmVarDecl *Param = FD->getParamDecl(P);
1329     // If the parameter has an identifier, then add it to the scope
1330     if (Param->getIdentifier()) {
1331       S->AddDecl(Param);
1332       IdResolver.AddDecl(Param);
1333     }
1334   }
1335 }
1336 
1337 void Sema::ActOnExitFunctionContext() {
1338   // Same implementation as PopDeclContext, but returns to the lexical parent,
1339   // rather than the top-level class.
1340   assert(CurContext && "DeclContext imbalance!");
1341   CurContext = CurContext->getLexicalParent();
1342   assert(CurContext && "Popped translation unit!");
1343 }
1344 
1345 /// Determine whether we allow overloading of the function
1346 /// PrevDecl with another declaration.
1347 ///
1348 /// This routine determines whether overloading is possible, not
1349 /// whether some new function is actually an overload. It will return
1350 /// true in C++ (where we can always provide overloads) or, as an
1351 /// extension, in C when the previous function is already an
1352 /// overloaded function declaration or has the "overloadable"
1353 /// attribute.
1354 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1355                                        ASTContext &Context,
1356                                        const FunctionDecl *New) {
1357   if (Context.getLangOpts().CPlusPlus)
1358     return true;
1359 
1360   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1361     return true;
1362 
1363   return Previous.getResultKind() == LookupResult::Found &&
1364          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1365           New->hasAttr<OverloadableAttr>());
1366 }
1367 
1368 /// Add this decl to the scope shadowed decl chains.
1369 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1370   // Move up the scope chain until we find the nearest enclosing
1371   // non-transparent context. The declaration will be introduced into this
1372   // scope.
1373   while (S->getEntity() && S->getEntity()->isTransparentContext())
1374     S = S->getParent();
1375 
1376   // Add scoped declarations into their context, so that they can be
1377   // found later. Declarations without a context won't be inserted
1378   // into any context.
1379   if (AddToContext)
1380     CurContext->addDecl(D);
1381 
1382   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1383   // are function-local declarations.
1384   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1385       !D->getDeclContext()->getRedeclContext()->Equals(
1386         D->getLexicalDeclContext()->getRedeclContext()) &&
1387       !D->getLexicalDeclContext()->isFunctionOrMethod())
1388     return;
1389 
1390   // Template instantiations should also not be pushed into scope.
1391   if (isa<FunctionDecl>(D) &&
1392       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1393     return;
1394 
1395   // If this replaces anything in the current scope,
1396   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1397                                IEnd = IdResolver.end();
1398   for (; I != IEnd; ++I) {
1399     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1400       S->RemoveDecl(*I);
1401       IdResolver.RemoveDecl(*I);
1402 
1403       // Should only need to replace one decl.
1404       break;
1405     }
1406   }
1407 
1408   S->AddDecl(D);
1409 
1410   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1411     // Implicitly-generated labels may end up getting generated in an order that
1412     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1413     // the label at the appropriate place in the identifier chain.
1414     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1415       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1416       if (IDC == CurContext) {
1417         if (!S->isDeclScope(*I))
1418           continue;
1419       } else if (IDC->Encloses(CurContext))
1420         break;
1421     }
1422 
1423     IdResolver.InsertDeclAfter(I, D);
1424   } else {
1425     IdResolver.AddDecl(D);
1426   }
1427 }
1428 
1429 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1430                          bool AllowInlineNamespace) {
1431   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1432 }
1433 
1434 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1435   DeclContext *TargetDC = DC->getPrimaryContext();
1436   do {
1437     if (DeclContext *ScopeDC = S->getEntity())
1438       if (ScopeDC->getPrimaryContext() == TargetDC)
1439         return S;
1440   } while ((S = S->getParent()));
1441 
1442   return nullptr;
1443 }
1444 
1445 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1446                                             DeclContext*,
1447                                             ASTContext&);
1448 
1449 /// Filters out lookup results that don't fall within the given scope
1450 /// as determined by isDeclInScope.
1451 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1452                                 bool ConsiderLinkage,
1453                                 bool AllowInlineNamespace) {
1454   LookupResult::Filter F = R.makeFilter();
1455   while (F.hasNext()) {
1456     NamedDecl *D = F.next();
1457 
1458     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1459       continue;
1460 
1461     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1462       continue;
1463 
1464     F.erase();
1465   }
1466 
1467   F.done();
1468 }
1469 
1470 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1471 /// have compatible owning modules.
1472 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1473   // FIXME: The Modules TS is not clear about how friend declarations are
1474   // to be treated. It's not meaningful to have different owning modules for
1475   // linkage in redeclarations of the same entity, so for now allow the
1476   // redeclaration and change the owning modules to match.
1477   if (New->getFriendObjectKind() &&
1478       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1479     New->setLocalOwningModule(Old->getOwningModule());
1480     makeMergedDefinitionVisible(New);
1481     return false;
1482   }
1483 
1484   Module *NewM = New->getOwningModule();
1485   Module *OldM = Old->getOwningModule();
1486 
1487   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1488     NewM = NewM->Parent;
1489   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1490     OldM = OldM->Parent;
1491 
1492   if (NewM == OldM)
1493     return false;
1494 
1495   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1496   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1497   if (NewIsModuleInterface || OldIsModuleInterface) {
1498     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1499     //   if a declaration of D [...] appears in the purview of a module, all
1500     //   other such declarations shall appear in the purview of the same module
1501     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1502       << New
1503       << NewIsModuleInterface
1504       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1505       << OldIsModuleInterface
1506       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1507     Diag(Old->getLocation(), diag::note_previous_declaration);
1508     New->setInvalidDecl();
1509     return true;
1510   }
1511 
1512   return false;
1513 }
1514 
1515 static bool isUsingDecl(NamedDecl *D) {
1516   return isa<UsingShadowDecl>(D) ||
1517          isa<UnresolvedUsingTypenameDecl>(D) ||
1518          isa<UnresolvedUsingValueDecl>(D);
1519 }
1520 
1521 /// Removes using shadow declarations from the lookup results.
1522 static void RemoveUsingDecls(LookupResult &R) {
1523   LookupResult::Filter F = R.makeFilter();
1524   while (F.hasNext())
1525     if (isUsingDecl(F.next()))
1526       F.erase();
1527 
1528   F.done();
1529 }
1530 
1531 /// Check for this common pattern:
1532 /// @code
1533 /// class S {
1534 ///   S(const S&); // DO NOT IMPLEMENT
1535 ///   void operator=(const S&); // DO NOT IMPLEMENT
1536 /// };
1537 /// @endcode
1538 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1539   // FIXME: Should check for private access too but access is set after we get
1540   // the decl here.
1541   if (D->doesThisDeclarationHaveABody())
1542     return false;
1543 
1544   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1545     return CD->isCopyConstructor();
1546   return D->isCopyAssignmentOperator();
1547 }
1548 
1549 // We need this to handle
1550 //
1551 // typedef struct {
1552 //   void *foo() { return 0; }
1553 // } A;
1554 //
1555 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1556 // for example. If 'A', foo will have external linkage. If we have '*A',
1557 // foo will have no linkage. Since we can't know until we get to the end
1558 // of the typedef, this function finds out if D might have non-external linkage.
1559 // Callers should verify at the end of the TU if it D has external linkage or
1560 // not.
1561 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1562   const DeclContext *DC = D->getDeclContext();
1563   while (!DC->isTranslationUnit()) {
1564     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1565       if (!RD->hasNameForLinkage())
1566         return true;
1567     }
1568     DC = DC->getParent();
1569   }
1570 
1571   return !D->isExternallyVisible();
1572 }
1573 
1574 // FIXME: This needs to be refactored; some other isInMainFile users want
1575 // these semantics.
1576 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1577   if (S.TUKind != TU_Complete)
1578     return false;
1579   return S.SourceMgr.isInMainFile(Loc);
1580 }
1581 
1582 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1583   assert(D);
1584 
1585   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1586     return false;
1587 
1588   // Ignore all entities declared within templates, and out-of-line definitions
1589   // of members of class templates.
1590   if (D->getDeclContext()->isDependentContext() ||
1591       D->getLexicalDeclContext()->isDependentContext())
1592     return false;
1593 
1594   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1595     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1596       return false;
1597     // A non-out-of-line declaration of a member specialization was implicitly
1598     // instantiated; it's the out-of-line declaration that we're interested in.
1599     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1600         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1601       return false;
1602 
1603     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1604       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1605         return false;
1606     } else {
1607       // 'static inline' functions are defined in headers; don't warn.
1608       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1609         return false;
1610     }
1611 
1612     if (FD->doesThisDeclarationHaveABody() &&
1613         Context.DeclMustBeEmitted(FD))
1614       return false;
1615   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1616     // Constants and utility variables are defined in headers with internal
1617     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1618     // like "inline".)
1619     if (!isMainFileLoc(*this, VD->getLocation()))
1620       return false;
1621 
1622     if (Context.DeclMustBeEmitted(VD))
1623       return false;
1624 
1625     if (VD->isStaticDataMember() &&
1626         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1627       return false;
1628     if (VD->isStaticDataMember() &&
1629         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1630         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1631       return false;
1632 
1633     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1634       return false;
1635   } else {
1636     return false;
1637   }
1638 
1639   // Only warn for unused decls internal to the translation unit.
1640   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1641   // for inline functions defined in the main source file, for instance.
1642   return mightHaveNonExternalLinkage(D);
1643 }
1644 
1645 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1646   if (!D)
1647     return;
1648 
1649   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1650     const FunctionDecl *First = FD->getFirstDecl();
1651     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1652       return; // First should already be in the vector.
1653   }
1654 
1655   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1656     const VarDecl *First = VD->getFirstDecl();
1657     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1658       return; // First should already be in the vector.
1659   }
1660 
1661   if (ShouldWarnIfUnusedFileScopedDecl(D))
1662     UnusedFileScopedDecls.push_back(D);
1663 }
1664 
1665 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1666   if (D->isInvalidDecl())
1667     return false;
1668 
1669   bool Referenced = false;
1670   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1671     // For a decomposition declaration, warn if none of the bindings are
1672     // referenced, instead of if the variable itself is referenced (which
1673     // it is, by the bindings' expressions).
1674     for (auto *BD : DD->bindings()) {
1675       if (BD->isReferenced()) {
1676         Referenced = true;
1677         break;
1678       }
1679     }
1680   } else if (!D->getDeclName()) {
1681     return false;
1682   } else if (D->isReferenced() || D->isUsed()) {
1683     Referenced = true;
1684   }
1685 
1686   if (Referenced || D->hasAttr<UnusedAttr>() ||
1687       D->hasAttr<ObjCPreciseLifetimeAttr>())
1688     return false;
1689 
1690   if (isa<LabelDecl>(D))
1691     return true;
1692 
1693   // Except for labels, we only care about unused decls that are local to
1694   // functions.
1695   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1696   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1697     // For dependent types, the diagnostic is deferred.
1698     WithinFunction =
1699         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1700   if (!WithinFunction)
1701     return false;
1702 
1703   if (isa<TypedefNameDecl>(D))
1704     return true;
1705 
1706   // White-list anything that isn't a local variable.
1707   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1708     return false;
1709 
1710   // Types of valid local variables should be complete, so this should succeed.
1711   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1712 
1713     // White-list anything with an __attribute__((unused)) type.
1714     const auto *Ty = VD->getType().getTypePtr();
1715 
1716     // Only look at the outermost level of typedef.
1717     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1718       if (TT->getDecl()->hasAttr<UnusedAttr>())
1719         return false;
1720     }
1721 
1722     // If we failed to complete the type for some reason, or if the type is
1723     // dependent, don't diagnose the variable.
1724     if (Ty->isIncompleteType() || Ty->isDependentType())
1725       return false;
1726 
1727     // Look at the element type to ensure that the warning behaviour is
1728     // consistent for both scalars and arrays.
1729     Ty = Ty->getBaseElementTypeUnsafe();
1730 
1731     if (const TagType *TT = Ty->getAs<TagType>()) {
1732       const TagDecl *Tag = TT->getDecl();
1733       if (Tag->hasAttr<UnusedAttr>())
1734         return false;
1735 
1736       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1737         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1738           return false;
1739 
1740         if (const Expr *Init = VD->getInit()) {
1741           if (const ExprWithCleanups *Cleanups =
1742                   dyn_cast<ExprWithCleanups>(Init))
1743             Init = Cleanups->getSubExpr();
1744           const CXXConstructExpr *Construct =
1745             dyn_cast<CXXConstructExpr>(Init);
1746           if (Construct && !Construct->isElidable()) {
1747             CXXConstructorDecl *CD = Construct->getConstructor();
1748             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1749                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1750               return false;
1751           }
1752         }
1753       }
1754     }
1755 
1756     // TODO: __attribute__((unused)) templates?
1757   }
1758 
1759   return true;
1760 }
1761 
1762 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1763                                      FixItHint &Hint) {
1764   if (isa<LabelDecl>(D)) {
1765     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1766         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1767         true);
1768     if (AfterColon.isInvalid())
1769       return;
1770     Hint = FixItHint::CreateRemoval(
1771         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1772   }
1773 }
1774 
1775 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1776   if (D->getTypeForDecl()->isDependentType())
1777     return;
1778 
1779   for (auto *TmpD : D->decls()) {
1780     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1781       DiagnoseUnusedDecl(T);
1782     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1783       DiagnoseUnusedNestedTypedefs(R);
1784   }
1785 }
1786 
1787 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1788 /// unless they are marked attr(unused).
1789 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1790   if (!ShouldDiagnoseUnusedDecl(D))
1791     return;
1792 
1793   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1794     // typedefs can be referenced later on, so the diagnostics are emitted
1795     // at end-of-translation-unit.
1796     UnusedLocalTypedefNameCandidates.insert(TD);
1797     return;
1798   }
1799 
1800   FixItHint Hint;
1801   GenerateFixForUnusedDecl(D, Context, Hint);
1802 
1803   unsigned DiagID;
1804   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1805     DiagID = diag::warn_unused_exception_param;
1806   else if (isa<LabelDecl>(D))
1807     DiagID = diag::warn_unused_label;
1808   else
1809     DiagID = diag::warn_unused_variable;
1810 
1811   Diag(D->getLocation(), DiagID) << D << Hint;
1812 }
1813 
1814 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1815   // Verify that we have no forward references left.  If so, there was a goto
1816   // or address of a label taken, but no definition of it.  Label fwd
1817   // definitions are indicated with a null substmt which is also not a resolved
1818   // MS inline assembly label name.
1819   bool Diagnose = false;
1820   if (L->isMSAsmLabel())
1821     Diagnose = !L->isResolvedMSAsmLabel();
1822   else
1823     Diagnose = L->getStmt() == nullptr;
1824   if (Diagnose)
1825     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1826 }
1827 
1828 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1829   S->mergeNRVOIntoParent();
1830 
1831   if (S->decl_empty()) return;
1832   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1833          "Scope shouldn't contain decls!");
1834 
1835   for (auto *TmpD : S->decls()) {
1836     assert(TmpD && "This decl didn't get pushed??");
1837 
1838     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1839     NamedDecl *D = cast<NamedDecl>(TmpD);
1840 
1841     // Diagnose unused variables in this scope.
1842     if (!S->hasUnrecoverableErrorOccurred()) {
1843       DiagnoseUnusedDecl(D);
1844       if (const auto *RD = dyn_cast<RecordDecl>(D))
1845         DiagnoseUnusedNestedTypedefs(RD);
1846     }
1847 
1848     if (!D->getDeclName()) continue;
1849 
1850     // If this was a forward reference to a label, verify it was defined.
1851     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1852       CheckPoppedLabel(LD, *this);
1853 
1854     // Remove this name from our lexical scope, and warn on it if we haven't
1855     // already.
1856     IdResolver.RemoveDecl(D);
1857     auto ShadowI = ShadowingDecls.find(D);
1858     if (ShadowI != ShadowingDecls.end()) {
1859       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1860         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1861             << D << FD << FD->getParent();
1862         Diag(FD->getLocation(), diag::note_previous_declaration);
1863       }
1864       ShadowingDecls.erase(ShadowI);
1865     }
1866   }
1867 }
1868 
1869 /// Look for an Objective-C class in the translation unit.
1870 ///
1871 /// \param Id The name of the Objective-C class we're looking for. If
1872 /// typo-correction fixes this name, the Id will be updated
1873 /// to the fixed name.
1874 ///
1875 /// \param IdLoc The location of the name in the translation unit.
1876 ///
1877 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1878 /// if there is no class with the given name.
1879 ///
1880 /// \returns The declaration of the named Objective-C class, or NULL if the
1881 /// class could not be found.
1882 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1883                                               SourceLocation IdLoc,
1884                                               bool DoTypoCorrection) {
1885   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1886   // creation from this context.
1887   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1888 
1889   if (!IDecl && DoTypoCorrection) {
1890     // Perform typo correction at the given location, but only if we
1891     // find an Objective-C class name.
1892     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1893     if (TypoCorrection C =
1894             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1895                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1896       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1897       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1898       Id = IDecl->getIdentifier();
1899     }
1900   }
1901   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1902   // This routine must always return a class definition, if any.
1903   if (Def && Def->getDefinition())
1904       Def = Def->getDefinition();
1905   return Def;
1906 }
1907 
1908 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1909 /// from S, where a non-field would be declared. This routine copes
1910 /// with the difference between C and C++ scoping rules in structs and
1911 /// unions. For example, the following code is well-formed in C but
1912 /// ill-formed in C++:
1913 /// @code
1914 /// struct S6 {
1915 ///   enum { BAR } e;
1916 /// };
1917 ///
1918 /// void test_S6() {
1919 ///   struct S6 a;
1920 ///   a.e = BAR;
1921 /// }
1922 /// @endcode
1923 /// For the declaration of BAR, this routine will return a different
1924 /// scope. The scope S will be the scope of the unnamed enumeration
1925 /// within S6. In C++, this routine will return the scope associated
1926 /// with S6, because the enumeration's scope is a transparent
1927 /// context but structures can contain non-field names. In C, this
1928 /// routine will return the translation unit scope, since the
1929 /// enumeration's scope is a transparent context and structures cannot
1930 /// contain non-field names.
1931 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1932   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1933          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1934          (S->isClassScope() && !getLangOpts().CPlusPlus))
1935     S = S->getParent();
1936   return S;
1937 }
1938 
1939 /// Looks up the declaration of "struct objc_super" and
1940 /// saves it for later use in building builtin declaration of
1941 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1942 /// pre-existing declaration exists no action takes place.
1943 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1944                                         IdentifierInfo *II) {
1945   if (!II->isStr("objc_msgSendSuper"))
1946     return;
1947   ASTContext &Context = ThisSema.Context;
1948 
1949   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1950                       SourceLocation(), Sema::LookupTagName);
1951   ThisSema.LookupName(Result, S);
1952   if (Result.getResultKind() == LookupResult::Found)
1953     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1954       Context.setObjCSuperType(Context.getTagDeclType(TD));
1955 }
1956 
1957 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1958                                ASTContext::GetBuiltinTypeError Error) {
1959   switch (Error) {
1960   case ASTContext::GE_None:
1961     return "";
1962   case ASTContext::GE_Missing_type:
1963     return BuiltinInfo.getHeaderName(ID);
1964   case ASTContext::GE_Missing_stdio:
1965     return "stdio.h";
1966   case ASTContext::GE_Missing_setjmp:
1967     return "setjmp.h";
1968   case ASTContext::GE_Missing_ucontext:
1969     return "ucontext.h";
1970   }
1971   llvm_unreachable("unhandled error kind");
1972 }
1973 
1974 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1975 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1976 /// if we're creating this built-in in anticipation of redeclaring the
1977 /// built-in.
1978 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1979                                      Scope *S, bool ForRedeclaration,
1980                                      SourceLocation Loc) {
1981   LookupPredefedObjCSuperType(*this, S, II);
1982 
1983   ASTContext::GetBuiltinTypeError Error;
1984   QualType R = Context.GetBuiltinType(ID, Error);
1985   if (Error) {
1986     if (!ForRedeclaration)
1987       return nullptr;
1988 
1989     // If we have a builtin without an associated type we should not emit a
1990     // warning when we were not able to find a type for it.
1991     if (Error == ASTContext::GE_Missing_type)
1992       return nullptr;
1993 
1994     // If we could not find a type for setjmp it is because the jmp_buf type was
1995     // not defined prior to the setjmp declaration.
1996     if (Error == ASTContext::GE_Missing_setjmp) {
1997       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
1998           << Context.BuiltinInfo.getName(ID);
1999       return nullptr;
2000     }
2001 
2002     // Generally, we emit a warning that the declaration requires the
2003     // appropriate header.
2004     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2005         << getHeaderName(Context.BuiltinInfo, ID, Error)
2006         << Context.BuiltinInfo.getName(ID);
2007     return nullptr;
2008   }
2009 
2010   if (!ForRedeclaration &&
2011       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2012        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2013     Diag(Loc, diag::ext_implicit_lib_function_decl)
2014         << Context.BuiltinInfo.getName(ID) << R;
2015     if (Context.BuiltinInfo.getHeaderName(ID) &&
2016         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2017       Diag(Loc, diag::note_include_header_or_declare)
2018           << Context.BuiltinInfo.getHeaderName(ID)
2019           << Context.BuiltinInfo.getName(ID);
2020   }
2021 
2022   if (R.isNull())
2023     return nullptr;
2024 
2025   DeclContext *Parent = Context.getTranslationUnitDecl();
2026   if (getLangOpts().CPlusPlus) {
2027     LinkageSpecDecl *CLinkageDecl =
2028         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2029                                 LinkageSpecDecl::lang_c, false);
2030     CLinkageDecl->setImplicit();
2031     Parent->addDecl(CLinkageDecl);
2032     Parent = CLinkageDecl;
2033   }
2034 
2035   FunctionDecl *New = FunctionDecl::Create(Context,
2036                                            Parent,
2037                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
2038                                            SC_Extern,
2039                                            false,
2040                                            R->isFunctionProtoType());
2041   New->setImplicit();
2042 
2043   // Create Decl objects for each parameter, adding them to the
2044   // FunctionDecl.
2045   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2046     SmallVector<ParmVarDecl*, 16> Params;
2047     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2048       ParmVarDecl *parm =
2049           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2050                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2051                               SC_None, nullptr);
2052       parm->setScopeInfo(0, i);
2053       Params.push_back(parm);
2054     }
2055     New->setParams(Params);
2056   }
2057 
2058   AddKnownFunctionAttributes(New);
2059   RegisterLocallyScopedExternCDecl(New, S);
2060 
2061   // TUScope is the translation-unit scope to insert this function into.
2062   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2063   // relate Scopes to DeclContexts, and probably eliminate CurContext
2064   // entirely, but we're not there yet.
2065   DeclContext *SavedContext = CurContext;
2066   CurContext = Parent;
2067   PushOnScopeChains(New, TUScope);
2068   CurContext = SavedContext;
2069   return New;
2070 }
2071 
2072 /// Typedef declarations don't have linkage, but they still denote the same
2073 /// entity if their types are the same.
2074 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2075 /// isSameEntity.
2076 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2077                                                      TypedefNameDecl *Decl,
2078                                                      LookupResult &Previous) {
2079   // This is only interesting when modules are enabled.
2080   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2081     return;
2082 
2083   // Empty sets are uninteresting.
2084   if (Previous.empty())
2085     return;
2086 
2087   LookupResult::Filter Filter = Previous.makeFilter();
2088   while (Filter.hasNext()) {
2089     NamedDecl *Old = Filter.next();
2090 
2091     // Non-hidden declarations are never ignored.
2092     if (S.isVisible(Old))
2093       continue;
2094 
2095     // Declarations of the same entity are not ignored, even if they have
2096     // different linkages.
2097     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2098       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2099                                 Decl->getUnderlyingType()))
2100         continue;
2101 
2102       // If both declarations give a tag declaration a typedef name for linkage
2103       // purposes, then they declare the same entity.
2104       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2105           Decl->getAnonDeclWithTypedefName())
2106         continue;
2107     }
2108 
2109     Filter.erase();
2110   }
2111 
2112   Filter.done();
2113 }
2114 
2115 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2116   QualType OldType;
2117   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2118     OldType = OldTypedef->getUnderlyingType();
2119   else
2120     OldType = Context.getTypeDeclType(Old);
2121   QualType NewType = New->getUnderlyingType();
2122 
2123   if (NewType->isVariablyModifiedType()) {
2124     // Must not redefine a typedef with a variably-modified type.
2125     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2126     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2127       << Kind << NewType;
2128     if (Old->getLocation().isValid())
2129       notePreviousDefinition(Old, New->getLocation());
2130     New->setInvalidDecl();
2131     return true;
2132   }
2133 
2134   if (OldType != NewType &&
2135       !OldType->isDependentType() &&
2136       !NewType->isDependentType() &&
2137       !Context.hasSameType(OldType, NewType)) {
2138     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2139     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2140       << Kind << NewType << OldType;
2141     if (Old->getLocation().isValid())
2142       notePreviousDefinition(Old, New->getLocation());
2143     New->setInvalidDecl();
2144     return true;
2145   }
2146   return false;
2147 }
2148 
2149 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2150 /// same name and scope as a previous declaration 'Old'.  Figure out
2151 /// how to resolve this situation, merging decls or emitting
2152 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2153 ///
2154 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2155                                 LookupResult &OldDecls) {
2156   // If the new decl is known invalid already, don't bother doing any
2157   // merging checks.
2158   if (New->isInvalidDecl()) return;
2159 
2160   // Allow multiple definitions for ObjC built-in typedefs.
2161   // FIXME: Verify the underlying types are equivalent!
2162   if (getLangOpts().ObjC) {
2163     const IdentifierInfo *TypeID = New->getIdentifier();
2164     switch (TypeID->getLength()) {
2165     default: break;
2166     case 2:
2167       {
2168         if (!TypeID->isStr("id"))
2169           break;
2170         QualType T = New->getUnderlyingType();
2171         if (!T->isPointerType())
2172           break;
2173         if (!T->isVoidPointerType()) {
2174           QualType PT = T->getAs<PointerType>()->getPointeeType();
2175           if (!PT->isStructureType())
2176             break;
2177         }
2178         Context.setObjCIdRedefinitionType(T);
2179         // Install the built-in type for 'id', ignoring the current definition.
2180         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2181         return;
2182       }
2183     case 5:
2184       if (!TypeID->isStr("Class"))
2185         break;
2186       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2187       // Install the built-in type for 'Class', ignoring the current definition.
2188       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2189       return;
2190     case 3:
2191       if (!TypeID->isStr("SEL"))
2192         break;
2193       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2194       // Install the built-in type for 'SEL', ignoring the current definition.
2195       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2196       return;
2197     }
2198     // Fall through - the typedef name was not a builtin type.
2199   }
2200 
2201   // Verify the old decl was also a type.
2202   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2203   if (!Old) {
2204     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2205       << New->getDeclName();
2206 
2207     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2208     if (OldD->getLocation().isValid())
2209       notePreviousDefinition(OldD, New->getLocation());
2210 
2211     return New->setInvalidDecl();
2212   }
2213 
2214   // If the old declaration is invalid, just give up here.
2215   if (Old->isInvalidDecl())
2216     return New->setInvalidDecl();
2217 
2218   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2219     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2220     auto *NewTag = New->getAnonDeclWithTypedefName();
2221     NamedDecl *Hidden = nullptr;
2222     if (OldTag && NewTag &&
2223         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2224         !hasVisibleDefinition(OldTag, &Hidden)) {
2225       // There is a definition of this tag, but it is not visible. Use it
2226       // instead of our tag.
2227       New->setTypeForDecl(OldTD->getTypeForDecl());
2228       if (OldTD->isModed())
2229         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2230                                     OldTD->getUnderlyingType());
2231       else
2232         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2233 
2234       // Make the old tag definition visible.
2235       makeMergedDefinitionVisible(Hidden);
2236 
2237       // If this was an unscoped enumeration, yank all of its enumerators
2238       // out of the scope.
2239       if (isa<EnumDecl>(NewTag)) {
2240         Scope *EnumScope = getNonFieldDeclScope(S);
2241         for (auto *D : NewTag->decls()) {
2242           auto *ED = cast<EnumConstantDecl>(D);
2243           assert(EnumScope->isDeclScope(ED));
2244           EnumScope->RemoveDecl(ED);
2245           IdResolver.RemoveDecl(ED);
2246           ED->getLexicalDeclContext()->removeDecl(ED);
2247         }
2248       }
2249     }
2250   }
2251 
2252   // If the typedef types are not identical, reject them in all languages and
2253   // with any extensions enabled.
2254   if (isIncompatibleTypedef(Old, New))
2255     return;
2256 
2257   // The types match.  Link up the redeclaration chain and merge attributes if
2258   // the old declaration was a typedef.
2259   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2260     New->setPreviousDecl(Typedef);
2261     mergeDeclAttributes(New, Old);
2262   }
2263 
2264   if (getLangOpts().MicrosoftExt)
2265     return;
2266 
2267   if (getLangOpts().CPlusPlus) {
2268     // C++ [dcl.typedef]p2:
2269     //   In a given non-class scope, a typedef specifier can be used to
2270     //   redefine the name of any type declared in that scope to refer
2271     //   to the type to which it already refers.
2272     if (!isa<CXXRecordDecl>(CurContext))
2273       return;
2274 
2275     // C++0x [dcl.typedef]p4:
2276     //   In a given class scope, a typedef specifier can be used to redefine
2277     //   any class-name declared in that scope that is not also a typedef-name
2278     //   to refer to the type to which it already refers.
2279     //
2280     // This wording came in via DR424, which was a correction to the
2281     // wording in DR56, which accidentally banned code like:
2282     //
2283     //   struct S {
2284     //     typedef struct A { } A;
2285     //   };
2286     //
2287     // in the C++03 standard. We implement the C++0x semantics, which
2288     // allow the above but disallow
2289     //
2290     //   struct S {
2291     //     typedef int I;
2292     //     typedef int I;
2293     //   };
2294     //
2295     // since that was the intent of DR56.
2296     if (!isa<TypedefNameDecl>(Old))
2297       return;
2298 
2299     Diag(New->getLocation(), diag::err_redefinition)
2300       << New->getDeclName();
2301     notePreviousDefinition(Old, New->getLocation());
2302     return New->setInvalidDecl();
2303   }
2304 
2305   // Modules always permit redefinition of typedefs, as does C11.
2306   if (getLangOpts().Modules || getLangOpts().C11)
2307     return;
2308 
2309   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2310   // is normally mapped to an error, but can be controlled with
2311   // -Wtypedef-redefinition.  If either the original or the redefinition is
2312   // in a system header, don't emit this for compatibility with GCC.
2313   if (getDiagnostics().getSuppressSystemWarnings() &&
2314       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2315       (Old->isImplicit() ||
2316        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2317        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2318     return;
2319 
2320   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2321     << New->getDeclName();
2322   notePreviousDefinition(Old, New->getLocation());
2323 }
2324 
2325 /// DeclhasAttr - returns true if decl Declaration already has the target
2326 /// attribute.
2327 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2328   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2329   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2330   for (const auto *i : D->attrs())
2331     if (i->getKind() == A->getKind()) {
2332       if (Ann) {
2333         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2334           return true;
2335         continue;
2336       }
2337       // FIXME: Don't hardcode this check
2338       if (OA && isa<OwnershipAttr>(i))
2339         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2340       return true;
2341     }
2342 
2343   return false;
2344 }
2345 
2346 static bool isAttributeTargetADefinition(Decl *D) {
2347   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2348     return VD->isThisDeclarationADefinition();
2349   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2350     return TD->isCompleteDefinition() || TD->isBeingDefined();
2351   return true;
2352 }
2353 
2354 /// Merge alignment attributes from \p Old to \p New, taking into account the
2355 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2356 ///
2357 /// \return \c true if any attributes were added to \p New.
2358 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2359   // Look for alignas attributes on Old, and pick out whichever attribute
2360   // specifies the strictest alignment requirement.
2361   AlignedAttr *OldAlignasAttr = nullptr;
2362   AlignedAttr *OldStrictestAlignAttr = nullptr;
2363   unsigned OldAlign = 0;
2364   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2365     // FIXME: We have no way of representing inherited dependent alignments
2366     // in a case like:
2367     //   template<int A, int B> struct alignas(A) X;
2368     //   template<int A, int B> struct alignas(B) X {};
2369     // For now, we just ignore any alignas attributes which are not on the
2370     // definition in such a case.
2371     if (I->isAlignmentDependent())
2372       return false;
2373 
2374     if (I->isAlignas())
2375       OldAlignasAttr = I;
2376 
2377     unsigned Align = I->getAlignment(S.Context);
2378     if (Align > OldAlign) {
2379       OldAlign = Align;
2380       OldStrictestAlignAttr = I;
2381     }
2382   }
2383 
2384   // Look for alignas attributes on New.
2385   AlignedAttr *NewAlignasAttr = nullptr;
2386   unsigned NewAlign = 0;
2387   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2388     if (I->isAlignmentDependent())
2389       return false;
2390 
2391     if (I->isAlignas())
2392       NewAlignasAttr = I;
2393 
2394     unsigned Align = I->getAlignment(S.Context);
2395     if (Align > NewAlign)
2396       NewAlign = Align;
2397   }
2398 
2399   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2400     // Both declarations have 'alignas' attributes. We require them to match.
2401     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2402     // fall short. (If two declarations both have alignas, they must both match
2403     // every definition, and so must match each other if there is a definition.)
2404 
2405     // If either declaration only contains 'alignas(0)' specifiers, then it
2406     // specifies the natural alignment for the type.
2407     if (OldAlign == 0 || NewAlign == 0) {
2408       QualType Ty;
2409       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2410         Ty = VD->getType();
2411       else
2412         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2413 
2414       if (OldAlign == 0)
2415         OldAlign = S.Context.getTypeAlign(Ty);
2416       if (NewAlign == 0)
2417         NewAlign = S.Context.getTypeAlign(Ty);
2418     }
2419 
2420     if (OldAlign != NewAlign) {
2421       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2422         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2423         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2424       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2425     }
2426   }
2427 
2428   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2429     // C++11 [dcl.align]p6:
2430     //   if any declaration of an entity has an alignment-specifier,
2431     //   every defining declaration of that entity shall specify an
2432     //   equivalent alignment.
2433     // C11 6.7.5/7:
2434     //   If the definition of an object does not have an alignment
2435     //   specifier, any other declaration of that object shall also
2436     //   have no alignment specifier.
2437     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2438       << OldAlignasAttr;
2439     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2440       << OldAlignasAttr;
2441   }
2442 
2443   bool AnyAdded = false;
2444 
2445   // Ensure we have an attribute representing the strictest alignment.
2446   if (OldAlign > NewAlign) {
2447     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2448     Clone->setInherited(true);
2449     New->addAttr(Clone);
2450     AnyAdded = true;
2451   }
2452 
2453   // Ensure we have an alignas attribute if the old declaration had one.
2454   if (OldAlignasAttr && !NewAlignasAttr &&
2455       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2456     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2457     Clone->setInherited(true);
2458     New->addAttr(Clone);
2459     AnyAdded = true;
2460   }
2461 
2462   return AnyAdded;
2463 }
2464 
2465 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2466                                const InheritableAttr *Attr,
2467                                Sema::AvailabilityMergeKind AMK) {
2468   // This function copies an attribute Attr from a previous declaration to the
2469   // new declaration D if the new declaration doesn't itself have that attribute
2470   // yet or if that attribute allows duplicates.
2471   // If you're adding a new attribute that requires logic different from
2472   // "use explicit attribute on decl if present, else use attribute from
2473   // previous decl", for example if the attribute needs to be consistent
2474   // between redeclarations, you need to call a custom merge function here.
2475   InheritableAttr *NewAttr = nullptr;
2476   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2477   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2478     NewAttr = S.mergeAvailabilityAttr(
2479         D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2480         AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2481         AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2482         AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2483   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2484     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2485                                     AttrSpellingListIndex);
2486   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2487     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2488                                         AttrSpellingListIndex);
2489   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2490     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2491                                    AttrSpellingListIndex);
2492   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2493     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2494                                    AttrSpellingListIndex);
2495   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2496     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2497                                 FA->getFormatIdx(), FA->getFirstArg(),
2498                                 AttrSpellingListIndex);
2499   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2500     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2501                                  AttrSpellingListIndex);
2502   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2503     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2504                                  AttrSpellingListIndex);
2505   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2506     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2507                                        AttrSpellingListIndex,
2508                                        IA->getSemanticSpelling());
2509   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2510     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2511                                       &S.Context.Idents.get(AA->getSpelling()),
2512                                       AttrSpellingListIndex);
2513   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2514            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2515             isa<CUDAGlobalAttr>(Attr))) {
2516     // CUDA target attributes are part of function signature for
2517     // overloading purposes and must not be merged.
2518     return false;
2519   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2520     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2521   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2522     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2523   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2524     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2525   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2526     NewAttr = S.mergeCommonAttr(D, *CommonA);
2527   else if (isa<AlignedAttr>(Attr))
2528     // AlignedAttrs are handled separately, because we need to handle all
2529     // such attributes on a declaration at the same time.
2530     NewAttr = nullptr;
2531   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2532            (AMK == Sema::AMK_Override ||
2533             AMK == Sema::AMK_ProtocolImplementation))
2534     NewAttr = nullptr;
2535   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2536     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2537                               UA->getGuid());
2538   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2539     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2540   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2541     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2542   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2543     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2544 
2545   if (NewAttr) {
2546     NewAttr->setInherited(true);
2547     D->addAttr(NewAttr);
2548     if (isa<MSInheritanceAttr>(NewAttr))
2549       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2550     return true;
2551   }
2552 
2553   return false;
2554 }
2555 
2556 static const NamedDecl *getDefinition(const Decl *D) {
2557   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2558     return TD->getDefinition();
2559   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2560     const VarDecl *Def = VD->getDefinition();
2561     if (Def)
2562       return Def;
2563     return VD->getActingDefinition();
2564   }
2565   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2566     return FD->getDefinition();
2567   return nullptr;
2568 }
2569 
2570 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2571   for (const auto *Attribute : D->attrs())
2572     if (Attribute->getKind() == Kind)
2573       return true;
2574   return false;
2575 }
2576 
2577 /// checkNewAttributesAfterDef - If we already have a definition, check that
2578 /// there are no new attributes in this declaration.
2579 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2580   if (!New->hasAttrs())
2581     return;
2582 
2583   const NamedDecl *Def = getDefinition(Old);
2584   if (!Def || Def == New)
2585     return;
2586 
2587   AttrVec &NewAttributes = New->getAttrs();
2588   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2589     const Attr *NewAttribute = NewAttributes[I];
2590 
2591     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2592       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2593         Sema::SkipBodyInfo SkipBody;
2594         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2595 
2596         // If we're skipping this definition, drop the "alias" attribute.
2597         if (SkipBody.ShouldSkip) {
2598           NewAttributes.erase(NewAttributes.begin() + I);
2599           --E;
2600           continue;
2601         }
2602       } else {
2603         VarDecl *VD = cast<VarDecl>(New);
2604         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2605                                 VarDecl::TentativeDefinition
2606                             ? diag::err_alias_after_tentative
2607                             : diag::err_redefinition;
2608         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2609         if (Diag == diag::err_redefinition)
2610           S.notePreviousDefinition(Def, VD->getLocation());
2611         else
2612           S.Diag(Def->getLocation(), diag::note_previous_definition);
2613         VD->setInvalidDecl();
2614       }
2615       ++I;
2616       continue;
2617     }
2618 
2619     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2620       // Tentative definitions are only interesting for the alias check above.
2621       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2622         ++I;
2623         continue;
2624       }
2625     }
2626 
2627     if (hasAttribute(Def, NewAttribute->getKind())) {
2628       ++I;
2629       continue; // regular attr merging will take care of validating this.
2630     }
2631 
2632     if (isa<C11NoReturnAttr>(NewAttribute)) {
2633       // C's _Noreturn is allowed to be added to a function after it is defined.
2634       ++I;
2635       continue;
2636     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2637       if (AA->isAlignas()) {
2638         // C++11 [dcl.align]p6:
2639         //   if any declaration of an entity has an alignment-specifier,
2640         //   every defining declaration of that entity shall specify an
2641         //   equivalent alignment.
2642         // C11 6.7.5/7:
2643         //   If the definition of an object does not have an alignment
2644         //   specifier, any other declaration of that object shall also
2645         //   have no alignment specifier.
2646         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2647           << AA;
2648         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2649           << AA;
2650         NewAttributes.erase(NewAttributes.begin() + I);
2651         --E;
2652         continue;
2653       }
2654     }
2655 
2656     S.Diag(NewAttribute->getLocation(),
2657            diag::warn_attribute_precede_definition);
2658     S.Diag(Def->getLocation(), diag::note_previous_definition);
2659     NewAttributes.erase(NewAttributes.begin() + I);
2660     --E;
2661   }
2662 }
2663 
2664 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2665 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2666                                AvailabilityMergeKind AMK) {
2667   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2668     UsedAttr *NewAttr = OldAttr->clone(Context);
2669     NewAttr->setInherited(true);
2670     New->addAttr(NewAttr);
2671   }
2672 
2673   if (!Old->hasAttrs() && !New->hasAttrs())
2674     return;
2675 
2676   // Attributes declared post-definition are currently ignored.
2677   checkNewAttributesAfterDef(*this, New, Old);
2678 
2679   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2680     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2681       if (OldA->getLabel() != NewA->getLabel()) {
2682         // This redeclaration changes __asm__ label.
2683         Diag(New->getLocation(), diag::err_different_asm_label);
2684         Diag(OldA->getLocation(), diag::note_previous_declaration);
2685       }
2686     } else if (Old->isUsed()) {
2687       // This redeclaration adds an __asm__ label to a declaration that has
2688       // already been ODR-used.
2689       Diag(New->getLocation(), diag::err_late_asm_label_name)
2690         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2691     }
2692   }
2693 
2694   // Re-declaration cannot add abi_tag's.
2695   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2696     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2697       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2698         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2699                       NewTag) == OldAbiTagAttr->tags_end()) {
2700           Diag(NewAbiTagAttr->getLocation(),
2701                diag::err_new_abi_tag_on_redeclaration)
2702               << NewTag;
2703           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2704         }
2705       }
2706     } else {
2707       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2708       Diag(Old->getLocation(), diag::note_previous_declaration);
2709     }
2710   }
2711 
2712   // This redeclaration adds a section attribute.
2713   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2714     if (auto *VD = dyn_cast<VarDecl>(New)) {
2715       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2716         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2717         Diag(Old->getLocation(), diag::note_previous_declaration);
2718       }
2719     }
2720   }
2721 
2722   // Redeclaration adds code-seg attribute.
2723   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2724   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2725       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2726     Diag(New->getLocation(), diag::warn_mismatched_section)
2727          << 0 /*codeseg*/;
2728     Diag(Old->getLocation(), diag::note_previous_declaration);
2729   }
2730 
2731   if (!Old->hasAttrs())
2732     return;
2733 
2734   bool foundAny = New->hasAttrs();
2735 
2736   // Ensure that any moving of objects within the allocated map is done before
2737   // we process them.
2738   if (!foundAny) New->setAttrs(AttrVec());
2739 
2740   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2741     // Ignore deprecated/unavailable/availability attributes if requested.
2742     AvailabilityMergeKind LocalAMK = AMK_None;
2743     if (isa<DeprecatedAttr>(I) ||
2744         isa<UnavailableAttr>(I) ||
2745         isa<AvailabilityAttr>(I)) {
2746       switch (AMK) {
2747       case AMK_None:
2748         continue;
2749 
2750       case AMK_Redeclaration:
2751       case AMK_Override:
2752       case AMK_ProtocolImplementation:
2753         LocalAMK = AMK;
2754         break;
2755       }
2756     }
2757 
2758     // Already handled.
2759     if (isa<UsedAttr>(I))
2760       continue;
2761 
2762     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2763       foundAny = true;
2764   }
2765 
2766   if (mergeAlignedAttrs(*this, New, Old))
2767     foundAny = true;
2768 
2769   if (!foundAny) New->dropAttrs();
2770 }
2771 
2772 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2773 /// to the new one.
2774 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2775                                      const ParmVarDecl *oldDecl,
2776                                      Sema &S) {
2777   // C++11 [dcl.attr.depend]p2:
2778   //   The first declaration of a function shall specify the
2779   //   carries_dependency attribute for its declarator-id if any declaration
2780   //   of the function specifies the carries_dependency attribute.
2781   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2782   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2783     S.Diag(CDA->getLocation(),
2784            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2785     // Find the first declaration of the parameter.
2786     // FIXME: Should we build redeclaration chains for function parameters?
2787     const FunctionDecl *FirstFD =
2788       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2789     const ParmVarDecl *FirstVD =
2790       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2791     S.Diag(FirstVD->getLocation(),
2792            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2793   }
2794 
2795   if (!oldDecl->hasAttrs())
2796     return;
2797 
2798   bool foundAny = newDecl->hasAttrs();
2799 
2800   // Ensure that any moving of objects within the allocated map is
2801   // done before we process them.
2802   if (!foundAny) newDecl->setAttrs(AttrVec());
2803 
2804   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2805     if (!DeclHasAttr(newDecl, I)) {
2806       InheritableAttr *newAttr =
2807         cast<InheritableParamAttr>(I->clone(S.Context));
2808       newAttr->setInherited(true);
2809       newDecl->addAttr(newAttr);
2810       foundAny = true;
2811     }
2812   }
2813 
2814   if (!foundAny) newDecl->dropAttrs();
2815 }
2816 
2817 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2818                                 const ParmVarDecl *OldParam,
2819                                 Sema &S) {
2820   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2821     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2822       if (*Oldnullability != *Newnullability) {
2823         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2824           << DiagNullabilityKind(
2825                *Newnullability,
2826                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2827                 != 0))
2828           << DiagNullabilityKind(
2829                *Oldnullability,
2830                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2831                 != 0));
2832         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2833       }
2834     } else {
2835       QualType NewT = NewParam->getType();
2836       NewT = S.Context.getAttributedType(
2837                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2838                          NewT, NewT);
2839       NewParam->setType(NewT);
2840     }
2841   }
2842 }
2843 
2844 namespace {
2845 
2846 /// Used in MergeFunctionDecl to keep track of function parameters in
2847 /// C.
2848 struct GNUCompatibleParamWarning {
2849   ParmVarDecl *OldParm;
2850   ParmVarDecl *NewParm;
2851   QualType PromotedType;
2852 };
2853 
2854 } // end anonymous namespace
2855 
2856 /// getSpecialMember - get the special member enum for a method.
2857 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2858   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2859     if (Ctor->isDefaultConstructor())
2860       return Sema::CXXDefaultConstructor;
2861 
2862     if (Ctor->isCopyConstructor())
2863       return Sema::CXXCopyConstructor;
2864 
2865     if (Ctor->isMoveConstructor())
2866       return Sema::CXXMoveConstructor;
2867   } else if (isa<CXXDestructorDecl>(MD)) {
2868     return Sema::CXXDestructor;
2869   } else if (MD->isCopyAssignmentOperator()) {
2870     return Sema::CXXCopyAssignment;
2871   } else if (MD->isMoveAssignmentOperator()) {
2872     return Sema::CXXMoveAssignment;
2873   }
2874 
2875   return Sema::CXXInvalid;
2876 }
2877 
2878 // Determine whether the previous declaration was a definition, implicit
2879 // declaration, or a declaration.
2880 template <typename T>
2881 static std::pair<diag::kind, SourceLocation>
2882 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2883   diag::kind PrevDiag;
2884   SourceLocation OldLocation = Old->getLocation();
2885   if (Old->isThisDeclarationADefinition())
2886     PrevDiag = diag::note_previous_definition;
2887   else if (Old->isImplicit()) {
2888     PrevDiag = diag::note_previous_implicit_declaration;
2889     if (OldLocation.isInvalid())
2890       OldLocation = New->getLocation();
2891   } else
2892     PrevDiag = diag::note_previous_declaration;
2893   return std::make_pair(PrevDiag, OldLocation);
2894 }
2895 
2896 /// canRedefineFunction - checks if a function can be redefined. Currently,
2897 /// only extern inline functions can be redefined, and even then only in
2898 /// GNU89 mode.
2899 static bool canRedefineFunction(const FunctionDecl *FD,
2900                                 const LangOptions& LangOpts) {
2901   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2902           !LangOpts.CPlusPlus &&
2903           FD->isInlineSpecified() &&
2904           FD->getStorageClass() == SC_Extern);
2905 }
2906 
2907 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2908   const AttributedType *AT = T->getAs<AttributedType>();
2909   while (AT && !AT->isCallingConv())
2910     AT = AT->getModifiedType()->getAs<AttributedType>();
2911   return AT;
2912 }
2913 
2914 template <typename T>
2915 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2916   const DeclContext *DC = Old->getDeclContext();
2917   if (DC->isRecord())
2918     return false;
2919 
2920   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2921   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2922     return true;
2923   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2924     return true;
2925   return false;
2926 }
2927 
2928 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2929 static bool isExternC(VarTemplateDecl *) { return false; }
2930 
2931 /// Check whether a redeclaration of an entity introduced by a
2932 /// using-declaration is valid, given that we know it's not an overload
2933 /// (nor a hidden tag declaration).
2934 template<typename ExpectedDecl>
2935 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2936                                    ExpectedDecl *New) {
2937   // C++11 [basic.scope.declarative]p4:
2938   //   Given a set of declarations in a single declarative region, each of
2939   //   which specifies the same unqualified name,
2940   //   -- they shall all refer to the same entity, or all refer to functions
2941   //      and function templates; or
2942   //   -- exactly one declaration shall declare a class name or enumeration
2943   //      name that is not a typedef name and the other declarations shall all
2944   //      refer to the same variable or enumerator, or all refer to functions
2945   //      and function templates; in this case the class name or enumeration
2946   //      name is hidden (3.3.10).
2947 
2948   // C++11 [namespace.udecl]p14:
2949   //   If a function declaration in namespace scope or block scope has the
2950   //   same name and the same parameter-type-list as a function introduced
2951   //   by a using-declaration, and the declarations do not declare the same
2952   //   function, the program is ill-formed.
2953 
2954   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2955   if (Old &&
2956       !Old->getDeclContext()->getRedeclContext()->Equals(
2957           New->getDeclContext()->getRedeclContext()) &&
2958       !(isExternC(Old) && isExternC(New)))
2959     Old = nullptr;
2960 
2961   if (!Old) {
2962     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2963     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2964     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2965     return true;
2966   }
2967   return false;
2968 }
2969 
2970 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2971                                             const FunctionDecl *B) {
2972   assert(A->getNumParams() == B->getNumParams());
2973 
2974   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2975     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2976     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2977     if (AttrA == AttrB)
2978       return true;
2979     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2980            AttrA->isDynamic() == AttrB->isDynamic();
2981   };
2982 
2983   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2984 }
2985 
2986 /// If necessary, adjust the semantic declaration context for a qualified
2987 /// declaration to name the correct inline namespace within the qualifier.
2988 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2989                                                DeclaratorDecl *OldD) {
2990   // The only case where we need to update the DeclContext is when
2991   // redeclaration lookup for a qualified name finds a declaration
2992   // in an inline namespace within the context named by the qualifier:
2993   //
2994   //   inline namespace N { int f(); }
2995   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2996   //
2997   // For unqualified declarations, the semantic context *can* change
2998   // along the redeclaration chain (for local extern declarations,
2999   // extern "C" declarations, and friend declarations in particular).
3000   if (!NewD->getQualifier())
3001     return;
3002 
3003   // NewD is probably already in the right context.
3004   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3005   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3006   if (NamedDC->Equals(SemaDC))
3007     return;
3008 
3009   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3010           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3011          "unexpected context for redeclaration");
3012 
3013   auto *LexDC = NewD->getLexicalDeclContext();
3014   auto FixSemaDC = [=](NamedDecl *D) {
3015     if (!D)
3016       return;
3017     D->setDeclContext(SemaDC);
3018     D->setLexicalDeclContext(LexDC);
3019   };
3020 
3021   FixSemaDC(NewD);
3022   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3023     FixSemaDC(FD->getDescribedFunctionTemplate());
3024   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3025     FixSemaDC(VD->getDescribedVarTemplate());
3026 }
3027 
3028 /// MergeFunctionDecl - We just parsed a function 'New' from
3029 /// declarator D which has the same name and scope as a previous
3030 /// declaration 'Old'.  Figure out how to resolve this situation,
3031 /// merging decls or emitting diagnostics as appropriate.
3032 ///
3033 /// In C++, New and Old must be declarations that are not
3034 /// overloaded. Use IsOverload to determine whether New and Old are
3035 /// overloaded, and to select the Old declaration that New should be
3036 /// merged with.
3037 ///
3038 /// Returns true if there was an error, false otherwise.
3039 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3040                              Scope *S, bool MergeTypeWithOld) {
3041   // Verify the old decl was also a function.
3042   FunctionDecl *Old = OldD->getAsFunction();
3043   if (!Old) {
3044     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3045       if (New->getFriendObjectKind()) {
3046         Diag(New->getLocation(), diag::err_using_decl_friend);
3047         Diag(Shadow->getTargetDecl()->getLocation(),
3048              diag::note_using_decl_target);
3049         Diag(Shadow->getUsingDecl()->getLocation(),
3050              diag::note_using_decl) << 0;
3051         return true;
3052       }
3053 
3054       // Check whether the two declarations might declare the same function.
3055       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3056         return true;
3057       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3058     } else {
3059       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3060         << New->getDeclName();
3061       notePreviousDefinition(OldD, New->getLocation());
3062       return true;
3063     }
3064   }
3065 
3066   // If the old declaration is invalid, just give up here.
3067   if (Old->isInvalidDecl())
3068     return true;
3069 
3070   // Disallow redeclaration of some builtins.
3071   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3072     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3073     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3074         << Old << Old->getType();
3075     return true;
3076   }
3077 
3078   diag::kind PrevDiag;
3079   SourceLocation OldLocation;
3080   std::tie(PrevDiag, OldLocation) =
3081       getNoteDiagForInvalidRedeclaration(Old, New);
3082 
3083   // Don't complain about this if we're in GNU89 mode and the old function
3084   // is an extern inline function.
3085   // Don't complain about specializations. They are not supposed to have
3086   // storage classes.
3087   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3088       New->getStorageClass() == SC_Static &&
3089       Old->hasExternalFormalLinkage() &&
3090       !New->getTemplateSpecializationInfo() &&
3091       !canRedefineFunction(Old, getLangOpts())) {
3092     if (getLangOpts().MicrosoftExt) {
3093       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3094       Diag(OldLocation, PrevDiag);
3095     } else {
3096       Diag(New->getLocation(), diag::err_static_non_static) << New;
3097       Diag(OldLocation, PrevDiag);
3098       return true;
3099     }
3100   }
3101 
3102   if (New->hasAttr<InternalLinkageAttr>() &&
3103       !Old->hasAttr<InternalLinkageAttr>()) {
3104     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3105         << New->getDeclName();
3106     notePreviousDefinition(Old, New->getLocation());
3107     New->dropAttr<InternalLinkageAttr>();
3108   }
3109 
3110   if (CheckRedeclarationModuleOwnership(New, Old))
3111     return true;
3112 
3113   if (!getLangOpts().CPlusPlus) {
3114     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3115     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3116       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3117         << New << OldOvl;
3118 
3119       // Try our best to find a decl that actually has the overloadable
3120       // attribute for the note. In most cases (e.g. programs with only one
3121       // broken declaration/definition), this won't matter.
3122       //
3123       // FIXME: We could do this if we juggled some extra state in
3124       // OverloadableAttr, rather than just removing it.
3125       const Decl *DiagOld = Old;
3126       if (OldOvl) {
3127         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3128           const auto *A = D->getAttr<OverloadableAttr>();
3129           return A && !A->isImplicit();
3130         });
3131         // If we've implicitly added *all* of the overloadable attrs to this
3132         // chain, emitting a "previous redecl" note is pointless.
3133         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3134       }
3135 
3136       if (DiagOld)
3137         Diag(DiagOld->getLocation(),
3138              diag::note_attribute_overloadable_prev_overload)
3139           << OldOvl;
3140 
3141       if (OldOvl)
3142         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3143       else
3144         New->dropAttr<OverloadableAttr>();
3145     }
3146   }
3147 
3148   // If a function is first declared with a calling convention, but is later
3149   // declared or defined without one, all following decls assume the calling
3150   // convention of the first.
3151   //
3152   // It's OK if a function is first declared without a calling convention,
3153   // but is later declared or defined with the default calling convention.
3154   //
3155   // To test if either decl has an explicit calling convention, we look for
3156   // AttributedType sugar nodes on the type as written.  If they are missing or
3157   // were canonicalized away, we assume the calling convention was implicit.
3158   //
3159   // Note also that we DO NOT return at this point, because we still have
3160   // other tests to run.
3161   QualType OldQType = Context.getCanonicalType(Old->getType());
3162   QualType NewQType = Context.getCanonicalType(New->getType());
3163   const FunctionType *OldType = cast<FunctionType>(OldQType);
3164   const FunctionType *NewType = cast<FunctionType>(NewQType);
3165   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3166   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3167   bool RequiresAdjustment = false;
3168 
3169   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3170     FunctionDecl *First = Old->getFirstDecl();
3171     const FunctionType *FT =
3172         First->getType().getCanonicalType()->castAs<FunctionType>();
3173     FunctionType::ExtInfo FI = FT->getExtInfo();
3174     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3175     if (!NewCCExplicit) {
3176       // Inherit the CC from the previous declaration if it was specified
3177       // there but not here.
3178       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3179       RequiresAdjustment = true;
3180     } else if (New->getBuiltinID()) {
3181       // Calling Conventions on a Builtin aren't really useful and setting a
3182       // default calling convention and cdecl'ing some builtin redeclarations is
3183       // common, so warn and ignore the calling convention on the redeclaration.
3184       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3185           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3186           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3187       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3188       RequiresAdjustment = true;
3189     } else {
3190       // Calling conventions aren't compatible, so complain.
3191       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3192       Diag(New->getLocation(), diag::err_cconv_change)
3193         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3194         << !FirstCCExplicit
3195         << (!FirstCCExplicit ? "" :
3196             FunctionType::getNameForCallConv(FI.getCC()));
3197 
3198       // Put the note on the first decl, since it is the one that matters.
3199       Diag(First->getLocation(), diag::note_previous_declaration);
3200       return true;
3201     }
3202   }
3203 
3204   // FIXME: diagnose the other way around?
3205   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3206     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3207     RequiresAdjustment = true;
3208   }
3209 
3210   // Merge regparm attribute.
3211   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3212       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3213     if (NewTypeInfo.getHasRegParm()) {
3214       Diag(New->getLocation(), diag::err_regparm_mismatch)
3215         << NewType->getRegParmType()
3216         << OldType->getRegParmType();
3217       Diag(OldLocation, diag::note_previous_declaration);
3218       return true;
3219     }
3220 
3221     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3222     RequiresAdjustment = true;
3223   }
3224 
3225   // Merge ns_returns_retained attribute.
3226   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3227     if (NewTypeInfo.getProducesResult()) {
3228       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3229           << "'ns_returns_retained'";
3230       Diag(OldLocation, diag::note_previous_declaration);
3231       return true;
3232     }
3233 
3234     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3235     RequiresAdjustment = true;
3236   }
3237 
3238   if (OldTypeInfo.getNoCallerSavedRegs() !=
3239       NewTypeInfo.getNoCallerSavedRegs()) {
3240     if (NewTypeInfo.getNoCallerSavedRegs()) {
3241       AnyX86NoCallerSavedRegistersAttr *Attr =
3242         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3243       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3244       Diag(OldLocation, diag::note_previous_declaration);
3245       return true;
3246     }
3247 
3248     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3249     RequiresAdjustment = true;
3250   }
3251 
3252   if (RequiresAdjustment) {
3253     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3254     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3255     New->setType(QualType(AdjustedType, 0));
3256     NewQType = Context.getCanonicalType(New->getType());
3257   }
3258 
3259   // If this redeclaration makes the function inline, we may need to add it to
3260   // UndefinedButUsed.
3261   if (!Old->isInlined() && New->isInlined() &&
3262       !New->hasAttr<GNUInlineAttr>() &&
3263       !getLangOpts().GNUInline &&
3264       Old->isUsed(false) &&
3265       !Old->isDefined() && !New->isThisDeclarationADefinition())
3266     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3267                                            SourceLocation()));
3268 
3269   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3270   // about it.
3271   if (New->hasAttr<GNUInlineAttr>() &&
3272       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3273     UndefinedButUsed.erase(Old->getCanonicalDecl());
3274   }
3275 
3276   // If pass_object_size params don't match up perfectly, this isn't a valid
3277   // redeclaration.
3278   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3279       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3280     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3281         << New->getDeclName();
3282     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3283     return true;
3284   }
3285 
3286   if (getLangOpts().CPlusPlus) {
3287     // C++1z [over.load]p2
3288     //   Certain function declarations cannot be overloaded:
3289     //     -- Function declarations that differ only in the return type,
3290     //        the exception specification, or both cannot be overloaded.
3291 
3292     // Check the exception specifications match. This may recompute the type of
3293     // both Old and New if it resolved exception specifications, so grab the
3294     // types again after this. Because this updates the type, we do this before
3295     // any of the other checks below, which may update the "de facto" NewQType
3296     // but do not necessarily update the type of New.
3297     if (CheckEquivalentExceptionSpec(Old, New))
3298       return true;
3299     OldQType = Context.getCanonicalType(Old->getType());
3300     NewQType = Context.getCanonicalType(New->getType());
3301 
3302     // Go back to the type source info to compare the declared return types,
3303     // per C++1y [dcl.type.auto]p13:
3304     //   Redeclarations or specializations of a function or function template
3305     //   with a declared return type that uses a placeholder type shall also
3306     //   use that placeholder, not a deduced type.
3307     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3308     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3309     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3310         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3311                                        OldDeclaredReturnType)) {
3312       QualType ResQT;
3313       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3314           OldDeclaredReturnType->isObjCObjectPointerType())
3315         // FIXME: This does the wrong thing for a deduced return type.
3316         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3317       if (ResQT.isNull()) {
3318         if (New->isCXXClassMember() && New->isOutOfLine())
3319           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3320               << New << New->getReturnTypeSourceRange();
3321         else
3322           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3323               << New->getReturnTypeSourceRange();
3324         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3325                                     << Old->getReturnTypeSourceRange();
3326         return true;
3327       }
3328       else
3329         NewQType = ResQT;
3330     }
3331 
3332     QualType OldReturnType = OldType->getReturnType();
3333     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3334     if (OldReturnType != NewReturnType) {
3335       // If this function has a deduced return type and has already been
3336       // defined, copy the deduced value from the old declaration.
3337       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3338       if (OldAT && OldAT->isDeduced()) {
3339         New->setType(
3340             SubstAutoType(New->getType(),
3341                           OldAT->isDependentType() ? Context.DependentTy
3342                                                    : OldAT->getDeducedType()));
3343         NewQType = Context.getCanonicalType(
3344             SubstAutoType(NewQType,
3345                           OldAT->isDependentType() ? Context.DependentTy
3346                                                    : OldAT->getDeducedType()));
3347       }
3348     }
3349 
3350     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3351     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3352     if (OldMethod && NewMethod) {
3353       // Preserve triviality.
3354       NewMethod->setTrivial(OldMethod->isTrivial());
3355 
3356       // MSVC allows explicit template specialization at class scope:
3357       // 2 CXXMethodDecls referring to the same function will be injected.
3358       // We don't want a redeclaration error.
3359       bool IsClassScopeExplicitSpecialization =
3360                               OldMethod->isFunctionTemplateSpecialization() &&
3361                               NewMethod->isFunctionTemplateSpecialization();
3362       bool isFriend = NewMethod->getFriendObjectKind();
3363 
3364       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3365           !IsClassScopeExplicitSpecialization) {
3366         //    -- Member function declarations with the same name and the
3367         //       same parameter types cannot be overloaded if any of them
3368         //       is a static member function declaration.
3369         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3370           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3371           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3372           return true;
3373         }
3374 
3375         // C++ [class.mem]p1:
3376         //   [...] A member shall not be declared twice in the
3377         //   member-specification, except that a nested class or member
3378         //   class template can be declared and then later defined.
3379         if (!inTemplateInstantiation()) {
3380           unsigned NewDiag;
3381           if (isa<CXXConstructorDecl>(OldMethod))
3382             NewDiag = diag::err_constructor_redeclared;
3383           else if (isa<CXXDestructorDecl>(NewMethod))
3384             NewDiag = diag::err_destructor_redeclared;
3385           else if (isa<CXXConversionDecl>(NewMethod))
3386             NewDiag = diag::err_conv_function_redeclared;
3387           else
3388             NewDiag = diag::err_member_redeclared;
3389 
3390           Diag(New->getLocation(), NewDiag);
3391         } else {
3392           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3393             << New << New->getType();
3394         }
3395         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3396         return true;
3397 
3398       // Complain if this is an explicit declaration of a special
3399       // member that was initially declared implicitly.
3400       //
3401       // As an exception, it's okay to befriend such methods in order
3402       // to permit the implicit constructor/destructor/operator calls.
3403       } else if (OldMethod->isImplicit()) {
3404         if (isFriend) {
3405           NewMethod->setImplicit();
3406         } else {
3407           Diag(NewMethod->getLocation(),
3408                diag::err_definition_of_implicitly_declared_member)
3409             << New << getSpecialMember(OldMethod);
3410           return true;
3411         }
3412       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3413         Diag(NewMethod->getLocation(),
3414              diag::err_definition_of_explicitly_defaulted_member)
3415           << getSpecialMember(OldMethod);
3416         return true;
3417       }
3418     }
3419 
3420     // C++11 [dcl.attr.noreturn]p1:
3421     //   The first declaration of a function shall specify the noreturn
3422     //   attribute if any declaration of that function specifies the noreturn
3423     //   attribute.
3424     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3425     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3426       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3427       Diag(Old->getFirstDecl()->getLocation(),
3428            diag::note_noreturn_missing_first_decl);
3429     }
3430 
3431     // C++11 [dcl.attr.depend]p2:
3432     //   The first declaration of a function shall specify the
3433     //   carries_dependency attribute for its declarator-id if any declaration
3434     //   of the function specifies the carries_dependency attribute.
3435     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3436     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3437       Diag(CDA->getLocation(),
3438            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3439       Diag(Old->getFirstDecl()->getLocation(),
3440            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3441     }
3442 
3443     // (C++98 8.3.5p3):
3444     //   All declarations for a function shall agree exactly in both the
3445     //   return type and the parameter-type-list.
3446     // We also want to respect all the extended bits except noreturn.
3447 
3448     // noreturn should now match unless the old type info didn't have it.
3449     QualType OldQTypeForComparison = OldQType;
3450     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3451       auto *OldType = OldQType->castAs<FunctionProtoType>();
3452       const FunctionType *OldTypeForComparison
3453         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3454       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3455       assert(OldQTypeForComparison.isCanonical());
3456     }
3457 
3458     if (haveIncompatibleLanguageLinkages(Old, New)) {
3459       // As a special case, retain the language linkage from previous
3460       // declarations of a friend function as an extension.
3461       //
3462       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3463       // and is useful because there's otherwise no way to specify language
3464       // linkage within class scope.
3465       //
3466       // Check cautiously as the friend object kind isn't yet complete.
3467       if (New->getFriendObjectKind() != Decl::FOK_None) {
3468         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3469         Diag(OldLocation, PrevDiag);
3470       } else {
3471         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3472         Diag(OldLocation, PrevDiag);
3473         return true;
3474       }
3475     }
3476 
3477     if (OldQTypeForComparison == NewQType)
3478       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3479 
3480     // If the types are imprecise (due to dependent constructs in friends or
3481     // local extern declarations), it's OK if they differ. We'll check again
3482     // during instantiation.
3483     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3484       return false;
3485 
3486     // Fall through for conflicting redeclarations and redefinitions.
3487   }
3488 
3489   // C: Function types need to be compatible, not identical. This handles
3490   // duplicate function decls like "void f(int); void f(enum X);" properly.
3491   if (!getLangOpts().CPlusPlus &&
3492       Context.typesAreCompatible(OldQType, NewQType)) {
3493     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3494     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3495     const FunctionProtoType *OldProto = nullptr;
3496     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3497         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3498       // The old declaration provided a function prototype, but the
3499       // new declaration does not. Merge in the prototype.
3500       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3501       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3502       NewQType =
3503           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3504                                   OldProto->getExtProtoInfo());
3505       New->setType(NewQType);
3506       New->setHasInheritedPrototype();
3507 
3508       // Synthesize parameters with the same types.
3509       SmallVector<ParmVarDecl*, 16> Params;
3510       for (const auto &ParamType : OldProto->param_types()) {
3511         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3512                                                  SourceLocation(), nullptr,
3513                                                  ParamType, /*TInfo=*/nullptr,
3514                                                  SC_None, nullptr);
3515         Param->setScopeInfo(0, Params.size());
3516         Param->setImplicit();
3517         Params.push_back(Param);
3518       }
3519 
3520       New->setParams(Params);
3521     }
3522 
3523     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3524   }
3525 
3526   // GNU C permits a K&R definition to follow a prototype declaration
3527   // if the declared types of the parameters in the K&R definition
3528   // match the types in the prototype declaration, even when the
3529   // promoted types of the parameters from the K&R definition differ
3530   // from the types in the prototype. GCC then keeps the types from
3531   // the prototype.
3532   //
3533   // If a variadic prototype is followed by a non-variadic K&R definition,
3534   // the K&R definition becomes variadic.  This is sort of an edge case, but
3535   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3536   // C99 6.9.1p8.
3537   if (!getLangOpts().CPlusPlus &&
3538       Old->hasPrototype() && !New->hasPrototype() &&
3539       New->getType()->getAs<FunctionProtoType>() &&
3540       Old->getNumParams() == New->getNumParams()) {
3541     SmallVector<QualType, 16> ArgTypes;
3542     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3543     const FunctionProtoType *OldProto
3544       = Old->getType()->getAs<FunctionProtoType>();
3545     const FunctionProtoType *NewProto
3546       = New->getType()->getAs<FunctionProtoType>();
3547 
3548     // Determine whether this is the GNU C extension.
3549     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3550                                                NewProto->getReturnType());
3551     bool LooseCompatible = !MergedReturn.isNull();
3552     for (unsigned Idx = 0, End = Old->getNumParams();
3553          LooseCompatible && Idx != End; ++Idx) {
3554       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3555       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3556       if (Context.typesAreCompatible(OldParm->getType(),
3557                                      NewProto->getParamType(Idx))) {
3558         ArgTypes.push_back(NewParm->getType());
3559       } else if (Context.typesAreCompatible(OldParm->getType(),
3560                                             NewParm->getType(),
3561                                             /*CompareUnqualified=*/true)) {
3562         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3563                                            NewProto->getParamType(Idx) };
3564         Warnings.push_back(Warn);
3565         ArgTypes.push_back(NewParm->getType());
3566       } else
3567         LooseCompatible = false;
3568     }
3569 
3570     if (LooseCompatible) {
3571       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3572         Diag(Warnings[Warn].NewParm->getLocation(),
3573              diag::ext_param_promoted_not_compatible_with_prototype)
3574           << Warnings[Warn].PromotedType
3575           << Warnings[Warn].OldParm->getType();
3576         if (Warnings[Warn].OldParm->getLocation().isValid())
3577           Diag(Warnings[Warn].OldParm->getLocation(),
3578                diag::note_previous_declaration);
3579       }
3580 
3581       if (MergeTypeWithOld)
3582         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3583                                              OldProto->getExtProtoInfo()));
3584       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3585     }
3586 
3587     // Fall through to diagnose conflicting types.
3588   }
3589 
3590   // A function that has already been declared has been redeclared or
3591   // defined with a different type; show an appropriate diagnostic.
3592 
3593   // If the previous declaration was an implicitly-generated builtin
3594   // declaration, then at the very least we should use a specialized note.
3595   unsigned BuiltinID;
3596   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3597     // If it's actually a library-defined builtin function like 'malloc'
3598     // or 'printf', just warn about the incompatible redeclaration.
3599     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3600       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3601       Diag(OldLocation, diag::note_previous_builtin_declaration)
3602         << Old << Old->getType();
3603 
3604       // If this is a global redeclaration, just forget hereafter
3605       // about the "builtin-ness" of the function.
3606       //
3607       // Doing this for local extern declarations is problematic.  If
3608       // the builtin declaration remains visible, a second invalid
3609       // local declaration will produce a hard error; if it doesn't
3610       // remain visible, a single bogus local redeclaration (which is
3611       // actually only a warning) could break all the downstream code.
3612       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3613         New->getIdentifier()->revertBuiltin();
3614 
3615       return false;
3616     }
3617 
3618     PrevDiag = diag::note_previous_builtin_declaration;
3619   }
3620 
3621   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3622   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3623   return true;
3624 }
3625 
3626 /// Completes the merge of two function declarations that are
3627 /// known to be compatible.
3628 ///
3629 /// This routine handles the merging of attributes and other
3630 /// properties of function declarations from the old declaration to
3631 /// the new declaration, once we know that New is in fact a
3632 /// redeclaration of Old.
3633 ///
3634 /// \returns false
3635 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3636                                         Scope *S, bool MergeTypeWithOld) {
3637   // Merge the attributes
3638   mergeDeclAttributes(New, Old);
3639 
3640   // Merge "pure" flag.
3641   if (Old->isPure())
3642     New->setPure();
3643 
3644   // Merge "used" flag.
3645   if (Old->getMostRecentDecl()->isUsed(false))
3646     New->setIsUsed();
3647 
3648   // Merge attributes from the parameters.  These can mismatch with K&R
3649   // declarations.
3650   if (New->getNumParams() == Old->getNumParams())
3651       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3652         ParmVarDecl *NewParam = New->getParamDecl(i);
3653         ParmVarDecl *OldParam = Old->getParamDecl(i);
3654         mergeParamDeclAttributes(NewParam, OldParam, *this);
3655         mergeParamDeclTypes(NewParam, OldParam, *this);
3656       }
3657 
3658   if (getLangOpts().CPlusPlus)
3659     return MergeCXXFunctionDecl(New, Old, S);
3660 
3661   // Merge the function types so the we get the composite types for the return
3662   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3663   // was visible.
3664   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3665   if (!Merged.isNull() && MergeTypeWithOld)
3666     New->setType(Merged);
3667 
3668   return false;
3669 }
3670 
3671 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3672                                 ObjCMethodDecl *oldMethod) {
3673   // Merge the attributes, including deprecated/unavailable
3674   AvailabilityMergeKind MergeKind =
3675     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3676       ? AMK_ProtocolImplementation
3677       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3678                                                        : AMK_Override;
3679 
3680   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3681 
3682   // Merge attributes from the parameters.
3683   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3684                                        oe = oldMethod->param_end();
3685   for (ObjCMethodDecl::param_iterator
3686          ni = newMethod->param_begin(), ne = newMethod->param_end();
3687        ni != ne && oi != oe; ++ni, ++oi)
3688     mergeParamDeclAttributes(*ni, *oi, *this);
3689 
3690   CheckObjCMethodOverride(newMethod, oldMethod);
3691 }
3692 
3693 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3694   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3695 
3696   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3697          ? diag::err_redefinition_different_type
3698          : diag::err_redeclaration_different_type)
3699     << New->getDeclName() << New->getType() << Old->getType();
3700 
3701   diag::kind PrevDiag;
3702   SourceLocation OldLocation;
3703   std::tie(PrevDiag, OldLocation)
3704     = getNoteDiagForInvalidRedeclaration(Old, New);
3705   S.Diag(OldLocation, PrevDiag);
3706   New->setInvalidDecl();
3707 }
3708 
3709 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3710 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3711 /// emitting diagnostics as appropriate.
3712 ///
3713 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3714 /// to here in AddInitializerToDecl. We can't check them before the initializer
3715 /// is attached.
3716 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3717                              bool MergeTypeWithOld) {
3718   if (New->isInvalidDecl() || Old->isInvalidDecl())
3719     return;
3720 
3721   QualType MergedT;
3722   if (getLangOpts().CPlusPlus) {
3723     if (New->getType()->isUndeducedType()) {
3724       // We don't know what the new type is until the initializer is attached.
3725       return;
3726     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3727       // These could still be something that needs exception specs checked.
3728       return MergeVarDeclExceptionSpecs(New, Old);
3729     }
3730     // C++ [basic.link]p10:
3731     //   [...] the types specified by all declarations referring to a given
3732     //   object or function shall be identical, except that declarations for an
3733     //   array object can specify array types that differ by the presence or
3734     //   absence of a major array bound (8.3.4).
3735     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3736       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3737       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3738 
3739       // We are merging a variable declaration New into Old. If it has an array
3740       // bound, and that bound differs from Old's bound, we should diagnose the
3741       // mismatch.
3742       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3743         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3744              PrevVD = PrevVD->getPreviousDecl()) {
3745           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3746           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3747             continue;
3748 
3749           if (!Context.hasSameType(NewArray, PrevVDTy))
3750             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3751         }
3752       }
3753 
3754       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3755         if (Context.hasSameType(OldArray->getElementType(),
3756                                 NewArray->getElementType()))
3757           MergedT = New->getType();
3758       }
3759       // FIXME: Check visibility. New is hidden but has a complete type. If New
3760       // has no array bound, it should not inherit one from Old, if Old is not
3761       // visible.
3762       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3763         if (Context.hasSameType(OldArray->getElementType(),
3764                                 NewArray->getElementType()))
3765           MergedT = Old->getType();
3766       }
3767     }
3768     else if (New->getType()->isObjCObjectPointerType() &&
3769                Old->getType()->isObjCObjectPointerType()) {
3770       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3771                                               Old->getType());
3772     }
3773   } else {
3774     // C 6.2.7p2:
3775     //   All declarations that refer to the same object or function shall have
3776     //   compatible type.
3777     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3778   }
3779   if (MergedT.isNull()) {
3780     // It's OK if we couldn't merge types if either type is dependent, for a
3781     // block-scope variable. In other cases (static data members of class
3782     // templates, variable templates, ...), we require the types to be
3783     // equivalent.
3784     // FIXME: The C++ standard doesn't say anything about this.
3785     if ((New->getType()->isDependentType() ||
3786          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3787       // If the old type was dependent, we can't merge with it, so the new type
3788       // becomes dependent for now. We'll reproduce the original type when we
3789       // instantiate the TypeSourceInfo for the variable.
3790       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3791         New->setType(Context.DependentTy);
3792       return;
3793     }
3794     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3795   }
3796 
3797   // Don't actually update the type on the new declaration if the old
3798   // declaration was an extern declaration in a different scope.
3799   if (MergeTypeWithOld)
3800     New->setType(MergedT);
3801 }
3802 
3803 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3804                                   LookupResult &Previous) {
3805   // C11 6.2.7p4:
3806   //   For an identifier with internal or external linkage declared
3807   //   in a scope in which a prior declaration of that identifier is
3808   //   visible, if the prior declaration specifies internal or
3809   //   external linkage, the type of the identifier at the later
3810   //   declaration becomes the composite type.
3811   //
3812   // If the variable isn't visible, we do not merge with its type.
3813   if (Previous.isShadowed())
3814     return false;
3815 
3816   if (S.getLangOpts().CPlusPlus) {
3817     // C++11 [dcl.array]p3:
3818     //   If there is a preceding declaration of the entity in the same
3819     //   scope in which the bound was specified, an omitted array bound
3820     //   is taken to be the same as in that earlier declaration.
3821     return NewVD->isPreviousDeclInSameBlockScope() ||
3822            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3823             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3824   } else {
3825     // If the old declaration was function-local, don't merge with its
3826     // type unless we're in the same function.
3827     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3828            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3829   }
3830 }
3831 
3832 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3833 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3834 /// situation, merging decls or emitting diagnostics as appropriate.
3835 ///
3836 /// Tentative definition rules (C99 6.9.2p2) are checked by
3837 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3838 /// definitions here, since the initializer hasn't been attached.
3839 ///
3840 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3841   // If the new decl is already invalid, don't do any other checking.
3842   if (New->isInvalidDecl())
3843     return;
3844 
3845   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3846     return;
3847 
3848   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3849 
3850   // Verify the old decl was also a variable or variable template.
3851   VarDecl *Old = nullptr;
3852   VarTemplateDecl *OldTemplate = nullptr;
3853   if (Previous.isSingleResult()) {
3854     if (NewTemplate) {
3855       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3856       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3857 
3858       if (auto *Shadow =
3859               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3860         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3861           return New->setInvalidDecl();
3862     } else {
3863       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3864 
3865       if (auto *Shadow =
3866               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3867         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3868           return New->setInvalidDecl();
3869     }
3870   }
3871   if (!Old) {
3872     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3873         << New->getDeclName();
3874     notePreviousDefinition(Previous.getRepresentativeDecl(),
3875                            New->getLocation());
3876     return New->setInvalidDecl();
3877   }
3878 
3879   // Ensure the template parameters are compatible.
3880   if (NewTemplate &&
3881       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3882                                       OldTemplate->getTemplateParameters(),
3883                                       /*Complain=*/true, TPL_TemplateMatch))
3884     return New->setInvalidDecl();
3885 
3886   // C++ [class.mem]p1:
3887   //   A member shall not be declared twice in the member-specification [...]
3888   //
3889   // Here, we need only consider static data members.
3890   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3891     Diag(New->getLocation(), diag::err_duplicate_member)
3892       << New->getIdentifier();
3893     Diag(Old->getLocation(), diag::note_previous_declaration);
3894     New->setInvalidDecl();
3895   }
3896 
3897   mergeDeclAttributes(New, Old);
3898   // Warn if an already-declared variable is made a weak_import in a subsequent
3899   // declaration
3900   if (New->hasAttr<WeakImportAttr>() &&
3901       Old->getStorageClass() == SC_None &&
3902       !Old->hasAttr<WeakImportAttr>()) {
3903     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3904     notePreviousDefinition(Old, New->getLocation());
3905     // Remove weak_import attribute on new declaration.
3906     New->dropAttr<WeakImportAttr>();
3907   }
3908 
3909   if (New->hasAttr<InternalLinkageAttr>() &&
3910       !Old->hasAttr<InternalLinkageAttr>()) {
3911     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3912         << New->getDeclName();
3913     notePreviousDefinition(Old, New->getLocation());
3914     New->dropAttr<InternalLinkageAttr>();
3915   }
3916 
3917   // Merge the types.
3918   VarDecl *MostRecent = Old->getMostRecentDecl();
3919   if (MostRecent != Old) {
3920     MergeVarDeclTypes(New, MostRecent,
3921                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3922     if (New->isInvalidDecl())
3923       return;
3924   }
3925 
3926   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3927   if (New->isInvalidDecl())
3928     return;
3929 
3930   diag::kind PrevDiag;
3931   SourceLocation OldLocation;
3932   std::tie(PrevDiag, OldLocation) =
3933       getNoteDiagForInvalidRedeclaration(Old, New);
3934 
3935   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3936   if (New->getStorageClass() == SC_Static &&
3937       !New->isStaticDataMember() &&
3938       Old->hasExternalFormalLinkage()) {
3939     if (getLangOpts().MicrosoftExt) {
3940       Diag(New->getLocation(), diag::ext_static_non_static)
3941           << New->getDeclName();
3942       Diag(OldLocation, PrevDiag);
3943     } else {
3944       Diag(New->getLocation(), diag::err_static_non_static)
3945           << New->getDeclName();
3946       Diag(OldLocation, PrevDiag);
3947       return New->setInvalidDecl();
3948     }
3949   }
3950   // C99 6.2.2p4:
3951   //   For an identifier declared with the storage-class specifier
3952   //   extern in a scope in which a prior declaration of that
3953   //   identifier is visible,23) if the prior declaration specifies
3954   //   internal or external linkage, the linkage of the identifier at
3955   //   the later declaration is the same as the linkage specified at
3956   //   the prior declaration. If no prior declaration is visible, or
3957   //   if the prior declaration specifies no linkage, then the
3958   //   identifier has external linkage.
3959   if (New->hasExternalStorage() && Old->hasLinkage())
3960     /* Okay */;
3961   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3962            !New->isStaticDataMember() &&
3963            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3964     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3965     Diag(OldLocation, PrevDiag);
3966     return New->setInvalidDecl();
3967   }
3968 
3969   // Check if extern is followed by non-extern and vice-versa.
3970   if (New->hasExternalStorage() &&
3971       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3972     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3973     Diag(OldLocation, PrevDiag);
3974     return New->setInvalidDecl();
3975   }
3976   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3977       !New->hasExternalStorage()) {
3978     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3979     Diag(OldLocation, PrevDiag);
3980     return New->setInvalidDecl();
3981   }
3982 
3983   if (CheckRedeclarationModuleOwnership(New, Old))
3984     return;
3985 
3986   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3987 
3988   // FIXME: The test for external storage here seems wrong? We still
3989   // need to check for mismatches.
3990   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3991       // Don't complain about out-of-line definitions of static members.
3992       !(Old->getLexicalDeclContext()->isRecord() &&
3993         !New->getLexicalDeclContext()->isRecord())) {
3994     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3995     Diag(OldLocation, PrevDiag);
3996     return New->setInvalidDecl();
3997   }
3998 
3999   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4000     if (VarDecl *Def = Old->getDefinition()) {
4001       // C++1z [dcl.fcn.spec]p4:
4002       //   If the definition of a variable appears in a translation unit before
4003       //   its first declaration as inline, the program is ill-formed.
4004       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4005       Diag(Def->getLocation(), diag::note_previous_definition);
4006     }
4007   }
4008 
4009   // If this redeclaration makes the variable inline, we may need to add it to
4010   // UndefinedButUsed.
4011   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4012       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4013     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4014                                            SourceLocation()));
4015 
4016   if (New->getTLSKind() != Old->getTLSKind()) {
4017     if (!Old->getTLSKind()) {
4018       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4019       Diag(OldLocation, PrevDiag);
4020     } else if (!New->getTLSKind()) {
4021       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4022       Diag(OldLocation, PrevDiag);
4023     } else {
4024       // Do not allow redeclaration to change the variable between requiring
4025       // static and dynamic initialization.
4026       // FIXME: GCC allows this, but uses the TLS keyword on the first
4027       // declaration to determine the kind. Do we need to be compatible here?
4028       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4029         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4030       Diag(OldLocation, PrevDiag);
4031     }
4032   }
4033 
4034   // C++ doesn't have tentative definitions, so go right ahead and check here.
4035   if (getLangOpts().CPlusPlus &&
4036       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4037     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4038         Old->getCanonicalDecl()->isConstexpr()) {
4039       // This definition won't be a definition any more once it's been merged.
4040       Diag(New->getLocation(),
4041            diag::warn_deprecated_redundant_constexpr_static_def);
4042     } else if (VarDecl *Def = Old->getDefinition()) {
4043       if (checkVarDeclRedefinition(Def, New))
4044         return;
4045     }
4046   }
4047 
4048   if (haveIncompatibleLanguageLinkages(Old, New)) {
4049     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4050     Diag(OldLocation, PrevDiag);
4051     New->setInvalidDecl();
4052     return;
4053   }
4054 
4055   // Merge "used" flag.
4056   if (Old->getMostRecentDecl()->isUsed(false))
4057     New->setIsUsed();
4058 
4059   // Keep a chain of previous declarations.
4060   New->setPreviousDecl(Old);
4061   if (NewTemplate)
4062     NewTemplate->setPreviousDecl(OldTemplate);
4063   adjustDeclContextForDeclaratorDecl(New, Old);
4064 
4065   // Inherit access appropriately.
4066   New->setAccess(Old->getAccess());
4067   if (NewTemplate)
4068     NewTemplate->setAccess(New->getAccess());
4069 
4070   if (Old->isInline())
4071     New->setImplicitlyInline();
4072 }
4073 
4074 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4075   SourceManager &SrcMgr = getSourceManager();
4076   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4077   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4078   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4079   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4080   auto &HSI = PP.getHeaderSearchInfo();
4081   StringRef HdrFilename =
4082       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4083 
4084   auto noteFromModuleOrInclude = [&](Module *Mod,
4085                                      SourceLocation IncLoc) -> bool {
4086     // Redefinition errors with modules are common with non modular mapped
4087     // headers, example: a non-modular header H in module A that also gets
4088     // included directly in a TU. Pointing twice to the same header/definition
4089     // is confusing, try to get better diagnostics when modules is on.
4090     if (IncLoc.isValid()) {
4091       if (Mod) {
4092         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4093             << HdrFilename.str() << Mod->getFullModuleName();
4094         if (!Mod->DefinitionLoc.isInvalid())
4095           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4096               << Mod->getFullModuleName();
4097       } else {
4098         Diag(IncLoc, diag::note_redefinition_include_same_file)
4099             << HdrFilename.str();
4100       }
4101       return true;
4102     }
4103 
4104     return false;
4105   };
4106 
4107   // Is it the same file and same offset? Provide more information on why
4108   // this leads to a redefinition error.
4109   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4110     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4111     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4112     bool EmittedDiag =
4113         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4114     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4115 
4116     // If the header has no guards, emit a note suggesting one.
4117     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4118       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4119 
4120     if (EmittedDiag)
4121       return;
4122   }
4123 
4124   // Redefinition coming from different files or couldn't do better above.
4125   if (Old->getLocation().isValid())
4126     Diag(Old->getLocation(), diag::note_previous_definition);
4127 }
4128 
4129 /// We've just determined that \p Old and \p New both appear to be definitions
4130 /// of the same variable. Either diagnose or fix the problem.
4131 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4132   if (!hasVisibleDefinition(Old) &&
4133       (New->getFormalLinkage() == InternalLinkage ||
4134        New->isInline() ||
4135        New->getDescribedVarTemplate() ||
4136        New->getNumTemplateParameterLists() ||
4137        New->getDeclContext()->isDependentContext())) {
4138     // The previous definition is hidden, and multiple definitions are
4139     // permitted (in separate TUs). Demote this to a declaration.
4140     New->demoteThisDefinitionToDeclaration();
4141 
4142     // Make the canonical definition visible.
4143     if (auto *OldTD = Old->getDescribedVarTemplate())
4144       makeMergedDefinitionVisible(OldTD);
4145     makeMergedDefinitionVisible(Old);
4146     return false;
4147   } else {
4148     Diag(New->getLocation(), diag::err_redefinition) << New;
4149     notePreviousDefinition(Old, New->getLocation());
4150     New->setInvalidDecl();
4151     return true;
4152   }
4153 }
4154 
4155 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4156 /// no declarator (e.g. "struct foo;") is parsed.
4157 Decl *
4158 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4159                                  RecordDecl *&AnonRecord) {
4160   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4161                                     AnonRecord);
4162 }
4163 
4164 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4165 // disambiguate entities defined in different scopes.
4166 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4167 // compatibility.
4168 // We will pick our mangling number depending on which version of MSVC is being
4169 // targeted.
4170 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4171   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4172              ? S->getMSCurManglingNumber()
4173              : S->getMSLastManglingNumber();
4174 }
4175 
4176 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4177   if (!Context.getLangOpts().CPlusPlus)
4178     return;
4179 
4180   if (isa<CXXRecordDecl>(Tag->getParent())) {
4181     // If this tag is the direct child of a class, number it if
4182     // it is anonymous.
4183     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4184       return;
4185     MangleNumberingContext &MCtx =
4186         Context.getManglingNumberContext(Tag->getParent());
4187     Context.setManglingNumber(
4188         Tag, MCtx.getManglingNumber(
4189                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4190     return;
4191   }
4192 
4193   // If this tag isn't a direct child of a class, number it if it is local.
4194   Decl *ManglingContextDecl;
4195   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4196           Tag->getDeclContext(), ManglingContextDecl)) {
4197     Context.setManglingNumber(
4198         Tag, MCtx->getManglingNumber(
4199                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4200   }
4201 }
4202 
4203 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4204                                         TypedefNameDecl *NewTD) {
4205   if (TagFromDeclSpec->isInvalidDecl())
4206     return;
4207 
4208   // Do nothing if the tag already has a name for linkage purposes.
4209   if (TagFromDeclSpec->hasNameForLinkage())
4210     return;
4211 
4212   // A well-formed anonymous tag must always be a TUK_Definition.
4213   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4214 
4215   // The type must match the tag exactly;  no qualifiers allowed.
4216   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4217                            Context.getTagDeclType(TagFromDeclSpec))) {
4218     if (getLangOpts().CPlusPlus)
4219       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4220     return;
4221   }
4222 
4223   // If we've already computed linkage for the anonymous tag, then
4224   // adding a typedef name for the anonymous decl can change that
4225   // linkage, which might be a serious problem.  Diagnose this as
4226   // unsupported and ignore the typedef name.  TODO: we should
4227   // pursue this as a language defect and establish a formal rule
4228   // for how to handle it.
4229   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4230     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4231 
4232     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4233     tagLoc = getLocForEndOfToken(tagLoc);
4234 
4235     llvm::SmallString<40> textToInsert;
4236     textToInsert += ' ';
4237     textToInsert += NewTD->getIdentifier()->getName();
4238     Diag(tagLoc, diag::note_typedef_changes_linkage)
4239         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4240     return;
4241   }
4242 
4243   // Otherwise, set this is the anon-decl typedef for the tag.
4244   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4245 }
4246 
4247 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4248   switch (T) {
4249   case DeclSpec::TST_class:
4250     return 0;
4251   case DeclSpec::TST_struct:
4252     return 1;
4253   case DeclSpec::TST_interface:
4254     return 2;
4255   case DeclSpec::TST_union:
4256     return 3;
4257   case DeclSpec::TST_enum:
4258     return 4;
4259   default:
4260     llvm_unreachable("unexpected type specifier");
4261   }
4262 }
4263 
4264 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4265 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4266 /// parameters to cope with template friend declarations.
4267 Decl *
4268 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4269                                  MultiTemplateParamsArg TemplateParams,
4270                                  bool IsExplicitInstantiation,
4271                                  RecordDecl *&AnonRecord) {
4272   Decl *TagD = nullptr;
4273   TagDecl *Tag = nullptr;
4274   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4275       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4276       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4277       DS.getTypeSpecType() == DeclSpec::TST_union ||
4278       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4279     TagD = DS.getRepAsDecl();
4280 
4281     if (!TagD) // We probably had an error
4282       return nullptr;
4283 
4284     // Note that the above type specs guarantee that the
4285     // type rep is a Decl, whereas in many of the others
4286     // it's a Type.
4287     if (isa<TagDecl>(TagD))
4288       Tag = cast<TagDecl>(TagD);
4289     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4290       Tag = CTD->getTemplatedDecl();
4291   }
4292 
4293   if (Tag) {
4294     handleTagNumbering(Tag, S);
4295     Tag->setFreeStanding();
4296     if (Tag->isInvalidDecl())
4297       return Tag;
4298   }
4299 
4300   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4301     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4302     // or incomplete types shall not be restrict-qualified."
4303     if (TypeQuals & DeclSpec::TQ_restrict)
4304       Diag(DS.getRestrictSpecLoc(),
4305            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4306            << DS.getSourceRange();
4307   }
4308 
4309   if (DS.isInlineSpecified())
4310     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4311         << getLangOpts().CPlusPlus17;
4312 
4313   if (DS.hasConstexprSpecifier()) {
4314     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4315     // and definitions of functions and variables.
4316     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4317     // the declaration of a function or function template
4318     bool IsConsteval = DS.getConstexprSpecifier() == CSK_consteval;
4319     if (Tag)
4320       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4321           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << IsConsteval;
4322     else
4323       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4324           << IsConsteval;
4325     // Don't emit warnings after this error.
4326     return TagD;
4327   }
4328 
4329   DiagnoseFunctionSpecifiers(DS);
4330 
4331   if (DS.isFriendSpecified()) {
4332     // If we're dealing with a decl but not a TagDecl, assume that
4333     // whatever routines created it handled the friendship aspect.
4334     if (TagD && !Tag)
4335       return nullptr;
4336     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4337   }
4338 
4339   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4340   bool IsExplicitSpecialization =
4341     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4342   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4343       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4344       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4345     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4346     // nested-name-specifier unless it is an explicit instantiation
4347     // or an explicit specialization.
4348     //
4349     // FIXME: We allow class template partial specializations here too, per the
4350     // obvious intent of DR1819.
4351     //
4352     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4353     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4354         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4355     return nullptr;
4356   }
4357 
4358   // Track whether this decl-specifier declares anything.
4359   bool DeclaresAnything = true;
4360 
4361   // Handle anonymous struct definitions.
4362   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4363     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4364         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4365       if (getLangOpts().CPlusPlus ||
4366           Record->getDeclContext()->isRecord()) {
4367         // If CurContext is a DeclContext that can contain statements,
4368         // RecursiveASTVisitor won't visit the decls that
4369         // BuildAnonymousStructOrUnion() will put into CurContext.
4370         // Also store them here so that they can be part of the
4371         // DeclStmt that gets created in this case.
4372         // FIXME: Also return the IndirectFieldDecls created by
4373         // BuildAnonymousStructOr union, for the same reason?
4374         if (CurContext->isFunctionOrMethod())
4375           AnonRecord = Record;
4376         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4377                                            Context.getPrintingPolicy());
4378       }
4379 
4380       DeclaresAnything = false;
4381     }
4382   }
4383 
4384   // C11 6.7.2.1p2:
4385   //   A struct-declaration that does not declare an anonymous structure or
4386   //   anonymous union shall contain a struct-declarator-list.
4387   //
4388   // This rule also existed in C89 and C99; the grammar for struct-declaration
4389   // did not permit a struct-declaration without a struct-declarator-list.
4390   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4391       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4392     // Check for Microsoft C extension: anonymous struct/union member.
4393     // Handle 2 kinds of anonymous struct/union:
4394     //   struct STRUCT;
4395     //   union UNION;
4396     // and
4397     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4398     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4399     if ((Tag && Tag->getDeclName()) ||
4400         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4401       RecordDecl *Record = nullptr;
4402       if (Tag)
4403         Record = dyn_cast<RecordDecl>(Tag);
4404       else if (const RecordType *RT =
4405                    DS.getRepAsType().get()->getAsStructureType())
4406         Record = RT->getDecl();
4407       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4408         Record = UT->getDecl();
4409 
4410       if (Record && getLangOpts().MicrosoftExt) {
4411         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4412             << Record->isUnion() << DS.getSourceRange();
4413         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4414       }
4415 
4416       DeclaresAnything = false;
4417     }
4418   }
4419 
4420   // Skip all the checks below if we have a type error.
4421   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4422       (TagD && TagD->isInvalidDecl()))
4423     return TagD;
4424 
4425   if (getLangOpts().CPlusPlus &&
4426       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4427     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4428       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4429           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4430         DeclaresAnything = false;
4431 
4432   if (!DS.isMissingDeclaratorOk()) {
4433     // Customize diagnostic for a typedef missing a name.
4434     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4435       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4436           << DS.getSourceRange();
4437     else
4438       DeclaresAnything = false;
4439   }
4440 
4441   if (DS.isModulePrivateSpecified() &&
4442       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4443     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4444       << Tag->getTagKind()
4445       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4446 
4447   ActOnDocumentableDecl(TagD);
4448 
4449   // C 6.7/2:
4450   //   A declaration [...] shall declare at least a declarator [...], a tag,
4451   //   or the members of an enumeration.
4452   // C++ [dcl.dcl]p3:
4453   //   [If there are no declarators], and except for the declaration of an
4454   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4455   //   names into the program, or shall redeclare a name introduced by a
4456   //   previous declaration.
4457   if (!DeclaresAnything) {
4458     // In C, we allow this as a (popular) extension / bug. Don't bother
4459     // producing further diagnostics for redundant qualifiers after this.
4460     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4461     return TagD;
4462   }
4463 
4464   // C++ [dcl.stc]p1:
4465   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4466   //   init-declarator-list of the declaration shall not be empty.
4467   // C++ [dcl.fct.spec]p1:
4468   //   If a cv-qualifier appears in a decl-specifier-seq, the
4469   //   init-declarator-list of the declaration shall not be empty.
4470   //
4471   // Spurious qualifiers here appear to be valid in C.
4472   unsigned DiagID = diag::warn_standalone_specifier;
4473   if (getLangOpts().CPlusPlus)
4474     DiagID = diag::ext_standalone_specifier;
4475 
4476   // Note that a linkage-specification sets a storage class, but
4477   // 'extern "C" struct foo;' is actually valid and not theoretically
4478   // useless.
4479   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4480     if (SCS == DeclSpec::SCS_mutable)
4481       // Since mutable is not a viable storage class specifier in C, there is
4482       // no reason to treat it as an extension. Instead, diagnose as an error.
4483       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4484     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4485       Diag(DS.getStorageClassSpecLoc(), DiagID)
4486         << DeclSpec::getSpecifierName(SCS);
4487   }
4488 
4489   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4490     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4491       << DeclSpec::getSpecifierName(TSCS);
4492   if (DS.getTypeQualifiers()) {
4493     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4494       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4495     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4496       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4497     // Restrict is covered above.
4498     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4499       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4500     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4501       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4502   }
4503 
4504   // Warn about ignored type attributes, for example:
4505   // __attribute__((aligned)) struct A;
4506   // Attributes should be placed after tag to apply to type declaration.
4507   if (!DS.getAttributes().empty()) {
4508     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4509     if (TypeSpecType == DeclSpec::TST_class ||
4510         TypeSpecType == DeclSpec::TST_struct ||
4511         TypeSpecType == DeclSpec::TST_interface ||
4512         TypeSpecType == DeclSpec::TST_union ||
4513         TypeSpecType == DeclSpec::TST_enum) {
4514       for (const ParsedAttr &AL : DS.getAttributes())
4515         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4516             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4517     }
4518   }
4519 
4520   return TagD;
4521 }
4522 
4523 /// We are trying to inject an anonymous member into the given scope;
4524 /// check if there's an existing declaration that can't be overloaded.
4525 ///
4526 /// \return true if this is a forbidden redeclaration
4527 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4528                                          Scope *S,
4529                                          DeclContext *Owner,
4530                                          DeclarationName Name,
4531                                          SourceLocation NameLoc,
4532                                          bool IsUnion) {
4533   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4534                  Sema::ForVisibleRedeclaration);
4535   if (!SemaRef.LookupName(R, S)) return false;
4536 
4537   // Pick a representative declaration.
4538   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4539   assert(PrevDecl && "Expected a non-null Decl");
4540 
4541   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4542     return false;
4543 
4544   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4545     << IsUnion << Name;
4546   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4547 
4548   return true;
4549 }
4550 
4551 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4552 /// anonymous struct or union AnonRecord into the owning context Owner
4553 /// and scope S. This routine will be invoked just after we realize
4554 /// that an unnamed union or struct is actually an anonymous union or
4555 /// struct, e.g.,
4556 ///
4557 /// @code
4558 /// union {
4559 ///   int i;
4560 ///   float f;
4561 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4562 ///    // f into the surrounding scope.x
4563 /// @endcode
4564 ///
4565 /// This routine is recursive, injecting the names of nested anonymous
4566 /// structs/unions into the owning context and scope as well.
4567 static bool
4568 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4569                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4570                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4571   bool Invalid = false;
4572 
4573   // Look every FieldDecl and IndirectFieldDecl with a name.
4574   for (auto *D : AnonRecord->decls()) {
4575     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4576         cast<NamedDecl>(D)->getDeclName()) {
4577       ValueDecl *VD = cast<ValueDecl>(D);
4578       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4579                                        VD->getLocation(),
4580                                        AnonRecord->isUnion())) {
4581         // C++ [class.union]p2:
4582         //   The names of the members of an anonymous union shall be
4583         //   distinct from the names of any other entity in the
4584         //   scope in which the anonymous union is declared.
4585         Invalid = true;
4586       } else {
4587         // C++ [class.union]p2:
4588         //   For the purpose of name lookup, after the anonymous union
4589         //   definition, the members of the anonymous union are
4590         //   considered to have been defined in the scope in which the
4591         //   anonymous union is declared.
4592         unsigned OldChainingSize = Chaining.size();
4593         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4594           Chaining.append(IF->chain_begin(), IF->chain_end());
4595         else
4596           Chaining.push_back(VD);
4597 
4598         assert(Chaining.size() >= 2);
4599         NamedDecl **NamedChain =
4600           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4601         for (unsigned i = 0; i < Chaining.size(); i++)
4602           NamedChain[i] = Chaining[i];
4603 
4604         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4605             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4606             VD->getType(), {NamedChain, Chaining.size()});
4607 
4608         for (const auto *Attr : VD->attrs())
4609           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4610 
4611         IndirectField->setAccess(AS);
4612         IndirectField->setImplicit();
4613         SemaRef.PushOnScopeChains(IndirectField, S);
4614 
4615         // That includes picking up the appropriate access specifier.
4616         if (AS != AS_none) IndirectField->setAccess(AS);
4617 
4618         Chaining.resize(OldChainingSize);
4619       }
4620     }
4621   }
4622 
4623   return Invalid;
4624 }
4625 
4626 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4627 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4628 /// illegal input values are mapped to SC_None.
4629 static StorageClass
4630 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4631   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4632   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4633          "Parser allowed 'typedef' as storage class VarDecl.");
4634   switch (StorageClassSpec) {
4635   case DeclSpec::SCS_unspecified:    return SC_None;
4636   case DeclSpec::SCS_extern:
4637     if (DS.isExternInLinkageSpec())
4638       return SC_None;
4639     return SC_Extern;
4640   case DeclSpec::SCS_static:         return SC_Static;
4641   case DeclSpec::SCS_auto:           return SC_Auto;
4642   case DeclSpec::SCS_register:       return SC_Register;
4643   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4644     // Illegal SCSs map to None: error reporting is up to the caller.
4645   case DeclSpec::SCS_mutable:        // Fall through.
4646   case DeclSpec::SCS_typedef:        return SC_None;
4647   }
4648   llvm_unreachable("unknown storage class specifier");
4649 }
4650 
4651 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4652   assert(Record->hasInClassInitializer());
4653 
4654   for (const auto *I : Record->decls()) {
4655     const auto *FD = dyn_cast<FieldDecl>(I);
4656     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4657       FD = IFD->getAnonField();
4658     if (FD && FD->hasInClassInitializer())
4659       return FD->getLocation();
4660   }
4661 
4662   llvm_unreachable("couldn't find in-class initializer");
4663 }
4664 
4665 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4666                                       SourceLocation DefaultInitLoc) {
4667   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4668     return;
4669 
4670   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4671   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4672 }
4673 
4674 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4675                                       CXXRecordDecl *AnonUnion) {
4676   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4677     return;
4678 
4679   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4680 }
4681 
4682 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4683 /// anonymous structure or union. Anonymous unions are a C++ feature
4684 /// (C++ [class.union]) and a C11 feature; anonymous structures
4685 /// are a C11 feature and GNU C++ extension.
4686 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4687                                         AccessSpecifier AS,
4688                                         RecordDecl *Record,
4689                                         const PrintingPolicy &Policy) {
4690   DeclContext *Owner = Record->getDeclContext();
4691 
4692   // Diagnose whether this anonymous struct/union is an extension.
4693   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4694     Diag(Record->getLocation(), diag::ext_anonymous_union);
4695   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4696     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4697   else if (!Record->isUnion() && !getLangOpts().C11)
4698     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4699 
4700   // C and C++ require different kinds of checks for anonymous
4701   // structs/unions.
4702   bool Invalid = false;
4703   if (getLangOpts().CPlusPlus) {
4704     const char *PrevSpec = nullptr;
4705     if (Record->isUnion()) {
4706       // C++ [class.union]p6:
4707       // C++17 [class.union.anon]p2:
4708       //   Anonymous unions declared in a named namespace or in the
4709       //   global namespace shall be declared static.
4710       unsigned DiagID;
4711       DeclContext *OwnerScope = Owner->getRedeclContext();
4712       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4713           (OwnerScope->isTranslationUnit() ||
4714            (OwnerScope->isNamespace() &&
4715             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4716         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4717           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4718 
4719         // Recover by adding 'static'.
4720         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4721                                PrevSpec, DiagID, Policy);
4722       }
4723       // C++ [class.union]p6:
4724       //   A storage class is not allowed in a declaration of an
4725       //   anonymous union in a class scope.
4726       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4727                isa<RecordDecl>(Owner)) {
4728         Diag(DS.getStorageClassSpecLoc(),
4729              diag::err_anonymous_union_with_storage_spec)
4730           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4731 
4732         // Recover by removing the storage specifier.
4733         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4734                                SourceLocation(),
4735                                PrevSpec, DiagID, Context.getPrintingPolicy());
4736       }
4737     }
4738 
4739     // Ignore const/volatile/restrict qualifiers.
4740     if (DS.getTypeQualifiers()) {
4741       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4742         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4743           << Record->isUnion() << "const"
4744           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4745       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4746         Diag(DS.getVolatileSpecLoc(),
4747              diag::ext_anonymous_struct_union_qualified)
4748           << Record->isUnion() << "volatile"
4749           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4750       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4751         Diag(DS.getRestrictSpecLoc(),
4752              diag::ext_anonymous_struct_union_qualified)
4753           << Record->isUnion() << "restrict"
4754           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4755       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4756         Diag(DS.getAtomicSpecLoc(),
4757              diag::ext_anonymous_struct_union_qualified)
4758           << Record->isUnion() << "_Atomic"
4759           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4760       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4761         Diag(DS.getUnalignedSpecLoc(),
4762              diag::ext_anonymous_struct_union_qualified)
4763           << Record->isUnion() << "__unaligned"
4764           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4765 
4766       DS.ClearTypeQualifiers();
4767     }
4768 
4769     // C++ [class.union]p2:
4770     //   The member-specification of an anonymous union shall only
4771     //   define non-static data members. [Note: nested types and
4772     //   functions cannot be declared within an anonymous union. ]
4773     for (auto *Mem : Record->decls()) {
4774       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4775         // C++ [class.union]p3:
4776         //   An anonymous union shall not have private or protected
4777         //   members (clause 11).
4778         assert(FD->getAccess() != AS_none);
4779         if (FD->getAccess() != AS_public) {
4780           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4781             << Record->isUnion() << (FD->getAccess() == AS_protected);
4782           Invalid = true;
4783         }
4784 
4785         // C++ [class.union]p1
4786         //   An object of a class with a non-trivial constructor, a non-trivial
4787         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4788         //   assignment operator cannot be a member of a union, nor can an
4789         //   array of such objects.
4790         if (CheckNontrivialField(FD))
4791           Invalid = true;
4792       } else if (Mem->isImplicit()) {
4793         // Any implicit members are fine.
4794       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4795         // This is a type that showed up in an
4796         // elaborated-type-specifier inside the anonymous struct or
4797         // union, but which actually declares a type outside of the
4798         // anonymous struct or union. It's okay.
4799       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4800         if (!MemRecord->isAnonymousStructOrUnion() &&
4801             MemRecord->getDeclName()) {
4802           // Visual C++ allows type definition in anonymous struct or union.
4803           if (getLangOpts().MicrosoftExt)
4804             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4805               << Record->isUnion();
4806           else {
4807             // This is a nested type declaration.
4808             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4809               << Record->isUnion();
4810             Invalid = true;
4811           }
4812         } else {
4813           // This is an anonymous type definition within another anonymous type.
4814           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4815           // not part of standard C++.
4816           Diag(MemRecord->getLocation(),
4817                diag::ext_anonymous_record_with_anonymous_type)
4818             << Record->isUnion();
4819         }
4820       } else if (isa<AccessSpecDecl>(Mem)) {
4821         // Any access specifier is fine.
4822       } else if (isa<StaticAssertDecl>(Mem)) {
4823         // In C++1z, static_assert declarations are also fine.
4824       } else {
4825         // We have something that isn't a non-static data
4826         // member. Complain about it.
4827         unsigned DK = diag::err_anonymous_record_bad_member;
4828         if (isa<TypeDecl>(Mem))
4829           DK = diag::err_anonymous_record_with_type;
4830         else if (isa<FunctionDecl>(Mem))
4831           DK = diag::err_anonymous_record_with_function;
4832         else if (isa<VarDecl>(Mem))
4833           DK = diag::err_anonymous_record_with_static;
4834 
4835         // Visual C++ allows type definition in anonymous struct or union.
4836         if (getLangOpts().MicrosoftExt &&
4837             DK == diag::err_anonymous_record_with_type)
4838           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4839             << Record->isUnion();
4840         else {
4841           Diag(Mem->getLocation(), DK) << Record->isUnion();
4842           Invalid = true;
4843         }
4844       }
4845     }
4846 
4847     // C++11 [class.union]p8 (DR1460):
4848     //   At most one variant member of a union may have a
4849     //   brace-or-equal-initializer.
4850     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4851         Owner->isRecord())
4852       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4853                                 cast<CXXRecordDecl>(Record));
4854   }
4855 
4856   if (!Record->isUnion() && !Owner->isRecord()) {
4857     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4858       << getLangOpts().CPlusPlus;
4859     Invalid = true;
4860   }
4861 
4862   // C++ [dcl.dcl]p3:
4863   //   [If there are no declarators], and except for the declaration of an
4864   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4865   //   names into the program
4866   // C++ [class.mem]p2:
4867   //   each such member-declaration shall either declare at least one member
4868   //   name of the class or declare at least one unnamed bit-field
4869   //
4870   // For C this is an error even for a named struct, and is diagnosed elsewhere.
4871   if (getLangOpts().CPlusPlus && Record->field_empty())
4872     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4873 
4874   // Mock up a declarator.
4875   Declarator Dc(DS, DeclaratorContext::MemberContext);
4876   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4877   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4878 
4879   // Create a declaration for this anonymous struct/union.
4880   NamedDecl *Anon = nullptr;
4881   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4882     Anon = FieldDecl::Create(
4883         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4884         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4885         /*BitWidth=*/nullptr, /*Mutable=*/false,
4886         /*InitStyle=*/ICIS_NoInit);
4887     Anon->setAccess(AS);
4888     if (getLangOpts().CPlusPlus)
4889       FieldCollector->Add(cast<FieldDecl>(Anon));
4890   } else {
4891     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4892     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4893     if (SCSpec == DeclSpec::SCS_mutable) {
4894       // mutable can only appear on non-static class members, so it's always
4895       // an error here
4896       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4897       Invalid = true;
4898       SC = SC_None;
4899     }
4900 
4901     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4902                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4903                            Context.getTypeDeclType(Record), TInfo, SC);
4904 
4905     // Default-initialize the implicit variable. This initialization will be
4906     // trivial in almost all cases, except if a union member has an in-class
4907     // initializer:
4908     //   union { int n = 0; };
4909     ActOnUninitializedDecl(Anon);
4910   }
4911   Anon->setImplicit();
4912 
4913   // Mark this as an anonymous struct/union type.
4914   Record->setAnonymousStructOrUnion(true);
4915 
4916   // Add the anonymous struct/union object to the current
4917   // context. We'll be referencing this object when we refer to one of
4918   // its members.
4919   Owner->addDecl(Anon);
4920 
4921   // Inject the members of the anonymous struct/union into the owning
4922   // context and into the identifier resolver chain for name lookup
4923   // purposes.
4924   SmallVector<NamedDecl*, 2> Chain;
4925   Chain.push_back(Anon);
4926 
4927   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4928     Invalid = true;
4929 
4930   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4931     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4932       Decl *ManglingContextDecl;
4933       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4934               NewVD->getDeclContext(), ManglingContextDecl)) {
4935         Context.setManglingNumber(
4936             NewVD, MCtx->getManglingNumber(
4937                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4938         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4939       }
4940     }
4941   }
4942 
4943   if (Invalid)
4944     Anon->setInvalidDecl();
4945 
4946   return Anon;
4947 }
4948 
4949 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4950 /// Microsoft C anonymous structure.
4951 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4952 /// Example:
4953 ///
4954 /// struct A { int a; };
4955 /// struct B { struct A; int b; };
4956 ///
4957 /// void foo() {
4958 ///   B var;
4959 ///   var.a = 3;
4960 /// }
4961 ///
4962 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4963                                            RecordDecl *Record) {
4964   assert(Record && "expected a record!");
4965 
4966   // Mock up a declarator.
4967   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4968   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4969   assert(TInfo && "couldn't build declarator info for anonymous struct");
4970 
4971   auto *ParentDecl = cast<RecordDecl>(CurContext);
4972   QualType RecTy = Context.getTypeDeclType(Record);
4973 
4974   // Create a declaration for this anonymous struct.
4975   NamedDecl *Anon =
4976       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4977                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4978                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4979                         /*InitStyle=*/ICIS_NoInit);
4980   Anon->setImplicit();
4981 
4982   // Add the anonymous struct object to the current context.
4983   CurContext->addDecl(Anon);
4984 
4985   // Inject the members of the anonymous struct into the current
4986   // context and into the identifier resolver chain for name lookup
4987   // purposes.
4988   SmallVector<NamedDecl*, 2> Chain;
4989   Chain.push_back(Anon);
4990 
4991   RecordDecl *RecordDef = Record->getDefinition();
4992   if (RequireCompleteType(Anon->getLocation(), RecTy,
4993                           diag::err_field_incomplete) ||
4994       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4995                                           AS_none, Chain)) {
4996     Anon->setInvalidDecl();
4997     ParentDecl->setInvalidDecl();
4998   }
4999 
5000   return Anon;
5001 }
5002 
5003 /// GetNameForDeclarator - Determine the full declaration name for the
5004 /// given Declarator.
5005 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5006   return GetNameFromUnqualifiedId(D.getName());
5007 }
5008 
5009 /// Retrieves the declaration name from a parsed unqualified-id.
5010 DeclarationNameInfo
5011 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5012   DeclarationNameInfo NameInfo;
5013   NameInfo.setLoc(Name.StartLocation);
5014 
5015   switch (Name.getKind()) {
5016 
5017   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5018   case UnqualifiedIdKind::IK_Identifier:
5019     NameInfo.setName(Name.Identifier);
5020     return NameInfo;
5021 
5022   case UnqualifiedIdKind::IK_DeductionGuideName: {
5023     // C++ [temp.deduct.guide]p3:
5024     //   The simple-template-id shall name a class template specialization.
5025     //   The template-name shall be the same identifier as the template-name
5026     //   of the simple-template-id.
5027     // These together intend to imply that the template-name shall name a
5028     // class template.
5029     // FIXME: template<typename T> struct X {};
5030     //        template<typename T> using Y = X<T>;
5031     //        Y(int) -> Y<int>;
5032     //   satisfies these rules but does not name a class template.
5033     TemplateName TN = Name.TemplateName.get().get();
5034     auto *Template = TN.getAsTemplateDecl();
5035     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5036       Diag(Name.StartLocation,
5037            diag::err_deduction_guide_name_not_class_template)
5038         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5039       if (Template)
5040         Diag(Template->getLocation(), diag::note_template_decl_here);
5041       return DeclarationNameInfo();
5042     }
5043 
5044     NameInfo.setName(
5045         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5046     return NameInfo;
5047   }
5048 
5049   case UnqualifiedIdKind::IK_OperatorFunctionId:
5050     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5051                                            Name.OperatorFunctionId.Operator));
5052     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5053       = Name.OperatorFunctionId.SymbolLocations[0];
5054     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5055       = Name.EndLocation.getRawEncoding();
5056     return NameInfo;
5057 
5058   case UnqualifiedIdKind::IK_LiteralOperatorId:
5059     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5060                                                            Name.Identifier));
5061     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5062     return NameInfo;
5063 
5064   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5065     TypeSourceInfo *TInfo;
5066     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5067     if (Ty.isNull())
5068       return DeclarationNameInfo();
5069     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5070                                                Context.getCanonicalType(Ty)));
5071     NameInfo.setNamedTypeInfo(TInfo);
5072     return NameInfo;
5073   }
5074 
5075   case UnqualifiedIdKind::IK_ConstructorName: {
5076     TypeSourceInfo *TInfo;
5077     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5078     if (Ty.isNull())
5079       return DeclarationNameInfo();
5080     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5081                                               Context.getCanonicalType(Ty)));
5082     NameInfo.setNamedTypeInfo(TInfo);
5083     return NameInfo;
5084   }
5085 
5086   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5087     // In well-formed code, we can only have a constructor
5088     // template-id that refers to the current context, so go there
5089     // to find the actual type being constructed.
5090     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5091     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5092       return DeclarationNameInfo();
5093 
5094     // Determine the type of the class being constructed.
5095     QualType CurClassType = Context.getTypeDeclType(CurClass);
5096 
5097     // FIXME: Check two things: that the template-id names the same type as
5098     // CurClassType, and that the template-id does not occur when the name
5099     // was qualified.
5100 
5101     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5102                                     Context.getCanonicalType(CurClassType)));
5103     // FIXME: should we retrieve TypeSourceInfo?
5104     NameInfo.setNamedTypeInfo(nullptr);
5105     return NameInfo;
5106   }
5107 
5108   case UnqualifiedIdKind::IK_DestructorName: {
5109     TypeSourceInfo *TInfo;
5110     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5111     if (Ty.isNull())
5112       return DeclarationNameInfo();
5113     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5114                                               Context.getCanonicalType(Ty)));
5115     NameInfo.setNamedTypeInfo(TInfo);
5116     return NameInfo;
5117   }
5118 
5119   case UnqualifiedIdKind::IK_TemplateId: {
5120     TemplateName TName = Name.TemplateId->Template.get();
5121     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5122     return Context.getNameForTemplate(TName, TNameLoc);
5123   }
5124 
5125   } // switch (Name.getKind())
5126 
5127   llvm_unreachable("Unknown name kind");
5128 }
5129 
5130 static QualType getCoreType(QualType Ty) {
5131   do {
5132     if (Ty->isPointerType() || Ty->isReferenceType())
5133       Ty = Ty->getPointeeType();
5134     else if (Ty->isArrayType())
5135       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5136     else
5137       return Ty.withoutLocalFastQualifiers();
5138   } while (true);
5139 }
5140 
5141 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5142 /// and Definition have "nearly" matching parameters. This heuristic is
5143 /// used to improve diagnostics in the case where an out-of-line function
5144 /// definition doesn't match any declaration within the class or namespace.
5145 /// Also sets Params to the list of indices to the parameters that differ
5146 /// between the declaration and the definition. If hasSimilarParameters
5147 /// returns true and Params is empty, then all of the parameters match.
5148 static bool hasSimilarParameters(ASTContext &Context,
5149                                      FunctionDecl *Declaration,
5150                                      FunctionDecl *Definition,
5151                                      SmallVectorImpl<unsigned> &Params) {
5152   Params.clear();
5153   if (Declaration->param_size() != Definition->param_size())
5154     return false;
5155   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5156     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5157     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5158 
5159     // The parameter types are identical
5160     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5161       continue;
5162 
5163     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5164     QualType DefParamBaseTy = getCoreType(DefParamTy);
5165     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5166     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5167 
5168     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5169         (DeclTyName && DeclTyName == DefTyName))
5170       Params.push_back(Idx);
5171     else  // The two parameters aren't even close
5172       return false;
5173   }
5174 
5175   return true;
5176 }
5177 
5178 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5179 /// declarator needs to be rebuilt in the current instantiation.
5180 /// Any bits of declarator which appear before the name are valid for
5181 /// consideration here.  That's specifically the type in the decl spec
5182 /// and the base type in any member-pointer chunks.
5183 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5184                                                     DeclarationName Name) {
5185   // The types we specifically need to rebuild are:
5186   //   - typenames, typeofs, and decltypes
5187   //   - types which will become injected class names
5188   // Of course, we also need to rebuild any type referencing such a
5189   // type.  It's safest to just say "dependent", but we call out a
5190   // few cases here.
5191 
5192   DeclSpec &DS = D.getMutableDeclSpec();
5193   switch (DS.getTypeSpecType()) {
5194   case DeclSpec::TST_typename:
5195   case DeclSpec::TST_typeofType:
5196   case DeclSpec::TST_underlyingType:
5197   case DeclSpec::TST_atomic: {
5198     // Grab the type from the parser.
5199     TypeSourceInfo *TSI = nullptr;
5200     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5201     if (T.isNull() || !T->isDependentType()) break;
5202 
5203     // Make sure there's a type source info.  This isn't really much
5204     // of a waste; most dependent types should have type source info
5205     // attached already.
5206     if (!TSI)
5207       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5208 
5209     // Rebuild the type in the current instantiation.
5210     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5211     if (!TSI) return true;
5212 
5213     // Store the new type back in the decl spec.
5214     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5215     DS.UpdateTypeRep(LocType);
5216     break;
5217   }
5218 
5219   case DeclSpec::TST_decltype:
5220   case DeclSpec::TST_typeofExpr: {
5221     Expr *E = DS.getRepAsExpr();
5222     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5223     if (Result.isInvalid()) return true;
5224     DS.UpdateExprRep(Result.get());
5225     break;
5226   }
5227 
5228   default:
5229     // Nothing to do for these decl specs.
5230     break;
5231   }
5232 
5233   // It doesn't matter what order we do this in.
5234   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5235     DeclaratorChunk &Chunk = D.getTypeObject(I);
5236 
5237     // The only type information in the declarator which can come
5238     // before the declaration name is the base type of a member
5239     // pointer.
5240     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5241       continue;
5242 
5243     // Rebuild the scope specifier in-place.
5244     CXXScopeSpec &SS = Chunk.Mem.Scope();
5245     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5246       return true;
5247   }
5248 
5249   return false;
5250 }
5251 
5252 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5253   D.setFunctionDefinitionKind(FDK_Declaration);
5254   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5255 
5256   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5257       Dcl && Dcl->getDeclContext()->isFileContext())
5258     Dcl->setTopLevelDeclInObjCContainer();
5259 
5260   if (getLangOpts().OpenCL)
5261     setCurrentOpenCLExtensionForDecl(Dcl);
5262 
5263   return Dcl;
5264 }
5265 
5266 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5267 ///   If T is the name of a class, then each of the following shall have a
5268 ///   name different from T:
5269 ///     - every static data member of class T;
5270 ///     - every member function of class T
5271 ///     - every member of class T that is itself a type;
5272 /// \returns true if the declaration name violates these rules.
5273 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5274                                    DeclarationNameInfo NameInfo) {
5275   DeclarationName Name = NameInfo.getName();
5276 
5277   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5278   while (Record && Record->isAnonymousStructOrUnion())
5279     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5280   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5281     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5282     return true;
5283   }
5284 
5285   return false;
5286 }
5287 
5288 /// Diagnose a declaration whose declarator-id has the given
5289 /// nested-name-specifier.
5290 ///
5291 /// \param SS The nested-name-specifier of the declarator-id.
5292 ///
5293 /// \param DC The declaration context to which the nested-name-specifier
5294 /// resolves.
5295 ///
5296 /// \param Name The name of the entity being declared.
5297 ///
5298 /// \param Loc The location of the name of the entity being declared.
5299 ///
5300 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5301 /// we're declaring an explicit / partial specialization / instantiation.
5302 ///
5303 /// \returns true if we cannot safely recover from this error, false otherwise.
5304 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5305                                         DeclarationName Name,
5306                                         SourceLocation Loc, bool IsTemplateId) {
5307   DeclContext *Cur = CurContext;
5308   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5309     Cur = Cur->getParent();
5310 
5311   // If the user provided a superfluous scope specifier that refers back to the
5312   // class in which the entity is already declared, diagnose and ignore it.
5313   //
5314   // class X {
5315   //   void X::f();
5316   // };
5317   //
5318   // Note, it was once ill-formed to give redundant qualification in all
5319   // contexts, but that rule was removed by DR482.
5320   if (Cur->Equals(DC)) {
5321     if (Cur->isRecord()) {
5322       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5323                                       : diag::err_member_extra_qualification)
5324         << Name << FixItHint::CreateRemoval(SS.getRange());
5325       SS.clear();
5326     } else {
5327       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5328     }
5329     return false;
5330   }
5331 
5332   // Check whether the qualifying scope encloses the scope of the original
5333   // declaration. For a template-id, we perform the checks in
5334   // CheckTemplateSpecializationScope.
5335   if (!Cur->Encloses(DC) && !IsTemplateId) {
5336     if (Cur->isRecord())
5337       Diag(Loc, diag::err_member_qualification)
5338         << Name << SS.getRange();
5339     else if (isa<TranslationUnitDecl>(DC))
5340       Diag(Loc, diag::err_invalid_declarator_global_scope)
5341         << Name << SS.getRange();
5342     else if (isa<FunctionDecl>(Cur))
5343       Diag(Loc, diag::err_invalid_declarator_in_function)
5344         << Name << SS.getRange();
5345     else if (isa<BlockDecl>(Cur))
5346       Diag(Loc, diag::err_invalid_declarator_in_block)
5347         << Name << SS.getRange();
5348     else
5349       Diag(Loc, diag::err_invalid_declarator_scope)
5350       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5351 
5352     return true;
5353   }
5354 
5355   if (Cur->isRecord()) {
5356     // Cannot qualify members within a class.
5357     Diag(Loc, diag::err_member_qualification)
5358       << Name << SS.getRange();
5359     SS.clear();
5360 
5361     // C++ constructors and destructors with incorrect scopes can break
5362     // our AST invariants by having the wrong underlying types. If
5363     // that's the case, then drop this declaration entirely.
5364     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5365          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5366         !Context.hasSameType(Name.getCXXNameType(),
5367                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5368       return true;
5369 
5370     return false;
5371   }
5372 
5373   // C++11 [dcl.meaning]p1:
5374   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5375   //   not begin with a decltype-specifer"
5376   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5377   while (SpecLoc.getPrefix())
5378     SpecLoc = SpecLoc.getPrefix();
5379   if (dyn_cast_or_null<DecltypeType>(
5380         SpecLoc.getNestedNameSpecifier()->getAsType()))
5381     Diag(Loc, diag::err_decltype_in_declarator)
5382       << SpecLoc.getTypeLoc().getSourceRange();
5383 
5384   return false;
5385 }
5386 
5387 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5388                                   MultiTemplateParamsArg TemplateParamLists) {
5389   // TODO: consider using NameInfo for diagnostic.
5390   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5391   DeclarationName Name = NameInfo.getName();
5392 
5393   // All of these full declarators require an identifier.  If it doesn't have
5394   // one, the ParsedFreeStandingDeclSpec action should be used.
5395   if (D.isDecompositionDeclarator()) {
5396     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5397   } else if (!Name) {
5398     if (!D.isInvalidType())  // Reject this if we think it is valid.
5399       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5400           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5401     return nullptr;
5402   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5403     return nullptr;
5404 
5405   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5406   // we find one that is.
5407   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5408          (S->getFlags() & Scope::TemplateParamScope) != 0)
5409     S = S->getParent();
5410 
5411   DeclContext *DC = CurContext;
5412   if (D.getCXXScopeSpec().isInvalid())
5413     D.setInvalidType();
5414   else if (D.getCXXScopeSpec().isSet()) {
5415     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5416                                         UPPC_DeclarationQualifier))
5417       return nullptr;
5418 
5419     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5420     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5421     if (!DC || isa<EnumDecl>(DC)) {
5422       // If we could not compute the declaration context, it's because the
5423       // declaration context is dependent but does not refer to a class,
5424       // class template, or class template partial specialization. Complain
5425       // and return early, to avoid the coming semantic disaster.
5426       Diag(D.getIdentifierLoc(),
5427            diag::err_template_qualified_declarator_no_match)
5428         << D.getCXXScopeSpec().getScopeRep()
5429         << D.getCXXScopeSpec().getRange();
5430       return nullptr;
5431     }
5432     bool IsDependentContext = DC->isDependentContext();
5433 
5434     if (!IsDependentContext &&
5435         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5436       return nullptr;
5437 
5438     // If a class is incomplete, do not parse entities inside it.
5439     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5440       Diag(D.getIdentifierLoc(),
5441            diag::err_member_def_undefined_record)
5442         << Name << DC << D.getCXXScopeSpec().getRange();
5443       return nullptr;
5444     }
5445     if (!D.getDeclSpec().isFriendSpecified()) {
5446       if (diagnoseQualifiedDeclaration(
5447               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5448               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5449         if (DC->isRecord())
5450           return nullptr;
5451 
5452         D.setInvalidType();
5453       }
5454     }
5455 
5456     // Check whether we need to rebuild the type of the given
5457     // declaration in the current instantiation.
5458     if (EnteringContext && IsDependentContext &&
5459         TemplateParamLists.size() != 0) {
5460       ContextRAII SavedContext(*this, DC);
5461       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5462         D.setInvalidType();
5463     }
5464   }
5465 
5466   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5467   QualType R = TInfo->getType();
5468 
5469   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5470                                       UPPC_DeclarationType))
5471     D.setInvalidType();
5472 
5473   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5474                         forRedeclarationInCurContext());
5475 
5476   // See if this is a redefinition of a variable in the same scope.
5477   if (!D.getCXXScopeSpec().isSet()) {
5478     bool IsLinkageLookup = false;
5479     bool CreateBuiltins = false;
5480 
5481     // If the declaration we're planning to build will be a function
5482     // or object with linkage, then look for another declaration with
5483     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5484     //
5485     // If the declaration we're planning to build will be declared with
5486     // external linkage in the translation unit, create any builtin with
5487     // the same name.
5488     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5489       /* Do nothing*/;
5490     else if (CurContext->isFunctionOrMethod() &&
5491              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5492               R->isFunctionType())) {
5493       IsLinkageLookup = true;
5494       CreateBuiltins =
5495           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5496     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5497                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5498       CreateBuiltins = true;
5499 
5500     if (IsLinkageLookup) {
5501       Previous.clear(LookupRedeclarationWithLinkage);
5502       Previous.setRedeclarationKind(ForExternalRedeclaration);
5503     }
5504 
5505     LookupName(Previous, S, CreateBuiltins);
5506   } else { // Something like "int foo::x;"
5507     LookupQualifiedName(Previous, DC);
5508 
5509     // C++ [dcl.meaning]p1:
5510     //   When the declarator-id is qualified, the declaration shall refer to a
5511     //  previously declared member of the class or namespace to which the
5512     //  qualifier refers (or, in the case of a namespace, of an element of the
5513     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5514     //  thereof; [...]
5515     //
5516     // Note that we already checked the context above, and that we do not have
5517     // enough information to make sure that Previous contains the declaration
5518     // we want to match. For example, given:
5519     //
5520     //   class X {
5521     //     void f();
5522     //     void f(float);
5523     //   };
5524     //
5525     //   void X::f(int) { } // ill-formed
5526     //
5527     // In this case, Previous will point to the overload set
5528     // containing the two f's declared in X, but neither of them
5529     // matches.
5530 
5531     // C++ [dcl.meaning]p1:
5532     //   [...] the member shall not merely have been introduced by a
5533     //   using-declaration in the scope of the class or namespace nominated by
5534     //   the nested-name-specifier of the declarator-id.
5535     RemoveUsingDecls(Previous);
5536   }
5537 
5538   if (Previous.isSingleResult() &&
5539       Previous.getFoundDecl()->isTemplateParameter()) {
5540     // Maybe we will complain about the shadowed template parameter.
5541     if (!D.isInvalidType())
5542       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5543                                       Previous.getFoundDecl());
5544 
5545     // Just pretend that we didn't see the previous declaration.
5546     Previous.clear();
5547   }
5548 
5549   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5550     // Forget that the previous declaration is the injected-class-name.
5551     Previous.clear();
5552 
5553   // In C++, the previous declaration we find might be a tag type
5554   // (class or enum). In this case, the new declaration will hide the
5555   // tag type. Note that this applies to functions, function templates, and
5556   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5557   if (Previous.isSingleTagDecl() &&
5558       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5559       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5560     Previous.clear();
5561 
5562   // Check that there are no default arguments other than in the parameters
5563   // of a function declaration (C++ only).
5564   if (getLangOpts().CPlusPlus)
5565     CheckExtraCXXDefaultArguments(D);
5566 
5567   NamedDecl *New;
5568 
5569   bool AddToScope = true;
5570   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5571     if (TemplateParamLists.size()) {
5572       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5573       return nullptr;
5574     }
5575 
5576     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5577   } else if (R->isFunctionType()) {
5578     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5579                                   TemplateParamLists,
5580                                   AddToScope);
5581   } else {
5582     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5583                                   AddToScope);
5584   }
5585 
5586   if (!New)
5587     return nullptr;
5588 
5589   // If this has an identifier and is not a function template specialization,
5590   // add it to the scope stack.
5591   if (New->getDeclName() && AddToScope)
5592     PushOnScopeChains(New, S);
5593 
5594   if (isInOpenMPDeclareTargetContext())
5595     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5596 
5597   return New;
5598 }
5599 
5600 /// Helper method to turn variable array types into constant array
5601 /// types in certain situations which would otherwise be errors (for
5602 /// GCC compatibility).
5603 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5604                                                     ASTContext &Context,
5605                                                     bool &SizeIsNegative,
5606                                                     llvm::APSInt &Oversized) {
5607   // This method tries to turn a variable array into a constant
5608   // array even when the size isn't an ICE.  This is necessary
5609   // for compatibility with code that depends on gcc's buggy
5610   // constant expression folding, like struct {char x[(int)(char*)2];}
5611   SizeIsNegative = false;
5612   Oversized = 0;
5613 
5614   if (T->isDependentType())
5615     return QualType();
5616 
5617   QualifierCollector Qs;
5618   const Type *Ty = Qs.strip(T);
5619 
5620   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5621     QualType Pointee = PTy->getPointeeType();
5622     QualType FixedType =
5623         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5624                                             Oversized);
5625     if (FixedType.isNull()) return FixedType;
5626     FixedType = Context.getPointerType(FixedType);
5627     return Qs.apply(Context, FixedType);
5628   }
5629   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5630     QualType Inner = PTy->getInnerType();
5631     QualType FixedType =
5632         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5633                                             Oversized);
5634     if (FixedType.isNull()) return FixedType;
5635     FixedType = Context.getParenType(FixedType);
5636     return Qs.apply(Context, FixedType);
5637   }
5638 
5639   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5640   if (!VLATy)
5641     return QualType();
5642   // FIXME: We should probably handle this case
5643   if (VLATy->getElementType()->isVariablyModifiedType())
5644     return QualType();
5645 
5646   Expr::EvalResult Result;
5647   if (!VLATy->getSizeExpr() ||
5648       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5649     return QualType();
5650 
5651   llvm::APSInt Res = Result.Val.getInt();
5652 
5653   // Check whether the array size is negative.
5654   if (Res.isSigned() && Res.isNegative()) {
5655     SizeIsNegative = true;
5656     return QualType();
5657   }
5658 
5659   // Check whether the array is too large to be addressed.
5660   unsigned ActiveSizeBits
5661     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5662                                               Res);
5663   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5664     Oversized = Res;
5665     return QualType();
5666   }
5667 
5668   return Context.getConstantArrayType(VLATy->getElementType(),
5669                                       Res, ArrayType::Normal, 0);
5670 }
5671 
5672 static void
5673 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5674   SrcTL = SrcTL.getUnqualifiedLoc();
5675   DstTL = DstTL.getUnqualifiedLoc();
5676   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5677     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5678     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5679                                       DstPTL.getPointeeLoc());
5680     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5681     return;
5682   }
5683   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5684     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5685     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5686                                       DstPTL.getInnerLoc());
5687     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5688     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5689     return;
5690   }
5691   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5692   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5693   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5694   TypeLoc DstElemTL = DstATL.getElementLoc();
5695   DstElemTL.initializeFullCopy(SrcElemTL);
5696   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5697   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5698   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5699 }
5700 
5701 /// Helper method to turn variable array types into constant array
5702 /// types in certain situations which would otherwise be errors (for
5703 /// GCC compatibility).
5704 static TypeSourceInfo*
5705 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5706                                               ASTContext &Context,
5707                                               bool &SizeIsNegative,
5708                                               llvm::APSInt &Oversized) {
5709   QualType FixedTy
5710     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5711                                           SizeIsNegative, Oversized);
5712   if (FixedTy.isNull())
5713     return nullptr;
5714   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5715   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5716                                     FixedTInfo->getTypeLoc());
5717   return FixedTInfo;
5718 }
5719 
5720 /// Register the given locally-scoped extern "C" declaration so
5721 /// that it can be found later for redeclarations. We include any extern "C"
5722 /// declaration that is not visible in the translation unit here, not just
5723 /// function-scope declarations.
5724 void
5725 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5726   if (!getLangOpts().CPlusPlus &&
5727       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5728     // Don't need to track declarations in the TU in C.
5729     return;
5730 
5731   // Note that we have a locally-scoped external with this name.
5732   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5733 }
5734 
5735 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5736   // FIXME: We can have multiple results via __attribute__((overloadable)).
5737   auto Result = Context.getExternCContextDecl()->lookup(Name);
5738   return Result.empty() ? nullptr : *Result.begin();
5739 }
5740 
5741 /// Diagnose function specifiers on a declaration of an identifier that
5742 /// does not identify a function.
5743 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5744   // FIXME: We should probably indicate the identifier in question to avoid
5745   // confusion for constructs like "virtual int a(), b;"
5746   if (DS.isVirtualSpecified())
5747     Diag(DS.getVirtualSpecLoc(),
5748          diag::err_virtual_non_function);
5749 
5750   if (DS.hasExplicitSpecifier())
5751     Diag(DS.getExplicitSpecLoc(),
5752          diag::err_explicit_non_function);
5753 
5754   if (DS.isNoreturnSpecified())
5755     Diag(DS.getNoreturnSpecLoc(),
5756          diag::err_noreturn_non_function);
5757 }
5758 
5759 NamedDecl*
5760 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5761                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5762   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5763   if (D.getCXXScopeSpec().isSet()) {
5764     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5765       << D.getCXXScopeSpec().getRange();
5766     D.setInvalidType();
5767     // Pretend we didn't see the scope specifier.
5768     DC = CurContext;
5769     Previous.clear();
5770   }
5771 
5772   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5773 
5774   if (D.getDeclSpec().isInlineSpecified())
5775     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5776         << getLangOpts().CPlusPlus17;
5777   if (D.getDeclSpec().hasConstexprSpecifier())
5778     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5779         << 1 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
5780 
5781   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5782     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5783       Diag(D.getName().StartLocation,
5784            diag::err_deduction_guide_invalid_specifier)
5785           << "typedef";
5786     else
5787       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5788           << D.getName().getSourceRange();
5789     return nullptr;
5790   }
5791 
5792   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5793   if (!NewTD) return nullptr;
5794 
5795   // Handle attributes prior to checking for duplicates in MergeVarDecl
5796   ProcessDeclAttributes(S, NewTD, D);
5797 
5798   CheckTypedefForVariablyModifiedType(S, NewTD);
5799 
5800   bool Redeclaration = D.isRedeclaration();
5801   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5802   D.setRedeclaration(Redeclaration);
5803   return ND;
5804 }
5805 
5806 void
5807 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5808   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5809   // then it shall have block scope.
5810   // Note that variably modified types must be fixed before merging the decl so
5811   // that redeclarations will match.
5812   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5813   QualType T = TInfo->getType();
5814   if (T->isVariablyModifiedType()) {
5815     setFunctionHasBranchProtectedScope();
5816 
5817     if (S->getFnParent() == nullptr) {
5818       bool SizeIsNegative;
5819       llvm::APSInt Oversized;
5820       TypeSourceInfo *FixedTInfo =
5821         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5822                                                       SizeIsNegative,
5823                                                       Oversized);
5824       if (FixedTInfo) {
5825         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5826         NewTD->setTypeSourceInfo(FixedTInfo);
5827       } else {
5828         if (SizeIsNegative)
5829           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5830         else if (T->isVariableArrayType())
5831           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5832         else if (Oversized.getBoolValue())
5833           Diag(NewTD->getLocation(), diag::err_array_too_large)
5834             << Oversized.toString(10);
5835         else
5836           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5837         NewTD->setInvalidDecl();
5838       }
5839     }
5840   }
5841 }
5842 
5843 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5844 /// declares a typedef-name, either using the 'typedef' type specifier or via
5845 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5846 NamedDecl*
5847 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5848                            LookupResult &Previous, bool &Redeclaration) {
5849 
5850   // Find the shadowed declaration before filtering for scope.
5851   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5852 
5853   // Merge the decl with the existing one if appropriate. If the decl is
5854   // in an outer scope, it isn't the same thing.
5855   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5856                        /*AllowInlineNamespace*/false);
5857   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5858   if (!Previous.empty()) {
5859     Redeclaration = true;
5860     MergeTypedefNameDecl(S, NewTD, Previous);
5861   }
5862 
5863   if (ShadowedDecl && !Redeclaration)
5864     CheckShadow(NewTD, ShadowedDecl, Previous);
5865 
5866   // If this is the C FILE type, notify the AST context.
5867   if (IdentifierInfo *II = NewTD->getIdentifier())
5868     if (!NewTD->isInvalidDecl() &&
5869         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5870       if (II->isStr("FILE"))
5871         Context.setFILEDecl(NewTD);
5872       else if (II->isStr("jmp_buf"))
5873         Context.setjmp_bufDecl(NewTD);
5874       else if (II->isStr("sigjmp_buf"))
5875         Context.setsigjmp_bufDecl(NewTD);
5876       else if (II->isStr("ucontext_t"))
5877         Context.setucontext_tDecl(NewTD);
5878     }
5879 
5880   return NewTD;
5881 }
5882 
5883 /// Determines whether the given declaration is an out-of-scope
5884 /// previous declaration.
5885 ///
5886 /// This routine should be invoked when name lookup has found a
5887 /// previous declaration (PrevDecl) that is not in the scope where a
5888 /// new declaration by the same name is being introduced. If the new
5889 /// declaration occurs in a local scope, previous declarations with
5890 /// linkage may still be considered previous declarations (C99
5891 /// 6.2.2p4-5, C++ [basic.link]p6).
5892 ///
5893 /// \param PrevDecl the previous declaration found by name
5894 /// lookup
5895 ///
5896 /// \param DC the context in which the new declaration is being
5897 /// declared.
5898 ///
5899 /// \returns true if PrevDecl is an out-of-scope previous declaration
5900 /// for a new delcaration with the same name.
5901 static bool
5902 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5903                                 ASTContext &Context) {
5904   if (!PrevDecl)
5905     return false;
5906 
5907   if (!PrevDecl->hasLinkage())
5908     return false;
5909 
5910   if (Context.getLangOpts().CPlusPlus) {
5911     // C++ [basic.link]p6:
5912     //   If there is a visible declaration of an entity with linkage
5913     //   having the same name and type, ignoring entities declared
5914     //   outside the innermost enclosing namespace scope, the block
5915     //   scope declaration declares that same entity and receives the
5916     //   linkage of the previous declaration.
5917     DeclContext *OuterContext = DC->getRedeclContext();
5918     if (!OuterContext->isFunctionOrMethod())
5919       // This rule only applies to block-scope declarations.
5920       return false;
5921 
5922     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5923     if (PrevOuterContext->isRecord())
5924       // We found a member function: ignore it.
5925       return false;
5926 
5927     // Find the innermost enclosing namespace for the new and
5928     // previous declarations.
5929     OuterContext = OuterContext->getEnclosingNamespaceContext();
5930     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5931 
5932     // The previous declaration is in a different namespace, so it
5933     // isn't the same function.
5934     if (!OuterContext->Equals(PrevOuterContext))
5935       return false;
5936   }
5937 
5938   return true;
5939 }
5940 
5941 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5942   CXXScopeSpec &SS = D.getCXXScopeSpec();
5943   if (!SS.isSet()) return;
5944   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5945 }
5946 
5947 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5948   QualType type = decl->getType();
5949   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5950   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5951     // Various kinds of declaration aren't allowed to be __autoreleasing.
5952     unsigned kind = -1U;
5953     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5954       if (var->hasAttr<BlocksAttr>())
5955         kind = 0; // __block
5956       else if (!var->hasLocalStorage())
5957         kind = 1; // global
5958     } else if (isa<ObjCIvarDecl>(decl)) {
5959       kind = 3; // ivar
5960     } else if (isa<FieldDecl>(decl)) {
5961       kind = 2; // field
5962     }
5963 
5964     if (kind != -1U) {
5965       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5966         << kind;
5967     }
5968   } else if (lifetime == Qualifiers::OCL_None) {
5969     // Try to infer lifetime.
5970     if (!type->isObjCLifetimeType())
5971       return false;
5972 
5973     lifetime = type->getObjCARCImplicitLifetime();
5974     type = Context.getLifetimeQualifiedType(type, lifetime);
5975     decl->setType(type);
5976   }
5977 
5978   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5979     // Thread-local variables cannot have lifetime.
5980     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5981         var->getTLSKind()) {
5982       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5983         << var->getType();
5984       return true;
5985     }
5986   }
5987 
5988   return false;
5989 }
5990 
5991 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5992   // Ensure that an auto decl is deduced otherwise the checks below might cache
5993   // the wrong linkage.
5994   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5995 
5996   // 'weak' only applies to declarations with external linkage.
5997   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5998     if (!ND.isExternallyVisible()) {
5999       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6000       ND.dropAttr<WeakAttr>();
6001     }
6002   }
6003   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6004     if (ND.isExternallyVisible()) {
6005       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6006       ND.dropAttr<WeakRefAttr>();
6007       ND.dropAttr<AliasAttr>();
6008     }
6009   }
6010 
6011   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6012     if (VD->hasInit()) {
6013       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6014         assert(VD->isThisDeclarationADefinition() &&
6015                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6016         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6017         VD->dropAttr<AliasAttr>();
6018       }
6019     }
6020   }
6021 
6022   // 'selectany' only applies to externally visible variable declarations.
6023   // It does not apply to functions.
6024   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6025     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6026       S.Diag(Attr->getLocation(),
6027              diag::err_attribute_selectany_non_extern_data);
6028       ND.dropAttr<SelectAnyAttr>();
6029     }
6030   }
6031 
6032   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6033     auto *VD = dyn_cast<VarDecl>(&ND);
6034     bool IsAnonymousNS = false;
6035     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6036     if (VD) {
6037       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6038       while (NS && !IsAnonymousNS) {
6039         IsAnonymousNS = NS->isAnonymousNamespace();
6040         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6041       }
6042     }
6043     // dll attributes require external linkage. Static locals may have external
6044     // linkage but still cannot be explicitly imported or exported.
6045     // In Microsoft mode, a variable defined in anonymous namespace must have
6046     // external linkage in order to be exported.
6047     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6048     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6049         (!AnonNSInMicrosoftMode &&
6050          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6051       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6052         << &ND << Attr;
6053       ND.setInvalidDecl();
6054     }
6055   }
6056 
6057   // Virtual functions cannot be marked as 'notail'.
6058   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6059     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6060       if (MD->isVirtual()) {
6061         S.Diag(ND.getLocation(),
6062                diag::err_invalid_attribute_on_virtual_function)
6063             << Attr;
6064         ND.dropAttr<NotTailCalledAttr>();
6065       }
6066 
6067   // Check the attributes on the function type, if any.
6068   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6069     // Don't declare this variable in the second operand of the for-statement;
6070     // GCC miscompiles that by ending its lifetime before evaluating the
6071     // third operand. See gcc.gnu.org/PR86769.
6072     AttributedTypeLoc ATL;
6073     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6074          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6075          TL = ATL.getModifiedLoc()) {
6076       // The [[lifetimebound]] attribute can be applied to the implicit object
6077       // parameter of a non-static member function (other than a ctor or dtor)
6078       // by applying it to the function type.
6079       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6080         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6081         if (!MD || MD->isStatic()) {
6082           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6083               << !MD << A->getRange();
6084         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6085           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6086               << isa<CXXDestructorDecl>(MD) << A->getRange();
6087         }
6088       }
6089     }
6090   }
6091 }
6092 
6093 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6094                                            NamedDecl *NewDecl,
6095                                            bool IsSpecialization,
6096                                            bool IsDefinition) {
6097   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6098     return;
6099 
6100   bool IsTemplate = false;
6101   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6102     OldDecl = OldTD->getTemplatedDecl();
6103     IsTemplate = true;
6104     if (!IsSpecialization)
6105       IsDefinition = false;
6106   }
6107   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6108     NewDecl = NewTD->getTemplatedDecl();
6109     IsTemplate = true;
6110   }
6111 
6112   if (!OldDecl || !NewDecl)
6113     return;
6114 
6115   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6116   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6117   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6118   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6119 
6120   // dllimport and dllexport are inheritable attributes so we have to exclude
6121   // inherited attribute instances.
6122   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6123                     (NewExportAttr && !NewExportAttr->isInherited());
6124 
6125   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6126   // the only exception being explicit specializations.
6127   // Implicitly generated declarations are also excluded for now because there
6128   // is no other way to switch these to use dllimport or dllexport.
6129   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6130 
6131   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6132     // Allow with a warning for free functions and global variables.
6133     bool JustWarn = false;
6134     if (!OldDecl->isCXXClassMember()) {
6135       auto *VD = dyn_cast<VarDecl>(OldDecl);
6136       if (VD && !VD->getDescribedVarTemplate())
6137         JustWarn = true;
6138       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6139       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6140         JustWarn = true;
6141     }
6142 
6143     // We cannot change a declaration that's been used because IR has already
6144     // been emitted. Dllimported functions will still work though (modulo
6145     // address equality) as they can use the thunk.
6146     if (OldDecl->isUsed())
6147       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6148         JustWarn = false;
6149 
6150     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6151                                : diag::err_attribute_dll_redeclaration;
6152     S.Diag(NewDecl->getLocation(), DiagID)
6153         << NewDecl
6154         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6155     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6156     if (!JustWarn) {
6157       NewDecl->setInvalidDecl();
6158       return;
6159     }
6160   }
6161 
6162   // A redeclaration is not allowed to drop a dllimport attribute, the only
6163   // exceptions being inline function definitions (except for function
6164   // templates), local extern declarations, qualified friend declarations or
6165   // special MSVC extension: in the last case, the declaration is treated as if
6166   // it were marked dllexport.
6167   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6168   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6169   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6170     // Ignore static data because out-of-line definitions are diagnosed
6171     // separately.
6172     IsStaticDataMember = VD->isStaticDataMember();
6173     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6174                    VarDecl::DeclarationOnly;
6175   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6176     IsInline = FD->isInlined();
6177     IsQualifiedFriend = FD->getQualifier() &&
6178                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6179   }
6180 
6181   if (OldImportAttr && !HasNewAttr &&
6182       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6183       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6184     if (IsMicrosoft && IsDefinition) {
6185       S.Diag(NewDecl->getLocation(),
6186              diag::warn_redeclaration_without_import_attribute)
6187           << NewDecl;
6188       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6189       NewDecl->dropAttr<DLLImportAttr>();
6190       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6191           NewImportAttr->getRange(), S.Context,
6192           NewImportAttr->getSpellingListIndex()));
6193     } else {
6194       S.Diag(NewDecl->getLocation(),
6195              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6196           << NewDecl << OldImportAttr;
6197       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6198       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6199       OldDecl->dropAttr<DLLImportAttr>();
6200       NewDecl->dropAttr<DLLImportAttr>();
6201     }
6202   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6203     // In MinGW, seeing a function declared inline drops the dllimport
6204     // attribute.
6205     OldDecl->dropAttr<DLLImportAttr>();
6206     NewDecl->dropAttr<DLLImportAttr>();
6207     S.Diag(NewDecl->getLocation(),
6208            diag::warn_dllimport_dropped_from_inline_function)
6209         << NewDecl << OldImportAttr;
6210   }
6211 
6212   // A specialization of a class template member function is processed here
6213   // since it's a redeclaration. If the parent class is dllexport, the
6214   // specialization inherits that attribute. This doesn't happen automatically
6215   // since the parent class isn't instantiated until later.
6216   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6217     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6218         !NewImportAttr && !NewExportAttr) {
6219       if (const DLLExportAttr *ParentExportAttr =
6220               MD->getParent()->getAttr<DLLExportAttr>()) {
6221         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6222         NewAttr->setInherited(true);
6223         NewDecl->addAttr(NewAttr);
6224       }
6225     }
6226   }
6227 }
6228 
6229 /// Given that we are within the definition of the given function,
6230 /// will that definition behave like C99's 'inline', where the
6231 /// definition is discarded except for optimization purposes?
6232 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6233   // Try to avoid calling GetGVALinkageForFunction.
6234 
6235   // All cases of this require the 'inline' keyword.
6236   if (!FD->isInlined()) return false;
6237 
6238   // This is only possible in C++ with the gnu_inline attribute.
6239   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6240     return false;
6241 
6242   // Okay, go ahead and call the relatively-more-expensive function.
6243   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6244 }
6245 
6246 /// Determine whether a variable is extern "C" prior to attaching
6247 /// an initializer. We can't just call isExternC() here, because that
6248 /// will also compute and cache whether the declaration is externally
6249 /// visible, which might change when we attach the initializer.
6250 ///
6251 /// This can only be used if the declaration is known to not be a
6252 /// redeclaration of an internal linkage declaration.
6253 ///
6254 /// For instance:
6255 ///
6256 ///   auto x = []{};
6257 ///
6258 /// Attaching the initializer here makes this declaration not externally
6259 /// visible, because its type has internal linkage.
6260 ///
6261 /// FIXME: This is a hack.
6262 template<typename T>
6263 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6264   if (S.getLangOpts().CPlusPlus) {
6265     // In C++, the overloadable attribute negates the effects of extern "C".
6266     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6267       return false;
6268 
6269     // So do CUDA's host/device attributes.
6270     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6271                                  D->template hasAttr<CUDAHostAttr>()))
6272       return false;
6273   }
6274   return D->isExternC();
6275 }
6276 
6277 static bool shouldConsiderLinkage(const VarDecl *VD) {
6278   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6279   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6280       isa<OMPDeclareMapperDecl>(DC))
6281     return VD->hasExternalStorage();
6282   if (DC->isFileContext())
6283     return true;
6284   if (DC->isRecord())
6285     return false;
6286   llvm_unreachable("Unexpected context");
6287 }
6288 
6289 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6290   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6291   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6292       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6293     return true;
6294   if (DC->isRecord())
6295     return false;
6296   llvm_unreachable("Unexpected context");
6297 }
6298 
6299 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6300                           ParsedAttr::Kind Kind) {
6301   // Check decl attributes on the DeclSpec.
6302   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6303     return true;
6304 
6305   // Walk the declarator structure, checking decl attributes that were in a type
6306   // position to the decl itself.
6307   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6308     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6309       return true;
6310   }
6311 
6312   // Finally, check attributes on the decl itself.
6313   return PD.getAttributes().hasAttribute(Kind);
6314 }
6315 
6316 /// Adjust the \c DeclContext for a function or variable that might be a
6317 /// function-local external declaration.
6318 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6319   if (!DC->isFunctionOrMethod())
6320     return false;
6321 
6322   // If this is a local extern function or variable declared within a function
6323   // template, don't add it into the enclosing namespace scope until it is
6324   // instantiated; it might have a dependent type right now.
6325   if (DC->isDependentContext())
6326     return true;
6327 
6328   // C++11 [basic.link]p7:
6329   //   When a block scope declaration of an entity with linkage is not found to
6330   //   refer to some other declaration, then that entity is a member of the
6331   //   innermost enclosing namespace.
6332   //
6333   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6334   // semantically-enclosing namespace, not a lexically-enclosing one.
6335   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6336     DC = DC->getParent();
6337   return true;
6338 }
6339 
6340 /// Returns true if given declaration has external C language linkage.
6341 static bool isDeclExternC(const Decl *D) {
6342   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6343     return FD->isExternC();
6344   if (const auto *VD = dyn_cast<VarDecl>(D))
6345     return VD->isExternC();
6346 
6347   llvm_unreachable("Unknown type of decl!");
6348 }
6349 
6350 NamedDecl *Sema::ActOnVariableDeclarator(
6351     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6352     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6353     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6354   QualType R = TInfo->getType();
6355   DeclarationName Name = GetNameForDeclarator(D).getName();
6356 
6357   IdentifierInfo *II = Name.getAsIdentifierInfo();
6358 
6359   if (D.isDecompositionDeclarator()) {
6360     // Take the name of the first declarator as our name for diagnostic
6361     // purposes.
6362     auto &Decomp = D.getDecompositionDeclarator();
6363     if (!Decomp.bindings().empty()) {
6364       II = Decomp.bindings()[0].Name;
6365       Name = II;
6366     }
6367   } else if (!II) {
6368     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6369     return nullptr;
6370   }
6371 
6372   if (getLangOpts().OpenCL) {
6373     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6374     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6375     // argument.
6376     if (R->isImageType() || R->isPipeType()) {
6377       Diag(D.getIdentifierLoc(),
6378            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6379           << R;
6380       D.setInvalidType();
6381       return nullptr;
6382     }
6383 
6384     // OpenCL v1.2 s6.9.r:
6385     // The event type cannot be used to declare a program scope variable.
6386     // OpenCL v2.0 s6.9.q:
6387     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6388     if (NULL == S->getParent()) {
6389       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6390         Diag(D.getIdentifierLoc(),
6391              diag::err_invalid_type_for_program_scope_var) << R;
6392         D.setInvalidType();
6393         return nullptr;
6394       }
6395     }
6396 
6397     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6398     QualType NR = R;
6399     while (NR->isPointerType()) {
6400       if (NR->isFunctionPointerType()) {
6401         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6402         D.setInvalidType();
6403         break;
6404       }
6405       NR = NR->getPointeeType();
6406     }
6407 
6408     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6409       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6410       // half array type (unless the cl_khr_fp16 extension is enabled).
6411       if (Context.getBaseElementType(R)->isHalfType()) {
6412         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6413         D.setInvalidType();
6414       }
6415     }
6416 
6417     if (R->isSamplerT()) {
6418       // OpenCL v1.2 s6.9.b p4:
6419       // The sampler type cannot be used with the __local and __global address
6420       // space qualifiers.
6421       if (R.getAddressSpace() == LangAS::opencl_local ||
6422           R.getAddressSpace() == LangAS::opencl_global) {
6423         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6424       }
6425 
6426       // OpenCL v1.2 s6.12.14.1:
6427       // A global sampler must be declared with either the constant address
6428       // space qualifier or with the const qualifier.
6429       if (DC->isTranslationUnit() &&
6430           !(R.getAddressSpace() == LangAS::opencl_constant ||
6431           R.isConstQualified())) {
6432         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6433         D.setInvalidType();
6434       }
6435     }
6436 
6437     // OpenCL v1.2 s6.9.r:
6438     // The event type cannot be used with the __local, __constant and __global
6439     // address space qualifiers.
6440     if (R->isEventT()) {
6441       if (R.getAddressSpace() != LangAS::opencl_private) {
6442         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6443         D.setInvalidType();
6444       }
6445     }
6446 
6447     // C++ for OpenCL does not allow the thread_local storage qualifier.
6448     // OpenCL C does not support thread_local either, and
6449     // also reject all other thread storage class specifiers.
6450     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6451     if (TSC != TSCS_unspecified) {
6452       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6453       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6454            diag::err_opencl_unknown_type_specifier)
6455           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6456           << DeclSpec::getSpecifierName(TSC) << 1;
6457       D.setInvalidType();
6458       return nullptr;
6459     }
6460   }
6461 
6462   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6463   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6464 
6465   // dllimport globals without explicit storage class are treated as extern. We
6466   // have to change the storage class this early to get the right DeclContext.
6467   if (SC == SC_None && !DC->isRecord() &&
6468       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6469       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6470     SC = SC_Extern;
6471 
6472   DeclContext *OriginalDC = DC;
6473   bool IsLocalExternDecl = SC == SC_Extern &&
6474                            adjustContextForLocalExternDecl(DC);
6475 
6476   if (SCSpec == DeclSpec::SCS_mutable) {
6477     // mutable can only appear on non-static class members, so it's always
6478     // an error here
6479     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6480     D.setInvalidType();
6481     SC = SC_None;
6482   }
6483 
6484   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6485       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6486                               D.getDeclSpec().getStorageClassSpecLoc())) {
6487     // In C++11, the 'register' storage class specifier is deprecated.
6488     // Suppress the warning in system macros, it's used in macros in some
6489     // popular C system headers, such as in glibc's htonl() macro.
6490     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6491          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6492                                    : diag::warn_deprecated_register)
6493       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6494   }
6495 
6496   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6497 
6498   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6499     // C99 6.9p2: The storage-class specifiers auto and register shall not
6500     // appear in the declaration specifiers in an external declaration.
6501     // Global Register+Asm is a GNU extension we support.
6502     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6503       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6504       D.setInvalidType();
6505     }
6506   }
6507 
6508   bool IsMemberSpecialization = false;
6509   bool IsVariableTemplateSpecialization = false;
6510   bool IsPartialSpecialization = false;
6511   bool IsVariableTemplate = false;
6512   VarDecl *NewVD = nullptr;
6513   VarTemplateDecl *NewTemplate = nullptr;
6514   TemplateParameterList *TemplateParams = nullptr;
6515   if (!getLangOpts().CPlusPlus) {
6516     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6517                             II, R, TInfo, SC);
6518 
6519     if (R->getContainedDeducedType())
6520       ParsingInitForAutoVars.insert(NewVD);
6521 
6522     if (D.isInvalidType())
6523       NewVD->setInvalidDecl();
6524   } else {
6525     bool Invalid = false;
6526 
6527     if (DC->isRecord() && !CurContext->isRecord()) {
6528       // This is an out-of-line definition of a static data member.
6529       switch (SC) {
6530       case SC_None:
6531         break;
6532       case SC_Static:
6533         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6534              diag::err_static_out_of_line)
6535           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6536         break;
6537       case SC_Auto:
6538       case SC_Register:
6539       case SC_Extern:
6540         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6541         // to names of variables declared in a block or to function parameters.
6542         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6543         // of class members
6544 
6545         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6546              diag::err_storage_class_for_static_member)
6547           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6548         break;
6549       case SC_PrivateExtern:
6550         llvm_unreachable("C storage class in c++!");
6551       }
6552     }
6553 
6554     if (SC == SC_Static && CurContext->isRecord()) {
6555       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6556         if (RD->isLocalClass())
6557           Diag(D.getIdentifierLoc(),
6558                diag::err_static_data_member_not_allowed_in_local_class)
6559             << Name << RD->getDeclName();
6560 
6561         // C++98 [class.union]p1: If a union contains a static data member,
6562         // the program is ill-formed. C++11 drops this restriction.
6563         if (RD->isUnion())
6564           Diag(D.getIdentifierLoc(),
6565                getLangOpts().CPlusPlus11
6566                  ? diag::warn_cxx98_compat_static_data_member_in_union
6567                  : diag::ext_static_data_member_in_union) << Name;
6568         // We conservatively disallow static data members in anonymous structs.
6569         else if (!RD->getDeclName())
6570           Diag(D.getIdentifierLoc(),
6571                diag::err_static_data_member_not_allowed_in_anon_struct)
6572             << Name << RD->isUnion();
6573       }
6574     }
6575 
6576     // Match up the template parameter lists with the scope specifier, then
6577     // determine whether we have a template or a template specialization.
6578     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6579         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6580         D.getCXXScopeSpec(),
6581         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6582             ? D.getName().TemplateId
6583             : nullptr,
6584         TemplateParamLists,
6585         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6586 
6587     if (TemplateParams) {
6588       if (!TemplateParams->size() &&
6589           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6590         // There is an extraneous 'template<>' for this variable. Complain
6591         // about it, but allow the declaration of the variable.
6592         Diag(TemplateParams->getTemplateLoc(),
6593              diag::err_template_variable_noparams)
6594           << II
6595           << SourceRange(TemplateParams->getTemplateLoc(),
6596                          TemplateParams->getRAngleLoc());
6597         TemplateParams = nullptr;
6598       } else {
6599         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6600           // This is an explicit specialization or a partial specialization.
6601           // FIXME: Check that we can declare a specialization here.
6602           IsVariableTemplateSpecialization = true;
6603           IsPartialSpecialization = TemplateParams->size() > 0;
6604         } else { // if (TemplateParams->size() > 0)
6605           // This is a template declaration.
6606           IsVariableTemplate = true;
6607 
6608           // Check that we can declare a template here.
6609           if (CheckTemplateDeclScope(S, TemplateParams))
6610             return nullptr;
6611 
6612           // Only C++1y supports variable templates (N3651).
6613           Diag(D.getIdentifierLoc(),
6614                getLangOpts().CPlusPlus14
6615                    ? diag::warn_cxx11_compat_variable_template
6616                    : diag::ext_variable_template);
6617         }
6618       }
6619     } else {
6620       assert((Invalid ||
6621               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6622              "should have a 'template<>' for this decl");
6623     }
6624 
6625     if (IsVariableTemplateSpecialization) {
6626       SourceLocation TemplateKWLoc =
6627           TemplateParamLists.size() > 0
6628               ? TemplateParamLists[0]->getTemplateLoc()
6629               : SourceLocation();
6630       DeclResult Res = ActOnVarTemplateSpecialization(
6631           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6632           IsPartialSpecialization);
6633       if (Res.isInvalid())
6634         return nullptr;
6635       NewVD = cast<VarDecl>(Res.get());
6636       AddToScope = false;
6637     } else if (D.isDecompositionDeclarator()) {
6638       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6639                                         D.getIdentifierLoc(), R, TInfo, SC,
6640                                         Bindings);
6641     } else
6642       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6643                               D.getIdentifierLoc(), II, R, TInfo, SC);
6644 
6645     // If this is supposed to be a variable template, create it as such.
6646     if (IsVariableTemplate) {
6647       NewTemplate =
6648           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6649                                   TemplateParams, NewVD);
6650       NewVD->setDescribedVarTemplate(NewTemplate);
6651     }
6652 
6653     // If this decl has an auto type in need of deduction, make a note of the
6654     // Decl so we can diagnose uses of it in its own initializer.
6655     if (R->getContainedDeducedType())
6656       ParsingInitForAutoVars.insert(NewVD);
6657 
6658     if (D.isInvalidType() || Invalid) {
6659       NewVD->setInvalidDecl();
6660       if (NewTemplate)
6661         NewTemplate->setInvalidDecl();
6662     }
6663 
6664     SetNestedNameSpecifier(*this, NewVD, D);
6665 
6666     // If we have any template parameter lists that don't directly belong to
6667     // the variable (matching the scope specifier), store them.
6668     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6669     if (TemplateParamLists.size() > VDTemplateParamLists)
6670       NewVD->setTemplateParameterListsInfo(
6671           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6672 
6673     if (D.getDeclSpec().hasConstexprSpecifier()) {
6674       NewVD->setConstexpr(true);
6675       // C++1z [dcl.spec.constexpr]p1:
6676       //   A static data member declared with the constexpr specifier is
6677       //   implicitly an inline variable.
6678       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6679         NewVD->setImplicitlyInline();
6680       if (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval)
6681         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6682              diag::err_constexpr_wrong_decl_kind)
6683             << /*consteval*/ 1;
6684     }
6685   }
6686 
6687   if (D.getDeclSpec().isInlineSpecified()) {
6688     if (!getLangOpts().CPlusPlus) {
6689       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6690           << 0;
6691     } else if (CurContext->isFunctionOrMethod()) {
6692       // 'inline' is not allowed on block scope variable declaration.
6693       Diag(D.getDeclSpec().getInlineSpecLoc(),
6694            diag::err_inline_declaration_block_scope) << Name
6695         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6696     } else {
6697       Diag(D.getDeclSpec().getInlineSpecLoc(),
6698            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6699                                      : diag::ext_inline_variable);
6700       NewVD->setInlineSpecified();
6701     }
6702   }
6703 
6704   // Set the lexical context. If the declarator has a C++ scope specifier, the
6705   // lexical context will be different from the semantic context.
6706   NewVD->setLexicalDeclContext(CurContext);
6707   if (NewTemplate)
6708     NewTemplate->setLexicalDeclContext(CurContext);
6709 
6710   if (IsLocalExternDecl) {
6711     if (D.isDecompositionDeclarator())
6712       for (auto *B : Bindings)
6713         B->setLocalExternDecl();
6714     else
6715       NewVD->setLocalExternDecl();
6716   }
6717 
6718   bool EmitTLSUnsupportedError = false;
6719   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6720     // C++11 [dcl.stc]p4:
6721     //   When thread_local is applied to a variable of block scope the
6722     //   storage-class-specifier static is implied if it does not appear
6723     //   explicitly.
6724     // Core issue: 'static' is not implied if the variable is declared
6725     //   'extern'.
6726     if (NewVD->hasLocalStorage() &&
6727         (SCSpec != DeclSpec::SCS_unspecified ||
6728          TSCS != DeclSpec::TSCS_thread_local ||
6729          !DC->isFunctionOrMethod()))
6730       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6731            diag::err_thread_non_global)
6732         << DeclSpec::getSpecifierName(TSCS);
6733     else if (!Context.getTargetInfo().isTLSSupported()) {
6734       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6735         // Postpone error emission until we've collected attributes required to
6736         // figure out whether it's a host or device variable and whether the
6737         // error should be ignored.
6738         EmitTLSUnsupportedError = true;
6739         // We still need to mark the variable as TLS so it shows up in AST with
6740         // proper storage class for other tools to use even if we're not going
6741         // to emit any code for it.
6742         NewVD->setTSCSpec(TSCS);
6743       } else
6744         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6745              diag::err_thread_unsupported);
6746     } else
6747       NewVD->setTSCSpec(TSCS);
6748   }
6749 
6750   // C99 6.7.4p3
6751   //   An inline definition of a function with external linkage shall
6752   //   not contain a definition of a modifiable object with static or
6753   //   thread storage duration...
6754   // We only apply this when the function is required to be defined
6755   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6756   // that a local variable with thread storage duration still has to
6757   // be marked 'static'.  Also note that it's possible to get these
6758   // semantics in C++ using __attribute__((gnu_inline)).
6759   if (SC == SC_Static && S->getFnParent() != nullptr &&
6760       !NewVD->getType().isConstQualified()) {
6761     FunctionDecl *CurFD = getCurFunctionDecl();
6762     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6763       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6764            diag::warn_static_local_in_extern_inline);
6765       MaybeSuggestAddingStaticToDecl(CurFD);
6766     }
6767   }
6768 
6769   if (D.getDeclSpec().isModulePrivateSpecified()) {
6770     if (IsVariableTemplateSpecialization)
6771       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6772           << (IsPartialSpecialization ? 1 : 0)
6773           << FixItHint::CreateRemoval(
6774                  D.getDeclSpec().getModulePrivateSpecLoc());
6775     else if (IsMemberSpecialization)
6776       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6777         << 2
6778         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6779     else if (NewVD->hasLocalStorage())
6780       Diag(NewVD->getLocation(), diag::err_module_private_local)
6781         << 0 << NewVD->getDeclName()
6782         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6783         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6784     else {
6785       NewVD->setModulePrivate();
6786       if (NewTemplate)
6787         NewTemplate->setModulePrivate();
6788       for (auto *B : Bindings)
6789         B->setModulePrivate();
6790     }
6791   }
6792 
6793   // Handle attributes prior to checking for duplicates in MergeVarDecl
6794   ProcessDeclAttributes(S, NewVD, D);
6795 
6796   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6797     if (EmitTLSUnsupportedError &&
6798         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6799          (getLangOpts().OpenMPIsDevice &&
6800           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6801       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6802            diag::err_thread_unsupported);
6803     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6804     // storage [duration]."
6805     if (SC == SC_None && S->getFnParent() != nullptr &&
6806         (NewVD->hasAttr<CUDASharedAttr>() ||
6807          NewVD->hasAttr<CUDAConstantAttr>())) {
6808       NewVD->setStorageClass(SC_Static);
6809     }
6810   }
6811 
6812   // Ensure that dllimport globals without explicit storage class are treated as
6813   // extern. The storage class is set above using parsed attributes. Now we can
6814   // check the VarDecl itself.
6815   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6816          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6817          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6818 
6819   // In auto-retain/release, infer strong retension for variables of
6820   // retainable type.
6821   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6822     NewVD->setInvalidDecl();
6823 
6824   // Handle GNU asm-label extension (encoded as an attribute).
6825   if (Expr *E = (Expr*)D.getAsmLabel()) {
6826     // The parser guarantees this is a string.
6827     StringLiteral *SE = cast<StringLiteral>(E);
6828     StringRef Label = SE->getString();
6829     if (S->getFnParent() != nullptr) {
6830       switch (SC) {
6831       case SC_None:
6832       case SC_Auto:
6833         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6834         break;
6835       case SC_Register:
6836         // Local Named register
6837         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6838             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6839           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6840         break;
6841       case SC_Static:
6842       case SC_Extern:
6843       case SC_PrivateExtern:
6844         break;
6845       }
6846     } else if (SC == SC_Register) {
6847       // Global Named register
6848       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6849         const auto &TI = Context.getTargetInfo();
6850         bool HasSizeMismatch;
6851 
6852         if (!TI.isValidGCCRegisterName(Label))
6853           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6854         else if (!TI.validateGlobalRegisterVariable(Label,
6855                                                     Context.getTypeSize(R),
6856                                                     HasSizeMismatch))
6857           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6858         else if (HasSizeMismatch)
6859           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6860       }
6861 
6862       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6863         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6864         NewVD->setInvalidDecl(true);
6865       }
6866     }
6867 
6868     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6869                                                 Context, Label, 0));
6870   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6871     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6872       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6873     if (I != ExtnameUndeclaredIdentifiers.end()) {
6874       if (isDeclExternC(NewVD)) {
6875         NewVD->addAttr(I->second);
6876         ExtnameUndeclaredIdentifiers.erase(I);
6877       } else
6878         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6879             << /*Variable*/1 << NewVD;
6880     }
6881   }
6882 
6883   // Find the shadowed declaration before filtering for scope.
6884   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6885                                 ? getShadowedDeclaration(NewVD, Previous)
6886                                 : nullptr;
6887 
6888   // Don't consider existing declarations that are in a different
6889   // scope and are out-of-semantic-context declarations (if the new
6890   // declaration has linkage).
6891   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6892                        D.getCXXScopeSpec().isNotEmpty() ||
6893                        IsMemberSpecialization ||
6894                        IsVariableTemplateSpecialization);
6895 
6896   // Check whether the previous declaration is in the same block scope. This
6897   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6898   if (getLangOpts().CPlusPlus &&
6899       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6900     NewVD->setPreviousDeclInSameBlockScope(
6901         Previous.isSingleResult() && !Previous.isShadowed() &&
6902         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6903 
6904   if (!getLangOpts().CPlusPlus) {
6905     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6906   } else {
6907     // If this is an explicit specialization of a static data member, check it.
6908     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6909         CheckMemberSpecialization(NewVD, Previous))
6910       NewVD->setInvalidDecl();
6911 
6912     // Merge the decl with the existing one if appropriate.
6913     if (!Previous.empty()) {
6914       if (Previous.isSingleResult() &&
6915           isa<FieldDecl>(Previous.getFoundDecl()) &&
6916           D.getCXXScopeSpec().isSet()) {
6917         // The user tried to define a non-static data member
6918         // out-of-line (C++ [dcl.meaning]p1).
6919         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6920           << D.getCXXScopeSpec().getRange();
6921         Previous.clear();
6922         NewVD->setInvalidDecl();
6923       }
6924     } else if (D.getCXXScopeSpec().isSet()) {
6925       // No previous declaration in the qualifying scope.
6926       Diag(D.getIdentifierLoc(), diag::err_no_member)
6927         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6928         << D.getCXXScopeSpec().getRange();
6929       NewVD->setInvalidDecl();
6930     }
6931 
6932     if (!IsVariableTemplateSpecialization)
6933       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6934 
6935     if (NewTemplate) {
6936       VarTemplateDecl *PrevVarTemplate =
6937           NewVD->getPreviousDecl()
6938               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6939               : nullptr;
6940 
6941       // Check the template parameter list of this declaration, possibly
6942       // merging in the template parameter list from the previous variable
6943       // template declaration.
6944       if (CheckTemplateParameterList(
6945               TemplateParams,
6946               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6947                               : nullptr,
6948               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6949                DC->isDependentContext())
6950                   ? TPC_ClassTemplateMember
6951                   : TPC_VarTemplate))
6952         NewVD->setInvalidDecl();
6953 
6954       // If we are providing an explicit specialization of a static variable
6955       // template, make a note of that.
6956       if (PrevVarTemplate &&
6957           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6958         PrevVarTemplate->setMemberSpecialization();
6959     }
6960   }
6961 
6962   // Diagnose shadowed variables iff this isn't a redeclaration.
6963   if (ShadowedDecl && !D.isRedeclaration())
6964     CheckShadow(NewVD, ShadowedDecl, Previous);
6965 
6966   ProcessPragmaWeak(S, NewVD);
6967 
6968   // If this is the first declaration of an extern C variable, update
6969   // the map of such variables.
6970   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6971       isIncompleteDeclExternC(*this, NewVD))
6972     RegisterLocallyScopedExternCDecl(NewVD, S);
6973 
6974   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6975     Decl *ManglingContextDecl;
6976     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6977             NewVD->getDeclContext(), ManglingContextDecl)) {
6978       Context.setManglingNumber(
6979           NewVD, MCtx->getManglingNumber(
6980                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6981       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6982     }
6983   }
6984 
6985   // Special handling of variable named 'main'.
6986   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6987       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6988       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6989 
6990     // C++ [basic.start.main]p3
6991     // A program that declares a variable main at global scope is ill-formed.
6992     if (getLangOpts().CPlusPlus)
6993       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6994 
6995     // In C, and external-linkage variable named main results in undefined
6996     // behavior.
6997     else if (NewVD->hasExternalFormalLinkage())
6998       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6999   }
7000 
7001   if (D.isRedeclaration() && !Previous.empty()) {
7002     NamedDecl *Prev = Previous.getRepresentativeDecl();
7003     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7004                                    D.isFunctionDefinition());
7005   }
7006 
7007   if (NewTemplate) {
7008     if (NewVD->isInvalidDecl())
7009       NewTemplate->setInvalidDecl();
7010     ActOnDocumentableDecl(NewTemplate);
7011     return NewTemplate;
7012   }
7013 
7014   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7015     CompleteMemberSpecialization(NewVD, Previous);
7016 
7017   return NewVD;
7018 }
7019 
7020 /// Enum describing the %select options in diag::warn_decl_shadow.
7021 enum ShadowedDeclKind {
7022   SDK_Local,
7023   SDK_Global,
7024   SDK_StaticMember,
7025   SDK_Field,
7026   SDK_Typedef,
7027   SDK_Using
7028 };
7029 
7030 /// Determine what kind of declaration we're shadowing.
7031 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7032                                                 const DeclContext *OldDC) {
7033   if (isa<TypeAliasDecl>(ShadowedDecl))
7034     return SDK_Using;
7035   else if (isa<TypedefDecl>(ShadowedDecl))
7036     return SDK_Typedef;
7037   else if (isa<RecordDecl>(OldDC))
7038     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7039 
7040   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7041 }
7042 
7043 /// Return the location of the capture if the given lambda captures the given
7044 /// variable \p VD, or an invalid source location otherwise.
7045 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7046                                          const VarDecl *VD) {
7047   for (const Capture &Capture : LSI->Captures) {
7048     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7049       return Capture.getLocation();
7050   }
7051   return SourceLocation();
7052 }
7053 
7054 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7055                                      const LookupResult &R) {
7056   // Only diagnose if we're shadowing an unambiguous field or variable.
7057   if (R.getResultKind() != LookupResult::Found)
7058     return false;
7059 
7060   // Return false if warning is ignored.
7061   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7062 }
7063 
7064 /// Return the declaration shadowed by the given variable \p D, or null
7065 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7066 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7067                                         const LookupResult &R) {
7068   if (!shouldWarnIfShadowedDecl(Diags, R))
7069     return nullptr;
7070 
7071   // Don't diagnose declarations at file scope.
7072   if (D->hasGlobalStorage())
7073     return nullptr;
7074 
7075   NamedDecl *ShadowedDecl = R.getFoundDecl();
7076   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7077              ? ShadowedDecl
7078              : nullptr;
7079 }
7080 
7081 /// Return the declaration shadowed by the given typedef \p D, or null
7082 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7083 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7084                                         const LookupResult &R) {
7085   // Don't warn if typedef declaration is part of a class
7086   if (D->getDeclContext()->isRecord())
7087     return nullptr;
7088 
7089   if (!shouldWarnIfShadowedDecl(Diags, R))
7090     return nullptr;
7091 
7092   NamedDecl *ShadowedDecl = R.getFoundDecl();
7093   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7094 }
7095 
7096 /// Diagnose variable or built-in function shadowing.  Implements
7097 /// -Wshadow.
7098 ///
7099 /// This method is called whenever a VarDecl is added to a "useful"
7100 /// scope.
7101 ///
7102 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7103 /// \param R the lookup of the name
7104 ///
7105 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7106                        const LookupResult &R) {
7107   DeclContext *NewDC = D->getDeclContext();
7108 
7109   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7110     // Fields are not shadowed by variables in C++ static methods.
7111     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7112       if (MD->isStatic())
7113         return;
7114 
7115     // Fields shadowed by constructor parameters are a special case. Usually
7116     // the constructor initializes the field with the parameter.
7117     if (isa<CXXConstructorDecl>(NewDC))
7118       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7119         // Remember that this was shadowed so we can either warn about its
7120         // modification or its existence depending on warning settings.
7121         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7122         return;
7123       }
7124   }
7125 
7126   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7127     if (shadowedVar->isExternC()) {
7128       // For shadowing external vars, make sure that we point to the global
7129       // declaration, not a locally scoped extern declaration.
7130       for (auto I : shadowedVar->redecls())
7131         if (I->isFileVarDecl()) {
7132           ShadowedDecl = I;
7133           break;
7134         }
7135     }
7136 
7137   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7138 
7139   unsigned WarningDiag = diag::warn_decl_shadow;
7140   SourceLocation CaptureLoc;
7141   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7142       isa<CXXMethodDecl>(NewDC)) {
7143     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7144       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7145         if (RD->getLambdaCaptureDefault() == LCD_None) {
7146           // Try to avoid warnings for lambdas with an explicit capture list.
7147           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7148           // Warn only when the lambda captures the shadowed decl explicitly.
7149           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7150           if (CaptureLoc.isInvalid())
7151             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7152         } else {
7153           // Remember that this was shadowed so we can avoid the warning if the
7154           // shadowed decl isn't captured and the warning settings allow it.
7155           cast<LambdaScopeInfo>(getCurFunction())
7156               ->ShadowingDecls.push_back(
7157                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7158           return;
7159         }
7160       }
7161 
7162       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7163         // A variable can't shadow a local variable in an enclosing scope, if
7164         // they are separated by a non-capturing declaration context.
7165         for (DeclContext *ParentDC = NewDC;
7166              ParentDC && !ParentDC->Equals(OldDC);
7167              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7168           // Only block literals, captured statements, and lambda expressions
7169           // can capture; other scopes don't.
7170           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7171               !isLambdaCallOperator(ParentDC)) {
7172             return;
7173           }
7174         }
7175       }
7176     }
7177   }
7178 
7179   // Only warn about certain kinds of shadowing for class members.
7180   if (NewDC && NewDC->isRecord()) {
7181     // In particular, don't warn about shadowing non-class members.
7182     if (!OldDC->isRecord())
7183       return;
7184 
7185     // TODO: should we warn about static data members shadowing
7186     // static data members from base classes?
7187 
7188     // TODO: don't diagnose for inaccessible shadowed members.
7189     // This is hard to do perfectly because we might friend the
7190     // shadowing context, but that's just a false negative.
7191   }
7192 
7193 
7194   DeclarationName Name = R.getLookupName();
7195 
7196   // Emit warning and note.
7197   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7198     return;
7199   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7200   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7201   if (!CaptureLoc.isInvalid())
7202     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7203         << Name << /*explicitly*/ 1;
7204   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7205 }
7206 
7207 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7208 /// when these variables are captured by the lambda.
7209 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7210   for (const auto &Shadow : LSI->ShadowingDecls) {
7211     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7212     // Try to avoid the warning when the shadowed decl isn't captured.
7213     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7214     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7215     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7216                                        ? diag::warn_decl_shadow_uncaptured_local
7217                                        : diag::warn_decl_shadow)
7218         << Shadow.VD->getDeclName()
7219         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7220     if (!CaptureLoc.isInvalid())
7221       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7222           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7223     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7224   }
7225 }
7226 
7227 /// Check -Wshadow without the advantage of a previous lookup.
7228 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7229   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7230     return;
7231 
7232   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7233                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7234   LookupName(R, S);
7235   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7236     CheckShadow(D, ShadowedDecl, R);
7237 }
7238 
7239 /// Check if 'E', which is an expression that is about to be modified, refers
7240 /// to a constructor parameter that shadows a field.
7241 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7242   // Quickly ignore expressions that can't be shadowing ctor parameters.
7243   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7244     return;
7245   E = E->IgnoreParenImpCasts();
7246   auto *DRE = dyn_cast<DeclRefExpr>(E);
7247   if (!DRE)
7248     return;
7249   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7250   auto I = ShadowingDecls.find(D);
7251   if (I == ShadowingDecls.end())
7252     return;
7253   const NamedDecl *ShadowedDecl = I->second;
7254   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7255   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7256   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7257   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7258 
7259   // Avoid issuing multiple warnings about the same decl.
7260   ShadowingDecls.erase(I);
7261 }
7262 
7263 /// Check for conflict between this global or extern "C" declaration and
7264 /// previous global or extern "C" declarations. This is only used in C++.
7265 template<typename T>
7266 static bool checkGlobalOrExternCConflict(
7267     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7268   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7269   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7270 
7271   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7272     // The common case: this global doesn't conflict with any extern "C"
7273     // declaration.
7274     return false;
7275   }
7276 
7277   if (Prev) {
7278     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7279       // Both the old and new declarations have C language linkage. This is a
7280       // redeclaration.
7281       Previous.clear();
7282       Previous.addDecl(Prev);
7283       return true;
7284     }
7285 
7286     // This is a global, non-extern "C" declaration, and there is a previous
7287     // non-global extern "C" declaration. Diagnose if this is a variable
7288     // declaration.
7289     if (!isa<VarDecl>(ND))
7290       return false;
7291   } else {
7292     // The declaration is extern "C". Check for any declaration in the
7293     // translation unit which might conflict.
7294     if (IsGlobal) {
7295       // We have already performed the lookup into the translation unit.
7296       IsGlobal = false;
7297       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7298            I != E; ++I) {
7299         if (isa<VarDecl>(*I)) {
7300           Prev = *I;
7301           break;
7302         }
7303       }
7304     } else {
7305       DeclContext::lookup_result R =
7306           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7307       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7308            I != E; ++I) {
7309         if (isa<VarDecl>(*I)) {
7310           Prev = *I;
7311           break;
7312         }
7313         // FIXME: If we have any other entity with this name in global scope,
7314         // the declaration is ill-formed, but that is a defect: it breaks the
7315         // 'stat' hack, for instance. Only variables can have mangled name
7316         // clashes with extern "C" declarations, so only they deserve a
7317         // diagnostic.
7318       }
7319     }
7320 
7321     if (!Prev)
7322       return false;
7323   }
7324 
7325   // Use the first declaration's location to ensure we point at something which
7326   // is lexically inside an extern "C" linkage-spec.
7327   assert(Prev && "should have found a previous declaration to diagnose");
7328   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7329     Prev = FD->getFirstDecl();
7330   else
7331     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7332 
7333   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7334     << IsGlobal << ND;
7335   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7336     << IsGlobal;
7337   return false;
7338 }
7339 
7340 /// Apply special rules for handling extern "C" declarations. Returns \c true
7341 /// if we have found that this is a redeclaration of some prior entity.
7342 ///
7343 /// Per C++ [dcl.link]p6:
7344 ///   Two declarations [for a function or variable] with C language linkage
7345 ///   with the same name that appear in different scopes refer to the same
7346 ///   [entity]. An entity with C language linkage shall not be declared with
7347 ///   the same name as an entity in global scope.
7348 template<typename T>
7349 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7350                                                   LookupResult &Previous) {
7351   if (!S.getLangOpts().CPlusPlus) {
7352     // In C, when declaring a global variable, look for a corresponding 'extern'
7353     // variable declared in function scope. We don't need this in C++, because
7354     // we find local extern decls in the surrounding file-scope DeclContext.
7355     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7356       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7357         Previous.clear();
7358         Previous.addDecl(Prev);
7359         return true;
7360       }
7361     }
7362     return false;
7363   }
7364 
7365   // A declaration in the translation unit can conflict with an extern "C"
7366   // declaration.
7367   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7368     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7369 
7370   // An extern "C" declaration can conflict with a declaration in the
7371   // translation unit or can be a redeclaration of an extern "C" declaration
7372   // in another scope.
7373   if (isIncompleteDeclExternC(S,ND))
7374     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7375 
7376   // Neither global nor extern "C": nothing to do.
7377   return false;
7378 }
7379 
7380 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7381   // If the decl is already known invalid, don't check it.
7382   if (NewVD->isInvalidDecl())
7383     return;
7384 
7385   QualType T = NewVD->getType();
7386 
7387   // Defer checking an 'auto' type until its initializer is attached.
7388   if (T->isUndeducedType())
7389     return;
7390 
7391   if (NewVD->hasAttrs())
7392     CheckAlignasUnderalignment(NewVD);
7393 
7394   if (T->isObjCObjectType()) {
7395     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7396       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7397     T = Context.getObjCObjectPointerType(T);
7398     NewVD->setType(T);
7399   }
7400 
7401   // Emit an error if an address space was applied to decl with local storage.
7402   // This includes arrays of objects with address space qualifiers, but not
7403   // automatic variables that point to other address spaces.
7404   // ISO/IEC TR 18037 S5.1.2
7405   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7406       T.getAddressSpace() != LangAS::Default) {
7407     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7408     NewVD->setInvalidDecl();
7409     return;
7410   }
7411 
7412   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7413   // scope.
7414   if (getLangOpts().OpenCLVersion == 120 &&
7415       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7416       NewVD->isStaticLocal()) {
7417     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7418     NewVD->setInvalidDecl();
7419     return;
7420   }
7421 
7422   if (getLangOpts().OpenCL) {
7423     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7424     if (NewVD->hasAttr<BlocksAttr>()) {
7425       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7426       return;
7427     }
7428 
7429     if (T->isBlockPointerType()) {
7430       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7431       // can't use 'extern' storage class.
7432       if (!T.isConstQualified()) {
7433         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7434             << 0 /*const*/;
7435         NewVD->setInvalidDecl();
7436         return;
7437       }
7438       if (NewVD->hasExternalStorage()) {
7439         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7440         NewVD->setInvalidDecl();
7441         return;
7442       }
7443     }
7444     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7445     // __constant address space.
7446     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7447     // variables inside a function can also be declared in the global
7448     // address space.
7449     // C++ for OpenCL inherits rule from OpenCL C v2.0.
7450     // FIXME: Adding local AS in C++ for OpenCL might make sense.
7451     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7452         NewVD->hasExternalStorage()) {
7453       if (!T->isSamplerT() &&
7454           !(T.getAddressSpace() == LangAS::opencl_constant ||
7455             (T.getAddressSpace() == LangAS::opencl_global &&
7456              (getLangOpts().OpenCLVersion == 200 ||
7457               getLangOpts().OpenCLCPlusPlus)))) {
7458         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7459         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7460           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7461               << Scope << "global or constant";
7462         else
7463           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7464               << Scope << "constant";
7465         NewVD->setInvalidDecl();
7466         return;
7467       }
7468     } else {
7469       if (T.getAddressSpace() == LangAS::opencl_global) {
7470         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7471             << 1 /*is any function*/ << "global";
7472         NewVD->setInvalidDecl();
7473         return;
7474       }
7475       if (T.getAddressSpace() == LangAS::opencl_constant ||
7476           T.getAddressSpace() == LangAS::opencl_local) {
7477         FunctionDecl *FD = getCurFunctionDecl();
7478         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7479         // in functions.
7480         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7481           if (T.getAddressSpace() == LangAS::opencl_constant)
7482             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7483                 << 0 /*non-kernel only*/ << "constant";
7484           else
7485             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7486                 << 0 /*non-kernel only*/ << "local";
7487           NewVD->setInvalidDecl();
7488           return;
7489         }
7490         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7491         // in the outermost scope of a kernel function.
7492         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7493           if (!getCurScope()->isFunctionScope()) {
7494             if (T.getAddressSpace() == LangAS::opencl_constant)
7495               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7496                   << "constant";
7497             else
7498               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7499                   << "local";
7500             NewVD->setInvalidDecl();
7501             return;
7502           }
7503         }
7504       } else if (T.getAddressSpace() != LangAS::opencl_private &&
7505                  // If we are parsing a template we didn't deduce an addr
7506                  // space yet.
7507                  T.getAddressSpace() != LangAS::Default) {
7508         // Do not allow other address spaces on automatic variable.
7509         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7510         NewVD->setInvalidDecl();
7511         return;
7512       }
7513     }
7514   }
7515 
7516   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7517       && !NewVD->hasAttr<BlocksAttr>()) {
7518     if (getLangOpts().getGC() != LangOptions::NonGC)
7519       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7520     else {
7521       assert(!getLangOpts().ObjCAutoRefCount);
7522       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7523     }
7524   }
7525 
7526   bool isVM = T->isVariablyModifiedType();
7527   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7528       NewVD->hasAttr<BlocksAttr>())
7529     setFunctionHasBranchProtectedScope();
7530 
7531   if ((isVM && NewVD->hasLinkage()) ||
7532       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7533     bool SizeIsNegative;
7534     llvm::APSInt Oversized;
7535     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7536         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7537     QualType FixedT;
7538     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7539       FixedT = FixedTInfo->getType();
7540     else if (FixedTInfo) {
7541       // Type and type-as-written are canonically different. We need to fix up
7542       // both types separately.
7543       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7544                                                    Oversized);
7545     }
7546     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7547       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7548       // FIXME: This won't give the correct result for
7549       // int a[10][n];
7550       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7551 
7552       if (NewVD->isFileVarDecl())
7553         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7554         << SizeRange;
7555       else if (NewVD->isStaticLocal())
7556         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7557         << SizeRange;
7558       else
7559         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7560         << SizeRange;
7561       NewVD->setInvalidDecl();
7562       return;
7563     }
7564 
7565     if (!FixedTInfo) {
7566       if (NewVD->isFileVarDecl())
7567         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7568       else
7569         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7570       NewVD->setInvalidDecl();
7571       return;
7572     }
7573 
7574     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7575     NewVD->setType(FixedT);
7576     NewVD->setTypeSourceInfo(FixedTInfo);
7577   }
7578 
7579   if (T->isVoidType()) {
7580     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7581     //                    of objects and functions.
7582     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7583       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7584         << T;
7585       NewVD->setInvalidDecl();
7586       return;
7587     }
7588   }
7589 
7590   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7591     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7592     NewVD->setInvalidDecl();
7593     return;
7594   }
7595 
7596   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7597     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7598     NewVD->setInvalidDecl();
7599     return;
7600   }
7601 
7602   if (NewVD->isConstexpr() && !T->isDependentType() &&
7603       RequireLiteralType(NewVD->getLocation(), T,
7604                          diag::err_constexpr_var_non_literal)) {
7605     NewVD->setInvalidDecl();
7606     return;
7607   }
7608 }
7609 
7610 /// Perform semantic checking on a newly-created variable
7611 /// declaration.
7612 ///
7613 /// This routine performs all of the type-checking required for a
7614 /// variable declaration once it has been built. It is used both to
7615 /// check variables after they have been parsed and their declarators
7616 /// have been translated into a declaration, and to check variables
7617 /// that have been instantiated from a template.
7618 ///
7619 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7620 ///
7621 /// Returns true if the variable declaration is a redeclaration.
7622 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7623   CheckVariableDeclarationType(NewVD);
7624 
7625   // If the decl is already known invalid, don't check it.
7626   if (NewVD->isInvalidDecl())
7627     return false;
7628 
7629   // If we did not find anything by this name, look for a non-visible
7630   // extern "C" declaration with the same name.
7631   if (Previous.empty() &&
7632       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7633     Previous.setShadowed();
7634 
7635   if (!Previous.empty()) {
7636     MergeVarDecl(NewVD, Previous);
7637     return true;
7638   }
7639   return false;
7640 }
7641 
7642 namespace {
7643 struct FindOverriddenMethod {
7644   Sema *S;
7645   CXXMethodDecl *Method;
7646 
7647   /// Member lookup function that determines whether a given C++
7648   /// method overrides a method in a base class, to be used with
7649   /// CXXRecordDecl::lookupInBases().
7650   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7651     RecordDecl *BaseRecord =
7652         Specifier->getType()->getAs<RecordType>()->getDecl();
7653 
7654     DeclarationName Name = Method->getDeclName();
7655 
7656     // FIXME: Do we care about other names here too?
7657     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7658       // We really want to find the base class destructor here.
7659       QualType T = S->Context.getTypeDeclType(BaseRecord);
7660       CanQualType CT = S->Context.getCanonicalType(T);
7661 
7662       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7663     }
7664 
7665     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7666          Path.Decls = Path.Decls.slice(1)) {
7667       NamedDecl *D = Path.Decls.front();
7668       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7669         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7670           return true;
7671       }
7672     }
7673 
7674     return false;
7675   }
7676 };
7677 
7678 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7679 } // end anonymous namespace
7680 
7681 /// Report an error regarding overriding, along with any relevant
7682 /// overridden methods.
7683 ///
7684 /// \param DiagID the primary error to report.
7685 /// \param MD the overriding method.
7686 /// \param OEK which overrides to include as notes.
7687 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7688                             OverrideErrorKind OEK = OEK_All) {
7689   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7690   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7691     // This check (& the OEK parameter) could be replaced by a predicate, but
7692     // without lambdas that would be overkill. This is still nicer than writing
7693     // out the diag loop 3 times.
7694     if ((OEK == OEK_All) ||
7695         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7696         (OEK == OEK_Deleted && O->isDeleted()))
7697       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7698   }
7699 }
7700 
7701 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7702 /// and if so, check that it's a valid override and remember it.
7703 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7704   // Look for methods in base classes that this method might override.
7705   CXXBasePaths Paths;
7706   FindOverriddenMethod FOM;
7707   FOM.Method = MD;
7708   FOM.S = this;
7709   bool hasDeletedOverridenMethods = false;
7710   bool hasNonDeletedOverridenMethods = false;
7711   bool AddedAny = false;
7712   if (DC->lookupInBases(FOM, Paths)) {
7713     for (auto *I : Paths.found_decls()) {
7714       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7715         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7716         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7717             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7718             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7719             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7720           hasDeletedOverridenMethods |= OldMD->isDeleted();
7721           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7722           AddedAny = true;
7723         }
7724       }
7725     }
7726   }
7727 
7728   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7729     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7730   }
7731   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7732     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7733   }
7734 
7735   return AddedAny;
7736 }
7737 
7738 namespace {
7739   // Struct for holding all of the extra arguments needed by
7740   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7741   struct ActOnFDArgs {
7742     Scope *S;
7743     Declarator &D;
7744     MultiTemplateParamsArg TemplateParamLists;
7745     bool AddToScope;
7746   };
7747 } // end anonymous namespace
7748 
7749 namespace {
7750 
7751 // Callback to only accept typo corrections that have a non-zero edit distance.
7752 // Also only accept corrections that have the same parent decl.
7753 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7754  public:
7755   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7756                             CXXRecordDecl *Parent)
7757       : Context(Context), OriginalFD(TypoFD),
7758         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7759 
7760   bool ValidateCandidate(const TypoCorrection &candidate) override {
7761     if (candidate.getEditDistance() == 0)
7762       return false;
7763 
7764     SmallVector<unsigned, 1> MismatchedParams;
7765     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7766                                           CDeclEnd = candidate.end();
7767          CDecl != CDeclEnd; ++CDecl) {
7768       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7769 
7770       if (FD && !FD->hasBody() &&
7771           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7772         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7773           CXXRecordDecl *Parent = MD->getParent();
7774           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7775             return true;
7776         } else if (!ExpectedParent) {
7777           return true;
7778         }
7779       }
7780     }
7781 
7782     return false;
7783   }
7784 
7785   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7786     return llvm::make_unique<DifferentNameValidatorCCC>(*this);
7787   }
7788 
7789  private:
7790   ASTContext &Context;
7791   FunctionDecl *OriginalFD;
7792   CXXRecordDecl *ExpectedParent;
7793 };
7794 
7795 } // end anonymous namespace
7796 
7797 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7798   TypoCorrectedFunctionDefinitions.insert(F);
7799 }
7800 
7801 /// Generate diagnostics for an invalid function redeclaration.
7802 ///
7803 /// This routine handles generating the diagnostic messages for an invalid
7804 /// function redeclaration, including finding possible similar declarations
7805 /// or performing typo correction if there are no previous declarations with
7806 /// the same name.
7807 ///
7808 /// Returns a NamedDecl iff typo correction was performed and substituting in
7809 /// the new declaration name does not cause new errors.
7810 static NamedDecl *DiagnoseInvalidRedeclaration(
7811     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7812     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7813   DeclarationName Name = NewFD->getDeclName();
7814   DeclContext *NewDC = NewFD->getDeclContext();
7815   SmallVector<unsigned, 1> MismatchedParams;
7816   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7817   TypoCorrection Correction;
7818   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7819   unsigned DiagMsg =
7820     IsLocalFriend ? diag::err_no_matching_local_friend :
7821     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7822     diag::err_member_decl_does_not_match;
7823   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7824                     IsLocalFriend ? Sema::LookupLocalFriendName
7825                                   : Sema::LookupOrdinaryName,
7826                     Sema::ForVisibleRedeclaration);
7827 
7828   NewFD->setInvalidDecl();
7829   if (IsLocalFriend)
7830     SemaRef.LookupName(Prev, S);
7831   else
7832     SemaRef.LookupQualifiedName(Prev, NewDC);
7833   assert(!Prev.isAmbiguous() &&
7834          "Cannot have an ambiguity in previous-declaration lookup");
7835   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7836   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7837                                 MD ? MD->getParent() : nullptr);
7838   if (!Prev.empty()) {
7839     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7840          Func != FuncEnd; ++Func) {
7841       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7842       if (FD &&
7843           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7844         // Add 1 to the index so that 0 can mean the mismatch didn't
7845         // involve a parameter
7846         unsigned ParamNum =
7847             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7848         NearMatches.push_back(std::make_pair(FD, ParamNum));
7849       }
7850     }
7851   // If the qualified name lookup yielded nothing, try typo correction
7852   } else if ((Correction = SemaRef.CorrectTypo(
7853                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7854                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7855                   IsLocalFriend ? nullptr : NewDC))) {
7856     // Set up everything for the call to ActOnFunctionDeclarator
7857     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7858                               ExtraArgs.D.getIdentifierLoc());
7859     Previous.clear();
7860     Previous.setLookupName(Correction.getCorrection());
7861     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7862                                     CDeclEnd = Correction.end();
7863          CDecl != CDeclEnd; ++CDecl) {
7864       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7865       if (FD && !FD->hasBody() &&
7866           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7867         Previous.addDecl(FD);
7868       }
7869     }
7870     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7871 
7872     NamedDecl *Result;
7873     // Retry building the function declaration with the new previous
7874     // declarations, and with errors suppressed.
7875     {
7876       // Trap errors.
7877       Sema::SFINAETrap Trap(SemaRef);
7878 
7879       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7880       // pieces need to verify the typo-corrected C++ declaration and hopefully
7881       // eliminate the need for the parameter pack ExtraArgs.
7882       Result = SemaRef.ActOnFunctionDeclarator(
7883           ExtraArgs.S, ExtraArgs.D,
7884           Correction.getCorrectionDecl()->getDeclContext(),
7885           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7886           ExtraArgs.AddToScope);
7887 
7888       if (Trap.hasErrorOccurred())
7889         Result = nullptr;
7890     }
7891 
7892     if (Result) {
7893       // Determine which correction we picked.
7894       Decl *Canonical = Result->getCanonicalDecl();
7895       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7896            I != E; ++I)
7897         if ((*I)->getCanonicalDecl() == Canonical)
7898           Correction.setCorrectionDecl(*I);
7899 
7900       // Let Sema know about the correction.
7901       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7902       SemaRef.diagnoseTypo(
7903           Correction,
7904           SemaRef.PDiag(IsLocalFriend
7905                           ? diag::err_no_matching_local_friend_suggest
7906                           : diag::err_member_decl_does_not_match_suggest)
7907             << Name << NewDC << IsDefinition);
7908       return Result;
7909     }
7910 
7911     // Pretend the typo correction never occurred
7912     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7913                               ExtraArgs.D.getIdentifierLoc());
7914     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7915     Previous.clear();
7916     Previous.setLookupName(Name);
7917   }
7918 
7919   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7920       << Name << NewDC << IsDefinition << NewFD->getLocation();
7921 
7922   bool NewFDisConst = false;
7923   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7924     NewFDisConst = NewMD->isConst();
7925 
7926   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7927        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7928        NearMatch != NearMatchEnd; ++NearMatch) {
7929     FunctionDecl *FD = NearMatch->first;
7930     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7931     bool FDisConst = MD && MD->isConst();
7932     bool IsMember = MD || !IsLocalFriend;
7933 
7934     // FIXME: These notes are poorly worded for the local friend case.
7935     if (unsigned Idx = NearMatch->second) {
7936       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7937       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7938       if (Loc.isInvalid()) Loc = FD->getLocation();
7939       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7940                                  : diag::note_local_decl_close_param_match)
7941         << Idx << FDParam->getType()
7942         << NewFD->getParamDecl(Idx - 1)->getType();
7943     } else if (FDisConst != NewFDisConst) {
7944       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7945           << NewFDisConst << FD->getSourceRange().getEnd();
7946     } else
7947       SemaRef.Diag(FD->getLocation(),
7948                    IsMember ? diag::note_member_def_close_match
7949                             : diag::note_local_decl_close_match);
7950   }
7951   return nullptr;
7952 }
7953 
7954 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7955   switch (D.getDeclSpec().getStorageClassSpec()) {
7956   default: llvm_unreachable("Unknown storage class!");
7957   case DeclSpec::SCS_auto:
7958   case DeclSpec::SCS_register:
7959   case DeclSpec::SCS_mutable:
7960     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7961                  diag::err_typecheck_sclass_func);
7962     D.getMutableDeclSpec().ClearStorageClassSpecs();
7963     D.setInvalidType();
7964     break;
7965   case DeclSpec::SCS_unspecified: break;
7966   case DeclSpec::SCS_extern:
7967     if (D.getDeclSpec().isExternInLinkageSpec())
7968       return SC_None;
7969     return SC_Extern;
7970   case DeclSpec::SCS_static: {
7971     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7972       // C99 6.7.1p5:
7973       //   The declaration of an identifier for a function that has
7974       //   block scope shall have no explicit storage-class specifier
7975       //   other than extern
7976       // See also (C++ [dcl.stc]p4).
7977       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7978                    diag::err_static_block_func);
7979       break;
7980     } else
7981       return SC_Static;
7982   }
7983   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7984   }
7985 
7986   // No explicit storage class has already been returned
7987   return SC_None;
7988 }
7989 
7990 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7991                                            DeclContext *DC, QualType &R,
7992                                            TypeSourceInfo *TInfo,
7993                                            StorageClass SC,
7994                                            bool &IsVirtualOkay) {
7995   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7996   DeclarationName Name = NameInfo.getName();
7997 
7998   FunctionDecl *NewFD = nullptr;
7999   bool isInline = D.getDeclSpec().isInlineSpecified();
8000 
8001   if (!SemaRef.getLangOpts().CPlusPlus) {
8002     // Determine whether the function was written with a
8003     // prototype. This true when:
8004     //   - there is a prototype in the declarator, or
8005     //   - the type R of the function is some kind of typedef or other non-
8006     //     attributed reference to a type name (which eventually refers to a
8007     //     function type).
8008     bool HasPrototype =
8009       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8010       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8011 
8012     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8013                                  R, TInfo, SC, isInline, HasPrototype,
8014                                  CSK_unspecified);
8015     if (D.isInvalidType())
8016       NewFD->setInvalidDecl();
8017 
8018     return NewFD;
8019   }
8020 
8021   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8022   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8023   // Check that the return type is not an abstract class type.
8024   // For record types, this is done by the AbstractClassUsageDiagnoser once
8025   // the class has been completely parsed.
8026   if (!DC->isRecord() &&
8027       SemaRef.RequireNonAbstractType(
8028           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
8029           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8030     D.setInvalidType();
8031 
8032   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8033     // This is a C++ constructor declaration.
8034     assert(DC->isRecord() &&
8035            "Constructors can only be declared in a member context");
8036 
8037     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8038     return CXXConstructorDecl::Create(
8039         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8040         TInfo, ExplicitSpecifier, isInline,
8041         /*isImplicitlyDeclared=*/false, ConstexprKind);
8042 
8043   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8044     // This is a C++ destructor declaration.
8045     if (DC->isRecord()) {
8046       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8047       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8048       CXXDestructorDecl *NewDD =
8049           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
8050                                     NameInfo, R, TInfo, isInline,
8051                                     /*isImplicitlyDeclared=*/false);
8052 
8053       // If the destructor needs an implicit exception specification, set it
8054       // now. FIXME: It'd be nice to be able to create the right type to start
8055       // with, but the type needs to reference the destructor declaration.
8056       if (SemaRef.getLangOpts().CPlusPlus11)
8057         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8058 
8059       IsVirtualOkay = true;
8060       return NewDD;
8061 
8062     } else {
8063       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8064       D.setInvalidType();
8065 
8066       // Create a FunctionDecl to satisfy the function definition parsing
8067       // code path.
8068       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8069                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8070                                   isInline,
8071                                   /*hasPrototype=*/true, ConstexprKind);
8072     }
8073 
8074   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8075     if (!DC->isRecord()) {
8076       SemaRef.Diag(D.getIdentifierLoc(),
8077            diag::err_conv_function_not_member);
8078       return nullptr;
8079     }
8080 
8081     SemaRef.CheckConversionDeclarator(D, R, SC);
8082     IsVirtualOkay = true;
8083     return CXXConversionDecl::Create(
8084         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8085         TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
8086 
8087   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8088     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8089 
8090     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8091                                          ExplicitSpecifier, NameInfo, R, TInfo,
8092                                          D.getEndLoc());
8093   } else if (DC->isRecord()) {
8094     // If the name of the function is the same as the name of the record,
8095     // then this must be an invalid constructor that has a return type.
8096     // (The parser checks for a return type and makes the declarator a
8097     // constructor if it has no return type).
8098     if (Name.getAsIdentifierInfo() &&
8099         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8100       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8101         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8102         << SourceRange(D.getIdentifierLoc());
8103       return nullptr;
8104     }
8105 
8106     // This is a C++ method declaration.
8107     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8108         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8109         TInfo, SC, isInline, ConstexprKind, SourceLocation());
8110     IsVirtualOkay = !Ret->isStatic();
8111     return Ret;
8112   } else {
8113     bool isFriend =
8114         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8115     if (!isFriend && SemaRef.CurContext->isRecord())
8116       return nullptr;
8117 
8118     // Determine whether the function was written with a
8119     // prototype. This true when:
8120     //   - we're in C++ (where every function has a prototype),
8121     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8122                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8123                                 ConstexprKind);
8124   }
8125 }
8126 
8127 enum OpenCLParamType {
8128   ValidKernelParam,
8129   PtrPtrKernelParam,
8130   PtrKernelParam,
8131   InvalidAddrSpacePtrKernelParam,
8132   InvalidKernelParam,
8133   RecordKernelParam
8134 };
8135 
8136 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8137   // Size dependent types are just typedefs to normal integer types
8138   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8139   // integers other than by their names.
8140   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8141 
8142   // Remove typedefs one by one until we reach a typedef
8143   // for a size dependent type.
8144   QualType DesugaredTy = Ty;
8145   do {
8146     ArrayRef<StringRef> Names(SizeTypeNames);
8147     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8148     if (Names.end() != Match)
8149       return true;
8150 
8151     Ty = DesugaredTy;
8152     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8153   } while (DesugaredTy != Ty);
8154 
8155   return false;
8156 }
8157 
8158 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8159   if (PT->isPointerType()) {
8160     QualType PointeeType = PT->getPointeeType();
8161     if (PointeeType->isPointerType())
8162       return PtrPtrKernelParam;
8163     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8164         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8165         PointeeType.getAddressSpace() == LangAS::Default)
8166       return InvalidAddrSpacePtrKernelParam;
8167     return PtrKernelParam;
8168   }
8169 
8170   // OpenCL v1.2 s6.9.k:
8171   // Arguments to kernel functions in a program cannot be declared with the
8172   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8173   // uintptr_t or a struct and/or union that contain fields declared to be one
8174   // of these built-in scalar types.
8175   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8176     return InvalidKernelParam;
8177 
8178   if (PT->isImageType())
8179     return PtrKernelParam;
8180 
8181   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8182     return InvalidKernelParam;
8183 
8184   // OpenCL extension spec v1.2 s9.5:
8185   // This extension adds support for half scalar and vector types as built-in
8186   // types that can be used for arithmetic operations, conversions etc.
8187   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8188     return InvalidKernelParam;
8189 
8190   if (PT->isRecordType())
8191     return RecordKernelParam;
8192 
8193   // Look into an array argument to check if it has a forbidden type.
8194   if (PT->isArrayType()) {
8195     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8196     // Call ourself to check an underlying type of an array. Since the
8197     // getPointeeOrArrayElementType returns an innermost type which is not an
8198     // array, this recursive call only happens once.
8199     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8200   }
8201 
8202   return ValidKernelParam;
8203 }
8204 
8205 static void checkIsValidOpenCLKernelParameter(
8206   Sema &S,
8207   Declarator &D,
8208   ParmVarDecl *Param,
8209   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8210   QualType PT = Param->getType();
8211 
8212   // Cache the valid types we encounter to avoid rechecking structs that are
8213   // used again
8214   if (ValidTypes.count(PT.getTypePtr()))
8215     return;
8216 
8217   switch (getOpenCLKernelParameterType(S, PT)) {
8218   case PtrPtrKernelParam:
8219     // OpenCL v1.2 s6.9.a:
8220     // A kernel function argument cannot be declared as a
8221     // pointer to a pointer type.
8222     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8223     D.setInvalidType();
8224     return;
8225 
8226   case InvalidAddrSpacePtrKernelParam:
8227     // OpenCL v1.0 s6.5:
8228     // __kernel function arguments declared to be a pointer of a type can point
8229     // to one of the following address spaces only : __global, __local or
8230     // __constant.
8231     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8232     D.setInvalidType();
8233     return;
8234 
8235     // OpenCL v1.2 s6.9.k:
8236     // Arguments to kernel functions in a program cannot be declared with the
8237     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8238     // uintptr_t or a struct and/or union that contain fields declared to be
8239     // one of these built-in scalar types.
8240 
8241   case InvalidKernelParam:
8242     // OpenCL v1.2 s6.8 n:
8243     // A kernel function argument cannot be declared
8244     // of event_t type.
8245     // Do not diagnose half type since it is diagnosed as invalid argument
8246     // type for any function elsewhere.
8247     if (!PT->isHalfType()) {
8248       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8249 
8250       // Explain what typedefs are involved.
8251       const TypedefType *Typedef = nullptr;
8252       while ((Typedef = PT->getAs<TypedefType>())) {
8253         SourceLocation Loc = Typedef->getDecl()->getLocation();
8254         // SourceLocation may be invalid for a built-in type.
8255         if (Loc.isValid())
8256           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8257         PT = Typedef->desugar();
8258       }
8259     }
8260 
8261     D.setInvalidType();
8262     return;
8263 
8264   case PtrKernelParam:
8265   case ValidKernelParam:
8266     ValidTypes.insert(PT.getTypePtr());
8267     return;
8268 
8269   case RecordKernelParam:
8270     break;
8271   }
8272 
8273   // Track nested structs we will inspect
8274   SmallVector<const Decl *, 4> VisitStack;
8275 
8276   // Track where we are in the nested structs. Items will migrate from
8277   // VisitStack to HistoryStack as we do the DFS for bad field.
8278   SmallVector<const FieldDecl *, 4> HistoryStack;
8279   HistoryStack.push_back(nullptr);
8280 
8281   // At this point we already handled everything except of a RecordType or
8282   // an ArrayType of a RecordType.
8283   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8284   const RecordType *RecTy =
8285       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8286   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8287 
8288   VisitStack.push_back(RecTy->getDecl());
8289   assert(VisitStack.back() && "First decl null?");
8290 
8291   do {
8292     const Decl *Next = VisitStack.pop_back_val();
8293     if (!Next) {
8294       assert(!HistoryStack.empty());
8295       // Found a marker, we have gone up a level
8296       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8297         ValidTypes.insert(Hist->getType().getTypePtr());
8298 
8299       continue;
8300     }
8301 
8302     // Adds everything except the original parameter declaration (which is not a
8303     // field itself) to the history stack.
8304     const RecordDecl *RD;
8305     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8306       HistoryStack.push_back(Field);
8307 
8308       QualType FieldTy = Field->getType();
8309       // Other field types (known to be valid or invalid) are handled while we
8310       // walk around RecordDecl::fields().
8311       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8312              "Unexpected type.");
8313       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8314 
8315       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8316     } else {
8317       RD = cast<RecordDecl>(Next);
8318     }
8319 
8320     // Add a null marker so we know when we've gone back up a level
8321     VisitStack.push_back(nullptr);
8322 
8323     for (const auto *FD : RD->fields()) {
8324       QualType QT = FD->getType();
8325 
8326       if (ValidTypes.count(QT.getTypePtr()))
8327         continue;
8328 
8329       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8330       if (ParamType == ValidKernelParam)
8331         continue;
8332 
8333       if (ParamType == RecordKernelParam) {
8334         VisitStack.push_back(FD);
8335         continue;
8336       }
8337 
8338       // OpenCL v1.2 s6.9.p:
8339       // Arguments to kernel functions that are declared to be a struct or union
8340       // do not allow OpenCL objects to be passed as elements of the struct or
8341       // union.
8342       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8343           ParamType == InvalidAddrSpacePtrKernelParam) {
8344         S.Diag(Param->getLocation(),
8345                diag::err_record_with_pointers_kernel_param)
8346           << PT->isUnionType()
8347           << PT;
8348       } else {
8349         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8350       }
8351 
8352       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8353           << OrigRecDecl->getDeclName();
8354 
8355       // We have an error, now let's go back up through history and show where
8356       // the offending field came from
8357       for (ArrayRef<const FieldDecl *>::const_iterator
8358                I = HistoryStack.begin() + 1,
8359                E = HistoryStack.end();
8360            I != E; ++I) {
8361         const FieldDecl *OuterField = *I;
8362         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8363           << OuterField->getType();
8364       }
8365 
8366       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8367         << QT->isPointerType()
8368         << QT;
8369       D.setInvalidType();
8370       return;
8371     }
8372   } while (!VisitStack.empty());
8373 }
8374 
8375 /// Find the DeclContext in which a tag is implicitly declared if we see an
8376 /// elaborated type specifier in the specified context, and lookup finds
8377 /// nothing.
8378 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8379   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8380     DC = DC->getParent();
8381   return DC;
8382 }
8383 
8384 /// Find the Scope in which a tag is implicitly declared if we see an
8385 /// elaborated type specifier in the specified context, and lookup finds
8386 /// nothing.
8387 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8388   while (S->isClassScope() ||
8389          (LangOpts.CPlusPlus &&
8390           S->isFunctionPrototypeScope()) ||
8391          ((S->getFlags() & Scope::DeclScope) == 0) ||
8392          (S->getEntity() && S->getEntity()->isTransparentContext()))
8393     S = S->getParent();
8394   return S;
8395 }
8396 
8397 NamedDecl*
8398 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8399                               TypeSourceInfo *TInfo, LookupResult &Previous,
8400                               MultiTemplateParamsArg TemplateParamLists,
8401                               bool &AddToScope) {
8402   QualType R = TInfo->getType();
8403 
8404   assert(R->isFunctionType());
8405 
8406   // TODO: consider using NameInfo for diagnostic.
8407   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8408   DeclarationName Name = NameInfo.getName();
8409   StorageClass SC = getFunctionStorageClass(*this, D);
8410 
8411   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8412     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8413          diag::err_invalid_thread)
8414       << DeclSpec::getSpecifierName(TSCS);
8415 
8416   if (D.isFirstDeclarationOfMember())
8417     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8418                            D.getIdentifierLoc());
8419 
8420   bool isFriend = false;
8421   FunctionTemplateDecl *FunctionTemplate = nullptr;
8422   bool isMemberSpecialization = false;
8423   bool isFunctionTemplateSpecialization = false;
8424 
8425   bool isDependentClassScopeExplicitSpecialization = false;
8426   bool HasExplicitTemplateArgs = false;
8427   TemplateArgumentListInfo TemplateArgs;
8428 
8429   bool isVirtualOkay = false;
8430 
8431   DeclContext *OriginalDC = DC;
8432   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8433 
8434   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8435                                               isVirtualOkay);
8436   if (!NewFD) return nullptr;
8437 
8438   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8439     NewFD->setTopLevelDeclInObjCContainer();
8440 
8441   // Set the lexical context. If this is a function-scope declaration, or has a
8442   // C++ scope specifier, or is the object of a friend declaration, the lexical
8443   // context will be different from the semantic context.
8444   NewFD->setLexicalDeclContext(CurContext);
8445 
8446   if (IsLocalExternDecl)
8447     NewFD->setLocalExternDecl();
8448 
8449   if (getLangOpts().CPlusPlus) {
8450     bool isInline = D.getDeclSpec().isInlineSpecified();
8451     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8452     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8453     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8454     isFriend = D.getDeclSpec().isFriendSpecified();
8455     if (isFriend && !isInline && D.isFunctionDefinition()) {
8456       // C++ [class.friend]p5
8457       //   A function can be defined in a friend declaration of a
8458       //   class . . . . Such a function is implicitly inline.
8459       NewFD->setImplicitlyInline();
8460     }
8461 
8462     // If this is a method defined in an __interface, and is not a constructor
8463     // or an overloaded operator, then set the pure flag (isVirtual will already
8464     // return true).
8465     if (const CXXRecordDecl *Parent =
8466           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8467       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8468         NewFD->setPure(true);
8469 
8470       // C++ [class.union]p2
8471       //   A union can have member functions, but not virtual functions.
8472       if (isVirtual && Parent->isUnion())
8473         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8474     }
8475 
8476     SetNestedNameSpecifier(*this, NewFD, D);
8477     isMemberSpecialization = false;
8478     isFunctionTemplateSpecialization = false;
8479     if (D.isInvalidType())
8480       NewFD->setInvalidDecl();
8481 
8482     // Match up the template parameter lists with the scope specifier, then
8483     // determine whether we have a template or a template specialization.
8484     bool Invalid = false;
8485     if (TemplateParameterList *TemplateParams =
8486             MatchTemplateParametersToScopeSpecifier(
8487                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8488                 D.getCXXScopeSpec(),
8489                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8490                     ? D.getName().TemplateId
8491                     : nullptr,
8492                 TemplateParamLists, isFriend, isMemberSpecialization,
8493                 Invalid)) {
8494       if (TemplateParams->size() > 0) {
8495         // This is a function template
8496 
8497         // Check that we can declare a template here.
8498         if (CheckTemplateDeclScope(S, TemplateParams))
8499           NewFD->setInvalidDecl();
8500 
8501         // A destructor cannot be a template.
8502         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8503           Diag(NewFD->getLocation(), diag::err_destructor_template);
8504           NewFD->setInvalidDecl();
8505         }
8506 
8507         // If we're adding a template to a dependent context, we may need to
8508         // rebuilding some of the types used within the template parameter list,
8509         // now that we know what the current instantiation is.
8510         if (DC->isDependentContext()) {
8511           ContextRAII SavedContext(*this, DC);
8512           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8513             Invalid = true;
8514         }
8515 
8516         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8517                                                         NewFD->getLocation(),
8518                                                         Name, TemplateParams,
8519                                                         NewFD);
8520         FunctionTemplate->setLexicalDeclContext(CurContext);
8521         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8522 
8523         // For source fidelity, store the other template param lists.
8524         if (TemplateParamLists.size() > 1) {
8525           NewFD->setTemplateParameterListsInfo(Context,
8526                                                TemplateParamLists.drop_back(1));
8527         }
8528       } else {
8529         // This is a function template specialization.
8530         isFunctionTemplateSpecialization = true;
8531         // For source fidelity, store all the template param lists.
8532         if (TemplateParamLists.size() > 0)
8533           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8534 
8535         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8536         if (isFriend) {
8537           // We want to remove the "template<>", found here.
8538           SourceRange RemoveRange = TemplateParams->getSourceRange();
8539 
8540           // If we remove the template<> and the name is not a
8541           // template-id, we're actually silently creating a problem:
8542           // the friend declaration will refer to an untemplated decl,
8543           // and clearly the user wants a template specialization.  So
8544           // we need to insert '<>' after the name.
8545           SourceLocation InsertLoc;
8546           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8547             InsertLoc = D.getName().getSourceRange().getEnd();
8548             InsertLoc = getLocForEndOfToken(InsertLoc);
8549           }
8550 
8551           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8552             << Name << RemoveRange
8553             << FixItHint::CreateRemoval(RemoveRange)
8554             << FixItHint::CreateInsertion(InsertLoc, "<>");
8555         }
8556       }
8557     } else {
8558       // All template param lists were matched against the scope specifier:
8559       // this is NOT (an explicit specialization of) a template.
8560       if (TemplateParamLists.size() > 0)
8561         // For source fidelity, store all the template param lists.
8562         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8563     }
8564 
8565     if (Invalid) {
8566       NewFD->setInvalidDecl();
8567       if (FunctionTemplate)
8568         FunctionTemplate->setInvalidDecl();
8569     }
8570 
8571     // C++ [dcl.fct.spec]p5:
8572     //   The virtual specifier shall only be used in declarations of
8573     //   nonstatic class member functions that appear within a
8574     //   member-specification of a class declaration; see 10.3.
8575     //
8576     if (isVirtual && !NewFD->isInvalidDecl()) {
8577       if (!isVirtualOkay) {
8578         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8579              diag::err_virtual_non_function);
8580       } else if (!CurContext->isRecord()) {
8581         // 'virtual' was specified outside of the class.
8582         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8583              diag::err_virtual_out_of_class)
8584           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8585       } else if (NewFD->getDescribedFunctionTemplate()) {
8586         // C++ [temp.mem]p3:
8587         //  A member function template shall not be virtual.
8588         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8589              diag::err_virtual_member_function_template)
8590           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8591       } else {
8592         // Okay: Add virtual to the method.
8593         NewFD->setVirtualAsWritten(true);
8594       }
8595 
8596       if (getLangOpts().CPlusPlus14 &&
8597           NewFD->getReturnType()->isUndeducedType())
8598         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8599     }
8600 
8601     if (getLangOpts().CPlusPlus14 &&
8602         (NewFD->isDependentContext() ||
8603          (isFriend && CurContext->isDependentContext())) &&
8604         NewFD->getReturnType()->isUndeducedType()) {
8605       // If the function template is referenced directly (for instance, as a
8606       // member of the current instantiation), pretend it has a dependent type.
8607       // This is not really justified by the standard, but is the only sane
8608       // thing to do.
8609       // FIXME: For a friend function, we have not marked the function as being
8610       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8611       const FunctionProtoType *FPT =
8612           NewFD->getType()->castAs<FunctionProtoType>();
8613       QualType Result =
8614           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8615       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8616                                              FPT->getExtProtoInfo()));
8617     }
8618 
8619     // C++ [dcl.fct.spec]p3:
8620     //  The inline specifier shall not appear on a block scope function
8621     //  declaration.
8622     if (isInline && !NewFD->isInvalidDecl()) {
8623       if (CurContext->isFunctionOrMethod()) {
8624         // 'inline' is not allowed on block scope function declaration.
8625         Diag(D.getDeclSpec().getInlineSpecLoc(),
8626              diag::err_inline_declaration_block_scope) << Name
8627           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8628       }
8629     }
8630 
8631     // C++ [dcl.fct.spec]p6:
8632     //  The explicit specifier shall be used only in the declaration of a
8633     //  constructor or conversion function within its class definition;
8634     //  see 12.3.1 and 12.3.2.
8635     if (hasExplicit && !NewFD->isInvalidDecl() &&
8636         !isa<CXXDeductionGuideDecl>(NewFD)) {
8637       if (!CurContext->isRecord()) {
8638         // 'explicit' was specified outside of the class.
8639         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8640              diag::err_explicit_out_of_class)
8641             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8642       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8643                  !isa<CXXConversionDecl>(NewFD)) {
8644         // 'explicit' was specified on a function that wasn't a constructor
8645         // or conversion function.
8646         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8647              diag::err_explicit_non_ctor_or_conv_function)
8648             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
8649       }
8650     }
8651 
8652     if (ConstexprKind != CSK_unspecified) {
8653       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8654       // are implicitly inline.
8655       NewFD->setImplicitlyInline();
8656 
8657       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8658       // be either constructors or to return a literal type. Therefore,
8659       // destructors cannot be declared constexpr.
8660       if (isa<CXXDestructorDecl>(NewFD))
8661         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
8662             << (ConstexprKind == CSK_consteval);
8663     }
8664 
8665     // If __module_private__ was specified, mark the function accordingly.
8666     if (D.getDeclSpec().isModulePrivateSpecified()) {
8667       if (isFunctionTemplateSpecialization) {
8668         SourceLocation ModulePrivateLoc
8669           = D.getDeclSpec().getModulePrivateSpecLoc();
8670         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8671           << 0
8672           << FixItHint::CreateRemoval(ModulePrivateLoc);
8673       } else {
8674         NewFD->setModulePrivate();
8675         if (FunctionTemplate)
8676           FunctionTemplate->setModulePrivate();
8677       }
8678     }
8679 
8680     if (isFriend) {
8681       if (FunctionTemplate) {
8682         FunctionTemplate->setObjectOfFriendDecl();
8683         FunctionTemplate->setAccess(AS_public);
8684       }
8685       NewFD->setObjectOfFriendDecl();
8686       NewFD->setAccess(AS_public);
8687     }
8688 
8689     // If a function is defined as defaulted or deleted, mark it as such now.
8690     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8691     // definition kind to FDK_Definition.
8692     switch (D.getFunctionDefinitionKind()) {
8693       case FDK_Declaration:
8694       case FDK_Definition:
8695         break;
8696 
8697       case FDK_Defaulted:
8698         NewFD->setDefaulted();
8699         break;
8700 
8701       case FDK_Deleted:
8702         NewFD->setDeletedAsWritten();
8703         break;
8704     }
8705 
8706     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8707         D.isFunctionDefinition()) {
8708       // C++ [class.mfct]p2:
8709       //   A member function may be defined (8.4) in its class definition, in
8710       //   which case it is an inline member function (7.1.2)
8711       NewFD->setImplicitlyInline();
8712     }
8713 
8714     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8715         !CurContext->isRecord()) {
8716       // C++ [class.static]p1:
8717       //   A data or function member of a class may be declared static
8718       //   in a class definition, in which case it is a static member of
8719       //   the class.
8720 
8721       // Complain about the 'static' specifier if it's on an out-of-line
8722       // member function definition.
8723 
8724       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8725       // member function template declaration and class member template
8726       // declaration (MSVC versions before 2015), warn about this.
8727       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8728            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
8729              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
8730            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
8731            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8732         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8733     }
8734 
8735     // C++11 [except.spec]p15:
8736     //   A deallocation function with no exception-specification is treated
8737     //   as if it were specified with noexcept(true).
8738     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8739     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8740          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8741         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8742       NewFD->setType(Context.getFunctionType(
8743           FPT->getReturnType(), FPT->getParamTypes(),
8744           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8745   }
8746 
8747   // Filter out previous declarations that don't match the scope.
8748   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8749                        D.getCXXScopeSpec().isNotEmpty() ||
8750                        isMemberSpecialization ||
8751                        isFunctionTemplateSpecialization);
8752 
8753   // Handle GNU asm-label extension (encoded as an attribute).
8754   if (Expr *E = (Expr*) D.getAsmLabel()) {
8755     // The parser guarantees this is a string.
8756     StringLiteral *SE = cast<StringLiteral>(E);
8757     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8758                                                 SE->getString(), 0));
8759   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8760     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8761       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8762     if (I != ExtnameUndeclaredIdentifiers.end()) {
8763       if (isDeclExternC(NewFD)) {
8764         NewFD->addAttr(I->second);
8765         ExtnameUndeclaredIdentifiers.erase(I);
8766       } else
8767         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8768             << /*Variable*/0 << NewFD;
8769     }
8770   }
8771 
8772   // Copy the parameter declarations from the declarator D to the function
8773   // declaration NewFD, if they are available.  First scavenge them into Params.
8774   SmallVector<ParmVarDecl*, 16> Params;
8775   unsigned FTIIdx;
8776   if (D.isFunctionDeclarator(FTIIdx)) {
8777     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8778 
8779     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8780     // function that takes no arguments, not a function that takes a
8781     // single void argument.
8782     // We let through "const void" here because Sema::GetTypeForDeclarator
8783     // already checks for that case.
8784     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8785       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8786         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8787         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8788         Param->setDeclContext(NewFD);
8789         Params.push_back(Param);
8790 
8791         if (Param->isInvalidDecl())
8792           NewFD->setInvalidDecl();
8793       }
8794     }
8795 
8796     if (!getLangOpts().CPlusPlus) {
8797       // In C, find all the tag declarations from the prototype and move them
8798       // into the function DeclContext. Remove them from the surrounding tag
8799       // injection context of the function, which is typically but not always
8800       // the TU.
8801       DeclContext *PrototypeTagContext =
8802           getTagInjectionContext(NewFD->getLexicalDeclContext());
8803       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8804         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8805 
8806         // We don't want to reparent enumerators. Look at their parent enum
8807         // instead.
8808         if (!TD) {
8809           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8810             TD = cast<EnumDecl>(ECD->getDeclContext());
8811         }
8812         if (!TD)
8813           continue;
8814         DeclContext *TagDC = TD->getLexicalDeclContext();
8815         if (!TagDC->containsDecl(TD))
8816           continue;
8817         TagDC->removeDecl(TD);
8818         TD->setDeclContext(NewFD);
8819         NewFD->addDecl(TD);
8820 
8821         // Preserve the lexical DeclContext if it is not the surrounding tag
8822         // injection context of the FD. In this example, the semantic context of
8823         // E will be f and the lexical context will be S, while both the
8824         // semantic and lexical contexts of S will be f:
8825         //   void f(struct S { enum E { a } f; } s);
8826         if (TagDC != PrototypeTagContext)
8827           TD->setLexicalDeclContext(TagDC);
8828       }
8829     }
8830   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8831     // When we're declaring a function with a typedef, typeof, etc as in the
8832     // following example, we'll need to synthesize (unnamed)
8833     // parameters for use in the declaration.
8834     //
8835     // @code
8836     // typedef void fn(int);
8837     // fn f;
8838     // @endcode
8839 
8840     // Synthesize a parameter for each argument type.
8841     for (const auto &AI : FT->param_types()) {
8842       ParmVarDecl *Param =
8843           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8844       Param->setScopeInfo(0, Params.size());
8845       Params.push_back(Param);
8846     }
8847   } else {
8848     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8849            "Should not need args for typedef of non-prototype fn");
8850   }
8851 
8852   // Finally, we know we have the right number of parameters, install them.
8853   NewFD->setParams(Params);
8854 
8855   if (D.getDeclSpec().isNoreturnSpecified())
8856     NewFD->addAttr(
8857         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8858                                        Context, 0));
8859 
8860   // Functions returning a variably modified type violate C99 6.7.5.2p2
8861   // because all functions have linkage.
8862   if (!NewFD->isInvalidDecl() &&
8863       NewFD->getReturnType()->isVariablyModifiedType()) {
8864     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8865     NewFD->setInvalidDecl();
8866   }
8867 
8868   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8869   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8870       !NewFD->hasAttr<SectionAttr>()) {
8871     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8872                                                  PragmaClangTextSection.SectionName,
8873                                                  PragmaClangTextSection.PragmaLocation));
8874   }
8875 
8876   // Apply an implicit SectionAttr if #pragma code_seg is active.
8877   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8878       !NewFD->hasAttr<SectionAttr>()) {
8879     NewFD->addAttr(
8880         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8881                                     CodeSegStack.CurrentValue->getString(),
8882                                     CodeSegStack.CurrentPragmaLocation));
8883     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8884                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8885                          ASTContext::PSF_Read,
8886                      NewFD))
8887       NewFD->dropAttr<SectionAttr>();
8888   }
8889 
8890   // Apply an implicit CodeSegAttr from class declspec or
8891   // apply an implicit SectionAttr from #pragma code_seg if active.
8892   if (!NewFD->hasAttr<CodeSegAttr>()) {
8893     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8894                                                                  D.isFunctionDefinition())) {
8895       NewFD->addAttr(SAttr);
8896     }
8897   }
8898 
8899   // Handle attributes.
8900   ProcessDeclAttributes(S, NewFD, D);
8901 
8902   if (getLangOpts().OpenCL) {
8903     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8904     // type declaration will generate a compilation error.
8905     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8906     if (AddressSpace != LangAS::Default) {
8907       Diag(NewFD->getLocation(),
8908            diag::err_opencl_return_value_with_address_space);
8909       NewFD->setInvalidDecl();
8910     }
8911   }
8912 
8913   if (!getLangOpts().CPlusPlus) {
8914     // Perform semantic checking on the function declaration.
8915     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8916       CheckMain(NewFD, D.getDeclSpec());
8917 
8918     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8919       CheckMSVCRTEntryPoint(NewFD);
8920 
8921     if (!NewFD->isInvalidDecl())
8922       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8923                                                   isMemberSpecialization));
8924     else if (!Previous.empty())
8925       // Recover gracefully from an invalid redeclaration.
8926       D.setRedeclaration(true);
8927     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8928             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8929            "previous declaration set still overloaded");
8930 
8931     // Diagnose no-prototype function declarations with calling conventions that
8932     // don't support variadic calls. Only do this in C and do it after merging
8933     // possibly prototyped redeclarations.
8934     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8935     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8936       CallingConv CC = FT->getExtInfo().getCC();
8937       if (!supportsVariadicCall(CC)) {
8938         // Windows system headers sometimes accidentally use stdcall without
8939         // (void) parameters, so we relax this to a warning.
8940         int DiagID =
8941             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8942         Diag(NewFD->getLocation(), DiagID)
8943             << FunctionType::getNameForCallConv(CC);
8944       }
8945     }
8946   } else {
8947     // C++11 [replacement.functions]p3:
8948     //  The program's definitions shall not be specified as inline.
8949     //
8950     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8951     //
8952     // Suppress the diagnostic if the function is __attribute__((used)), since
8953     // that forces an external definition to be emitted.
8954     if (D.getDeclSpec().isInlineSpecified() &&
8955         NewFD->isReplaceableGlobalAllocationFunction() &&
8956         !NewFD->hasAttr<UsedAttr>())
8957       Diag(D.getDeclSpec().getInlineSpecLoc(),
8958            diag::ext_operator_new_delete_declared_inline)
8959         << NewFD->getDeclName();
8960 
8961     // If the declarator is a template-id, translate the parser's template
8962     // argument list into our AST format.
8963     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8964       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8965       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8966       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8967       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8968                                          TemplateId->NumArgs);
8969       translateTemplateArguments(TemplateArgsPtr,
8970                                  TemplateArgs);
8971 
8972       HasExplicitTemplateArgs = true;
8973 
8974       if (NewFD->isInvalidDecl()) {
8975         HasExplicitTemplateArgs = false;
8976       } else if (FunctionTemplate) {
8977         // Function template with explicit template arguments.
8978         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8979           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8980 
8981         HasExplicitTemplateArgs = false;
8982       } else {
8983         assert((isFunctionTemplateSpecialization ||
8984                 D.getDeclSpec().isFriendSpecified()) &&
8985                "should have a 'template<>' for this decl");
8986         // "friend void foo<>(int);" is an implicit specialization decl.
8987         isFunctionTemplateSpecialization = true;
8988       }
8989     } else if (isFriend && isFunctionTemplateSpecialization) {
8990       // This combination is only possible in a recovery case;  the user
8991       // wrote something like:
8992       //   template <> friend void foo(int);
8993       // which we're recovering from as if the user had written:
8994       //   friend void foo<>(int);
8995       // Go ahead and fake up a template id.
8996       HasExplicitTemplateArgs = true;
8997       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8998       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8999     }
9000 
9001     // We do not add HD attributes to specializations here because
9002     // they may have different constexpr-ness compared to their
9003     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9004     // may end up with different effective targets. Instead, a
9005     // specialization inherits its target attributes from its template
9006     // in the CheckFunctionTemplateSpecialization() call below.
9007     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
9008       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9009 
9010     // If it's a friend (and only if it's a friend), it's possible
9011     // that either the specialized function type or the specialized
9012     // template is dependent, and therefore matching will fail.  In
9013     // this case, don't check the specialization yet.
9014     bool InstantiationDependent = false;
9015     if (isFunctionTemplateSpecialization && isFriend &&
9016         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9017          TemplateSpecializationType::anyDependentTemplateArguments(
9018             TemplateArgs,
9019             InstantiationDependent))) {
9020       assert(HasExplicitTemplateArgs &&
9021              "friend function specialization without template args");
9022       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9023                                                        Previous))
9024         NewFD->setInvalidDecl();
9025     } else if (isFunctionTemplateSpecialization) {
9026       if (CurContext->isDependentContext() && CurContext->isRecord()
9027           && !isFriend) {
9028         isDependentClassScopeExplicitSpecialization = true;
9029       } else if (!NewFD->isInvalidDecl() &&
9030                  CheckFunctionTemplateSpecialization(
9031                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9032                      Previous))
9033         NewFD->setInvalidDecl();
9034 
9035       // C++ [dcl.stc]p1:
9036       //   A storage-class-specifier shall not be specified in an explicit
9037       //   specialization (14.7.3)
9038       FunctionTemplateSpecializationInfo *Info =
9039           NewFD->getTemplateSpecializationInfo();
9040       if (Info && SC != SC_None) {
9041         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9042           Diag(NewFD->getLocation(),
9043                diag::err_explicit_specialization_inconsistent_storage_class)
9044             << SC
9045             << FixItHint::CreateRemoval(
9046                                       D.getDeclSpec().getStorageClassSpecLoc());
9047 
9048         else
9049           Diag(NewFD->getLocation(),
9050                diag::ext_explicit_specialization_storage_class)
9051             << FixItHint::CreateRemoval(
9052                                       D.getDeclSpec().getStorageClassSpecLoc());
9053       }
9054     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9055       if (CheckMemberSpecialization(NewFD, Previous))
9056           NewFD->setInvalidDecl();
9057     }
9058 
9059     // Perform semantic checking on the function declaration.
9060     if (!isDependentClassScopeExplicitSpecialization) {
9061       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9062         CheckMain(NewFD, D.getDeclSpec());
9063 
9064       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9065         CheckMSVCRTEntryPoint(NewFD);
9066 
9067       if (!NewFD->isInvalidDecl())
9068         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9069                                                     isMemberSpecialization));
9070       else if (!Previous.empty())
9071         // Recover gracefully from an invalid redeclaration.
9072         D.setRedeclaration(true);
9073     }
9074 
9075     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9076             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9077            "previous declaration set still overloaded");
9078 
9079     NamedDecl *PrincipalDecl = (FunctionTemplate
9080                                 ? cast<NamedDecl>(FunctionTemplate)
9081                                 : NewFD);
9082 
9083     if (isFriend && NewFD->getPreviousDecl()) {
9084       AccessSpecifier Access = AS_public;
9085       if (!NewFD->isInvalidDecl())
9086         Access = NewFD->getPreviousDecl()->getAccess();
9087 
9088       NewFD->setAccess(Access);
9089       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9090     }
9091 
9092     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9093         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9094       PrincipalDecl->setNonMemberOperator();
9095 
9096     // If we have a function template, check the template parameter
9097     // list. This will check and merge default template arguments.
9098     if (FunctionTemplate) {
9099       FunctionTemplateDecl *PrevTemplate =
9100                                      FunctionTemplate->getPreviousDecl();
9101       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9102                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9103                                     : nullptr,
9104                             D.getDeclSpec().isFriendSpecified()
9105                               ? (D.isFunctionDefinition()
9106                                    ? TPC_FriendFunctionTemplateDefinition
9107                                    : TPC_FriendFunctionTemplate)
9108                               : (D.getCXXScopeSpec().isSet() &&
9109                                  DC && DC->isRecord() &&
9110                                  DC->isDependentContext())
9111                                   ? TPC_ClassTemplateMember
9112                                   : TPC_FunctionTemplate);
9113     }
9114 
9115     if (NewFD->isInvalidDecl()) {
9116       // Ignore all the rest of this.
9117     } else if (!D.isRedeclaration()) {
9118       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9119                                        AddToScope };
9120       // Fake up an access specifier if it's supposed to be a class member.
9121       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9122         NewFD->setAccess(AS_public);
9123 
9124       // Qualified decls generally require a previous declaration.
9125       if (D.getCXXScopeSpec().isSet()) {
9126         // ...with the major exception of templated-scope or
9127         // dependent-scope friend declarations.
9128 
9129         // TODO: we currently also suppress this check in dependent
9130         // contexts because (1) the parameter depth will be off when
9131         // matching friend templates and (2) we might actually be
9132         // selecting a friend based on a dependent factor.  But there
9133         // are situations where these conditions don't apply and we
9134         // can actually do this check immediately.
9135         //
9136         // Unless the scope is dependent, it's always an error if qualified
9137         // redeclaration lookup found nothing at all. Diagnose that now;
9138         // nothing will diagnose that error later.
9139         if (isFriend &&
9140             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9141              (!Previous.empty() && CurContext->isDependentContext()))) {
9142           // ignore these
9143         } else {
9144           // The user tried to provide an out-of-line definition for a
9145           // function that is a member of a class or namespace, but there
9146           // was no such member function declared (C++ [class.mfct]p2,
9147           // C++ [namespace.memdef]p2). For example:
9148           //
9149           // class X {
9150           //   void f() const;
9151           // };
9152           //
9153           // void X::f() { } // ill-formed
9154           //
9155           // Complain about this problem, and attempt to suggest close
9156           // matches (e.g., those that differ only in cv-qualifiers and
9157           // whether the parameter types are references).
9158 
9159           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9160                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9161             AddToScope = ExtraArgs.AddToScope;
9162             return Result;
9163           }
9164         }
9165 
9166         // Unqualified local friend declarations are required to resolve
9167         // to something.
9168       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9169         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9170                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9171           AddToScope = ExtraArgs.AddToScope;
9172           return Result;
9173         }
9174       }
9175     } else if (!D.isFunctionDefinition() &&
9176                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9177                !isFriend && !isFunctionTemplateSpecialization &&
9178                !isMemberSpecialization) {
9179       // An out-of-line member function declaration must also be a
9180       // definition (C++ [class.mfct]p2).
9181       // Note that this is not the case for explicit specializations of
9182       // function templates or member functions of class templates, per
9183       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9184       // extension for compatibility with old SWIG code which likes to
9185       // generate them.
9186       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9187         << D.getCXXScopeSpec().getRange();
9188     }
9189   }
9190 
9191   ProcessPragmaWeak(S, NewFD);
9192   checkAttributesAfterMerging(*this, *NewFD);
9193 
9194   AddKnownFunctionAttributes(NewFD);
9195 
9196   if (NewFD->hasAttr<OverloadableAttr>() &&
9197       !NewFD->getType()->getAs<FunctionProtoType>()) {
9198     Diag(NewFD->getLocation(),
9199          diag::err_attribute_overloadable_no_prototype)
9200       << NewFD;
9201 
9202     // Turn this into a variadic function with no parameters.
9203     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9204     FunctionProtoType::ExtProtoInfo EPI(
9205         Context.getDefaultCallingConvention(true, false));
9206     EPI.Variadic = true;
9207     EPI.ExtInfo = FT->getExtInfo();
9208 
9209     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9210     NewFD->setType(R);
9211   }
9212 
9213   // If there's a #pragma GCC visibility in scope, and this isn't a class
9214   // member, set the visibility of this function.
9215   if (!DC->isRecord() && NewFD->isExternallyVisible())
9216     AddPushedVisibilityAttribute(NewFD);
9217 
9218   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9219   // marking the function.
9220   AddCFAuditedAttribute(NewFD);
9221 
9222   // If this is a function definition, check if we have to apply optnone due to
9223   // a pragma.
9224   if(D.isFunctionDefinition())
9225     AddRangeBasedOptnone(NewFD);
9226 
9227   // If this is the first declaration of an extern C variable, update
9228   // the map of such variables.
9229   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9230       isIncompleteDeclExternC(*this, NewFD))
9231     RegisterLocallyScopedExternCDecl(NewFD, S);
9232 
9233   // Set this FunctionDecl's range up to the right paren.
9234   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9235 
9236   if (D.isRedeclaration() && !Previous.empty()) {
9237     NamedDecl *Prev = Previous.getRepresentativeDecl();
9238     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9239                                    isMemberSpecialization ||
9240                                        isFunctionTemplateSpecialization,
9241                                    D.isFunctionDefinition());
9242   }
9243 
9244   if (getLangOpts().CUDA) {
9245     IdentifierInfo *II = NewFD->getIdentifier();
9246     if (II && II->isStr(getCudaConfigureFuncName()) &&
9247         !NewFD->isInvalidDecl() &&
9248         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9249       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9250         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9251             << getCudaConfigureFuncName();
9252       Context.setcudaConfigureCallDecl(NewFD);
9253     }
9254 
9255     // Variadic functions, other than a *declaration* of printf, are not allowed
9256     // in device-side CUDA code, unless someone passed
9257     // -fcuda-allow-variadic-functions.
9258     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9259         (NewFD->hasAttr<CUDADeviceAttr>() ||
9260          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9261         !(II && II->isStr("printf") && NewFD->isExternC() &&
9262           !D.isFunctionDefinition())) {
9263       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9264     }
9265   }
9266 
9267   MarkUnusedFileScopedDecl(NewFD);
9268 
9269 
9270 
9271   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9272     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9273     if ((getLangOpts().OpenCLVersion >= 120)
9274         && (SC == SC_Static)) {
9275       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9276       D.setInvalidType();
9277     }
9278 
9279     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9280     if (!NewFD->getReturnType()->isVoidType()) {
9281       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9282       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9283           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9284                                 : FixItHint());
9285       D.setInvalidType();
9286     }
9287 
9288     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9289     for (auto Param : NewFD->parameters())
9290       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9291 
9292     if (getLangOpts().OpenCLCPlusPlus) {
9293       if (DC->isRecord()) {
9294         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9295         D.setInvalidType();
9296       }
9297       if (FunctionTemplate) {
9298         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9299         D.setInvalidType();
9300       }
9301     }
9302   }
9303 
9304   if (getLangOpts().CPlusPlus) {
9305     if (FunctionTemplate) {
9306       if (NewFD->isInvalidDecl())
9307         FunctionTemplate->setInvalidDecl();
9308       return FunctionTemplate;
9309     }
9310 
9311     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9312       CompleteMemberSpecialization(NewFD, Previous);
9313   }
9314 
9315   for (const ParmVarDecl *Param : NewFD->parameters()) {
9316     QualType PT = Param->getType();
9317 
9318     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9319     // types.
9320     if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9321       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9322         QualType ElemTy = PipeTy->getElementType();
9323           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9324             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9325             D.setInvalidType();
9326           }
9327       }
9328     }
9329   }
9330 
9331   // Here we have an function template explicit specialization at class scope.
9332   // The actual specialization will be postponed to template instatiation
9333   // time via the ClassScopeFunctionSpecializationDecl node.
9334   if (isDependentClassScopeExplicitSpecialization) {
9335     ClassScopeFunctionSpecializationDecl *NewSpec =
9336                          ClassScopeFunctionSpecializationDecl::Create(
9337                                 Context, CurContext, NewFD->getLocation(),
9338                                 cast<CXXMethodDecl>(NewFD),
9339                                 HasExplicitTemplateArgs, TemplateArgs);
9340     CurContext->addDecl(NewSpec);
9341     AddToScope = false;
9342   }
9343 
9344   // Diagnose availability attributes. Availability cannot be used on functions
9345   // that are run during load/unload.
9346   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9347     if (NewFD->hasAttr<ConstructorAttr>()) {
9348       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9349           << 1;
9350       NewFD->dropAttr<AvailabilityAttr>();
9351     }
9352     if (NewFD->hasAttr<DestructorAttr>()) {
9353       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9354           << 2;
9355       NewFD->dropAttr<AvailabilityAttr>();
9356     }
9357   }
9358 
9359   return NewFD;
9360 }
9361 
9362 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9363 /// when __declspec(code_seg) "is applied to a class, all member functions of
9364 /// the class and nested classes -- this includes compiler-generated special
9365 /// member functions -- are put in the specified segment."
9366 /// The actual behavior is a little more complicated. The Microsoft compiler
9367 /// won't check outer classes if there is an active value from #pragma code_seg.
9368 /// The CodeSeg is always applied from the direct parent but only from outer
9369 /// classes when the #pragma code_seg stack is empty. See:
9370 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9371 /// available since MS has removed the page.
9372 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9373   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9374   if (!Method)
9375     return nullptr;
9376   const CXXRecordDecl *Parent = Method->getParent();
9377   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9378     Attr *NewAttr = SAttr->clone(S.getASTContext());
9379     NewAttr->setImplicit(true);
9380     return NewAttr;
9381   }
9382 
9383   // The Microsoft compiler won't check outer classes for the CodeSeg
9384   // when the #pragma code_seg stack is active.
9385   if (S.CodeSegStack.CurrentValue)
9386    return nullptr;
9387 
9388   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9389     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9390       Attr *NewAttr = SAttr->clone(S.getASTContext());
9391       NewAttr->setImplicit(true);
9392       return NewAttr;
9393     }
9394   }
9395   return nullptr;
9396 }
9397 
9398 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9399 /// containing class. Otherwise it will return implicit SectionAttr if the
9400 /// function is a definition and there is an active value on CodeSegStack
9401 /// (from the current #pragma code-seg value).
9402 ///
9403 /// \param FD Function being declared.
9404 /// \param IsDefinition Whether it is a definition or just a declarartion.
9405 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9406 ///          nullptr if no attribute should be added.
9407 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9408                                                        bool IsDefinition) {
9409   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9410     return A;
9411   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9412       CodeSegStack.CurrentValue) {
9413     return SectionAttr::CreateImplicit(getASTContext(),
9414                                        SectionAttr::Declspec_allocate,
9415                                        CodeSegStack.CurrentValue->getString(),
9416                                        CodeSegStack.CurrentPragmaLocation);
9417   }
9418   return nullptr;
9419 }
9420 
9421 /// Determines if we can perform a correct type check for \p D as a
9422 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9423 /// best-effort check.
9424 ///
9425 /// \param NewD The new declaration.
9426 /// \param OldD The old declaration.
9427 /// \param NewT The portion of the type of the new declaration to check.
9428 /// \param OldT The portion of the type of the old declaration to check.
9429 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9430                                           QualType NewT, QualType OldT) {
9431   if (!NewD->getLexicalDeclContext()->isDependentContext())
9432     return true;
9433 
9434   // For dependently-typed local extern declarations and friends, we can't
9435   // perform a correct type check in general until instantiation:
9436   //
9437   //   int f();
9438   //   template<typename T> void g() { T f(); }
9439   //
9440   // (valid if g() is only instantiated with T = int).
9441   if (NewT->isDependentType() &&
9442       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9443     return false;
9444 
9445   // Similarly, if the previous declaration was a dependent local extern
9446   // declaration, we don't really know its type yet.
9447   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9448     return false;
9449 
9450   return true;
9451 }
9452 
9453 /// Checks if the new declaration declared in dependent context must be
9454 /// put in the same redeclaration chain as the specified declaration.
9455 ///
9456 /// \param D Declaration that is checked.
9457 /// \param PrevDecl Previous declaration found with proper lookup method for the
9458 ///                 same declaration name.
9459 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9460 ///          belongs to.
9461 ///
9462 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9463   if (!D->getLexicalDeclContext()->isDependentContext())
9464     return true;
9465 
9466   // Don't chain dependent friend function definitions until instantiation, to
9467   // permit cases like
9468   //
9469   //   void func();
9470   //   template<typename T> class C1 { friend void func() {} };
9471   //   template<typename T> class C2 { friend void func() {} };
9472   //
9473   // ... which is valid if only one of C1 and C2 is ever instantiated.
9474   //
9475   // FIXME: This need only apply to function definitions. For now, we proxy
9476   // this by checking for a file-scope function. We do not want this to apply
9477   // to friend declarations nominating member functions, because that gets in
9478   // the way of access checks.
9479   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9480     return false;
9481 
9482   auto *VD = dyn_cast<ValueDecl>(D);
9483   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9484   return !VD || !PrevVD ||
9485          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9486                                         PrevVD->getType());
9487 }
9488 
9489 /// Check the target attribute of the function for MultiVersion
9490 /// validity.
9491 ///
9492 /// Returns true if there was an error, false otherwise.
9493 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9494   const auto *TA = FD->getAttr<TargetAttr>();
9495   assert(TA && "MultiVersion Candidate requires a target attribute");
9496   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9497   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9498   enum ErrType { Feature = 0, Architecture = 1 };
9499 
9500   if (!ParseInfo.Architecture.empty() &&
9501       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9502     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9503         << Architecture << ParseInfo.Architecture;
9504     return true;
9505   }
9506 
9507   for (const auto &Feat : ParseInfo.Features) {
9508     auto BareFeat = StringRef{Feat}.substr(1);
9509     if (Feat[0] == '-') {
9510       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9511           << Feature << ("no-" + BareFeat).str();
9512       return true;
9513     }
9514 
9515     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9516         !TargetInfo.isValidFeatureName(BareFeat)) {
9517       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9518           << Feature << BareFeat;
9519       return true;
9520     }
9521   }
9522   return false;
9523 }
9524 
9525 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9526                                          MultiVersionKind MVType) {
9527   for (const Attr *A : FD->attrs()) {
9528     switch (A->getKind()) {
9529     case attr::CPUDispatch:
9530     case attr::CPUSpecific:
9531       if (MVType != MultiVersionKind::CPUDispatch &&
9532           MVType != MultiVersionKind::CPUSpecific)
9533         return true;
9534       break;
9535     case attr::Target:
9536       if (MVType != MultiVersionKind::Target)
9537         return true;
9538       break;
9539     default:
9540       return true;
9541     }
9542   }
9543   return false;
9544 }
9545 
9546 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9547                                              const FunctionDecl *NewFD,
9548                                              bool CausesMV,
9549                                              MultiVersionKind MVType) {
9550   enum DoesntSupport {
9551     FuncTemplates = 0,
9552     VirtFuncs = 1,
9553     DeducedReturn = 2,
9554     Constructors = 3,
9555     Destructors = 4,
9556     DeletedFuncs = 5,
9557     DefaultedFuncs = 6,
9558     ConstexprFuncs = 7,
9559     ConstevalFuncs = 8,
9560   };
9561   enum Different {
9562     CallingConv = 0,
9563     ReturnType = 1,
9564     ConstexprSpec = 2,
9565     InlineSpec = 3,
9566     StorageClass = 4,
9567     Linkage = 5
9568   };
9569 
9570   bool IsCPUSpecificCPUDispatchMVType =
9571       MVType == MultiVersionKind::CPUDispatch ||
9572       MVType == MultiVersionKind::CPUSpecific;
9573 
9574   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9575     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9576     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9577     return true;
9578   }
9579 
9580   if (!NewFD->getType()->getAs<FunctionProtoType>())
9581     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9582 
9583   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9584     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9585     if (OldFD)
9586       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9587     return true;
9588   }
9589 
9590   // For now, disallow all other attributes.  These should be opt-in, but
9591   // an analysis of all of them is a future FIXME.
9592   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9593     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9594         << IsCPUSpecificCPUDispatchMVType;
9595     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9596     return true;
9597   }
9598 
9599   if (HasNonMultiVersionAttributes(NewFD, MVType))
9600     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9601            << IsCPUSpecificCPUDispatchMVType;
9602 
9603   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9604     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9605            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9606 
9607   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9608     if (NewCXXFD->isVirtual())
9609       return S.Diag(NewCXXFD->getLocation(),
9610                     diag::err_multiversion_doesnt_support)
9611              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9612 
9613     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9614       return S.Diag(NewCXXCtor->getLocation(),
9615                     diag::err_multiversion_doesnt_support)
9616              << IsCPUSpecificCPUDispatchMVType << Constructors;
9617 
9618     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9619       return S.Diag(NewCXXDtor->getLocation(),
9620                     diag::err_multiversion_doesnt_support)
9621              << IsCPUSpecificCPUDispatchMVType << Destructors;
9622   }
9623 
9624   if (NewFD->isDeleted())
9625     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9626            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9627 
9628   if (NewFD->isDefaulted())
9629     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9630            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9631 
9632   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9633                                MVType == MultiVersionKind::CPUSpecific))
9634     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9635            << IsCPUSpecificCPUDispatchMVType
9636            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
9637 
9638   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9639   const auto *NewType = cast<FunctionType>(NewQType);
9640   QualType NewReturnType = NewType->getReturnType();
9641 
9642   if (NewReturnType->isUndeducedType())
9643     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9644            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9645 
9646   // Only allow transition to MultiVersion if it hasn't been used.
9647   if (OldFD && CausesMV && OldFD->isUsed(false))
9648     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9649 
9650   // Ensure the return type is identical.
9651   if (OldFD) {
9652     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9653     const auto *OldType = cast<FunctionType>(OldQType);
9654     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9655     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9656 
9657     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9658       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9659              << CallingConv;
9660 
9661     QualType OldReturnType = OldType->getReturnType();
9662 
9663     if (OldReturnType != NewReturnType)
9664       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9665              << ReturnType;
9666 
9667     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
9668       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9669              << ConstexprSpec;
9670 
9671     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9672       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9673              << InlineSpec;
9674 
9675     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9676       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9677              << StorageClass;
9678 
9679     if (OldFD->isExternC() != NewFD->isExternC())
9680       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9681              << Linkage;
9682 
9683     if (S.CheckEquivalentExceptionSpec(
9684             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9685             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9686       return true;
9687   }
9688   return false;
9689 }
9690 
9691 /// Check the validity of a multiversion function declaration that is the
9692 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9693 ///
9694 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9695 ///
9696 /// Returns true if there was an error, false otherwise.
9697 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9698                                            MultiVersionKind MVType,
9699                                            const TargetAttr *TA) {
9700   assert(MVType != MultiVersionKind::None &&
9701          "Function lacks multiversion attribute");
9702 
9703   // Target only causes MV if it is default, otherwise this is a normal
9704   // function.
9705   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9706     return false;
9707 
9708   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9709     FD->setInvalidDecl();
9710     return true;
9711   }
9712 
9713   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9714     FD->setInvalidDecl();
9715     return true;
9716   }
9717 
9718   FD->setIsMultiVersion();
9719   return false;
9720 }
9721 
9722 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9723   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9724     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9725       return true;
9726   }
9727 
9728   return false;
9729 }
9730 
9731 static bool CheckTargetCausesMultiVersioning(
9732     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9733     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9734     LookupResult &Previous) {
9735   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9736   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9737   // Sort order doesn't matter, it just needs to be consistent.
9738   llvm::sort(NewParsed.Features);
9739 
9740   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9741   // to change, this is a simple redeclaration.
9742   if (!NewTA->isDefaultVersion() &&
9743       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9744     return false;
9745 
9746   // Otherwise, this decl causes MultiVersioning.
9747   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9748     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9749     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9750     NewFD->setInvalidDecl();
9751     return true;
9752   }
9753 
9754   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9755                                        MultiVersionKind::Target)) {
9756     NewFD->setInvalidDecl();
9757     return true;
9758   }
9759 
9760   if (CheckMultiVersionValue(S, NewFD)) {
9761     NewFD->setInvalidDecl();
9762     return true;
9763   }
9764 
9765   // If this is 'default', permit the forward declaration.
9766   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9767     Redeclaration = true;
9768     OldDecl = OldFD;
9769     OldFD->setIsMultiVersion();
9770     NewFD->setIsMultiVersion();
9771     return false;
9772   }
9773 
9774   if (CheckMultiVersionValue(S, OldFD)) {
9775     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9776     NewFD->setInvalidDecl();
9777     return true;
9778   }
9779 
9780   TargetAttr::ParsedTargetAttr OldParsed =
9781       OldTA->parse(std::less<std::string>());
9782 
9783   if (OldParsed == NewParsed) {
9784     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9785     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9786     NewFD->setInvalidDecl();
9787     return true;
9788   }
9789 
9790   for (const auto *FD : OldFD->redecls()) {
9791     const auto *CurTA = FD->getAttr<TargetAttr>();
9792     // We allow forward declarations before ANY multiversioning attributes, but
9793     // nothing after the fact.
9794     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9795         (!CurTA || CurTA->isInherited())) {
9796       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9797           << 0;
9798       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9799       NewFD->setInvalidDecl();
9800       return true;
9801     }
9802   }
9803 
9804   OldFD->setIsMultiVersion();
9805   NewFD->setIsMultiVersion();
9806   Redeclaration = false;
9807   MergeTypeWithPrevious = false;
9808   OldDecl = nullptr;
9809   Previous.clear();
9810   return false;
9811 }
9812 
9813 /// Check the validity of a new function declaration being added to an existing
9814 /// multiversioned declaration collection.
9815 static bool CheckMultiVersionAdditionalDecl(
9816     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9817     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9818     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9819     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9820     LookupResult &Previous) {
9821 
9822   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9823   // Disallow mixing of multiversioning types.
9824   if ((OldMVType == MultiVersionKind::Target &&
9825        NewMVType != MultiVersionKind::Target) ||
9826       (NewMVType == MultiVersionKind::Target &&
9827        OldMVType != MultiVersionKind::Target)) {
9828     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9829     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9830     NewFD->setInvalidDecl();
9831     return true;
9832   }
9833 
9834   TargetAttr::ParsedTargetAttr NewParsed;
9835   if (NewTA) {
9836     NewParsed = NewTA->parse();
9837     llvm::sort(NewParsed.Features);
9838   }
9839 
9840   bool UseMemberUsingDeclRules =
9841       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9842 
9843   // Next, check ALL non-overloads to see if this is a redeclaration of a
9844   // previous member of the MultiVersion set.
9845   for (NamedDecl *ND : Previous) {
9846     FunctionDecl *CurFD = ND->getAsFunction();
9847     if (!CurFD)
9848       continue;
9849     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9850       continue;
9851 
9852     if (NewMVType == MultiVersionKind::Target) {
9853       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9854       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9855         NewFD->setIsMultiVersion();
9856         Redeclaration = true;
9857         OldDecl = ND;
9858         return false;
9859       }
9860 
9861       TargetAttr::ParsedTargetAttr CurParsed =
9862           CurTA->parse(std::less<std::string>());
9863       if (CurParsed == NewParsed) {
9864         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9865         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9866         NewFD->setInvalidDecl();
9867         return true;
9868       }
9869     } else {
9870       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9871       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9872       // Handle CPUDispatch/CPUSpecific versions.
9873       // Only 1 CPUDispatch function is allowed, this will make it go through
9874       // the redeclaration errors.
9875       if (NewMVType == MultiVersionKind::CPUDispatch &&
9876           CurFD->hasAttr<CPUDispatchAttr>()) {
9877         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9878             std::equal(
9879                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9880                 NewCPUDisp->cpus_begin(),
9881                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9882                   return Cur->getName() == New->getName();
9883                 })) {
9884           NewFD->setIsMultiVersion();
9885           Redeclaration = true;
9886           OldDecl = ND;
9887           return false;
9888         }
9889 
9890         // If the declarations don't match, this is an error condition.
9891         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9892         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9893         NewFD->setInvalidDecl();
9894         return true;
9895       }
9896       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9897 
9898         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9899             std::equal(
9900                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9901                 NewCPUSpec->cpus_begin(),
9902                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9903                   return Cur->getName() == New->getName();
9904                 })) {
9905           NewFD->setIsMultiVersion();
9906           Redeclaration = true;
9907           OldDecl = ND;
9908           return false;
9909         }
9910 
9911         // Only 1 version of CPUSpecific is allowed for each CPU.
9912         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9913           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9914             if (CurII == NewII) {
9915               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9916                   << NewII;
9917               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9918               NewFD->setInvalidDecl();
9919               return true;
9920             }
9921           }
9922         }
9923       }
9924       // If the two decls aren't the same MVType, there is no possible error
9925       // condition.
9926     }
9927   }
9928 
9929   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9930   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9931   // handled in the attribute adding step.
9932   if (NewMVType == MultiVersionKind::Target &&
9933       CheckMultiVersionValue(S, NewFD)) {
9934     NewFD->setInvalidDecl();
9935     return true;
9936   }
9937 
9938   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9939                                        !OldFD->isMultiVersion(), NewMVType)) {
9940     NewFD->setInvalidDecl();
9941     return true;
9942   }
9943 
9944   // Permit forward declarations in the case where these two are compatible.
9945   if (!OldFD->isMultiVersion()) {
9946     OldFD->setIsMultiVersion();
9947     NewFD->setIsMultiVersion();
9948     Redeclaration = true;
9949     OldDecl = OldFD;
9950     return false;
9951   }
9952 
9953   NewFD->setIsMultiVersion();
9954   Redeclaration = false;
9955   MergeTypeWithPrevious = false;
9956   OldDecl = nullptr;
9957   Previous.clear();
9958   return false;
9959 }
9960 
9961 
9962 /// Check the validity of a mulitversion function declaration.
9963 /// Also sets the multiversion'ness' of the function itself.
9964 ///
9965 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9966 ///
9967 /// Returns true if there was an error, false otherwise.
9968 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9969                                       bool &Redeclaration, NamedDecl *&OldDecl,
9970                                       bool &MergeTypeWithPrevious,
9971                                       LookupResult &Previous) {
9972   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9973   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9974   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9975 
9976   // Mixing Multiversioning types is prohibited.
9977   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9978       (NewCPUDisp && NewCPUSpec)) {
9979     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9980     NewFD->setInvalidDecl();
9981     return true;
9982   }
9983 
9984   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9985 
9986   // Main isn't allowed to become a multiversion function, however it IS
9987   // permitted to have 'main' be marked with the 'target' optimization hint.
9988   if (NewFD->isMain()) {
9989     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9990         MVType == MultiVersionKind::CPUDispatch ||
9991         MVType == MultiVersionKind::CPUSpecific) {
9992       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9993       NewFD->setInvalidDecl();
9994       return true;
9995     }
9996     return false;
9997   }
9998 
9999   if (!OldDecl || !OldDecl->getAsFunction() ||
10000       OldDecl->getDeclContext()->getRedeclContext() !=
10001           NewFD->getDeclContext()->getRedeclContext()) {
10002     // If there's no previous declaration, AND this isn't attempting to cause
10003     // multiversioning, this isn't an error condition.
10004     if (MVType == MultiVersionKind::None)
10005       return false;
10006     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10007   }
10008 
10009   FunctionDecl *OldFD = OldDecl->getAsFunction();
10010 
10011   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10012     return false;
10013 
10014   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10015     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10016         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10017     NewFD->setInvalidDecl();
10018     return true;
10019   }
10020 
10021   // Handle the target potentially causes multiversioning case.
10022   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10023     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10024                                             Redeclaration, OldDecl,
10025                                             MergeTypeWithPrevious, Previous);
10026 
10027   // At this point, we have a multiversion function decl (in OldFD) AND an
10028   // appropriate attribute in the current function decl.  Resolve that these are
10029   // still compatible with previous declarations.
10030   return CheckMultiVersionAdditionalDecl(
10031       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10032       OldDecl, MergeTypeWithPrevious, Previous);
10033 }
10034 
10035 /// Perform semantic checking of a new function declaration.
10036 ///
10037 /// Performs semantic analysis of the new function declaration
10038 /// NewFD. This routine performs all semantic checking that does not
10039 /// require the actual declarator involved in the declaration, and is
10040 /// used both for the declaration of functions as they are parsed
10041 /// (called via ActOnDeclarator) and for the declaration of functions
10042 /// that have been instantiated via C++ template instantiation (called
10043 /// via InstantiateDecl).
10044 ///
10045 /// \param IsMemberSpecialization whether this new function declaration is
10046 /// a member specialization (that replaces any definition provided by the
10047 /// previous declaration).
10048 ///
10049 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10050 ///
10051 /// \returns true if the function declaration is a redeclaration.
10052 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10053                                     LookupResult &Previous,
10054                                     bool IsMemberSpecialization) {
10055   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10056          "Variably modified return types are not handled here");
10057 
10058   // Determine whether the type of this function should be merged with
10059   // a previous visible declaration. This never happens for functions in C++,
10060   // and always happens in C if the previous declaration was visible.
10061   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10062                                !Previous.isShadowed();
10063 
10064   bool Redeclaration = false;
10065   NamedDecl *OldDecl = nullptr;
10066   bool MayNeedOverloadableChecks = false;
10067 
10068   // Merge or overload the declaration with an existing declaration of
10069   // the same name, if appropriate.
10070   if (!Previous.empty()) {
10071     // Determine whether NewFD is an overload of PrevDecl or
10072     // a declaration that requires merging. If it's an overload,
10073     // there's no more work to do here; we'll just add the new
10074     // function to the scope.
10075     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10076       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10077       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10078         Redeclaration = true;
10079         OldDecl = Candidate;
10080       }
10081     } else {
10082       MayNeedOverloadableChecks = true;
10083       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10084                             /*NewIsUsingDecl*/ false)) {
10085       case Ovl_Match:
10086         Redeclaration = true;
10087         break;
10088 
10089       case Ovl_NonFunction:
10090         Redeclaration = true;
10091         break;
10092 
10093       case Ovl_Overload:
10094         Redeclaration = false;
10095         break;
10096       }
10097     }
10098   }
10099 
10100   // Check for a previous extern "C" declaration with this name.
10101   if (!Redeclaration &&
10102       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10103     if (!Previous.empty()) {
10104       // This is an extern "C" declaration with the same name as a previous
10105       // declaration, and thus redeclares that entity...
10106       Redeclaration = true;
10107       OldDecl = Previous.getFoundDecl();
10108       MergeTypeWithPrevious = false;
10109 
10110       // ... except in the presence of __attribute__((overloadable)).
10111       if (OldDecl->hasAttr<OverloadableAttr>() ||
10112           NewFD->hasAttr<OverloadableAttr>()) {
10113         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10114           MayNeedOverloadableChecks = true;
10115           Redeclaration = false;
10116           OldDecl = nullptr;
10117         }
10118       }
10119     }
10120   }
10121 
10122   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10123                                 MergeTypeWithPrevious, Previous))
10124     return Redeclaration;
10125 
10126   // C++11 [dcl.constexpr]p8:
10127   //   A constexpr specifier for a non-static member function that is not
10128   //   a constructor declares that member function to be const.
10129   //
10130   // This needs to be delayed until we know whether this is an out-of-line
10131   // definition of a static member function.
10132   //
10133   // This rule is not present in C++1y, so we produce a backwards
10134   // compatibility warning whenever it happens in C++11.
10135   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10136   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10137       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10138       !MD->getMethodQualifiers().hasConst()) {
10139     CXXMethodDecl *OldMD = nullptr;
10140     if (OldDecl)
10141       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10142     if (!OldMD || !OldMD->isStatic()) {
10143       const FunctionProtoType *FPT =
10144         MD->getType()->castAs<FunctionProtoType>();
10145       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10146       EPI.TypeQuals.addConst();
10147       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10148                                           FPT->getParamTypes(), EPI));
10149 
10150       // Warn that we did this, if we're not performing template instantiation.
10151       // In that case, we'll have warned already when the template was defined.
10152       if (!inTemplateInstantiation()) {
10153         SourceLocation AddConstLoc;
10154         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10155                 .IgnoreParens().getAs<FunctionTypeLoc>())
10156           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10157 
10158         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10159           << FixItHint::CreateInsertion(AddConstLoc, " const");
10160       }
10161     }
10162   }
10163 
10164   if (Redeclaration) {
10165     // NewFD and OldDecl represent declarations that need to be
10166     // merged.
10167     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10168       NewFD->setInvalidDecl();
10169       return Redeclaration;
10170     }
10171 
10172     Previous.clear();
10173     Previous.addDecl(OldDecl);
10174 
10175     if (FunctionTemplateDecl *OldTemplateDecl =
10176             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10177       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10178       FunctionTemplateDecl *NewTemplateDecl
10179         = NewFD->getDescribedFunctionTemplate();
10180       assert(NewTemplateDecl && "Template/non-template mismatch");
10181 
10182       // The call to MergeFunctionDecl above may have created some state in
10183       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10184       // can add it as a redeclaration.
10185       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10186 
10187       NewFD->setPreviousDeclaration(OldFD);
10188       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10189       if (NewFD->isCXXClassMember()) {
10190         NewFD->setAccess(OldTemplateDecl->getAccess());
10191         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10192       }
10193 
10194       // If this is an explicit specialization of a member that is a function
10195       // template, mark it as a member specialization.
10196       if (IsMemberSpecialization &&
10197           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10198         NewTemplateDecl->setMemberSpecialization();
10199         assert(OldTemplateDecl->isMemberSpecialization());
10200         // Explicit specializations of a member template do not inherit deleted
10201         // status from the parent member template that they are specializing.
10202         if (OldFD->isDeleted()) {
10203           // FIXME: This assert will not hold in the presence of modules.
10204           assert(OldFD->getCanonicalDecl() == OldFD);
10205           // FIXME: We need an update record for this AST mutation.
10206           OldFD->setDeletedAsWritten(false);
10207         }
10208       }
10209 
10210     } else {
10211       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10212         auto *OldFD = cast<FunctionDecl>(OldDecl);
10213         // This needs to happen first so that 'inline' propagates.
10214         NewFD->setPreviousDeclaration(OldFD);
10215         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10216         if (NewFD->isCXXClassMember())
10217           NewFD->setAccess(OldFD->getAccess());
10218       }
10219     }
10220   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10221              !NewFD->getAttr<OverloadableAttr>()) {
10222     assert((Previous.empty() ||
10223             llvm::any_of(Previous,
10224                          [](const NamedDecl *ND) {
10225                            return ND->hasAttr<OverloadableAttr>();
10226                          })) &&
10227            "Non-redecls shouldn't happen without overloadable present");
10228 
10229     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10230       const auto *FD = dyn_cast<FunctionDecl>(ND);
10231       return FD && !FD->hasAttr<OverloadableAttr>();
10232     });
10233 
10234     if (OtherUnmarkedIter != Previous.end()) {
10235       Diag(NewFD->getLocation(),
10236            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10237       Diag((*OtherUnmarkedIter)->getLocation(),
10238            diag::note_attribute_overloadable_prev_overload)
10239           << false;
10240 
10241       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10242     }
10243   }
10244 
10245   // Semantic checking for this function declaration (in isolation).
10246 
10247   if (getLangOpts().CPlusPlus) {
10248     // C++-specific checks.
10249     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10250       CheckConstructor(Constructor);
10251     } else if (CXXDestructorDecl *Destructor =
10252                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10253       CXXRecordDecl *Record = Destructor->getParent();
10254       QualType ClassType = Context.getTypeDeclType(Record);
10255 
10256       // FIXME: Shouldn't we be able to perform this check even when the class
10257       // type is dependent? Both gcc and edg can handle that.
10258       if (!ClassType->isDependentType()) {
10259         DeclarationName Name
10260           = Context.DeclarationNames.getCXXDestructorName(
10261                                         Context.getCanonicalType(ClassType));
10262         if (NewFD->getDeclName() != Name) {
10263           Diag(NewFD->getLocation(), diag::err_destructor_name);
10264           NewFD->setInvalidDecl();
10265           return Redeclaration;
10266         }
10267       }
10268     } else if (CXXConversionDecl *Conversion
10269                = dyn_cast<CXXConversionDecl>(NewFD)) {
10270       ActOnConversionDeclarator(Conversion);
10271     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10272       if (auto *TD = Guide->getDescribedFunctionTemplate())
10273         CheckDeductionGuideTemplate(TD);
10274 
10275       // A deduction guide is not on the list of entities that can be
10276       // explicitly specialized.
10277       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10278         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10279             << /*explicit specialization*/ 1;
10280     }
10281 
10282     // Find any virtual functions that this function overrides.
10283     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10284       if (!Method->isFunctionTemplateSpecialization() &&
10285           !Method->getDescribedFunctionTemplate() &&
10286           Method->isCanonicalDecl()) {
10287         if (AddOverriddenMethods(Method->getParent(), Method)) {
10288           // If the function was marked as "static", we have a problem.
10289           if (NewFD->getStorageClass() == SC_Static) {
10290             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10291           }
10292         }
10293       }
10294 
10295       if (Method->isStatic())
10296         checkThisInStaticMemberFunctionType(Method);
10297     }
10298 
10299     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10300     if (NewFD->isOverloadedOperator() &&
10301         CheckOverloadedOperatorDeclaration(NewFD)) {
10302       NewFD->setInvalidDecl();
10303       return Redeclaration;
10304     }
10305 
10306     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10307     if (NewFD->getLiteralIdentifier() &&
10308         CheckLiteralOperatorDeclaration(NewFD)) {
10309       NewFD->setInvalidDecl();
10310       return Redeclaration;
10311     }
10312 
10313     // In C++, check default arguments now that we have merged decls. Unless
10314     // the lexical context is the class, because in this case this is done
10315     // during delayed parsing anyway.
10316     if (!CurContext->isRecord())
10317       CheckCXXDefaultArguments(NewFD);
10318 
10319     // If this function declares a builtin function, check the type of this
10320     // declaration against the expected type for the builtin.
10321     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10322       ASTContext::GetBuiltinTypeError Error;
10323       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10324       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10325       // If the type of the builtin differs only in its exception
10326       // specification, that's OK.
10327       // FIXME: If the types do differ in this way, it would be better to
10328       // retain the 'noexcept' form of the type.
10329       if (!T.isNull() &&
10330           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10331                                                             NewFD->getType()))
10332         // The type of this function differs from the type of the builtin,
10333         // so forget about the builtin entirely.
10334         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10335     }
10336 
10337     // If this function is declared as being extern "C", then check to see if
10338     // the function returns a UDT (class, struct, or union type) that is not C
10339     // compatible, and if it does, warn the user.
10340     // But, issue any diagnostic on the first declaration only.
10341     if (Previous.empty() && NewFD->isExternC()) {
10342       QualType R = NewFD->getReturnType();
10343       if (R->isIncompleteType() && !R->isVoidType())
10344         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10345             << NewFD << R;
10346       else if (!R.isPODType(Context) && !R->isVoidType() &&
10347                !R->isObjCObjectPointerType())
10348         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10349     }
10350 
10351     // C++1z [dcl.fct]p6:
10352     //   [...] whether the function has a non-throwing exception-specification
10353     //   [is] part of the function type
10354     //
10355     // This results in an ABI break between C++14 and C++17 for functions whose
10356     // declared type includes an exception-specification in a parameter or
10357     // return type. (Exception specifications on the function itself are OK in
10358     // most cases, and exception specifications are not permitted in most other
10359     // contexts where they could make it into a mangling.)
10360     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10361       auto HasNoexcept = [&](QualType T) -> bool {
10362         // Strip off declarator chunks that could be between us and a function
10363         // type. We don't need to look far, exception specifications are very
10364         // restricted prior to C++17.
10365         if (auto *RT = T->getAs<ReferenceType>())
10366           T = RT->getPointeeType();
10367         else if (T->isAnyPointerType())
10368           T = T->getPointeeType();
10369         else if (auto *MPT = T->getAs<MemberPointerType>())
10370           T = MPT->getPointeeType();
10371         if (auto *FPT = T->getAs<FunctionProtoType>())
10372           if (FPT->isNothrow())
10373             return true;
10374         return false;
10375       };
10376 
10377       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10378       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10379       for (QualType T : FPT->param_types())
10380         AnyNoexcept |= HasNoexcept(T);
10381       if (AnyNoexcept)
10382         Diag(NewFD->getLocation(),
10383              diag::warn_cxx17_compat_exception_spec_in_signature)
10384             << NewFD;
10385     }
10386 
10387     if (!Redeclaration && LangOpts.CUDA)
10388       checkCUDATargetOverload(NewFD, Previous);
10389   }
10390   return Redeclaration;
10391 }
10392 
10393 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10394   // C++11 [basic.start.main]p3:
10395   //   A program that [...] declares main to be inline, static or
10396   //   constexpr is ill-formed.
10397   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10398   //   appear in a declaration of main.
10399   // static main is not an error under C99, but we should warn about it.
10400   // We accept _Noreturn main as an extension.
10401   if (FD->getStorageClass() == SC_Static)
10402     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10403          ? diag::err_static_main : diag::warn_static_main)
10404       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10405   if (FD->isInlineSpecified())
10406     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10407       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10408   if (DS.isNoreturnSpecified()) {
10409     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10410     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10411     Diag(NoreturnLoc, diag::ext_noreturn_main);
10412     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10413       << FixItHint::CreateRemoval(NoreturnRange);
10414   }
10415   if (FD->isConstexpr()) {
10416     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10417         << FD->isConsteval()
10418         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10419     FD->setConstexprKind(CSK_unspecified);
10420   }
10421 
10422   if (getLangOpts().OpenCL) {
10423     Diag(FD->getLocation(), diag::err_opencl_no_main)
10424         << FD->hasAttr<OpenCLKernelAttr>();
10425     FD->setInvalidDecl();
10426     return;
10427   }
10428 
10429   QualType T = FD->getType();
10430   assert(T->isFunctionType() && "function decl is not of function type");
10431   const FunctionType* FT = T->castAs<FunctionType>();
10432 
10433   // Set default calling convention for main()
10434   if (FT->getCallConv() != CC_C) {
10435     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10436     FD->setType(QualType(FT, 0));
10437     T = Context.getCanonicalType(FD->getType());
10438   }
10439 
10440   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10441     // In C with GNU extensions we allow main() to have non-integer return
10442     // type, but we should warn about the extension, and we disable the
10443     // implicit-return-zero rule.
10444 
10445     // GCC in C mode accepts qualified 'int'.
10446     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10447       FD->setHasImplicitReturnZero(true);
10448     else {
10449       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10450       SourceRange RTRange = FD->getReturnTypeSourceRange();
10451       if (RTRange.isValid())
10452         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10453             << FixItHint::CreateReplacement(RTRange, "int");
10454     }
10455   } else {
10456     // In C and C++, main magically returns 0 if you fall off the end;
10457     // set the flag which tells us that.
10458     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10459 
10460     // All the standards say that main() should return 'int'.
10461     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10462       FD->setHasImplicitReturnZero(true);
10463     else {
10464       // Otherwise, this is just a flat-out error.
10465       SourceRange RTRange = FD->getReturnTypeSourceRange();
10466       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10467           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10468                                 : FixItHint());
10469       FD->setInvalidDecl(true);
10470     }
10471   }
10472 
10473   // Treat protoless main() as nullary.
10474   if (isa<FunctionNoProtoType>(FT)) return;
10475 
10476   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10477   unsigned nparams = FTP->getNumParams();
10478   assert(FD->getNumParams() == nparams);
10479 
10480   bool HasExtraParameters = (nparams > 3);
10481 
10482   if (FTP->isVariadic()) {
10483     Diag(FD->getLocation(), diag::ext_variadic_main);
10484     // FIXME: if we had information about the location of the ellipsis, we
10485     // could add a FixIt hint to remove it as a parameter.
10486   }
10487 
10488   // Darwin passes an undocumented fourth argument of type char**.  If
10489   // other platforms start sprouting these, the logic below will start
10490   // getting shifty.
10491   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10492     HasExtraParameters = false;
10493 
10494   if (HasExtraParameters) {
10495     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10496     FD->setInvalidDecl(true);
10497     nparams = 3;
10498   }
10499 
10500   // FIXME: a lot of the following diagnostics would be improved
10501   // if we had some location information about types.
10502 
10503   QualType CharPP =
10504     Context.getPointerType(Context.getPointerType(Context.CharTy));
10505   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10506 
10507   for (unsigned i = 0; i < nparams; ++i) {
10508     QualType AT = FTP->getParamType(i);
10509 
10510     bool mismatch = true;
10511 
10512     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10513       mismatch = false;
10514     else if (Expected[i] == CharPP) {
10515       // As an extension, the following forms are okay:
10516       //   char const **
10517       //   char const * const *
10518       //   char * const *
10519 
10520       QualifierCollector qs;
10521       const PointerType* PT;
10522       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10523           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10524           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10525                               Context.CharTy)) {
10526         qs.removeConst();
10527         mismatch = !qs.empty();
10528       }
10529     }
10530 
10531     if (mismatch) {
10532       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10533       // TODO: suggest replacing given type with expected type
10534       FD->setInvalidDecl(true);
10535     }
10536   }
10537 
10538   if (nparams == 1 && !FD->isInvalidDecl()) {
10539     Diag(FD->getLocation(), diag::warn_main_one_arg);
10540   }
10541 
10542   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10543     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10544     FD->setInvalidDecl();
10545   }
10546 }
10547 
10548 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10549   QualType T = FD->getType();
10550   assert(T->isFunctionType() && "function decl is not of function type");
10551   const FunctionType *FT = T->castAs<FunctionType>();
10552 
10553   // Set an implicit return of 'zero' if the function can return some integral,
10554   // enumeration, pointer or nullptr type.
10555   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10556       FT->getReturnType()->isAnyPointerType() ||
10557       FT->getReturnType()->isNullPtrType())
10558     // DllMain is exempt because a return value of zero means it failed.
10559     if (FD->getName() != "DllMain")
10560       FD->setHasImplicitReturnZero(true);
10561 
10562   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10563     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10564     FD->setInvalidDecl();
10565   }
10566 }
10567 
10568 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10569   // FIXME: Need strict checking.  In C89, we need to check for
10570   // any assignment, increment, decrement, function-calls, or
10571   // commas outside of a sizeof.  In C99, it's the same list,
10572   // except that the aforementioned are allowed in unevaluated
10573   // expressions.  Everything else falls under the
10574   // "may accept other forms of constant expressions" exception.
10575   // (We never end up here for C++, so the constant expression
10576   // rules there don't matter.)
10577   const Expr *Culprit;
10578   if (Init->isConstantInitializer(Context, false, &Culprit))
10579     return false;
10580   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10581     << Culprit->getSourceRange();
10582   return true;
10583 }
10584 
10585 namespace {
10586   // Visits an initialization expression to see if OrigDecl is evaluated in
10587   // its own initialization and throws a warning if it does.
10588   class SelfReferenceChecker
10589       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10590     Sema &S;
10591     Decl *OrigDecl;
10592     bool isRecordType;
10593     bool isPODType;
10594     bool isReferenceType;
10595 
10596     bool isInitList;
10597     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10598 
10599   public:
10600     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10601 
10602     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10603                                                     S(S), OrigDecl(OrigDecl) {
10604       isPODType = false;
10605       isRecordType = false;
10606       isReferenceType = false;
10607       isInitList = false;
10608       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10609         isPODType = VD->getType().isPODType(S.Context);
10610         isRecordType = VD->getType()->isRecordType();
10611         isReferenceType = VD->getType()->isReferenceType();
10612       }
10613     }
10614 
10615     // For most expressions, just call the visitor.  For initializer lists,
10616     // track the index of the field being initialized since fields are
10617     // initialized in order allowing use of previously initialized fields.
10618     void CheckExpr(Expr *E) {
10619       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10620       if (!InitList) {
10621         Visit(E);
10622         return;
10623       }
10624 
10625       // Track and increment the index here.
10626       isInitList = true;
10627       InitFieldIndex.push_back(0);
10628       for (auto Child : InitList->children()) {
10629         CheckExpr(cast<Expr>(Child));
10630         ++InitFieldIndex.back();
10631       }
10632       InitFieldIndex.pop_back();
10633     }
10634 
10635     // Returns true if MemberExpr is checked and no further checking is needed.
10636     // Returns false if additional checking is required.
10637     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10638       llvm::SmallVector<FieldDecl*, 4> Fields;
10639       Expr *Base = E;
10640       bool ReferenceField = false;
10641 
10642       // Get the field members used.
10643       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10644         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10645         if (!FD)
10646           return false;
10647         Fields.push_back(FD);
10648         if (FD->getType()->isReferenceType())
10649           ReferenceField = true;
10650         Base = ME->getBase()->IgnoreParenImpCasts();
10651       }
10652 
10653       // Keep checking only if the base Decl is the same.
10654       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10655       if (!DRE || DRE->getDecl() != OrigDecl)
10656         return false;
10657 
10658       // A reference field can be bound to an unininitialized field.
10659       if (CheckReference && !ReferenceField)
10660         return true;
10661 
10662       // Convert FieldDecls to their index number.
10663       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10664       for (const FieldDecl *I : llvm::reverse(Fields))
10665         UsedFieldIndex.push_back(I->getFieldIndex());
10666 
10667       // See if a warning is needed by checking the first difference in index
10668       // numbers.  If field being used has index less than the field being
10669       // initialized, then the use is safe.
10670       for (auto UsedIter = UsedFieldIndex.begin(),
10671                 UsedEnd = UsedFieldIndex.end(),
10672                 OrigIter = InitFieldIndex.begin(),
10673                 OrigEnd = InitFieldIndex.end();
10674            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10675         if (*UsedIter < *OrigIter)
10676           return true;
10677         if (*UsedIter > *OrigIter)
10678           break;
10679       }
10680 
10681       // TODO: Add a different warning which will print the field names.
10682       HandleDeclRefExpr(DRE);
10683       return true;
10684     }
10685 
10686     // For most expressions, the cast is directly above the DeclRefExpr.
10687     // For conditional operators, the cast can be outside the conditional
10688     // operator if both expressions are DeclRefExpr's.
10689     void HandleValue(Expr *E) {
10690       E = E->IgnoreParens();
10691       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10692         HandleDeclRefExpr(DRE);
10693         return;
10694       }
10695 
10696       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10697         Visit(CO->getCond());
10698         HandleValue(CO->getTrueExpr());
10699         HandleValue(CO->getFalseExpr());
10700         return;
10701       }
10702 
10703       if (BinaryConditionalOperator *BCO =
10704               dyn_cast<BinaryConditionalOperator>(E)) {
10705         Visit(BCO->getCond());
10706         HandleValue(BCO->getFalseExpr());
10707         return;
10708       }
10709 
10710       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10711         HandleValue(OVE->getSourceExpr());
10712         return;
10713       }
10714 
10715       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10716         if (BO->getOpcode() == BO_Comma) {
10717           Visit(BO->getLHS());
10718           HandleValue(BO->getRHS());
10719           return;
10720         }
10721       }
10722 
10723       if (isa<MemberExpr>(E)) {
10724         if (isInitList) {
10725           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10726                                       false /*CheckReference*/))
10727             return;
10728         }
10729 
10730         Expr *Base = E->IgnoreParenImpCasts();
10731         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10732           // Check for static member variables and don't warn on them.
10733           if (!isa<FieldDecl>(ME->getMemberDecl()))
10734             return;
10735           Base = ME->getBase()->IgnoreParenImpCasts();
10736         }
10737         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10738           HandleDeclRefExpr(DRE);
10739         return;
10740       }
10741 
10742       Visit(E);
10743     }
10744 
10745     // Reference types not handled in HandleValue are handled here since all
10746     // uses of references are bad, not just r-value uses.
10747     void VisitDeclRefExpr(DeclRefExpr *E) {
10748       if (isReferenceType)
10749         HandleDeclRefExpr(E);
10750     }
10751 
10752     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10753       if (E->getCastKind() == CK_LValueToRValue) {
10754         HandleValue(E->getSubExpr());
10755         return;
10756       }
10757 
10758       Inherited::VisitImplicitCastExpr(E);
10759     }
10760 
10761     void VisitMemberExpr(MemberExpr *E) {
10762       if (isInitList) {
10763         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10764           return;
10765       }
10766 
10767       // Don't warn on arrays since they can be treated as pointers.
10768       if (E->getType()->canDecayToPointerType()) return;
10769 
10770       // Warn when a non-static method call is followed by non-static member
10771       // field accesses, which is followed by a DeclRefExpr.
10772       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10773       bool Warn = (MD && !MD->isStatic());
10774       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10775       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10776         if (!isa<FieldDecl>(ME->getMemberDecl()))
10777           Warn = false;
10778         Base = ME->getBase()->IgnoreParenImpCasts();
10779       }
10780 
10781       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10782         if (Warn)
10783           HandleDeclRefExpr(DRE);
10784         return;
10785       }
10786 
10787       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10788       // Visit that expression.
10789       Visit(Base);
10790     }
10791 
10792     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10793       Expr *Callee = E->getCallee();
10794 
10795       if (isa<UnresolvedLookupExpr>(Callee))
10796         return Inherited::VisitCXXOperatorCallExpr(E);
10797 
10798       Visit(Callee);
10799       for (auto Arg: E->arguments())
10800         HandleValue(Arg->IgnoreParenImpCasts());
10801     }
10802 
10803     void VisitUnaryOperator(UnaryOperator *E) {
10804       // For POD record types, addresses of its own members are well-defined.
10805       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10806           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10807         if (!isPODType)
10808           HandleValue(E->getSubExpr());
10809         return;
10810       }
10811 
10812       if (E->isIncrementDecrementOp()) {
10813         HandleValue(E->getSubExpr());
10814         return;
10815       }
10816 
10817       Inherited::VisitUnaryOperator(E);
10818     }
10819 
10820     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10821 
10822     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10823       if (E->getConstructor()->isCopyConstructor()) {
10824         Expr *ArgExpr = E->getArg(0);
10825         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10826           if (ILE->getNumInits() == 1)
10827             ArgExpr = ILE->getInit(0);
10828         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10829           if (ICE->getCastKind() == CK_NoOp)
10830             ArgExpr = ICE->getSubExpr();
10831         HandleValue(ArgExpr);
10832         return;
10833       }
10834       Inherited::VisitCXXConstructExpr(E);
10835     }
10836 
10837     void VisitCallExpr(CallExpr *E) {
10838       // Treat std::move as a use.
10839       if (E->isCallToStdMove()) {
10840         HandleValue(E->getArg(0));
10841         return;
10842       }
10843 
10844       Inherited::VisitCallExpr(E);
10845     }
10846 
10847     void VisitBinaryOperator(BinaryOperator *E) {
10848       if (E->isCompoundAssignmentOp()) {
10849         HandleValue(E->getLHS());
10850         Visit(E->getRHS());
10851         return;
10852       }
10853 
10854       Inherited::VisitBinaryOperator(E);
10855     }
10856 
10857     // A custom visitor for BinaryConditionalOperator is needed because the
10858     // regular visitor would check the condition and true expression separately
10859     // but both point to the same place giving duplicate diagnostics.
10860     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10861       Visit(E->getCond());
10862       Visit(E->getFalseExpr());
10863     }
10864 
10865     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10866       Decl* ReferenceDecl = DRE->getDecl();
10867       if (OrigDecl != ReferenceDecl) return;
10868       unsigned diag;
10869       if (isReferenceType) {
10870         diag = diag::warn_uninit_self_reference_in_reference_init;
10871       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10872         diag = diag::warn_static_self_reference_in_init;
10873       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10874                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10875                  DRE->getDecl()->getType()->isRecordType()) {
10876         diag = diag::warn_uninit_self_reference_in_init;
10877       } else {
10878         // Local variables will be handled by the CFG analysis.
10879         return;
10880       }
10881 
10882       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10883                             S.PDiag(diag)
10884                                 << DRE->getDecl() << OrigDecl->getLocation()
10885                                 << DRE->getSourceRange());
10886     }
10887   };
10888 
10889   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10890   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10891                                  bool DirectInit) {
10892     // Parameters arguments are occassionially constructed with itself,
10893     // for instance, in recursive functions.  Skip them.
10894     if (isa<ParmVarDecl>(OrigDecl))
10895       return;
10896 
10897     E = E->IgnoreParens();
10898 
10899     // Skip checking T a = a where T is not a record or reference type.
10900     // Doing so is a way to silence uninitialized warnings.
10901     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10902       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10903         if (ICE->getCastKind() == CK_LValueToRValue)
10904           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10905             if (DRE->getDecl() == OrigDecl)
10906               return;
10907 
10908     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10909   }
10910 } // end anonymous namespace
10911 
10912 namespace {
10913   // Simple wrapper to add the name of a variable or (if no variable is
10914   // available) a DeclarationName into a diagnostic.
10915   struct VarDeclOrName {
10916     VarDecl *VDecl;
10917     DeclarationName Name;
10918 
10919     friend const Sema::SemaDiagnosticBuilder &
10920     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10921       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10922     }
10923   };
10924 } // end anonymous namespace
10925 
10926 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10927                                             DeclarationName Name, QualType Type,
10928                                             TypeSourceInfo *TSI,
10929                                             SourceRange Range, bool DirectInit,
10930                                             Expr *Init) {
10931   bool IsInitCapture = !VDecl;
10932   assert((!VDecl || !VDecl->isInitCapture()) &&
10933          "init captures are expected to be deduced prior to initialization");
10934 
10935   VarDeclOrName VN{VDecl, Name};
10936 
10937   DeducedType *Deduced = Type->getContainedDeducedType();
10938   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10939 
10940   // C++11 [dcl.spec.auto]p3
10941   if (!Init) {
10942     assert(VDecl && "no init for init capture deduction?");
10943 
10944     // Except for class argument deduction, and then for an initializing
10945     // declaration only, i.e. no static at class scope or extern.
10946     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10947         VDecl->hasExternalStorage() ||
10948         VDecl->isStaticDataMember()) {
10949       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10950         << VDecl->getDeclName() << Type;
10951       return QualType();
10952     }
10953   }
10954 
10955   ArrayRef<Expr*> DeduceInits;
10956   if (Init)
10957     DeduceInits = Init;
10958 
10959   if (DirectInit) {
10960     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10961       DeduceInits = PL->exprs();
10962   }
10963 
10964   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10965     assert(VDecl && "non-auto type for init capture deduction?");
10966     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10967     InitializationKind Kind = InitializationKind::CreateForInit(
10968         VDecl->getLocation(), DirectInit, Init);
10969     // FIXME: Initialization should not be taking a mutable list of inits.
10970     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10971     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10972                                                        InitsCopy);
10973   }
10974 
10975   if (DirectInit) {
10976     if (auto *IL = dyn_cast<InitListExpr>(Init))
10977       DeduceInits = IL->inits();
10978   }
10979 
10980   // Deduction only works if we have exactly one source expression.
10981   if (DeduceInits.empty()) {
10982     // It isn't possible to write this directly, but it is possible to
10983     // end up in this situation with "auto x(some_pack...);"
10984     Diag(Init->getBeginLoc(), IsInitCapture
10985                                   ? diag::err_init_capture_no_expression
10986                                   : diag::err_auto_var_init_no_expression)
10987         << VN << Type << Range;
10988     return QualType();
10989   }
10990 
10991   if (DeduceInits.size() > 1) {
10992     Diag(DeduceInits[1]->getBeginLoc(),
10993          IsInitCapture ? diag::err_init_capture_multiple_expressions
10994                        : diag::err_auto_var_init_multiple_expressions)
10995         << VN << Type << Range;
10996     return QualType();
10997   }
10998 
10999   Expr *DeduceInit = DeduceInits[0];
11000   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11001     Diag(Init->getBeginLoc(), IsInitCapture
11002                                   ? diag::err_init_capture_paren_braces
11003                                   : diag::err_auto_var_init_paren_braces)
11004         << isa<InitListExpr>(Init) << VN << Type << Range;
11005     return QualType();
11006   }
11007 
11008   // Expressions default to 'id' when we're in a debugger.
11009   bool DefaultedAnyToId = false;
11010   if (getLangOpts().DebuggerCastResultToId &&
11011       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11012     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11013     if (Result.isInvalid()) {
11014       return QualType();
11015     }
11016     Init = Result.get();
11017     DefaultedAnyToId = true;
11018   }
11019 
11020   // C++ [dcl.decomp]p1:
11021   //   If the assignment-expression [...] has array type A and no ref-qualifier
11022   //   is present, e has type cv A
11023   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11024       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11025       DeduceInit->getType()->isConstantArrayType())
11026     return Context.getQualifiedType(DeduceInit->getType(),
11027                                     Type.getQualifiers());
11028 
11029   QualType DeducedType;
11030   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11031     if (!IsInitCapture)
11032       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11033     else if (isa<InitListExpr>(Init))
11034       Diag(Range.getBegin(),
11035            diag::err_init_capture_deduction_failure_from_init_list)
11036           << VN
11037           << (DeduceInit->getType().isNull() ? TSI->getType()
11038                                              : DeduceInit->getType())
11039           << DeduceInit->getSourceRange();
11040     else
11041       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11042           << VN << TSI->getType()
11043           << (DeduceInit->getType().isNull() ? TSI->getType()
11044                                              : DeduceInit->getType())
11045           << DeduceInit->getSourceRange();
11046   }
11047 
11048   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11049   // 'id' instead of a specific object type prevents most of our usual
11050   // checks.
11051   // We only want to warn outside of template instantiations, though:
11052   // inside a template, the 'id' could have come from a parameter.
11053   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11054       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11055     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11056     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11057   }
11058 
11059   return DeducedType;
11060 }
11061 
11062 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11063                                          Expr *Init) {
11064   QualType DeducedType = deduceVarTypeFromInitializer(
11065       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11066       VDecl->getSourceRange(), DirectInit, Init);
11067   if (DeducedType.isNull()) {
11068     VDecl->setInvalidDecl();
11069     return true;
11070   }
11071 
11072   VDecl->setType(DeducedType);
11073   assert(VDecl->isLinkageValid());
11074 
11075   // In ARC, infer lifetime.
11076   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11077     VDecl->setInvalidDecl();
11078 
11079   // If this is a redeclaration, check that the type we just deduced matches
11080   // the previously declared type.
11081   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11082     // We never need to merge the type, because we cannot form an incomplete
11083     // array of auto, nor deduce such a type.
11084     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11085   }
11086 
11087   // Check the deduced type is valid for a variable declaration.
11088   CheckVariableDeclarationType(VDecl);
11089   return VDecl->isInvalidDecl();
11090 }
11091 
11092 /// AddInitializerToDecl - Adds the initializer Init to the
11093 /// declaration dcl. If DirectInit is true, this is C++ direct
11094 /// initialization rather than copy initialization.
11095 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11096   // If there is no declaration, there was an error parsing it.  Just ignore
11097   // the initializer.
11098   if (!RealDecl || RealDecl->isInvalidDecl()) {
11099     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11100     return;
11101   }
11102 
11103   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11104     // Pure-specifiers are handled in ActOnPureSpecifier.
11105     Diag(Method->getLocation(), diag::err_member_function_initialization)
11106       << Method->getDeclName() << Init->getSourceRange();
11107     Method->setInvalidDecl();
11108     return;
11109   }
11110 
11111   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11112   if (!VDecl) {
11113     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11114     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11115     RealDecl->setInvalidDecl();
11116     return;
11117   }
11118 
11119   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11120   if (VDecl->getType()->isUndeducedType()) {
11121     // Attempt typo correction early so that the type of the init expression can
11122     // be deduced based on the chosen correction if the original init contains a
11123     // TypoExpr.
11124     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11125     if (!Res.isUsable()) {
11126       RealDecl->setInvalidDecl();
11127       return;
11128     }
11129     Init = Res.get();
11130 
11131     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11132       return;
11133   }
11134 
11135   // dllimport cannot be used on variable definitions.
11136   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11137     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11138     VDecl->setInvalidDecl();
11139     return;
11140   }
11141 
11142   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11143     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11144     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11145     VDecl->setInvalidDecl();
11146     return;
11147   }
11148 
11149   if (!VDecl->getType()->isDependentType()) {
11150     // A definition must end up with a complete type, which means it must be
11151     // complete with the restriction that an array type might be completed by
11152     // the initializer; note that later code assumes this restriction.
11153     QualType BaseDeclType = VDecl->getType();
11154     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11155       BaseDeclType = Array->getElementType();
11156     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11157                             diag::err_typecheck_decl_incomplete_type)) {
11158       RealDecl->setInvalidDecl();
11159       return;
11160     }
11161 
11162     // The variable can not have an abstract class type.
11163     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11164                                diag::err_abstract_type_in_decl,
11165                                AbstractVariableType))
11166       VDecl->setInvalidDecl();
11167   }
11168 
11169   // If adding the initializer will turn this declaration into a definition,
11170   // and we already have a definition for this variable, diagnose or otherwise
11171   // handle the situation.
11172   VarDecl *Def;
11173   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11174       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11175       !VDecl->isThisDeclarationADemotedDefinition() &&
11176       checkVarDeclRedefinition(Def, VDecl))
11177     return;
11178 
11179   if (getLangOpts().CPlusPlus) {
11180     // C++ [class.static.data]p4
11181     //   If a static data member is of const integral or const
11182     //   enumeration type, its declaration in the class definition can
11183     //   specify a constant-initializer which shall be an integral
11184     //   constant expression (5.19). In that case, the member can appear
11185     //   in integral constant expressions. The member shall still be
11186     //   defined in a namespace scope if it is used in the program and the
11187     //   namespace scope definition shall not contain an initializer.
11188     //
11189     // We already performed a redefinition check above, but for static
11190     // data members we also need to check whether there was an in-class
11191     // declaration with an initializer.
11192     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11193       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11194           << VDecl->getDeclName();
11195       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11196            diag::note_previous_initializer)
11197           << 0;
11198       return;
11199     }
11200 
11201     if (VDecl->hasLocalStorage())
11202       setFunctionHasBranchProtectedScope();
11203 
11204     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11205       VDecl->setInvalidDecl();
11206       return;
11207     }
11208   }
11209 
11210   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11211   // a kernel function cannot be initialized."
11212   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11213     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11214     VDecl->setInvalidDecl();
11215     return;
11216   }
11217 
11218   // Get the decls type and save a reference for later, since
11219   // CheckInitializerTypes may change it.
11220   QualType DclT = VDecl->getType(), SavT = DclT;
11221 
11222   // Expressions default to 'id' when we're in a debugger
11223   // and we are assigning it to a variable of Objective-C pointer type.
11224   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11225       Init->getType() == Context.UnknownAnyTy) {
11226     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11227     if (Result.isInvalid()) {
11228       VDecl->setInvalidDecl();
11229       return;
11230     }
11231     Init = Result.get();
11232   }
11233 
11234   // Perform the initialization.
11235   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11236   if (!VDecl->isInvalidDecl()) {
11237     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11238     InitializationKind Kind = InitializationKind::CreateForInit(
11239         VDecl->getLocation(), DirectInit, Init);
11240 
11241     MultiExprArg Args = Init;
11242     if (CXXDirectInit)
11243       Args = MultiExprArg(CXXDirectInit->getExprs(),
11244                           CXXDirectInit->getNumExprs());
11245 
11246     // Try to correct any TypoExprs in the initialization arguments.
11247     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11248       ExprResult Res = CorrectDelayedTyposInExpr(
11249           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11250             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11251             return Init.Failed() ? ExprError() : E;
11252           });
11253       if (Res.isInvalid()) {
11254         VDecl->setInvalidDecl();
11255       } else if (Res.get() != Args[Idx]) {
11256         Args[Idx] = Res.get();
11257       }
11258     }
11259     if (VDecl->isInvalidDecl())
11260       return;
11261 
11262     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11263                                    /*TopLevelOfInitList=*/false,
11264                                    /*TreatUnavailableAsInvalid=*/false);
11265     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11266     if (Result.isInvalid()) {
11267       VDecl->setInvalidDecl();
11268       return;
11269     }
11270 
11271     Init = Result.getAs<Expr>();
11272   }
11273 
11274   // Check for self-references within variable initializers.
11275   // Variables declared within a function/method body (except for references)
11276   // are handled by a dataflow analysis.
11277   // This is undefined behavior in C++, but valid in C.
11278   if (getLangOpts().CPlusPlus) {
11279     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11280         VDecl->getType()->isReferenceType()) {
11281       CheckSelfReference(*this, RealDecl, Init, DirectInit);
11282     }
11283   }
11284 
11285   // If the type changed, it means we had an incomplete type that was
11286   // completed by the initializer. For example:
11287   //   int ary[] = { 1, 3, 5 };
11288   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11289   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11290     VDecl->setType(DclT);
11291 
11292   if (!VDecl->isInvalidDecl()) {
11293     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11294 
11295     if (VDecl->hasAttr<BlocksAttr>())
11296       checkRetainCycles(VDecl, Init);
11297 
11298     // It is safe to assign a weak reference into a strong variable.
11299     // Although this code can still have problems:
11300     //   id x = self.weakProp;
11301     //   id y = self.weakProp;
11302     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11303     // paths through the function. This should be revisited if
11304     // -Wrepeated-use-of-weak is made flow-sensitive.
11305     if (FunctionScopeInfo *FSI = getCurFunction())
11306       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11307            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11308           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11309                            Init->getBeginLoc()))
11310         FSI->markSafeWeakUse(Init);
11311   }
11312 
11313   // The initialization is usually a full-expression.
11314   //
11315   // FIXME: If this is a braced initialization of an aggregate, it is not
11316   // an expression, and each individual field initializer is a separate
11317   // full-expression. For instance, in:
11318   //
11319   //   struct Temp { ~Temp(); };
11320   //   struct S { S(Temp); };
11321   //   struct T { S a, b; } t = { Temp(), Temp() }
11322   //
11323   // we should destroy the first Temp before constructing the second.
11324   ExprResult Result =
11325       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11326                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11327   if (Result.isInvalid()) {
11328     VDecl->setInvalidDecl();
11329     return;
11330   }
11331   Init = Result.get();
11332 
11333   // Attach the initializer to the decl.
11334   VDecl->setInit(Init);
11335 
11336   if (VDecl->isLocalVarDecl()) {
11337     // Don't check the initializer if the declaration is malformed.
11338     if (VDecl->isInvalidDecl()) {
11339       // do nothing
11340 
11341     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11342     // This is true even in C++ for OpenCL.
11343     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11344       CheckForConstantInitializer(Init, DclT);
11345 
11346     // Otherwise, C++ does not restrict the initializer.
11347     } else if (getLangOpts().CPlusPlus) {
11348       // do nothing
11349 
11350     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11351     // static storage duration shall be constant expressions or string literals.
11352     } else if (VDecl->getStorageClass() == SC_Static) {
11353       CheckForConstantInitializer(Init, DclT);
11354 
11355     // C89 is stricter than C99 for aggregate initializers.
11356     // C89 6.5.7p3: All the expressions [...] in an initializer list
11357     // for an object that has aggregate or union type shall be
11358     // constant expressions.
11359     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11360                isa<InitListExpr>(Init)) {
11361       const Expr *Culprit;
11362       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11363         Diag(Culprit->getExprLoc(),
11364              diag::ext_aggregate_init_not_constant)
11365           << Culprit->getSourceRange();
11366       }
11367     }
11368 
11369     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11370       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11371         if (VDecl->hasLocalStorage())
11372           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11373   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11374              VDecl->getLexicalDeclContext()->isRecord()) {
11375     // This is an in-class initialization for a static data member, e.g.,
11376     //
11377     // struct S {
11378     //   static const int value = 17;
11379     // };
11380 
11381     // C++ [class.mem]p4:
11382     //   A member-declarator can contain a constant-initializer only
11383     //   if it declares a static member (9.4) of const integral or
11384     //   const enumeration type, see 9.4.2.
11385     //
11386     // C++11 [class.static.data]p3:
11387     //   If a non-volatile non-inline const static data member is of integral
11388     //   or enumeration type, its declaration in the class definition can
11389     //   specify a brace-or-equal-initializer in which every initializer-clause
11390     //   that is an assignment-expression is a constant expression. A static
11391     //   data member of literal type can be declared in the class definition
11392     //   with the constexpr specifier; if so, its declaration shall specify a
11393     //   brace-or-equal-initializer in which every initializer-clause that is
11394     //   an assignment-expression is a constant expression.
11395 
11396     // Do nothing on dependent types.
11397     if (DclT->isDependentType()) {
11398 
11399     // Allow any 'static constexpr' members, whether or not they are of literal
11400     // type. We separately check that every constexpr variable is of literal
11401     // type.
11402     } else if (VDecl->isConstexpr()) {
11403 
11404     // Require constness.
11405     } else if (!DclT.isConstQualified()) {
11406       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11407         << Init->getSourceRange();
11408       VDecl->setInvalidDecl();
11409 
11410     // We allow integer constant expressions in all cases.
11411     } else if (DclT->isIntegralOrEnumerationType()) {
11412       // Check whether the expression is a constant expression.
11413       SourceLocation Loc;
11414       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11415         // In C++11, a non-constexpr const static data member with an
11416         // in-class initializer cannot be volatile.
11417         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11418       else if (Init->isValueDependent())
11419         ; // Nothing to check.
11420       else if (Init->isIntegerConstantExpr(Context, &Loc))
11421         ; // Ok, it's an ICE!
11422       else if (Init->getType()->isScopedEnumeralType() &&
11423                Init->isCXX11ConstantExpr(Context))
11424         ; // Ok, it is a scoped-enum constant expression.
11425       else if (Init->isEvaluatable(Context)) {
11426         // If we can constant fold the initializer through heroics, accept it,
11427         // but report this as a use of an extension for -pedantic.
11428         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11429           << Init->getSourceRange();
11430       } else {
11431         // Otherwise, this is some crazy unknown case.  Report the issue at the
11432         // location provided by the isIntegerConstantExpr failed check.
11433         Diag(Loc, diag::err_in_class_initializer_non_constant)
11434           << Init->getSourceRange();
11435         VDecl->setInvalidDecl();
11436       }
11437 
11438     // We allow foldable floating-point constants as an extension.
11439     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11440       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11441       // it anyway and provide a fixit to add the 'constexpr'.
11442       if (getLangOpts().CPlusPlus11) {
11443         Diag(VDecl->getLocation(),
11444              diag::ext_in_class_initializer_float_type_cxx11)
11445             << DclT << Init->getSourceRange();
11446         Diag(VDecl->getBeginLoc(),
11447              diag::note_in_class_initializer_float_type_cxx11)
11448             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11449       } else {
11450         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11451           << DclT << Init->getSourceRange();
11452 
11453         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11454           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11455             << Init->getSourceRange();
11456           VDecl->setInvalidDecl();
11457         }
11458       }
11459 
11460     // Suggest adding 'constexpr' in C++11 for literal types.
11461     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11462       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11463           << DclT << Init->getSourceRange()
11464           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11465       VDecl->setConstexpr(true);
11466 
11467     } else {
11468       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11469         << DclT << Init->getSourceRange();
11470       VDecl->setInvalidDecl();
11471     }
11472   } else if (VDecl->isFileVarDecl()) {
11473     // In C, extern is typically used to avoid tentative definitions when
11474     // declaring variables in headers, but adding an intializer makes it a
11475     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11476     // In C++, extern is often used to give implictly static const variables
11477     // external linkage, so don't warn in that case. If selectany is present,
11478     // this might be header code intended for C and C++ inclusion, so apply the
11479     // C++ rules.
11480     if (VDecl->getStorageClass() == SC_Extern &&
11481         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11482          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11483         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11484         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11485       Diag(VDecl->getLocation(), diag::warn_extern_init);
11486 
11487     // In Microsoft C++ mode, a const variable defined in namespace scope has
11488     // external linkage by default if the variable is declared with
11489     // __declspec(dllexport).
11490     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11491         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11492         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11493       VDecl->setStorageClass(SC_Extern);
11494 
11495     // C99 6.7.8p4. All file scoped initializers need to be constant.
11496     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11497       CheckForConstantInitializer(Init, DclT);
11498   }
11499 
11500   // We will represent direct-initialization similarly to copy-initialization:
11501   //    int x(1);  -as-> int x = 1;
11502   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11503   //
11504   // Clients that want to distinguish between the two forms, can check for
11505   // direct initializer using VarDecl::getInitStyle().
11506   // A major benefit is that clients that don't particularly care about which
11507   // exactly form was it (like the CodeGen) can handle both cases without
11508   // special case code.
11509 
11510   // C++ 8.5p11:
11511   // The form of initialization (using parentheses or '=') is generally
11512   // insignificant, but does matter when the entity being initialized has a
11513   // class type.
11514   if (CXXDirectInit) {
11515     assert(DirectInit && "Call-style initializer must be direct init.");
11516     VDecl->setInitStyle(VarDecl::CallInit);
11517   } else if (DirectInit) {
11518     // This must be list-initialization. No other way is direct-initialization.
11519     VDecl->setInitStyle(VarDecl::ListInit);
11520   }
11521 
11522   CheckCompleteVariableDeclaration(VDecl);
11523 }
11524 
11525 /// ActOnInitializerError - Given that there was an error parsing an
11526 /// initializer for the given declaration, try to return to some form
11527 /// of sanity.
11528 void Sema::ActOnInitializerError(Decl *D) {
11529   // Our main concern here is re-establishing invariants like "a
11530   // variable's type is either dependent or complete".
11531   if (!D || D->isInvalidDecl()) return;
11532 
11533   VarDecl *VD = dyn_cast<VarDecl>(D);
11534   if (!VD) return;
11535 
11536   // Bindings are not usable if we can't make sense of the initializer.
11537   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11538     for (auto *BD : DD->bindings())
11539       BD->setInvalidDecl();
11540 
11541   // Auto types are meaningless if we can't make sense of the initializer.
11542   if (ParsingInitForAutoVars.count(D)) {
11543     D->setInvalidDecl();
11544     return;
11545   }
11546 
11547   QualType Ty = VD->getType();
11548   if (Ty->isDependentType()) return;
11549 
11550   // Require a complete type.
11551   if (RequireCompleteType(VD->getLocation(),
11552                           Context.getBaseElementType(Ty),
11553                           diag::err_typecheck_decl_incomplete_type)) {
11554     VD->setInvalidDecl();
11555     return;
11556   }
11557 
11558   // Require a non-abstract type.
11559   if (RequireNonAbstractType(VD->getLocation(), Ty,
11560                              diag::err_abstract_type_in_decl,
11561                              AbstractVariableType)) {
11562     VD->setInvalidDecl();
11563     return;
11564   }
11565 
11566   // Don't bother complaining about constructors or destructors,
11567   // though.
11568 }
11569 
11570 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11571   // If there is no declaration, there was an error parsing it. Just ignore it.
11572   if (!RealDecl)
11573     return;
11574 
11575   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11576     QualType Type = Var->getType();
11577 
11578     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11579     if (isa<DecompositionDecl>(RealDecl)) {
11580       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11581       Var->setInvalidDecl();
11582       return;
11583     }
11584 
11585     if (Type->isUndeducedType() &&
11586         DeduceVariableDeclarationType(Var, false, nullptr))
11587       return;
11588 
11589     // C++11 [class.static.data]p3: A static data member can be declared with
11590     // the constexpr specifier; if so, its declaration shall specify
11591     // a brace-or-equal-initializer.
11592     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11593     // the definition of a variable [...] or the declaration of a static data
11594     // member.
11595     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11596         !Var->isThisDeclarationADemotedDefinition()) {
11597       if (Var->isStaticDataMember()) {
11598         // C++1z removes the relevant rule; the in-class declaration is always
11599         // a definition there.
11600         if (!getLangOpts().CPlusPlus17) {
11601           Diag(Var->getLocation(),
11602                diag::err_constexpr_static_mem_var_requires_init)
11603             << Var->getDeclName();
11604           Var->setInvalidDecl();
11605           return;
11606         }
11607       } else {
11608         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11609         Var->setInvalidDecl();
11610         return;
11611       }
11612     }
11613 
11614     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11615     // be initialized.
11616     if (!Var->isInvalidDecl() &&
11617         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11618         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11619       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11620       Var->setInvalidDecl();
11621       return;
11622     }
11623 
11624     switch (Var->isThisDeclarationADefinition()) {
11625     case VarDecl::Definition:
11626       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11627         break;
11628 
11629       // We have an out-of-line definition of a static data member
11630       // that has an in-class initializer, so we type-check this like
11631       // a declaration.
11632       //
11633       LLVM_FALLTHROUGH;
11634 
11635     case VarDecl::DeclarationOnly:
11636       // It's only a declaration.
11637 
11638       // Block scope. C99 6.7p7: If an identifier for an object is
11639       // declared with no linkage (C99 6.2.2p6), the type for the
11640       // object shall be complete.
11641       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11642           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11643           RequireCompleteType(Var->getLocation(), Type,
11644                               diag::err_typecheck_decl_incomplete_type))
11645         Var->setInvalidDecl();
11646 
11647       // Make sure that the type is not abstract.
11648       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11649           RequireNonAbstractType(Var->getLocation(), Type,
11650                                  diag::err_abstract_type_in_decl,
11651                                  AbstractVariableType))
11652         Var->setInvalidDecl();
11653       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11654           Var->getStorageClass() == SC_PrivateExtern) {
11655         Diag(Var->getLocation(), diag::warn_private_extern);
11656         Diag(Var->getLocation(), diag::note_private_extern);
11657       }
11658 
11659       return;
11660 
11661     case VarDecl::TentativeDefinition:
11662       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11663       // object that has file scope without an initializer, and without a
11664       // storage-class specifier or with the storage-class specifier "static",
11665       // constitutes a tentative definition. Note: A tentative definition with
11666       // external linkage is valid (C99 6.2.2p5).
11667       if (!Var->isInvalidDecl()) {
11668         if (const IncompleteArrayType *ArrayT
11669                                     = Context.getAsIncompleteArrayType(Type)) {
11670           if (RequireCompleteType(Var->getLocation(),
11671                                   ArrayT->getElementType(),
11672                                   diag::err_illegal_decl_array_incomplete_type))
11673             Var->setInvalidDecl();
11674         } else if (Var->getStorageClass() == SC_Static) {
11675           // C99 6.9.2p3: If the declaration of an identifier for an object is
11676           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11677           // declared type shall not be an incomplete type.
11678           // NOTE: code such as the following
11679           //     static struct s;
11680           //     struct s { int a; };
11681           // is accepted by gcc. Hence here we issue a warning instead of
11682           // an error and we do not invalidate the static declaration.
11683           // NOTE: to avoid multiple warnings, only check the first declaration.
11684           if (Var->isFirstDecl())
11685             RequireCompleteType(Var->getLocation(), Type,
11686                                 diag::ext_typecheck_decl_incomplete_type);
11687         }
11688       }
11689 
11690       // Record the tentative definition; we're done.
11691       if (!Var->isInvalidDecl())
11692         TentativeDefinitions.push_back(Var);
11693       return;
11694     }
11695 
11696     // Provide a specific diagnostic for uninitialized variable
11697     // definitions with incomplete array type.
11698     if (Type->isIncompleteArrayType()) {
11699       Diag(Var->getLocation(),
11700            diag::err_typecheck_incomplete_array_needs_initializer);
11701       Var->setInvalidDecl();
11702       return;
11703     }
11704 
11705     // Provide a specific diagnostic for uninitialized variable
11706     // definitions with reference type.
11707     if (Type->isReferenceType()) {
11708       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11709         << Var->getDeclName()
11710         << SourceRange(Var->getLocation(), Var->getLocation());
11711       Var->setInvalidDecl();
11712       return;
11713     }
11714 
11715     // Do not attempt to type-check the default initializer for a
11716     // variable with dependent type.
11717     if (Type->isDependentType())
11718       return;
11719 
11720     if (Var->isInvalidDecl())
11721       return;
11722 
11723     if (!Var->hasAttr<AliasAttr>()) {
11724       if (RequireCompleteType(Var->getLocation(),
11725                               Context.getBaseElementType(Type),
11726                               diag::err_typecheck_decl_incomplete_type)) {
11727         Var->setInvalidDecl();
11728         return;
11729       }
11730     } else {
11731       return;
11732     }
11733 
11734     // The variable can not have an abstract class type.
11735     if (RequireNonAbstractType(Var->getLocation(), Type,
11736                                diag::err_abstract_type_in_decl,
11737                                AbstractVariableType)) {
11738       Var->setInvalidDecl();
11739       return;
11740     }
11741 
11742     // Check for jumps past the implicit initializer.  C++0x
11743     // clarifies that this applies to a "variable with automatic
11744     // storage duration", not a "local variable".
11745     // C++11 [stmt.dcl]p3
11746     //   A program that jumps from a point where a variable with automatic
11747     //   storage duration is not in scope to a point where it is in scope is
11748     //   ill-formed unless the variable has scalar type, class type with a
11749     //   trivial default constructor and a trivial destructor, a cv-qualified
11750     //   version of one of these types, or an array of one of the preceding
11751     //   types and is declared without an initializer.
11752     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11753       if (const RecordType *Record
11754             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11755         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11756         // Mark the function (if we're in one) for further checking even if the
11757         // looser rules of C++11 do not require such checks, so that we can
11758         // diagnose incompatibilities with C++98.
11759         if (!CXXRecord->isPOD())
11760           setFunctionHasBranchProtectedScope();
11761       }
11762     }
11763     // In OpenCL, we can't initialize objects in the __local address space,
11764     // even implicitly, so don't synthesize an implicit initializer.
11765     if (getLangOpts().OpenCL &&
11766         Var->getType().getAddressSpace() == LangAS::opencl_local)
11767       return;
11768     // C++03 [dcl.init]p9:
11769     //   If no initializer is specified for an object, and the
11770     //   object is of (possibly cv-qualified) non-POD class type (or
11771     //   array thereof), the object shall be default-initialized; if
11772     //   the object is of const-qualified type, the underlying class
11773     //   type shall have a user-declared default
11774     //   constructor. Otherwise, if no initializer is specified for
11775     //   a non- static object, the object and its subobjects, if
11776     //   any, have an indeterminate initial value); if the object
11777     //   or any of its subobjects are of const-qualified type, the
11778     //   program is ill-formed.
11779     // C++0x [dcl.init]p11:
11780     //   If no initializer is specified for an object, the object is
11781     //   default-initialized; [...].
11782     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11783     InitializationKind Kind
11784       = InitializationKind::CreateDefault(Var->getLocation());
11785 
11786     InitializationSequence InitSeq(*this, Entity, Kind, None);
11787     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11788     if (Init.isInvalid())
11789       Var->setInvalidDecl();
11790     else if (Init.get()) {
11791       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11792       // This is important for template substitution.
11793       Var->setInitStyle(VarDecl::CallInit);
11794     }
11795 
11796     CheckCompleteVariableDeclaration(Var);
11797   }
11798 }
11799 
11800 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11801   // If there is no declaration, there was an error parsing it. Ignore it.
11802   if (!D)
11803     return;
11804 
11805   VarDecl *VD = dyn_cast<VarDecl>(D);
11806   if (!VD) {
11807     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11808     D->setInvalidDecl();
11809     return;
11810   }
11811 
11812   VD->setCXXForRangeDecl(true);
11813 
11814   // for-range-declaration cannot be given a storage class specifier.
11815   int Error = -1;
11816   switch (VD->getStorageClass()) {
11817   case SC_None:
11818     break;
11819   case SC_Extern:
11820     Error = 0;
11821     break;
11822   case SC_Static:
11823     Error = 1;
11824     break;
11825   case SC_PrivateExtern:
11826     Error = 2;
11827     break;
11828   case SC_Auto:
11829     Error = 3;
11830     break;
11831   case SC_Register:
11832     Error = 4;
11833     break;
11834   }
11835   if (Error != -1) {
11836     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11837       << VD->getDeclName() << Error;
11838     D->setInvalidDecl();
11839   }
11840 }
11841 
11842 StmtResult
11843 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11844                                  IdentifierInfo *Ident,
11845                                  ParsedAttributes &Attrs,
11846                                  SourceLocation AttrEnd) {
11847   // C++1y [stmt.iter]p1:
11848   //   A range-based for statement of the form
11849   //      for ( for-range-identifier : for-range-initializer ) statement
11850   //   is equivalent to
11851   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11852   DeclSpec DS(Attrs.getPool().getFactory());
11853 
11854   const char *PrevSpec;
11855   unsigned DiagID;
11856   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11857                      getPrintingPolicy());
11858 
11859   Declarator D(DS, DeclaratorContext::ForContext);
11860   D.SetIdentifier(Ident, IdentLoc);
11861   D.takeAttributes(Attrs, AttrEnd);
11862 
11863   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11864                 IdentLoc);
11865   Decl *Var = ActOnDeclarator(S, D);
11866   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11867   FinalizeDeclaration(Var);
11868   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11869                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11870 }
11871 
11872 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11873   if (var->isInvalidDecl()) return;
11874 
11875   if (getLangOpts().OpenCL) {
11876     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11877     // initialiser
11878     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11879         !var->hasInit()) {
11880       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11881           << 1 /*Init*/;
11882       var->setInvalidDecl();
11883       return;
11884     }
11885   }
11886 
11887   // In Objective-C, don't allow jumps past the implicit initialization of a
11888   // local retaining variable.
11889   if (getLangOpts().ObjC &&
11890       var->hasLocalStorage()) {
11891     switch (var->getType().getObjCLifetime()) {
11892     case Qualifiers::OCL_None:
11893     case Qualifiers::OCL_ExplicitNone:
11894     case Qualifiers::OCL_Autoreleasing:
11895       break;
11896 
11897     case Qualifiers::OCL_Weak:
11898     case Qualifiers::OCL_Strong:
11899       setFunctionHasBranchProtectedScope();
11900       break;
11901     }
11902   }
11903 
11904   if (var->hasLocalStorage() &&
11905       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11906     setFunctionHasBranchProtectedScope();
11907 
11908   // Warn about externally-visible variables being defined without a
11909   // prior declaration.  We only want to do this for global
11910   // declarations, but we also specifically need to avoid doing it for
11911   // class members because the linkage of an anonymous class can
11912   // change if it's later given a typedef name.
11913   if (var->isThisDeclarationADefinition() &&
11914       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11915       var->isExternallyVisible() && var->hasLinkage() &&
11916       !var->isInline() && !var->getDescribedVarTemplate() &&
11917       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11918       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11919                                   var->getLocation())) {
11920     // Find a previous declaration that's not a definition.
11921     VarDecl *prev = var->getPreviousDecl();
11922     while (prev && prev->isThisDeclarationADefinition())
11923       prev = prev->getPreviousDecl();
11924 
11925     if (!prev) {
11926       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11927       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
11928           << /* variable */ 0;
11929     }
11930   }
11931 
11932   // Cache the result of checking for constant initialization.
11933   Optional<bool> CacheHasConstInit;
11934   const Expr *CacheCulprit = nullptr;
11935   auto checkConstInit = [&]() mutable {
11936     if (!CacheHasConstInit)
11937       CacheHasConstInit = var->getInit()->isConstantInitializer(
11938             Context, var->getType()->isReferenceType(), &CacheCulprit);
11939     return *CacheHasConstInit;
11940   };
11941 
11942   if (var->getTLSKind() == VarDecl::TLS_Static) {
11943     if (var->getType().isDestructedType()) {
11944       // GNU C++98 edits for __thread, [basic.start.term]p3:
11945       //   The type of an object with thread storage duration shall not
11946       //   have a non-trivial destructor.
11947       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11948       if (getLangOpts().CPlusPlus11)
11949         Diag(var->getLocation(), diag::note_use_thread_local);
11950     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11951       if (!checkConstInit()) {
11952         // GNU C++98 edits for __thread, [basic.start.init]p4:
11953         //   An object of thread storage duration shall not require dynamic
11954         //   initialization.
11955         // FIXME: Need strict checking here.
11956         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11957           << CacheCulprit->getSourceRange();
11958         if (getLangOpts().CPlusPlus11)
11959           Diag(var->getLocation(), diag::note_use_thread_local);
11960       }
11961     }
11962   }
11963 
11964   // Apply section attributes and pragmas to global variables.
11965   bool GlobalStorage = var->hasGlobalStorage();
11966   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11967       !inTemplateInstantiation()) {
11968     PragmaStack<StringLiteral *> *Stack = nullptr;
11969     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11970     if (var->getType().isConstQualified())
11971       Stack = &ConstSegStack;
11972     else if (!var->getInit()) {
11973       Stack = &BSSSegStack;
11974       SectionFlags |= ASTContext::PSF_Write;
11975     } else {
11976       Stack = &DataSegStack;
11977       SectionFlags |= ASTContext::PSF_Write;
11978     }
11979     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11980       var->addAttr(SectionAttr::CreateImplicit(
11981           Context, SectionAttr::Declspec_allocate,
11982           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11983     }
11984     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11985       if (UnifySection(SA->getName(), SectionFlags, var))
11986         var->dropAttr<SectionAttr>();
11987 
11988     // Apply the init_seg attribute if this has an initializer.  If the
11989     // initializer turns out to not be dynamic, we'll end up ignoring this
11990     // attribute.
11991     if (CurInitSeg && var->getInit())
11992       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11993                                                CurInitSegLoc));
11994   }
11995 
11996   // All the following checks are C++ only.
11997   if (!getLangOpts().CPlusPlus) {
11998       // If this variable must be emitted, add it as an initializer for the
11999       // current module.
12000      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12001        Context.addModuleInitializer(ModuleScopes.back().Module, var);
12002      return;
12003   }
12004 
12005   if (auto *DD = dyn_cast<DecompositionDecl>(var))
12006     CheckCompleteDecompositionDeclaration(DD);
12007 
12008   QualType type = var->getType();
12009   if (type->isDependentType()) return;
12010 
12011   if (var->hasAttr<BlocksAttr>())
12012     getCurFunction()->addByrefBlockVar(var);
12013 
12014   Expr *Init = var->getInit();
12015   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12016   QualType baseType = Context.getBaseElementType(type);
12017 
12018   if (Init && !Init->isValueDependent()) {
12019     if (var->isConstexpr()) {
12020       SmallVector<PartialDiagnosticAt, 8> Notes;
12021       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12022         SourceLocation DiagLoc = var->getLocation();
12023         // If the note doesn't add any useful information other than a source
12024         // location, fold it into the primary diagnostic.
12025         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12026               diag::note_invalid_subexpr_in_const_expr) {
12027           DiagLoc = Notes[0].first;
12028           Notes.clear();
12029         }
12030         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12031           << var << Init->getSourceRange();
12032         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12033           Diag(Notes[I].first, Notes[I].second);
12034       }
12035     } else if (var->mightBeUsableInConstantExpressions(Context)) {
12036       // Check whether the initializer of a const variable of integral or
12037       // enumeration type is an ICE now, since we can't tell whether it was
12038       // initialized by a constant expression if we check later.
12039       var->checkInitIsICE();
12040     }
12041 
12042     // Don't emit further diagnostics about constexpr globals since they
12043     // were just diagnosed.
12044     if (!var->isConstexpr() && GlobalStorage &&
12045             var->hasAttr<RequireConstantInitAttr>()) {
12046       // FIXME: Need strict checking in C++03 here.
12047       bool DiagErr = getLangOpts().CPlusPlus11
12048           ? !var->checkInitIsICE() : !checkConstInit();
12049       if (DiagErr) {
12050         auto attr = var->getAttr<RequireConstantInitAttr>();
12051         Diag(var->getLocation(), diag::err_require_constant_init_failed)
12052           << Init->getSourceRange();
12053         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
12054           << attr->getRange();
12055         if (getLangOpts().CPlusPlus11) {
12056           APValue Value;
12057           SmallVector<PartialDiagnosticAt, 8> Notes;
12058           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
12059           for (auto &it : Notes)
12060             Diag(it.first, it.second);
12061         } else {
12062           Diag(CacheCulprit->getExprLoc(),
12063                diag::note_invalid_subexpr_in_const_expr)
12064               << CacheCulprit->getSourceRange();
12065         }
12066       }
12067     }
12068     else if (!var->isConstexpr() && IsGlobal &&
12069              !getDiagnostics().isIgnored(diag::warn_global_constructor,
12070                                     var->getLocation())) {
12071       // Warn about globals which don't have a constant initializer.  Don't
12072       // warn about globals with a non-trivial destructor because we already
12073       // warned about them.
12074       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
12075       if (!(RD && !RD->hasTrivialDestructor())) {
12076         if (!checkConstInit())
12077           Diag(var->getLocation(), diag::warn_global_constructor)
12078             << Init->getSourceRange();
12079       }
12080     }
12081   }
12082 
12083   // Require the destructor.
12084   if (const RecordType *recordType = baseType->getAs<RecordType>())
12085     FinalizeVarWithDestructor(var, recordType);
12086 
12087   // If this variable must be emitted, add it as an initializer for the current
12088   // module.
12089   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12090     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12091 }
12092 
12093 /// Determines if a variable's alignment is dependent.
12094 static bool hasDependentAlignment(VarDecl *VD) {
12095   if (VD->getType()->isDependentType())
12096     return true;
12097   for (auto *I : VD->specific_attrs<AlignedAttr>())
12098     if (I->isAlignmentDependent())
12099       return true;
12100   return false;
12101 }
12102 
12103 /// Check if VD needs to be dllexport/dllimport due to being in a
12104 /// dllexport/import function.
12105 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12106   assert(VD->isStaticLocal());
12107 
12108   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12109 
12110   // Find outermost function when VD is in lambda function.
12111   while (FD && !getDLLAttr(FD) &&
12112          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12113          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12114     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12115   }
12116 
12117   if (!FD)
12118     return;
12119 
12120   // Static locals inherit dll attributes from their function.
12121   if (Attr *A = getDLLAttr(FD)) {
12122     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12123     NewAttr->setInherited(true);
12124     VD->addAttr(NewAttr);
12125   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12126     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12127                                                           getASTContext(),
12128                                                           A->getSpellingListIndex());
12129     NewAttr->setInherited(true);
12130     VD->addAttr(NewAttr);
12131 
12132     // Export this function to enforce exporting this static variable even
12133     // if it is not used in this compilation unit.
12134     if (!FD->hasAttr<DLLExportAttr>())
12135       FD->addAttr(NewAttr);
12136 
12137   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12138     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12139                                                           getASTContext(),
12140                                                           A->getSpellingListIndex());
12141     NewAttr->setInherited(true);
12142     VD->addAttr(NewAttr);
12143   }
12144 }
12145 
12146 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12147 /// any semantic actions necessary after any initializer has been attached.
12148 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12149   // Note that we are no longer parsing the initializer for this declaration.
12150   ParsingInitForAutoVars.erase(ThisDecl);
12151 
12152   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12153   if (!VD)
12154     return;
12155 
12156   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12157   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12158       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12159     if (PragmaClangBSSSection.Valid)
12160       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12161                                                             PragmaClangBSSSection.SectionName,
12162                                                             PragmaClangBSSSection.PragmaLocation));
12163     if (PragmaClangDataSection.Valid)
12164       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12165                                                              PragmaClangDataSection.SectionName,
12166                                                              PragmaClangDataSection.PragmaLocation));
12167     if (PragmaClangRodataSection.Valid)
12168       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12169                                                                PragmaClangRodataSection.SectionName,
12170                                                                PragmaClangRodataSection.PragmaLocation));
12171   }
12172 
12173   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12174     for (auto *BD : DD->bindings()) {
12175       FinalizeDeclaration(BD);
12176     }
12177   }
12178 
12179   checkAttributesAfterMerging(*this, *VD);
12180 
12181   // Perform TLS alignment check here after attributes attached to the variable
12182   // which may affect the alignment have been processed. Only perform the check
12183   // if the target has a maximum TLS alignment (zero means no constraints).
12184   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12185     // Protect the check so that it's not performed on dependent types and
12186     // dependent alignments (we can't determine the alignment in that case).
12187     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12188         !VD->isInvalidDecl()) {
12189       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12190       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12191         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12192           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12193           << (unsigned)MaxAlignChars.getQuantity();
12194       }
12195     }
12196   }
12197 
12198   if (VD->isStaticLocal()) {
12199     CheckStaticLocalForDllExport(VD);
12200 
12201     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12202       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12203       // function, only __shared__ variables or variables without any device
12204       // memory qualifiers may be declared with static storage class.
12205       // Note: It is unclear how a function-scope non-const static variable
12206       // without device memory qualifier is implemented, therefore only static
12207       // const variable without device memory qualifier is allowed.
12208       [&]() {
12209         if (!getLangOpts().CUDA)
12210           return;
12211         if (VD->hasAttr<CUDASharedAttr>())
12212           return;
12213         if (VD->getType().isConstQualified() &&
12214             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12215           return;
12216         if (CUDADiagIfDeviceCode(VD->getLocation(),
12217                                  diag::err_device_static_local_var)
12218             << CurrentCUDATarget())
12219           VD->setInvalidDecl();
12220       }();
12221     }
12222   }
12223 
12224   // Perform check for initializers of device-side global variables.
12225   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12226   // 7.5). We must also apply the same checks to all __shared__
12227   // variables whether they are local or not. CUDA also allows
12228   // constant initializers for __constant__ and __device__ variables.
12229   if (getLangOpts().CUDA)
12230     checkAllowedCUDAInitializer(VD);
12231 
12232   // Grab the dllimport or dllexport attribute off of the VarDecl.
12233   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12234 
12235   // Imported static data members cannot be defined out-of-line.
12236   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12237     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12238         VD->isThisDeclarationADefinition()) {
12239       // We allow definitions of dllimport class template static data members
12240       // with a warning.
12241       CXXRecordDecl *Context =
12242         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12243       bool IsClassTemplateMember =
12244           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12245           Context->getDescribedClassTemplate();
12246 
12247       Diag(VD->getLocation(),
12248            IsClassTemplateMember
12249                ? diag::warn_attribute_dllimport_static_field_definition
12250                : diag::err_attribute_dllimport_static_field_definition);
12251       Diag(IA->getLocation(), diag::note_attribute);
12252       if (!IsClassTemplateMember)
12253         VD->setInvalidDecl();
12254     }
12255   }
12256 
12257   // dllimport/dllexport variables cannot be thread local, their TLS index
12258   // isn't exported with the variable.
12259   if (DLLAttr && VD->getTLSKind()) {
12260     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12261     if (F && getDLLAttr(F)) {
12262       assert(VD->isStaticLocal());
12263       // But if this is a static local in a dlimport/dllexport function, the
12264       // function will never be inlined, which means the var would never be
12265       // imported, so having it marked import/export is safe.
12266     } else {
12267       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12268                                                                     << DLLAttr;
12269       VD->setInvalidDecl();
12270     }
12271   }
12272 
12273   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12274     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12275       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12276       VD->dropAttr<UsedAttr>();
12277     }
12278   }
12279 
12280   const DeclContext *DC = VD->getDeclContext();
12281   // If there's a #pragma GCC visibility in scope, and this isn't a class
12282   // member, set the visibility of this variable.
12283   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12284     AddPushedVisibilityAttribute(VD);
12285 
12286   // FIXME: Warn on unused var template partial specializations.
12287   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12288     MarkUnusedFileScopedDecl(VD);
12289 
12290   // Now we have parsed the initializer and can update the table of magic
12291   // tag values.
12292   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12293       !VD->getType()->isIntegralOrEnumerationType())
12294     return;
12295 
12296   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12297     const Expr *MagicValueExpr = VD->getInit();
12298     if (!MagicValueExpr) {
12299       continue;
12300     }
12301     llvm::APSInt MagicValueInt;
12302     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12303       Diag(I->getRange().getBegin(),
12304            diag::err_type_tag_for_datatype_not_ice)
12305         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12306       continue;
12307     }
12308     if (MagicValueInt.getActiveBits() > 64) {
12309       Diag(I->getRange().getBegin(),
12310            diag::err_type_tag_for_datatype_too_large)
12311         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12312       continue;
12313     }
12314     uint64_t MagicValue = MagicValueInt.getZExtValue();
12315     RegisterTypeTagForDatatype(I->getArgumentKind(),
12316                                MagicValue,
12317                                I->getMatchingCType(),
12318                                I->getLayoutCompatible(),
12319                                I->getMustBeNull());
12320   }
12321 }
12322 
12323 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12324   auto *VD = dyn_cast<VarDecl>(DD);
12325   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12326 }
12327 
12328 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12329                                                    ArrayRef<Decl *> Group) {
12330   SmallVector<Decl*, 8> Decls;
12331 
12332   if (DS.isTypeSpecOwned())
12333     Decls.push_back(DS.getRepAsDecl());
12334 
12335   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12336   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12337   bool DiagnosedMultipleDecomps = false;
12338   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12339   bool DiagnosedNonDeducedAuto = false;
12340 
12341   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12342     if (Decl *D = Group[i]) {
12343       // For declarators, there are some additional syntactic-ish checks we need
12344       // to perform.
12345       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12346         if (!FirstDeclaratorInGroup)
12347           FirstDeclaratorInGroup = DD;
12348         if (!FirstDecompDeclaratorInGroup)
12349           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12350         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12351             !hasDeducedAuto(DD))
12352           FirstNonDeducedAutoInGroup = DD;
12353 
12354         if (FirstDeclaratorInGroup != DD) {
12355           // A decomposition declaration cannot be combined with any other
12356           // declaration in the same group.
12357           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12358             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12359                  diag::err_decomp_decl_not_alone)
12360                 << FirstDeclaratorInGroup->getSourceRange()
12361                 << DD->getSourceRange();
12362             DiagnosedMultipleDecomps = true;
12363           }
12364 
12365           // A declarator that uses 'auto' in any way other than to declare a
12366           // variable with a deduced type cannot be combined with any other
12367           // declarator in the same group.
12368           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12369             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12370                  diag::err_auto_non_deduced_not_alone)
12371                 << FirstNonDeducedAutoInGroup->getType()
12372                        ->hasAutoForTrailingReturnType()
12373                 << FirstDeclaratorInGroup->getSourceRange()
12374                 << DD->getSourceRange();
12375             DiagnosedNonDeducedAuto = true;
12376           }
12377         }
12378       }
12379 
12380       Decls.push_back(D);
12381     }
12382   }
12383 
12384   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12385     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12386       handleTagNumbering(Tag, S);
12387       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12388           getLangOpts().CPlusPlus)
12389         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12390     }
12391   }
12392 
12393   return BuildDeclaratorGroup(Decls);
12394 }
12395 
12396 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12397 /// group, performing any necessary semantic checking.
12398 Sema::DeclGroupPtrTy
12399 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12400   // C++14 [dcl.spec.auto]p7: (DR1347)
12401   //   If the type that replaces the placeholder type is not the same in each
12402   //   deduction, the program is ill-formed.
12403   if (Group.size() > 1) {
12404     QualType Deduced;
12405     VarDecl *DeducedDecl = nullptr;
12406     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12407       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12408       if (!D || D->isInvalidDecl())
12409         break;
12410       DeducedType *DT = D->getType()->getContainedDeducedType();
12411       if (!DT || DT->getDeducedType().isNull())
12412         continue;
12413       if (Deduced.isNull()) {
12414         Deduced = DT->getDeducedType();
12415         DeducedDecl = D;
12416       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12417         auto *AT = dyn_cast<AutoType>(DT);
12418         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12419              diag::err_auto_different_deductions)
12420           << (AT ? (unsigned)AT->getKeyword() : 3)
12421           << Deduced << DeducedDecl->getDeclName()
12422           << DT->getDeducedType() << D->getDeclName()
12423           << DeducedDecl->getInit()->getSourceRange()
12424           << D->getInit()->getSourceRange();
12425         D->setInvalidDecl();
12426         break;
12427       }
12428     }
12429   }
12430 
12431   ActOnDocumentableDecls(Group);
12432 
12433   return DeclGroupPtrTy::make(
12434       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12435 }
12436 
12437 void Sema::ActOnDocumentableDecl(Decl *D) {
12438   ActOnDocumentableDecls(D);
12439 }
12440 
12441 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12442   // Don't parse the comment if Doxygen diagnostics are ignored.
12443   if (Group.empty() || !Group[0])
12444     return;
12445 
12446   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12447                       Group[0]->getLocation()) &&
12448       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12449                       Group[0]->getLocation()))
12450     return;
12451 
12452   if (Group.size() >= 2) {
12453     // This is a decl group.  Normally it will contain only declarations
12454     // produced from declarator list.  But in case we have any definitions or
12455     // additional declaration references:
12456     //   'typedef struct S {} S;'
12457     //   'typedef struct S *S;'
12458     //   'struct S *pS;'
12459     // FinalizeDeclaratorGroup adds these as separate declarations.
12460     Decl *MaybeTagDecl = Group[0];
12461     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12462       Group = Group.slice(1);
12463     }
12464   }
12465 
12466   // See if there are any new comments that are not attached to a decl.
12467   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12468   if (!Comments.empty() &&
12469       !Comments.back()->isAttached()) {
12470     // There is at least one comment that not attached to a decl.
12471     // Maybe it should be attached to one of these decls?
12472     //
12473     // Note that this way we pick up not only comments that precede the
12474     // declaration, but also comments that *follow* the declaration -- thanks to
12475     // the lookahead in the lexer: we've consumed the semicolon and looked
12476     // ahead through comments.
12477     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12478       Context.getCommentForDecl(Group[i], &PP);
12479   }
12480 }
12481 
12482 /// Common checks for a parameter-declaration that should apply to both function
12483 /// parameters and non-type template parameters.
12484 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
12485   // Check that there are no default arguments inside the type of this
12486   // parameter.
12487   if (getLangOpts().CPlusPlus)
12488     CheckExtraCXXDefaultArguments(D);
12489 
12490   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12491   if (D.getCXXScopeSpec().isSet()) {
12492     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12493       << D.getCXXScopeSpec().getRange();
12494   }
12495 
12496   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
12497   // simple identifier except [...irrelevant cases...].
12498   switch (D.getName().getKind()) {
12499   case UnqualifiedIdKind::IK_Identifier:
12500     break;
12501 
12502   case UnqualifiedIdKind::IK_OperatorFunctionId:
12503   case UnqualifiedIdKind::IK_ConversionFunctionId:
12504   case UnqualifiedIdKind::IK_LiteralOperatorId:
12505   case UnqualifiedIdKind::IK_ConstructorName:
12506   case UnqualifiedIdKind::IK_DestructorName:
12507   case UnqualifiedIdKind::IK_ImplicitSelfParam:
12508   case UnqualifiedIdKind::IK_DeductionGuideName:
12509     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12510       << GetNameForDeclarator(D).getName();
12511     break;
12512 
12513   case UnqualifiedIdKind::IK_TemplateId:
12514   case UnqualifiedIdKind::IK_ConstructorTemplateId:
12515     // GetNameForDeclarator would not produce a useful name in this case.
12516     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
12517     break;
12518   }
12519 }
12520 
12521 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12522 /// to introduce parameters into function prototype scope.
12523 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12524   const DeclSpec &DS = D.getDeclSpec();
12525 
12526   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12527 
12528   // C++03 [dcl.stc]p2 also permits 'auto'.
12529   StorageClass SC = SC_None;
12530   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12531     SC = SC_Register;
12532     // In C++11, the 'register' storage class specifier is deprecated.
12533     // In C++17, it is not allowed, but we tolerate it as an extension.
12534     if (getLangOpts().CPlusPlus11) {
12535       Diag(DS.getStorageClassSpecLoc(),
12536            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12537                                      : diag::warn_deprecated_register)
12538         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12539     }
12540   } else if (getLangOpts().CPlusPlus &&
12541              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12542     SC = SC_Auto;
12543   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12544     Diag(DS.getStorageClassSpecLoc(),
12545          diag::err_invalid_storage_class_in_func_decl);
12546     D.getMutableDeclSpec().ClearStorageClassSpecs();
12547   }
12548 
12549   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12550     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12551       << DeclSpec::getSpecifierName(TSCS);
12552   if (DS.isInlineSpecified())
12553     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12554         << getLangOpts().CPlusPlus17;
12555   if (DS.hasConstexprSpecifier())
12556     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12557         << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
12558 
12559   DiagnoseFunctionSpecifiers(DS);
12560 
12561   CheckFunctionOrTemplateParamDeclarator(S, D);
12562 
12563   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12564   QualType parmDeclType = TInfo->getType();
12565 
12566   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12567   IdentifierInfo *II = D.getIdentifier();
12568   if (II) {
12569     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12570                    ForVisibleRedeclaration);
12571     LookupName(R, S);
12572     if (R.isSingleResult()) {
12573       NamedDecl *PrevDecl = R.getFoundDecl();
12574       if (PrevDecl->isTemplateParameter()) {
12575         // Maybe we will complain about the shadowed template parameter.
12576         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12577         // Just pretend that we didn't see the previous declaration.
12578         PrevDecl = nullptr;
12579       } else if (S->isDeclScope(PrevDecl)) {
12580         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12581         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12582 
12583         // Recover by removing the name
12584         II = nullptr;
12585         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12586         D.setInvalidType(true);
12587       }
12588     }
12589   }
12590 
12591   // Temporarily put parameter variables in the translation unit, not
12592   // the enclosing context.  This prevents them from accidentally
12593   // looking like class members in C++.
12594   ParmVarDecl *New =
12595       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12596                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12597 
12598   if (D.isInvalidType())
12599     New->setInvalidDecl();
12600 
12601   assert(S->isFunctionPrototypeScope());
12602   assert(S->getFunctionPrototypeDepth() >= 1);
12603   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12604                     S->getNextFunctionPrototypeIndex());
12605 
12606   // Add the parameter declaration into this scope.
12607   S->AddDecl(New);
12608   if (II)
12609     IdResolver.AddDecl(New);
12610 
12611   ProcessDeclAttributes(S, New, D);
12612 
12613   if (D.getDeclSpec().isModulePrivateSpecified())
12614     Diag(New->getLocation(), diag::err_module_private_local)
12615       << 1 << New->getDeclName()
12616       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12617       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12618 
12619   if (New->hasAttr<BlocksAttr>()) {
12620     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12621   }
12622   return New;
12623 }
12624 
12625 /// Synthesizes a variable for a parameter arising from a
12626 /// typedef.
12627 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12628                                               SourceLocation Loc,
12629                                               QualType T) {
12630   /* FIXME: setting StartLoc == Loc.
12631      Would it be worth to modify callers so as to provide proper source
12632      location for the unnamed parameters, embedding the parameter's type? */
12633   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12634                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12635                                            SC_None, nullptr);
12636   Param->setImplicit();
12637   return Param;
12638 }
12639 
12640 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12641   // Don't diagnose unused-parameter errors in template instantiations; we
12642   // will already have done so in the template itself.
12643   if (inTemplateInstantiation())
12644     return;
12645 
12646   for (const ParmVarDecl *Parameter : Parameters) {
12647     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12648         !Parameter->hasAttr<UnusedAttr>()) {
12649       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12650         << Parameter->getDeclName();
12651     }
12652   }
12653 }
12654 
12655 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12656     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12657   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12658     return;
12659 
12660   // Warn if the return value is pass-by-value and larger than the specified
12661   // threshold.
12662   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12663     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12664     if (Size > LangOpts.NumLargeByValueCopy)
12665       Diag(D->getLocation(), diag::warn_return_value_size)
12666           << D->getDeclName() << Size;
12667   }
12668 
12669   // Warn if any parameter is pass-by-value and larger than the specified
12670   // threshold.
12671   for (const ParmVarDecl *Parameter : Parameters) {
12672     QualType T = Parameter->getType();
12673     if (T->isDependentType() || !T.isPODType(Context))
12674       continue;
12675     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12676     if (Size > LangOpts.NumLargeByValueCopy)
12677       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12678           << Parameter->getDeclName() << Size;
12679   }
12680 }
12681 
12682 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12683                                   SourceLocation NameLoc, IdentifierInfo *Name,
12684                                   QualType T, TypeSourceInfo *TSInfo,
12685                                   StorageClass SC) {
12686   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12687   if (getLangOpts().ObjCAutoRefCount &&
12688       T.getObjCLifetime() == Qualifiers::OCL_None &&
12689       T->isObjCLifetimeType()) {
12690 
12691     Qualifiers::ObjCLifetime lifetime;
12692 
12693     // Special cases for arrays:
12694     //   - if it's const, use __unsafe_unretained
12695     //   - otherwise, it's an error
12696     if (T->isArrayType()) {
12697       if (!T.isConstQualified()) {
12698         if (DelayedDiagnostics.shouldDelayDiagnostics())
12699           DelayedDiagnostics.add(
12700               sema::DelayedDiagnostic::makeForbiddenType(
12701               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12702         else
12703           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12704               << TSInfo->getTypeLoc().getSourceRange();
12705       }
12706       lifetime = Qualifiers::OCL_ExplicitNone;
12707     } else {
12708       lifetime = T->getObjCARCImplicitLifetime();
12709     }
12710     T = Context.getLifetimeQualifiedType(T, lifetime);
12711   }
12712 
12713   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12714                                          Context.getAdjustedParameterType(T),
12715                                          TSInfo, SC, nullptr);
12716 
12717   // Parameters can not be abstract class types.
12718   // For record types, this is done by the AbstractClassUsageDiagnoser once
12719   // the class has been completely parsed.
12720   if (!CurContext->isRecord() &&
12721       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12722                              AbstractParamType))
12723     New->setInvalidDecl();
12724 
12725   // Parameter declarators cannot be interface types. All ObjC objects are
12726   // passed by reference.
12727   if (T->isObjCObjectType()) {
12728     SourceLocation TypeEndLoc =
12729         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12730     Diag(NameLoc,
12731          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12732       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12733     T = Context.getObjCObjectPointerType(T);
12734     New->setType(T);
12735   }
12736 
12737   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12738   // duration shall not be qualified by an address-space qualifier."
12739   // Since all parameters have automatic store duration, they can not have
12740   // an address space.
12741   if (T.getAddressSpace() != LangAS::Default &&
12742       // OpenCL allows function arguments declared to be an array of a type
12743       // to be qualified with an address space.
12744       !(getLangOpts().OpenCL &&
12745         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12746     Diag(NameLoc, diag::err_arg_with_address_space);
12747     New->setInvalidDecl();
12748   }
12749 
12750   return New;
12751 }
12752 
12753 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12754                                            SourceLocation LocAfterDecls) {
12755   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12756 
12757   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12758   // for a K&R function.
12759   if (!FTI.hasPrototype) {
12760     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12761       --i;
12762       if (FTI.Params[i].Param == nullptr) {
12763         SmallString<256> Code;
12764         llvm::raw_svector_ostream(Code)
12765             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12766         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12767             << FTI.Params[i].Ident
12768             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12769 
12770         // Implicitly declare the argument as type 'int' for lack of a better
12771         // type.
12772         AttributeFactory attrs;
12773         DeclSpec DS(attrs);
12774         const char* PrevSpec; // unused
12775         unsigned DiagID; // unused
12776         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12777                            DiagID, Context.getPrintingPolicy());
12778         // Use the identifier location for the type source range.
12779         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12780         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12781         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12782         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12783         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12784       }
12785     }
12786   }
12787 }
12788 
12789 Decl *
12790 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12791                               MultiTemplateParamsArg TemplateParameterLists,
12792                               SkipBodyInfo *SkipBody) {
12793   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12794   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12795   Scope *ParentScope = FnBodyScope->getParent();
12796 
12797   D.setFunctionDefinitionKind(FDK_Definition);
12798   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12799   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12800 }
12801 
12802 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12803   Consumer.HandleInlineFunctionDefinition(D);
12804 }
12805 
12806 static bool
12807 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12808                                 const FunctionDecl *&PossiblePrototype) {
12809   // Don't warn about invalid declarations.
12810   if (FD->isInvalidDecl())
12811     return false;
12812 
12813   // Or declarations that aren't global.
12814   if (!FD->isGlobal())
12815     return false;
12816 
12817   // Don't warn about C++ member functions.
12818   if (isa<CXXMethodDecl>(FD))
12819     return false;
12820 
12821   // Don't warn about 'main'.
12822   if (FD->isMain())
12823     return false;
12824 
12825   // Don't warn about inline functions.
12826   if (FD->isInlined())
12827     return false;
12828 
12829   // Don't warn about function templates.
12830   if (FD->getDescribedFunctionTemplate())
12831     return false;
12832 
12833   // Don't warn about function template specializations.
12834   if (FD->isFunctionTemplateSpecialization())
12835     return false;
12836 
12837   // Don't warn for OpenCL kernels.
12838   if (FD->hasAttr<OpenCLKernelAttr>())
12839     return false;
12840 
12841   // Don't warn on explicitly deleted functions.
12842   if (FD->isDeleted())
12843     return false;
12844 
12845   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12846        Prev; Prev = Prev->getPreviousDecl()) {
12847     // Ignore any declarations that occur in function or method
12848     // scope, because they aren't visible from the header.
12849     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12850       continue;
12851 
12852     PossiblePrototype = Prev;
12853     return Prev->getType()->isFunctionNoProtoType();
12854   }
12855 
12856   return true;
12857 }
12858 
12859 void
12860 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12861                                    const FunctionDecl *EffectiveDefinition,
12862                                    SkipBodyInfo *SkipBody) {
12863   const FunctionDecl *Definition = EffectiveDefinition;
12864   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12865     // If this is a friend function defined in a class template, it does not
12866     // have a body until it is used, nevertheless it is a definition, see
12867     // [temp.inst]p2:
12868     //
12869     // ... for the purpose of determining whether an instantiated redeclaration
12870     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12871     // corresponds to a definition in the template is considered to be a
12872     // definition.
12873     //
12874     // The following code must produce redefinition error:
12875     //
12876     //     template<typename T> struct C20 { friend void func_20() {} };
12877     //     C20<int> c20i;
12878     //     void func_20() {}
12879     //
12880     for (auto I : FD->redecls()) {
12881       if (I != FD && !I->isInvalidDecl() &&
12882           I->getFriendObjectKind() != Decl::FOK_None) {
12883         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12884           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12885             // A merged copy of the same function, instantiated as a member of
12886             // the same class, is OK.
12887             if (declaresSameEntity(OrigFD, Original) &&
12888                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12889                                    cast<Decl>(FD->getLexicalDeclContext())))
12890               continue;
12891           }
12892 
12893           if (Original->isThisDeclarationADefinition()) {
12894             Definition = I;
12895             break;
12896           }
12897         }
12898       }
12899     }
12900   }
12901 
12902   if (!Definition)
12903     // Similar to friend functions a friend function template may be a
12904     // definition and do not have a body if it is instantiated in a class
12905     // template.
12906     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12907       for (auto I : FTD->redecls()) {
12908         auto D = cast<FunctionTemplateDecl>(I);
12909         if (D != FTD) {
12910           assert(!D->isThisDeclarationADefinition() &&
12911                  "More than one definition in redeclaration chain");
12912           if (D->getFriendObjectKind() != Decl::FOK_None)
12913             if (FunctionTemplateDecl *FT =
12914                                        D->getInstantiatedFromMemberTemplate()) {
12915               if (FT->isThisDeclarationADefinition()) {
12916                 Definition = D->getTemplatedDecl();
12917                 break;
12918               }
12919             }
12920         }
12921       }
12922     }
12923 
12924   if (!Definition)
12925     return;
12926 
12927   if (canRedefineFunction(Definition, getLangOpts()))
12928     return;
12929 
12930   // Don't emit an error when this is redefinition of a typo-corrected
12931   // definition.
12932   if (TypoCorrectedFunctionDefinitions.count(Definition))
12933     return;
12934 
12935   // If we don't have a visible definition of the function, and it's inline or
12936   // a template, skip the new definition.
12937   if (SkipBody && !hasVisibleDefinition(Definition) &&
12938       (Definition->getFormalLinkage() == InternalLinkage ||
12939        Definition->isInlined() ||
12940        Definition->getDescribedFunctionTemplate() ||
12941        Definition->getNumTemplateParameterLists())) {
12942     SkipBody->ShouldSkip = true;
12943     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12944     if (auto *TD = Definition->getDescribedFunctionTemplate())
12945       makeMergedDefinitionVisible(TD);
12946     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12947     return;
12948   }
12949 
12950   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12951       Definition->getStorageClass() == SC_Extern)
12952     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12953         << FD->getDeclName() << getLangOpts().CPlusPlus;
12954   else
12955     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12956 
12957   Diag(Definition->getLocation(), diag::note_previous_definition);
12958   FD->setInvalidDecl();
12959 }
12960 
12961 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12962                                    Sema &S) {
12963   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12964 
12965   LambdaScopeInfo *LSI = S.PushLambdaScope();
12966   LSI->CallOperator = CallOperator;
12967   LSI->Lambda = LambdaClass;
12968   LSI->ReturnType = CallOperator->getReturnType();
12969   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12970 
12971   if (LCD == LCD_None)
12972     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12973   else if (LCD == LCD_ByCopy)
12974     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12975   else if (LCD == LCD_ByRef)
12976     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12977   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12978 
12979   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12980   LSI->Mutable = !CallOperator->isConst();
12981 
12982   // Add the captures to the LSI so they can be noted as already
12983   // captured within tryCaptureVar.
12984   auto I = LambdaClass->field_begin();
12985   for (const auto &C : LambdaClass->captures()) {
12986     if (C.capturesVariable()) {
12987       VarDecl *VD = C.getCapturedVar();
12988       if (VD->isInitCapture())
12989         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12990       QualType CaptureType = VD->getType();
12991       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12992       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12993           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12994           /*EllipsisLoc*/C.isPackExpansion()
12995                          ? C.getEllipsisLoc() : SourceLocation(),
12996           CaptureType, /*Invalid*/false);
12997 
12998     } else if (C.capturesThis()) {
12999       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13000                           C.getCaptureKind() == LCK_StarThis);
13001     } else {
13002       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13003                              I->getType());
13004     }
13005     ++I;
13006   }
13007 }
13008 
13009 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13010                                     SkipBodyInfo *SkipBody) {
13011   if (!D) {
13012     // Parsing the function declaration failed in some way. Push on a fake scope
13013     // anyway so we can try to parse the function body.
13014     PushFunctionScope();
13015     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13016     return D;
13017   }
13018 
13019   FunctionDecl *FD = nullptr;
13020 
13021   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13022     FD = FunTmpl->getTemplatedDecl();
13023   else
13024     FD = cast<FunctionDecl>(D);
13025 
13026   // Do not push if it is a lambda because one is already pushed when building
13027   // the lambda in ActOnStartOfLambdaDefinition().
13028   if (!isLambdaCallOperator(FD))
13029     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13030 
13031   // Check for defining attributes before the check for redefinition.
13032   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13033     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13034     FD->dropAttr<AliasAttr>();
13035     FD->setInvalidDecl();
13036   }
13037   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13038     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13039     FD->dropAttr<IFuncAttr>();
13040     FD->setInvalidDecl();
13041   }
13042 
13043   // See if this is a redefinition. If 'will have body' is already set, then
13044   // these checks were already performed when it was set.
13045   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
13046     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
13047 
13048     // If we're skipping the body, we're done. Don't enter the scope.
13049     if (SkipBody && SkipBody->ShouldSkip)
13050       return D;
13051   }
13052 
13053   // Mark this function as "will have a body eventually".  This lets users to
13054   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
13055   // this function.
13056   FD->setWillHaveBody();
13057 
13058   // If we are instantiating a generic lambda call operator, push
13059   // a LambdaScopeInfo onto the function stack.  But use the information
13060   // that's already been calculated (ActOnLambdaExpr) to prime the current
13061   // LambdaScopeInfo.
13062   // When the template operator is being specialized, the LambdaScopeInfo,
13063   // has to be properly restored so that tryCaptureVariable doesn't try
13064   // and capture any new variables. In addition when calculating potential
13065   // captures during transformation of nested lambdas, it is necessary to
13066   // have the LSI properly restored.
13067   if (isGenericLambdaCallOperatorSpecialization(FD)) {
13068     assert(inTemplateInstantiation() &&
13069            "There should be an active template instantiation on the stack "
13070            "when instantiating a generic lambda!");
13071     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
13072   } else {
13073     // Enter a new function scope
13074     PushFunctionScope();
13075   }
13076 
13077   // Builtin functions cannot be defined.
13078   if (unsigned BuiltinID = FD->getBuiltinID()) {
13079     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
13080         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
13081       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
13082       FD->setInvalidDecl();
13083     }
13084   }
13085 
13086   // The return type of a function definition must be complete
13087   // (C99 6.9.1p3, C++ [dcl.fct]p6).
13088   QualType ResultType = FD->getReturnType();
13089   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
13090       !FD->isInvalidDecl() &&
13091       RequireCompleteType(FD->getLocation(), ResultType,
13092                           diag::err_func_def_incomplete_result))
13093     FD->setInvalidDecl();
13094 
13095   if (FnBodyScope)
13096     PushDeclContext(FnBodyScope, FD);
13097 
13098   // Check the validity of our function parameters
13099   CheckParmsForFunctionDef(FD->parameters(),
13100                            /*CheckParameterNames=*/true);
13101 
13102   // Add non-parameter declarations already in the function to the current
13103   // scope.
13104   if (FnBodyScope) {
13105     for (Decl *NPD : FD->decls()) {
13106       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13107       if (!NonParmDecl)
13108         continue;
13109       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13110              "parameters should not be in newly created FD yet");
13111 
13112       // If the decl has a name, make it accessible in the current scope.
13113       if (NonParmDecl->getDeclName())
13114         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13115 
13116       // Similarly, dive into enums and fish their constants out, making them
13117       // accessible in this scope.
13118       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13119         for (auto *EI : ED->enumerators())
13120           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13121       }
13122     }
13123   }
13124 
13125   // Introduce our parameters into the function scope
13126   for (auto Param : FD->parameters()) {
13127     Param->setOwningFunction(FD);
13128 
13129     // If this has an identifier, add it to the scope stack.
13130     if (Param->getIdentifier() && FnBodyScope) {
13131       CheckShadow(FnBodyScope, Param);
13132 
13133       PushOnScopeChains(Param, FnBodyScope);
13134     }
13135   }
13136 
13137   // Ensure that the function's exception specification is instantiated.
13138   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13139     ResolveExceptionSpec(D->getLocation(), FPT);
13140 
13141   // dllimport cannot be applied to non-inline function definitions.
13142   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13143       !FD->isTemplateInstantiation()) {
13144     assert(!FD->hasAttr<DLLExportAttr>());
13145     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13146     FD->setInvalidDecl();
13147     return D;
13148   }
13149   // We want to attach documentation to original Decl (which might be
13150   // a function template).
13151   ActOnDocumentableDecl(D);
13152   if (getCurLexicalContext()->isObjCContainer() &&
13153       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13154       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13155     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13156 
13157   return D;
13158 }
13159 
13160 /// Given the set of return statements within a function body,
13161 /// compute the variables that are subject to the named return value
13162 /// optimization.
13163 ///
13164 /// Each of the variables that is subject to the named return value
13165 /// optimization will be marked as NRVO variables in the AST, and any
13166 /// return statement that has a marked NRVO variable as its NRVO candidate can
13167 /// use the named return value optimization.
13168 ///
13169 /// This function applies a very simplistic algorithm for NRVO: if every return
13170 /// statement in the scope of a variable has the same NRVO candidate, that
13171 /// candidate is an NRVO variable.
13172 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13173   ReturnStmt **Returns = Scope->Returns.data();
13174 
13175   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13176     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13177       if (!NRVOCandidate->isNRVOVariable())
13178         Returns[I]->setNRVOCandidate(nullptr);
13179     }
13180   }
13181 }
13182 
13183 bool Sema::canDelayFunctionBody(const Declarator &D) {
13184   // We can't delay parsing the body of a constexpr function template (yet).
13185   if (D.getDeclSpec().hasConstexprSpecifier())
13186     return false;
13187 
13188   // We can't delay parsing the body of a function template with a deduced
13189   // return type (yet).
13190   if (D.getDeclSpec().hasAutoTypeSpec()) {
13191     // If the placeholder introduces a non-deduced trailing return type,
13192     // we can still delay parsing it.
13193     if (D.getNumTypeObjects()) {
13194       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13195       if (Outer.Kind == DeclaratorChunk::Function &&
13196           Outer.Fun.hasTrailingReturnType()) {
13197         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13198         return Ty.isNull() || !Ty->isUndeducedType();
13199       }
13200     }
13201     return false;
13202   }
13203 
13204   return true;
13205 }
13206 
13207 bool Sema::canSkipFunctionBody(Decl *D) {
13208   // We cannot skip the body of a function (or function template) which is
13209   // constexpr, since we may need to evaluate its body in order to parse the
13210   // rest of the file.
13211   // We cannot skip the body of a function with an undeduced return type,
13212   // because any callers of that function need to know the type.
13213   if (const FunctionDecl *FD = D->getAsFunction()) {
13214     if (FD->isConstexpr())
13215       return false;
13216     // We can't simply call Type::isUndeducedType here, because inside template
13217     // auto can be deduced to a dependent type, which is not considered
13218     // "undeduced".
13219     if (FD->getReturnType()->getContainedDeducedType())
13220       return false;
13221   }
13222   return Consumer.shouldSkipFunctionBody(D);
13223 }
13224 
13225 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13226   if (!Decl)
13227     return nullptr;
13228   if (FunctionDecl *FD = Decl->getAsFunction())
13229     FD->setHasSkippedBody();
13230   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13231     MD->setHasSkippedBody();
13232   return Decl;
13233 }
13234 
13235 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13236   return ActOnFinishFunctionBody(D, BodyArg, false);
13237 }
13238 
13239 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13240 /// body.
13241 class ExitFunctionBodyRAII {
13242 public:
13243   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13244   ~ExitFunctionBodyRAII() {
13245     if (!IsLambda)
13246       S.PopExpressionEvaluationContext();
13247   }
13248 
13249 private:
13250   Sema &S;
13251   bool IsLambda = false;
13252 };
13253 
13254 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13255   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13256 
13257   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13258     if (EscapeInfo.count(BD))
13259       return EscapeInfo[BD];
13260 
13261     bool R = false;
13262     const BlockDecl *CurBD = BD;
13263 
13264     do {
13265       R = !CurBD->doesNotEscape();
13266       if (R)
13267         break;
13268       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13269     } while (CurBD);
13270 
13271     return EscapeInfo[BD] = R;
13272   };
13273 
13274   // If the location where 'self' is implicitly retained is inside a escaping
13275   // block, emit a diagnostic.
13276   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13277        S.ImplicitlyRetainedSelfLocs)
13278     if (IsOrNestedInEscapingBlock(P.second))
13279       S.Diag(P.first, diag::warn_implicitly_retains_self)
13280           << FixItHint::CreateInsertion(P.first, "self->");
13281 }
13282 
13283 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13284                                     bool IsInstantiation) {
13285   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13286 
13287   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13288   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13289 
13290   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13291     CheckCompletedCoroutineBody(FD, Body);
13292 
13293   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13294   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13295   // meant to pop the context added in ActOnStartOfFunctionDef().
13296   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13297 
13298   if (FD) {
13299     FD->setBody(Body);
13300     FD->setWillHaveBody(false);
13301 
13302     if (getLangOpts().CPlusPlus14) {
13303       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13304           FD->getReturnType()->isUndeducedType()) {
13305         // If the function has a deduced result type but contains no 'return'
13306         // statements, the result type as written must be exactly 'auto', and
13307         // the deduced result type is 'void'.
13308         if (!FD->getReturnType()->getAs<AutoType>()) {
13309           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13310               << FD->getReturnType();
13311           FD->setInvalidDecl();
13312         } else {
13313           // Substitute 'void' for the 'auto' in the type.
13314           TypeLoc ResultType = getReturnTypeLoc(FD);
13315           Context.adjustDeducedFunctionResultType(
13316               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13317         }
13318       }
13319     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13320       // In C++11, we don't use 'auto' deduction rules for lambda call
13321       // operators because we don't support return type deduction.
13322       auto *LSI = getCurLambda();
13323       if (LSI->HasImplicitReturnType) {
13324         deduceClosureReturnType(*LSI);
13325 
13326         // C++11 [expr.prim.lambda]p4:
13327         //   [...] if there are no return statements in the compound-statement
13328         //   [the deduced type is] the type void
13329         QualType RetType =
13330             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13331 
13332         // Update the return type to the deduced type.
13333         const FunctionProtoType *Proto =
13334             FD->getType()->getAs<FunctionProtoType>();
13335         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13336                                             Proto->getExtProtoInfo()));
13337       }
13338     }
13339 
13340     // If the function implicitly returns zero (like 'main') or is naked,
13341     // don't complain about missing return statements.
13342     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13343       WP.disableCheckFallThrough();
13344 
13345     // MSVC permits the use of pure specifier (=0) on function definition,
13346     // defined at class scope, warn about this non-standard construct.
13347     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13348       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13349 
13350     if (!FD->isInvalidDecl()) {
13351       // Don't diagnose unused parameters of defaulted or deleted functions.
13352       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13353         DiagnoseUnusedParameters(FD->parameters());
13354       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13355                                              FD->getReturnType(), FD);
13356 
13357       // If this is a structor, we need a vtable.
13358       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13359         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13360       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13361         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13362 
13363       // Try to apply the named return value optimization. We have to check
13364       // if we can do this here because lambdas keep return statements around
13365       // to deduce an implicit return type.
13366       if (FD->getReturnType()->isRecordType() &&
13367           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13368         computeNRVO(Body, getCurFunction());
13369     }
13370 
13371     // GNU warning -Wmissing-prototypes:
13372     //   Warn if a global function is defined without a previous
13373     //   prototype declaration. This warning is issued even if the
13374     //   definition itself provides a prototype. The aim is to detect
13375     //   global functions that fail to be declared in header files.
13376     const FunctionDecl *PossiblePrototype = nullptr;
13377     if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
13378       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13379 
13380       if (PossiblePrototype) {
13381         // We found a declaration that is not a prototype,
13382         // but that could be a zero-parameter prototype
13383         if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
13384           TypeLoc TL = TI->getTypeLoc();
13385           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13386             Diag(PossiblePrototype->getLocation(),
13387                  diag::note_declaration_not_a_prototype)
13388                 << (FD->getNumParams() != 0)
13389                 << (FD->getNumParams() == 0
13390                         ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
13391                         : FixItHint{});
13392         }
13393       } else {
13394         Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13395             << /* function */ 1
13396             << (FD->getStorageClass() == SC_None
13397                     ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
13398                                                  "static ")
13399                     : FixItHint{});
13400       }
13401 
13402       // GNU warning -Wstrict-prototypes
13403       //   Warn if K&R function is defined without a previous declaration.
13404       //   This warning is issued only if the definition itself does not provide
13405       //   a prototype. Only K&R definitions do not provide a prototype.
13406       //   An empty list in a function declarator that is part of a definition
13407       //   of that function specifies that the function has no parameters
13408       //   (C99 6.7.5.3p14)
13409       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13410           !LangOpts.CPlusPlus) {
13411         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13412         TypeLoc TL = TI->getTypeLoc();
13413         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13414         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13415       }
13416     }
13417 
13418     // Warn on CPUDispatch with an actual body.
13419     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13420       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13421         if (!CmpndBody->body_empty())
13422           Diag(CmpndBody->body_front()->getBeginLoc(),
13423                diag::warn_dispatch_body_ignored);
13424 
13425     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13426       const CXXMethodDecl *KeyFunction;
13427       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13428           MD->isVirtual() &&
13429           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13430           MD == KeyFunction->getCanonicalDecl()) {
13431         // Update the key-function state if necessary for this ABI.
13432         if (FD->isInlined() &&
13433             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13434           Context.setNonKeyFunction(MD);
13435 
13436           // If the newly-chosen key function is already defined, then we
13437           // need to mark the vtable as used retroactively.
13438           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13439           const FunctionDecl *Definition;
13440           if (KeyFunction && KeyFunction->isDefined(Definition))
13441             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13442         } else {
13443           // We just defined they key function; mark the vtable as used.
13444           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13445         }
13446       }
13447     }
13448 
13449     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13450            "Function parsing confused");
13451   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13452     assert(MD == getCurMethodDecl() && "Method parsing confused");
13453     MD->setBody(Body);
13454     if (!MD->isInvalidDecl()) {
13455       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13456                                              MD->getReturnType(), MD);
13457 
13458       if (Body)
13459         computeNRVO(Body, getCurFunction());
13460     }
13461     if (getCurFunction()->ObjCShouldCallSuper) {
13462       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13463           << MD->getSelector().getAsString();
13464       getCurFunction()->ObjCShouldCallSuper = false;
13465     }
13466     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13467       const ObjCMethodDecl *InitMethod = nullptr;
13468       bool isDesignated =
13469           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13470       assert(isDesignated && InitMethod);
13471       (void)isDesignated;
13472 
13473       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13474         auto IFace = MD->getClassInterface();
13475         if (!IFace)
13476           return false;
13477         auto SuperD = IFace->getSuperClass();
13478         if (!SuperD)
13479           return false;
13480         return SuperD->getIdentifier() ==
13481             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13482       };
13483       // Don't issue this warning for unavailable inits or direct subclasses
13484       // of NSObject.
13485       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13486         Diag(MD->getLocation(),
13487              diag::warn_objc_designated_init_missing_super_call);
13488         Diag(InitMethod->getLocation(),
13489              diag::note_objc_designated_init_marked_here);
13490       }
13491       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13492     }
13493     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13494       // Don't issue this warning for unavaialable inits.
13495       if (!MD->isUnavailable())
13496         Diag(MD->getLocation(),
13497              diag::warn_objc_secondary_init_missing_init_call);
13498       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13499     }
13500 
13501     diagnoseImplicitlyRetainedSelf(*this);
13502   } else {
13503     // Parsing the function declaration failed in some way. Pop the fake scope
13504     // we pushed on.
13505     PopFunctionScopeInfo(ActivePolicy, dcl);
13506     return nullptr;
13507   }
13508 
13509   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13510     DiagnoseUnguardedAvailabilityViolations(dcl);
13511 
13512   assert(!getCurFunction()->ObjCShouldCallSuper &&
13513          "This should only be set for ObjC methods, which should have been "
13514          "handled in the block above.");
13515 
13516   // Verify and clean out per-function state.
13517   if (Body && (!FD || !FD->isDefaulted())) {
13518     // C++ constructors that have function-try-blocks can't have return
13519     // statements in the handlers of that block. (C++ [except.handle]p14)
13520     // Verify this.
13521     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13522       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13523 
13524     // Verify that gotos and switch cases don't jump into scopes illegally.
13525     if (getCurFunction()->NeedsScopeChecking() &&
13526         !PP.isCodeCompletionEnabled())
13527       DiagnoseInvalidJumps(Body);
13528 
13529     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13530       if (!Destructor->getParent()->isDependentType())
13531         CheckDestructor(Destructor);
13532 
13533       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13534                                              Destructor->getParent());
13535     }
13536 
13537     // If any errors have occurred, clear out any temporaries that may have
13538     // been leftover. This ensures that these temporaries won't be picked up for
13539     // deletion in some later function.
13540     if (getDiagnostics().hasErrorOccurred() ||
13541         getDiagnostics().getSuppressAllDiagnostics()) {
13542       DiscardCleanupsInEvaluationContext();
13543     }
13544     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13545         !isa<FunctionTemplateDecl>(dcl)) {
13546       // Since the body is valid, issue any analysis-based warnings that are
13547       // enabled.
13548       ActivePolicy = &WP;
13549     }
13550 
13551     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13552         !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
13553       FD->setInvalidDecl();
13554 
13555     if (FD && FD->hasAttr<NakedAttr>()) {
13556       for (const Stmt *S : Body->children()) {
13557         // Allow local register variables without initializer as they don't
13558         // require prologue.
13559         bool RegisterVariables = false;
13560         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13561           for (const auto *Decl : DS->decls()) {
13562             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13563               RegisterVariables =
13564                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13565               if (!RegisterVariables)
13566                 break;
13567             }
13568           }
13569         }
13570         if (RegisterVariables)
13571           continue;
13572         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13573           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13574           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13575           FD->setInvalidDecl();
13576           break;
13577         }
13578       }
13579     }
13580 
13581     assert(ExprCleanupObjects.size() ==
13582                ExprEvalContexts.back().NumCleanupObjects &&
13583            "Leftover temporaries in function");
13584     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13585     assert(MaybeODRUseExprs.empty() &&
13586            "Leftover expressions for odr-use checking");
13587   }
13588 
13589   if (!IsInstantiation)
13590     PopDeclContext();
13591 
13592   PopFunctionScopeInfo(ActivePolicy, dcl);
13593   // If any errors have occurred, clear out any temporaries that may have
13594   // been leftover. This ensures that these temporaries won't be picked up for
13595   // deletion in some later function.
13596   if (getDiagnostics().hasErrorOccurred()) {
13597     DiscardCleanupsInEvaluationContext();
13598   }
13599 
13600   return dcl;
13601 }
13602 
13603 /// When we finish delayed parsing of an attribute, we must attach it to the
13604 /// relevant Decl.
13605 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13606                                        ParsedAttributes &Attrs) {
13607   // Always attach attributes to the underlying decl.
13608   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13609     D = TD->getTemplatedDecl();
13610   ProcessDeclAttributeList(S, D, Attrs);
13611 
13612   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13613     if (Method->isStatic())
13614       checkThisInStaticMemberFunctionAttributes(Method);
13615 }
13616 
13617 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13618 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13619 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13620                                           IdentifierInfo &II, Scope *S) {
13621   // Find the scope in which the identifier is injected and the corresponding
13622   // DeclContext.
13623   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13624   // In that case, we inject the declaration into the translation unit scope
13625   // instead.
13626   Scope *BlockScope = S;
13627   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13628     BlockScope = BlockScope->getParent();
13629 
13630   Scope *ContextScope = BlockScope;
13631   while (!ContextScope->getEntity())
13632     ContextScope = ContextScope->getParent();
13633   ContextRAII SavedContext(*this, ContextScope->getEntity());
13634 
13635   // Before we produce a declaration for an implicitly defined
13636   // function, see whether there was a locally-scoped declaration of
13637   // this name as a function or variable. If so, use that
13638   // (non-visible) declaration, and complain about it.
13639   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13640   if (ExternCPrev) {
13641     // We still need to inject the function into the enclosing block scope so
13642     // that later (non-call) uses can see it.
13643     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13644 
13645     // C89 footnote 38:
13646     //   If in fact it is not defined as having type "function returning int",
13647     //   the behavior is undefined.
13648     if (!isa<FunctionDecl>(ExternCPrev) ||
13649         !Context.typesAreCompatible(
13650             cast<FunctionDecl>(ExternCPrev)->getType(),
13651             Context.getFunctionNoProtoType(Context.IntTy))) {
13652       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13653           << ExternCPrev << !getLangOpts().C99;
13654       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13655       return ExternCPrev;
13656     }
13657   }
13658 
13659   // Extension in C99.  Legal in C90, but warn about it.
13660   unsigned diag_id;
13661   if (II.getName().startswith("__builtin_"))
13662     diag_id = diag::warn_builtin_unknown;
13663   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13664   else if (getLangOpts().OpenCL)
13665     diag_id = diag::err_opencl_implicit_function_decl;
13666   else if (getLangOpts().C99)
13667     diag_id = diag::ext_implicit_function_decl;
13668   else
13669     diag_id = diag::warn_implicit_function_decl;
13670   Diag(Loc, diag_id) << &II;
13671 
13672   // If we found a prior declaration of this function, don't bother building
13673   // another one. We've already pushed that one into scope, so there's nothing
13674   // more to do.
13675   if (ExternCPrev)
13676     return ExternCPrev;
13677 
13678   // Because typo correction is expensive, only do it if the implicit
13679   // function declaration is going to be treated as an error.
13680   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13681     TypoCorrection Corrected;
13682     DeclFilterCCC<FunctionDecl> CCC{};
13683     if (S && (Corrected =
13684                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
13685                               S, nullptr, CCC, CTK_NonError)))
13686       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13687                    /*ErrorRecovery*/false);
13688   }
13689 
13690   // Set a Declarator for the implicit definition: int foo();
13691   const char *Dummy;
13692   AttributeFactory attrFactory;
13693   DeclSpec DS(attrFactory);
13694   unsigned DiagID;
13695   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13696                                   Context.getPrintingPolicy());
13697   (void)Error; // Silence warning.
13698   assert(!Error && "Error setting up implicit decl!");
13699   SourceLocation NoLoc;
13700   Declarator D(DS, DeclaratorContext::BlockContext);
13701   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13702                                              /*IsAmbiguous=*/false,
13703                                              /*LParenLoc=*/NoLoc,
13704                                              /*Params=*/nullptr,
13705                                              /*NumParams=*/0,
13706                                              /*EllipsisLoc=*/NoLoc,
13707                                              /*RParenLoc=*/NoLoc,
13708                                              /*RefQualifierIsLvalueRef=*/true,
13709                                              /*RefQualifierLoc=*/NoLoc,
13710                                              /*MutableLoc=*/NoLoc, EST_None,
13711                                              /*ESpecRange=*/SourceRange(),
13712                                              /*Exceptions=*/nullptr,
13713                                              /*ExceptionRanges=*/nullptr,
13714                                              /*NumExceptions=*/0,
13715                                              /*NoexceptExpr=*/nullptr,
13716                                              /*ExceptionSpecTokens=*/nullptr,
13717                                              /*DeclsInPrototype=*/None, Loc,
13718                                              Loc, D),
13719                 std::move(DS.getAttributes()), SourceLocation());
13720   D.SetIdentifier(&II, Loc);
13721 
13722   // Insert this function into the enclosing block scope.
13723   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13724   FD->setImplicit();
13725 
13726   AddKnownFunctionAttributes(FD);
13727 
13728   return FD;
13729 }
13730 
13731 /// Adds any function attributes that we know a priori based on
13732 /// the declaration of this function.
13733 ///
13734 /// These attributes can apply both to implicitly-declared builtins
13735 /// (like __builtin___printf_chk) or to library-declared functions
13736 /// like NSLog or printf.
13737 ///
13738 /// We need to check for duplicate attributes both here and where user-written
13739 /// attributes are applied to declarations.
13740 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13741   if (FD->isInvalidDecl())
13742     return;
13743 
13744   // If this is a built-in function, map its builtin attributes to
13745   // actual attributes.
13746   if (unsigned BuiltinID = FD->getBuiltinID()) {
13747     // Handle printf-formatting attributes.
13748     unsigned FormatIdx;
13749     bool HasVAListArg;
13750     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13751       if (!FD->hasAttr<FormatAttr>()) {
13752         const char *fmt = "printf";
13753         unsigned int NumParams = FD->getNumParams();
13754         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13755             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13756           fmt = "NSString";
13757         FD->addAttr(FormatAttr::CreateImplicit(Context,
13758                                                &Context.Idents.get(fmt),
13759                                                FormatIdx+1,
13760                                                HasVAListArg ? 0 : FormatIdx+2,
13761                                                FD->getLocation()));
13762       }
13763     }
13764     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13765                                              HasVAListArg)) {
13766      if (!FD->hasAttr<FormatAttr>())
13767        FD->addAttr(FormatAttr::CreateImplicit(Context,
13768                                               &Context.Idents.get("scanf"),
13769                                               FormatIdx+1,
13770                                               HasVAListArg ? 0 : FormatIdx+2,
13771                                               FD->getLocation()));
13772     }
13773 
13774     // Handle automatically recognized callbacks.
13775     SmallVector<int, 4> Encoding;
13776     if (!FD->hasAttr<CallbackAttr>() &&
13777         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13778       FD->addAttr(CallbackAttr::CreateImplicit(
13779           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13780 
13781     // Mark const if we don't care about errno and that is the only thing
13782     // preventing the function from being const. This allows IRgen to use LLVM
13783     // intrinsics for such functions.
13784     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13785         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13786       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13787 
13788     // We make "fma" on some platforms const because we know it does not set
13789     // errno in those environments even though it could set errno based on the
13790     // C standard.
13791     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13792     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13793         !FD->hasAttr<ConstAttr>()) {
13794       switch (BuiltinID) {
13795       case Builtin::BI__builtin_fma:
13796       case Builtin::BI__builtin_fmaf:
13797       case Builtin::BI__builtin_fmal:
13798       case Builtin::BIfma:
13799       case Builtin::BIfmaf:
13800       case Builtin::BIfmal:
13801         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13802         break;
13803       default:
13804         break;
13805       }
13806     }
13807 
13808     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13809         !FD->hasAttr<ReturnsTwiceAttr>())
13810       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13811                                          FD->getLocation()));
13812     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13813       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13814     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13815       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13816     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13817       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13818     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13819         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13820       // Add the appropriate attribute, depending on the CUDA compilation mode
13821       // and which target the builtin belongs to. For example, during host
13822       // compilation, aux builtins are __device__, while the rest are __host__.
13823       if (getLangOpts().CUDAIsDevice !=
13824           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13825         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13826       else
13827         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13828     }
13829   }
13830 
13831   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13832   // throw, add an implicit nothrow attribute to any extern "C" function we come
13833   // across.
13834   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13835       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13836     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13837     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13838       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13839   }
13840 
13841   IdentifierInfo *Name = FD->getIdentifier();
13842   if (!Name)
13843     return;
13844   if ((!getLangOpts().CPlusPlus &&
13845        FD->getDeclContext()->isTranslationUnit()) ||
13846       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13847        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13848        LinkageSpecDecl::lang_c)) {
13849     // Okay: this could be a libc/libm/Objective-C function we know
13850     // about.
13851   } else
13852     return;
13853 
13854   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13855     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13856     // target-specific builtins, perhaps?
13857     if (!FD->hasAttr<FormatAttr>())
13858       FD->addAttr(FormatAttr::CreateImplicit(Context,
13859                                              &Context.Idents.get("printf"), 2,
13860                                              Name->isStr("vasprintf") ? 0 : 3,
13861                                              FD->getLocation()));
13862   }
13863 
13864   if (Name->isStr("__CFStringMakeConstantString")) {
13865     // We already have a __builtin___CFStringMakeConstantString,
13866     // but builds that use -fno-constant-cfstrings don't go through that.
13867     if (!FD->hasAttr<FormatArgAttr>())
13868       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13869                                                 FD->getLocation()));
13870   }
13871 }
13872 
13873 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13874                                     TypeSourceInfo *TInfo) {
13875   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13876   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13877 
13878   if (!TInfo) {
13879     assert(D.isInvalidType() && "no declarator info for valid type");
13880     TInfo = Context.getTrivialTypeSourceInfo(T);
13881   }
13882 
13883   // Scope manipulation handled by caller.
13884   TypedefDecl *NewTD =
13885       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13886                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13887 
13888   // Bail out immediately if we have an invalid declaration.
13889   if (D.isInvalidType()) {
13890     NewTD->setInvalidDecl();
13891     return NewTD;
13892   }
13893 
13894   if (D.getDeclSpec().isModulePrivateSpecified()) {
13895     if (CurContext->isFunctionOrMethod())
13896       Diag(NewTD->getLocation(), diag::err_module_private_local)
13897         << 2 << NewTD->getDeclName()
13898         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13899         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13900     else
13901       NewTD->setModulePrivate();
13902   }
13903 
13904   // C++ [dcl.typedef]p8:
13905   //   If the typedef declaration defines an unnamed class (or
13906   //   enum), the first typedef-name declared by the declaration
13907   //   to be that class type (or enum type) is used to denote the
13908   //   class type (or enum type) for linkage purposes only.
13909   // We need to check whether the type was declared in the declaration.
13910   switch (D.getDeclSpec().getTypeSpecType()) {
13911   case TST_enum:
13912   case TST_struct:
13913   case TST_interface:
13914   case TST_union:
13915   case TST_class: {
13916     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13917     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13918     break;
13919   }
13920 
13921   default:
13922     break;
13923   }
13924 
13925   return NewTD;
13926 }
13927 
13928 /// Check that this is a valid underlying type for an enum declaration.
13929 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13930   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13931   QualType T = TI->getType();
13932 
13933   if (T->isDependentType())
13934     return false;
13935 
13936   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13937     if (BT->isInteger())
13938       return false;
13939 
13940   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13941   return true;
13942 }
13943 
13944 /// Check whether this is a valid redeclaration of a previous enumeration.
13945 /// \return true if the redeclaration was invalid.
13946 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13947                                   QualType EnumUnderlyingTy, bool IsFixed,
13948                                   const EnumDecl *Prev) {
13949   if (IsScoped != Prev->isScoped()) {
13950     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13951       << Prev->isScoped();
13952     Diag(Prev->getLocation(), diag::note_previous_declaration);
13953     return true;
13954   }
13955 
13956   if (IsFixed && Prev->isFixed()) {
13957     if (!EnumUnderlyingTy->isDependentType() &&
13958         !Prev->getIntegerType()->isDependentType() &&
13959         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13960                                         Prev->getIntegerType())) {
13961       // TODO: Highlight the underlying type of the redeclaration.
13962       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13963         << EnumUnderlyingTy << Prev->getIntegerType();
13964       Diag(Prev->getLocation(), diag::note_previous_declaration)
13965           << Prev->getIntegerTypeRange();
13966       return true;
13967     }
13968   } else if (IsFixed != Prev->isFixed()) {
13969     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13970       << Prev->isFixed();
13971     Diag(Prev->getLocation(), diag::note_previous_declaration);
13972     return true;
13973   }
13974 
13975   return false;
13976 }
13977 
13978 /// Get diagnostic %select index for tag kind for
13979 /// redeclaration diagnostic message.
13980 /// WARNING: Indexes apply to particular diagnostics only!
13981 ///
13982 /// \returns diagnostic %select index.
13983 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13984   switch (Tag) {
13985   case TTK_Struct: return 0;
13986   case TTK_Interface: return 1;
13987   case TTK_Class:  return 2;
13988   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13989   }
13990 }
13991 
13992 /// Determine if tag kind is a class-key compatible with
13993 /// class for redeclaration (class, struct, or __interface).
13994 ///
13995 /// \returns true iff the tag kind is compatible.
13996 static bool isClassCompatTagKind(TagTypeKind Tag)
13997 {
13998   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13999 }
14000 
14001 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
14002                                              TagTypeKind TTK) {
14003   if (isa<TypedefDecl>(PrevDecl))
14004     return NTK_Typedef;
14005   else if (isa<TypeAliasDecl>(PrevDecl))
14006     return NTK_TypeAlias;
14007   else if (isa<ClassTemplateDecl>(PrevDecl))
14008     return NTK_Template;
14009   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
14010     return NTK_TypeAliasTemplate;
14011   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
14012     return NTK_TemplateTemplateArgument;
14013   switch (TTK) {
14014   case TTK_Struct:
14015   case TTK_Interface:
14016   case TTK_Class:
14017     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
14018   case TTK_Union:
14019     return NTK_NonUnion;
14020   case TTK_Enum:
14021     return NTK_NonEnum;
14022   }
14023   llvm_unreachable("invalid TTK");
14024 }
14025 
14026 /// Determine whether a tag with a given kind is acceptable
14027 /// as a redeclaration of the given tag declaration.
14028 ///
14029 /// \returns true if the new tag kind is acceptable, false otherwise.
14030 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
14031                                         TagTypeKind NewTag, bool isDefinition,
14032                                         SourceLocation NewTagLoc,
14033                                         const IdentifierInfo *Name) {
14034   // C++ [dcl.type.elab]p3:
14035   //   The class-key or enum keyword present in the
14036   //   elaborated-type-specifier shall agree in kind with the
14037   //   declaration to which the name in the elaborated-type-specifier
14038   //   refers. This rule also applies to the form of
14039   //   elaborated-type-specifier that declares a class-name or
14040   //   friend class since it can be construed as referring to the
14041   //   definition of the class. Thus, in any
14042   //   elaborated-type-specifier, the enum keyword shall be used to
14043   //   refer to an enumeration (7.2), the union class-key shall be
14044   //   used to refer to a union (clause 9), and either the class or
14045   //   struct class-key shall be used to refer to a class (clause 9)
14046   //   declared using the class or struct class-key.
14047   TagTypeKind OldTag = Previous->getTagKind();
14048   if (OldTag != NewTag &&
14049       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
14050     return false;
14051 
14052   // Tags are compatible, but we might still want to warn on mismatched tags.
14053   // Non-class tags can't be mismatched at this point.
14054   if (!isClassCompatTagKind(NewTag))
14055     return true;
14056 
14057   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
14058   // by our warning analysis. We don't want to warn about mismatches with (eg)
14059   // declarations in system headers that are designed to be specialized, but if
14060   // a user asks us to warn, we should warn if their code contains mismatched
14061   // declarations.
14062   auto IsIgnoredLoc = [&](SourceLocation Loc) {
14063     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
14064                                       Loc);
14065   };
14066   if (IsIgnoredLoc(NewTagLoc))
14067     return true;
14068 
14069   auto IsIgnored = [&](const TagDecl *Tag) {
14070     return IsIgnoredLoc(Tag->getLocation());
14071   };
14072   while (IsIgnored(Previous)) {
14073     Previous = Previous->getPreviousDecl();
14074     if (!Previous)
14075       return true;
14076     OldTag = Previous->getTagKind();
14077   }
14078 
14079   bool isTemplate = false;
14080   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
14081     isTemplate = Record->getDescribedClassTemplate();
14082 
14083   if (inTemplateInstantiation()) {
14084     if (OldTag != NewTag) {
14085       // In a template instantiation, do not offer fix-its for tag mismatches
14086       // since they usually mess up the template instead of fixing the problem.
14087       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14088         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14089         << getRedeclDiagFromTagKind(OldTag);
14090       // FIXME: Note previous location?
14091     }
14092     return true;
14093   }
14094 
14095   if (isDefinition) {
14096     // On definitions, check all previous tags and issue a fix-it for each
14097     // one that doesn't match the current tag.
14098     if (Previous->getDefinition()) {
14099       // Don't suggest fix-its for redefinitions.
14100       return true;
14101     }
14102 
14103     bool previousMismatch = false;
14104     for (const TagDecl *I : Previous->redecls()) {
14105       if (I->getTagKind() != NewTag) {
14106         // Ignore previous declarations for which the warning was disabled.
14107         if (IsIgnored(I))
14108           continue;
14109 
14110         if (!previousMismatch) {
14111           previousMismatch = true;
14112           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14113             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14114             << getRedeclDiagFromTagKind(I->getTagKind());
14115         }
14116         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14117           << getRedeclDiagFromTagKind(NewTag)
14118           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14119                TypeWithKeyword::getTagTypeKindName(NewTag));
14120       }
14121     }
14122     return true;
14123   }
14124 
14125   // Identify the prevailing tag kind: this is the kind of the definition (if
14126   // there is a non-ignored definition), or otherwise the kind of the prior
14127   // (non-ignored) declaration.
14128   const TagDecl *PrevDef = Previous->getDefinition();
14129   if (PrevDef && IsIgnored(PrevDef))
14130     PrevDef = nullptr;
14131   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14132   if (Redecl->getTagKind() != NewTag) {
14133     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14134       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14135       << getRedeclDiagFromTagKind(OldTag);
14136     Diag(Redecl->getLocation(), diag::note_previous_use);
14137 
14138     // If there is a previous definition, suggest a fix-it.
14139     if (PrevDef) {
14140       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14141         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14142         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14143              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14144     }
14145   }
14146 
14147   return true;
14148 }
14149 
14150 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14151 /// from an outer enclosing namespace or file scope inside a friend declaration.
14152 /// This should provide the commented out code in the following snippet:
14153 ///   namespace N {
14154 ///     struct X;
14155 ///     namespace M {
14156 ///       struct Y { friend struct /*N::*/ X; };
14157 ///     }
14158 ///   }
14159 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14160                                          SourceLocation NameLoc) {
14161   // While the decl is in a namespace, do repeated lookup of that name and see
14162   // if we get the same namespace back.  If we do not, continue until
14163   // translation unit scope, at which point we have a fully qualified NNS.
14164   SmallVector<IdentifierInfo *, 4> Namespaces;
14165   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14166   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14167     // This tag should be declared in a namespace, which can only be enclosed by
14168     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14169     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14170     if (!Namespace || Namespace->isAnonymousNamespace())
14171       return FixItHint();
14172     IdentifierInfo *II = Namespace->getIdentifier();
14173     Namespaces.push_back(II);
14174     NamedDecl *Lookup = SemaRef.LookupSingleName(
14175         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14176     if (Lookup == Namespace)
14177       break;
14178   }
14179 
14180   // Once we have all the namespaces, reverse them to go outermost first, and
14181   // build an NNS.
14182   SmallString<64> Insertion;
14183   llvm::raw_svector_ostream OS(Insertion);
14184   if (DC->isTranslationUnit())
14185     OS << "::";
14186   std::reverse(Namespaces.begin(), Namespaces.end());
14187   for (auto *II : Namespaces)
14188     OS << II->getName() << "::";
14189   return FixItHint::CreateInsertion(NameLoc, Insertion);
14190 }
14191 
14192 /// Determine whether a tag originally declared in context \p OldDC can
14193 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14194 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14195 /// using-declaration).
14196 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14197                                          DeclContext *NewDC) {
14198   OldDC = OldDC->getRedeclContext();
14199   NewDC = NewDC->getRedeclContext();
14200 
14201   if (OldDC->Equals(NewDC))
14202     return true;
14203 
14204   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14205   // encloses the other).
14206   if (S.getLangOpts().MSVCCompat &&
14207       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14208     return true;
14209 
14210   return false;
14211 }
14212 
14213 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14214 /// former case, Name will be non-null.  In the later case, Name will be null.
14215 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14216 /// reference/declaration/definition of a tag.
14217 ///
14218 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14219 /// trailing-type-specifier) other than one in an alias-declaration.
14220 ///
14221 /// \param SkipBody If non-null, will be set to indicate if the caller should
14222 /// skip the definition of this tag and treat it as if it were a declaration.
14223 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14224                      SourceLocation KWLoc, CXXScopeSpec &SS,
14225                      IdentifierInfo *Name, SourceLocation NameLoc,
14226                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14227                      SourceLocation ModulePrivateLoc,
14228                      MultiTemplateParamsArg TemplateParameterLists,
14229                      bool &OwnedDecl, bool &IsDependent,
14230                      SourceLocation ScopedEnumKWLoc,
14231                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14232                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14233                      SkipBodyInfo *SkipBody) {
14234   // If this is not a definition, it must have a name.
14235   IdentifierInfo *OrigName = Name;
14236   assert((Name != nullptr || TUK == TUK_Definition) &&
14237          "Nameless record must be a definition!");
14238   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14239 
14240   OwnedDecl = false;
14241   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14242   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14243 
14244   // FIXME: Check member specializations more carefully.
14245   bool isMemberSpecialization = false;
14246   bool Invalid = false;
14247 
14248   // We only need to do this matching if we have template parameters
14249   // or a scope specifier, which also conveniently avoids this work
14250   // for non-C++ cases.
14251   if (TemplateParameterLists.size() > 0 ||
14252       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14253     if (TemplateParameterList *TemplateParams =
14254             MatchTemplateParametersToScopeSpecifier(
14255                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14256                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14257       if (Kind == TTK_Enum) {
14258         Diag(KWLoc, diag::err_enum_template);
14259         return nullptr;
14260       }
14261 
14262       if (TemplateParams->size() > 0) {
14263         // This is a declaration or definition of a class template (which may
14264         // be a member of another template).
14265 
14266         if (Invalid)
14267           return nullptr;
14268 
14269         OwnedDecl = false;
14270         DeclResult Result = CheckClassTemplate(
14271             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14272             AS, ModulePrivateLoc,
14273             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14274             TemplateParameterLists.data(), SkipBody);
14275         return Result.get();
14276       } else {
14277         // The "template<>" header is extraneous.
14278         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14279           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14280         isMemberSpecialization = true;
14281       }
14282     }
14283   }
14284 
14285   // Figure out the underlying type if this a enum declaration. We need to do
14286   // this early, because it's needed to detect if this is an incompatible
14287   // redeclaration.
14288   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14289   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14290 
14291   if (Kind == TTK_Enum) {
14292     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14293       // No underlying type explicitly specified, or we failed to parse the
14294       // type, default to int.
14295       EnumUnderlying = Context.IntTy.getTypePtr();
14296     } else if (UnderlyingType.get()) {
14297       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14298       // integral type; any cv-qualification is ignored.
14299       TypeSourceInfo *TI = nullptr;
14300       GetTypeFromParser(UnderlyingType.get(), &TI);
14301       EnumUnderlying = TI;
14302 
14303       if (CheckEnumUnderlyingType(TI))
14304         // Recover by falling back to int.
14305         EnumUnderlying = Context.IntTy.getTypePtr();
14306 
14307       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14308                                           UPPC_FixedUnderlyingType))
14309         EnumUnderlying = Context.IntTy.getTypePtr();
14310 
14311     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14312       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14313       // of 'int'. However, if this is an unfixed forward declaration, don't set
14314       // the underlying type unless the user enables -fms-compatibility. This
14315       // makes unfixed forward declared enums incomplete and is more conforming.
14316       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14317         EnumUnderlying = Context.IntTy.getTypePtr();
14318     }
14319   }
14320 
14321   DeclContext *SearchDC = CurContext;
14322   DeclContext *DC = CurContext;
14323   bool isStdBadAlloc = false;
14324   bool isStdAlignValT = false;
14325 
14326   RedeclarationKind Redecl = forRedeclarationInCurContext();
14327   if (TUK == TUK_Friend || TUK == TUK_Reference)
14328     Redecl = NotForRedeclaration;
14329 
14330   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14331   /// implemented asks for structural equivalence checking, the returned decl
14332   /// here is passed back to the parser, allowing the tag body to be parsed.
14333   auto createTagFromNewDecl = [&]() -> TagDecl * {
14334     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14335     // If there is an identifier, use the location of the identifier as the
14336     // location of the decl, otherwise use the location of the struct/union
14337     // keyword.
14338     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14339     TagDecl *New = nullptr;
14340 
14341     if (Kind == TTK_Enum) {
14342       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14343                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14344       // If this is an undefined enum, bail.
14345       if (TUK != TUK_Definition && !Invalid)
14346         return nullptr;
14347       if (EnumUnderlying) {
14348         EnumDecl *ED = cast<EnumDecl>(New);
14349         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14350           ED->setIntegerTypeSourceInfo(TI);
14351         else
14352           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14353         ED->setPromotionType(ED->getIntegerType());
14354       }
14355     } else { // struct/union
14356       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14357                                nullptr);
14358     }
14359 
14360     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14361       // Add alignment attributes if necessary; these attributes are checked
14362       // when the ASTContext lays out the structure.
14363       //
14364       // It is important for implementing the correct semantics that this
14365       // happen here (in ActOnTag). The #pragma pack stack is
14366       // maintained as a result of parser callbacks which can occur at
14367       // many points during the parsing of a struct declaration (because
14368       // the #pragma tokens are effectively skipped over during the
14369       // parsing of the struct).
14370       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14371         AddAlignmentAttributesForRecord(RD);
14372         AddMsStructLayoutForRecord(RD);
14373       }
14374     }
14375     New->setLexicalDeclContext(CurContext);
14376     return New;
14377   };
14378 
14379   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14380   if (Name && SS.isNotEmpty()) {
14381     // We have a nested-name tag ('struct foo::bar').
14382 
14383     // Check for invalid 'foo::'.
14384     if (SS.isInvalid()) {
14385       Name = nullptr;
14386       goto CreateNewDecl;
14387     }
14388 
14389     // If this is a friend or a reference to a class in a dependent
14390     // context, don't try to make a decl for it.
14391     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14392       DC = computeDeclContext(SS, false);
14393       if (!DC) {
14394         IsDependent = true;
14395         return nullptr;
14396       }
14397     } else {
14398       DC = computeDeclContext(SS, true);
14399       if (!DC) {
14400         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14401           << SS.getRange();
14402         return nullptr;
14403       }
14404     }
14405 
14406     if (RequireCompleteDeclContext(SS, DC))
14407       return nullptr;
14408 
14409     SearchDC = DC;
14410     // Look-up name inside 'foo::'.
14411     LookupQualifiedName(Previous, DC);
14412 
14413     if (Previous.isAmbiguous())
14414       return nullptr;
14415 
14416     if (Previous.empty()) {
14417       // Name lookup did not find anything. However, if the
14418       // nested-name-specifier refers to the current instantiation,
14419       // and that current instantiation has any dependent base
14420       // classes, we might find something at instantiation time: treat
14421       // this as a dependent elaborated-type-specifier.
14422       // But this only makes any sense for reference-like lookups.
14423       if (Previous.wasNotFoundInCurrentInstantiation() &&
14424           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14425         IsDependent = true;
14426         return nullptr;
14427       }
14428 
14429       // A tag 'foo::bar' must already exist.
14430       Diag(NameLoc, diag::err_not_tag_in_scope)
14431         << Kind << Name << DC << SS.getRange();
14432       Name = nullptr;
14433       Invalid = true;
14434       goto CreateNewDecl;
14435     }
14436   } else if (Name) {
14437     // C++14 [class.mem]p14:
14438     //   If T is the name of a class, then each of the following shall have a
14439     //   name different from T:
14440     //    -- every member of class T that is itself a type
14441     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14442         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14443       return nullptr;
14444 
14445     // If this is a named struct, check to see if there was a previous forward
14446     // declaration or definition.
14447     // FIXME: We're looking into outer scopes here, even when we
14448     // shouldn't be. Doing so can result in ambiguities that we
14449     // shouldn't be diagnosing.
14450     LookupName(Previous, S);
14451 
14452     // When declaring or defining a tag, ignore ambiguities introduced
14453     // by types using'ed into this scope.
14454     if (Previous.isAmbiguous() &&
14455         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14456       LookupResult::Filter F = Previous.makeFilter();
14457       while (F.hasNext()) {
14458         NamedDecl *ND = F.next();
14459         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14460                 SearchDC->getRedeclContext()))
14461           F.erase();
14462       }
14463       F.done();
14464     }
14465 
14466     // C++11 [namespace.memdef]p3:
14467     //   If the name in a friend declaration is neither qualified nor
14468     //   a template-id and the declaration is a function or an
14469     //   elaborated-type-specifier, the lookup to determine whether
14470     //   the entity has been previously declared shall not consider
14471     //   any scopes outside the innermost enclosing namespace.
14472     //
14473     // MSVC doesn't implement the above rule for types, so a friend tag
14474     // declaration may be a redeclaration of a type declared in an enclosing
14475     // scope.  They do implement this rule for friend functions.
14476     //
14477     // Does it matter that this should be by scope instead of by
14478     // semantic context?
14479     if (!Previous.empty() && TUK == TUK_Friend) {
14480       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14481       LookupResult::Filter F = Previous.makeFilter();
14482       bool FriendSawTagOutsideEnclosingNamespace = false;
14483       while (F.hasNext()) {
14484         NamedDecl *ND = F.next();
14485         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14486         if (DC->isFileContext() &&
14487             !EnclosingNS->Encloses(ND->getDeclContext())) {
14488           if (getLangOpts().MSVCCompat)
14489             FriendSawTagOutsideEnclosingNamespace = true;
14490           else
14491             F.erase();
14492         }
14493       }
14494       F.done();
14495 
14496       // Diagnose this MSVC extension in the easy case where lookup would have
14497       // unambiguously found something outside the enclosing namespace.
14498       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14499         NamedDecl *ND = Previous.getFoundDecl();
14500         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14501             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14502       }
14503     }
14504 
14505     // Note:  there used to be some attempt at recovery here.
14506     if (Previous.isAmbiguous())
14507       return nullptr;
14508 
14509     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14510       // FIXME: This makes sure that we ignore the contexts associated
14511       // with C structs, unions, and enums when looking for a matching
14512       // tag declaration or definition. See the similar lookup tweak
14513       // in Sema::LookupName; is there a better way to deal with this?
14514       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14515         SearchDC = SearchDC->getParent();
14516     }
14517   }
14518 
14519   if (Previous.isSingleResult() &&
14520       Previous.getFoundDecl()->isTemplateParameter()) {
14521     // Maybe we will complain about the shadowed template parameter.
14522     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14523     // Just pretend that we didn't see the previous declaration.
14524     Previous.clear();
14525   }
14526 
14527   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14528       DC->Equals(getStdNamespace())) {
14529     if (Name->isStr("bad_alloc")) {
14530       // This is a declaration of or a reference to "std::bad_alloc".
14531       isStdBadAlloc = true;
14532 
14533       // If std::bad_alloc has been implicitly declared (but made invisible to
14534       // name lookup), fill in this implicit declaration as the previous
14535       // declaration, so that the declarations get chained appropriately.
14536       if (Previous.empty() && StdBadAlloc)
14537         Previous.addDecl(getStdBadAlloc());
14538     } else if (Name->isStr("align_val_t")) {
14539       isStdAlignValT = true;
14540       if (Previous.empty() && StdAlignValT)
14541         Previous.addDecl(getStdAlignValT());
14542     }
14543   }
14544 
14545   // If we didn't find a previous declaration, and this is a reference
14546   // (or friend reference), move to the correct scope.  In C++, we
14547   // also need to do a redeclaration lookup there, just in case
14548   // there's a shadow friend decl.
14549   if (Name && Previous.empty() &&
14550       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14551     if (Invalid) goto CreateNewDecl;
14552     assert(SS.isEmpty());
14553 
14554     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14555       // C++ [basic.scope.pdecl]p5:
14556       //   -- for an elaborated-type-specifier of the form
14557       //
14558       //          class-key identifier
14559       //
14560       //      if the elaborated-type-specifier is used in the
14561       //      decl-specifier-seq or parameter-declaration-clause of a
14562       //      function defined in namespace scope, the identifier is
14563       //      declared as a class-name in the namespace that contains
14564       //      the declaration; otherwise, except as a friend
14565       //      declaration, the identifier is declared in the smallest
14566       //      non-class, non-function-prototype scope that contains the
14567       //      declaration.
14568       //
14569       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14570       // C structs and unions.
14571       //
14572       // It is an error in C++ to declare (rather than define) an enum
14573       // type, including via an elaborated type specifier.  We'll
14574       // diagnose that later; for now, declare the enum in the same
14575       // scope as we would have picked for any other tag type.
14576       //
14577       // GNU C also supports this behavior as part of its incomplete
14578       // enum types extension, while GNU C++ does not.
14579       //
14580       // Find the context where we'll be declaring the tag.
14581       // FIXME: We would like to maintain the current DeclContext as the
14582       // lexical context,
14583       SearchDC = getTagInjectionContext(SearchDC);
14584 
14585       // Find the scope where we'll be declaring the tag.
14586       S = getTagInjectionScope(S, getLangOpts());
14587     } else {
14588       assert(TUK == TUK_Friend);
14589       // C++ [namespace.memdef]p3:
14590       //   If a friend declaration in a non-local class first declares a
14591       //   class or function, the friend class or function is a member of
14592       //   the innermost enclosing namespace.
14593       SearchDC = SearchDC->getEnclosingNamespaceContext();
14594     }
14595 
14596     // In C++, we need to do a redeclaration lookup to properly
14597     // diagnose some problems.
14598     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14599     // hidden declaration so that we don't get ambiguity errors when using a
14600     // type declared by an elaborated-type-specifier.  In C that is not correct
14601     // and we should instead merge compatible types found by lookup.
14602     if (getLangOpts().CPlusPlus) {
14603       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14604       LookupQualifiedName(Previous, SearchDC);
14605     } else {
14606       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14607       LookupName(Previous, S);
14608     }
14609   }
14610 
14611   // If we have a known previous declaration to use, then use it.
14612   if (Previous.empty() && SkipBody && SkipBody->Previous)
14613     Previous.addDecl(SkipBody->Previous);
14614 
14615   if (!Previous.empty()) {
14616     NamedDecl *PrevDecl = Previous.getFoundDecl();
14617     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14618 
14619     // It's okay to have a tag decl in the same scope as a typedef
14620     // which hides a tag decl in the same scope.  Finding this
14621     // insanity with a redeclaration lookup can only actually happen
14622     // in C++.
14623     //
14624     // This is also okay for elaborated-type-specifiers, which is
14625     // technically forbidden by the current standard but which is
14626     // okay according to the likely resolution of an open issue;
14627     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14628     if (getLangOpts().CPlusPlus) {
14629       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14630         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14631           TagDecl *Tag = TT->getDecl();
14632           if (Tag->getDeclName() == Name &&
14633               Tag->getDeclContext()->getRedeclContext()
14634                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14635             PrevDecl = Tag;
14636             Previous.clear();
14637             Previous.addDecl(Tag);
14638             Previous.resolveKind();
14639           }
14640         }
14641       }
14642     }
14643 
14644     // If this is a redeclaration of a using shadow declaration, it must
14645     // declare a tag in the same context. In MSVC mode, we allow a
14646     // redefinition if either context is within the other.
14647     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14648       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14649       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14650           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14651           !(OldTag && isAcceptableTagRedeclContext(
14652                           *this, OldTag->getDeclContext(), SearchDC))) {
14653         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14654         Diag(Shadow->getTargetDecl()->getLocation(),
14655              diag::note_using_decl_target);
14656         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14657             << 0;
14658         // Recover by ignoring the old declaration.
14659         Previous.clear();
14660         goto CreateNewDecl;
14661       }
14662     }
14663 
14664     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14665       // If this is a use of a previous tag, or if the tag is already declared
14666       // in the same scope (so that the definition/declaration completes or
14667       // rementions the tag), reuse the decl.
14668       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14669           isDeclInScope(DirectPrevDecl, SearchDC, S,
14670                         SS.isNotEmpty() || isMemberSpecialization)) {
14671         // Make sure that this wasn't declared as an enum and now used as a
14672         // struct or something similar.
14673         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14674                                           TUK == TUK_Definition, KWLoc,
14675                                           Name)) {
14676           bool SafeToContinue
14677             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14678                Kind != TTK_Enum);
14679           if (SafeToContinue)
14680             Diag(KWLoc, diag::err_use_with_wrong_tag)
14681               << Name
14682               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14683                                               PrevTagDecl->getKindName());
14684           else
14685             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14686           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14687 
14688           if (SafeToContinue)
14689             Kind = PrevTagDecl->getTagKind();
14690           else {
14691             // Recover by making this an anonymous redefinition.
14692             Name = nullptr;
14693             Previous.clear();
14694             Invalid = true;
14695           }
14696         }
14697 
14698         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14699           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14700 
14701           // If this is an elaborated-type-specifier for a scoped enumeration,
14702           // the 'class' keyword is not necessary and not permitted.
14703           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14704             if (ScopedEnum)
14705               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14706                 << PrevEnum->isScoped()
14707                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14708             return PrevTagDecl;
14709           }
14710 
14711           QualType EnumUnderlyingTy;
14712           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14713             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14714           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14715             EnumUnderlyingTy = QualType(T, 0);
14716 
14717           // All conflicts with previous declarations are recovered by
14718           // returning the previous declaration, unless this is a definition,
14719           // in which case we want the caller to bail out.
14720           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14721                                      ScopedEnum, EnumUnderlyingTy,
14722                                      IsFixed, PrevEnum))
14723             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14724         }
14725 
14726         // C++11 [class.mem]p1:
14727         //   A member shall not be declared twice in the member-specification,
14728         //   except that a nested class or member class template can be declared
14729         //   and then later defined.
14730         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14731             S->isDeclScope(PrevDecl)) {
14732           Diag(NameLoc, diag::ext_member_redeclared);
14733           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14734         }
14735 
14736         if (!Invalid) {
14737           // If this is a use, just return the declaration we found, unless
14738           // we have attributes.
14739           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14740             if (!Attrs.empty()) {
14741               // FIXME: Diagnose these attributes. For now, we create a new
14742               // declaration to hold them.
14743             } else if (TUK == TUK_Reference &&
14744                        (PrevTagDecl->getFriendObjectKind() ==
14745                             Decl::FOK_Undeclared ||
14746                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14747                        SS.isEmpty()) {
14748               // This declaration is a reference to an existing entity, but
14749               // has different visibility from that entity: it either makes
14750               // a friend visible or it makes a type visible in a new module.
14751               // In either case, create a new declaration. We only do this if
14752               // the declaration would have meant the same thing if no prior
14753               // declaration were found, that is, if it was found in the same
14754               // scope where we would have injected a declaration.
14755               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14756                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14757                 return PrevTagDecl;
14758               // This is in the injected scope, create a new declaration in
14759               // that scope.
14760               S = getTagInjectionScope(S, getLangOpts());
14761             } else {
14762               return PrevTagDecl;
14763             }
14764           }
14765 
14766           // Diagnose attempts to redefine a tag.
14767           if (TUK == TUK_Definition) {
14768             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14769               // If we're defining a specialization and the previous definition
14770               // is from an implicit instantiation, don't emit an error
14771               // here; we'll catch this in the general case below.
14772               bool IsExplicitSpecializationAfterInstantiation = false;
14773               if (isMemberSpecialization) {
14774                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14775                   IsExplicitSpecializationAfterInstantiation =
14776                     RD->getTemplateSpecializationKind() !=
14777                     TSK_ExplicitSpecialization;
14778                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14779                   IsExplicitSpecializationAfterInstantiation =
14780                     ED->getTemplateSpecializationKind() !=
14781                     TSK_ExplicitSpecialization;
14782               }
14783 
14784               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14785               // not keep more that one definition around (merge them). However,
14786               // ensure the decl passes the structural compatibility check in
14787               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14788               NamedDecl *Hidden = nullptr;
14789               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14790                 // There is a definition of this tag, but it is not visible. We
14791                 // explicitly make use of C++'s one definition rule here, and
14792                 // assume that this definition is identical to the hidden one
14793                 // we already have. Make the existing definition visible and
14794                 // use it in place of this one.
14795                 if (!getLangOpts().CPlusPlus) {
14796                   // Postpone making the old definition visible until after we
14797                   // complete parsing the new one and do the structural
14798                   // comparison.
14799                   SkipBody->CheckSameAsPrevious = true;
14800                   SkipBody->New = createTagFromNewDecl();
14801                   SkipBody->Previous = Def;
14802                   return Def;
14803                 } else {
14804                   SkipBody->ShouldSkip = true;
14805                   SkipBody->Previous = Def;
14806                   makeMergedDefinitionVisible(Hidden);
14807                   // Carry on and handle it like a normal definition. We'll
14808                   // skip starting the definitiion later.
14809                 }
14810               } else if (!IsExplicitSpecializationAfterInstantiation) {
14811                 // A redeclaration in function prototype scope in C isn't
14812                 // visible elsewhere, so merely issue a warning.
14813                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14814                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14815                 else
14816                   Diag(NameLoc, diag::err_redefinition) << Name;
14817                 notePreviousDefinition(Def,
14818                                        NameLoc.isValid() ? NameLoc : KWLoc);
14819                 // If this is a redefinition, recover by making this
14820                 // struct be anonymous, which will make any later
14821                 // references get the previous definition.
14822                 Name = nullptr;
14823                 Previous.clear();
14824                 Invalid = true;
14825               }
14826             } else {
14827               // If the type is currently being defined, complain
14828               // about a nested redefinition.
14829               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14830               if (TD->isBeingDefined()) {
14831                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14832                 Diag(PrevTagDecl->getLocation(),
14833                      diag::note_previous_definition);
14834                 Name = nullptr;
14835                 Previous.clear();
14836                 Invalid = true;
14837               }
14838             }
14839 
14840             // Okay, this is definition of a previously declared or referenced
14841             // tag. We're going to create a new Decl for it.
14842           }
14843 
14844           // Okay, we're going to make a redeclaration.  If this is some kind
14845           // of reference, make sure we build the redeclaration in the same DC
14846           // as the original, and ignore the current access specifier.
14847           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14848             SearchDC = PrevTagDecl->getDeclContext();
14849             AS = AS_none;
14850           }
14851         }
14852         // If we get here we have (another) forward declaration or we
14853         // have a definition.  Just create a new decl.
14854 
14855       } else {
14856         // If we get here, this is a definition of a new tag type in a nested
14857         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14858         // new decl/type.  We set PrevDecl to NULL so that the entities
14859         // have distinct types.
14860         Previous.clear();
14861       }
14862       // If we get here, we're going to create a new Decl. If PrevDecl
14863       // is non-NULL, it's a definition of the tag declared by
14864       // PrevDecl. If it's NULL, we have a new definition.
14865 
14866     // Otherwise, PrevDecl is not a tag, but was found with tag
14867     // lookup.  This is only actually possible in C++, where a few
14868     // things like templates still live in the tag namespace.
14869     } else {
14870       // Use a better diagnostic if an elaborated-type-specifier
14871       // found the wrong kind of type on the first
14872       // (non-redeclaration) lookup.
14873       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14874           !Previous.isForRedeclaration()) {
14875         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14876         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14877                                                        << Kind;
14878         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14879         Invalid = true;
14880 
14881       // Otherwise, only diagnose if the declaration is in scope.
14882       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14883                                 SS.isNotEmpty() || isMemberSpecialization)) {
14884         // do nothing
14885 
14886       // Diagnose implicit declarations introduced by elaborated types.
14887       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14888         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14889         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14890         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14891         Invalid = true;
14892 
14893       // Otherwise it's a declaration.  Call out a particularly common
14894       // case here.
14895       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14896         unsigned Kind = 0;
14897         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14898         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14899           << Name << Kind << TND->getUnderlyingType();
14900         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14901         Invalid = true;
14902 
14903       // Otherwise, diagnose.
14904       } else {
14905         // The tag name clashes with something else in the target scope,
14906         // issue an error and recover by making this tag be anonymous.
14907         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14908         notePreviousDefinition(PrevDecl, NameLoc);
14909         Name = nullptr;
14910         Invalid = true;
14911       }
14912 
14913       // The existing declaration isn't relevant to us; we're in a
14914       // new scope, so clear out the previous declaration.
14915       Previous.clear();
14916     }
14917   }
14918 
14919 CreateNewDecl:
14920 
14921   TagDecl *PrevDecl = nullptr;
14922   if (Previous.isSingleResult())
14923     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14924 
14925   // If there is an identifier, use the location of the identifier as the
14926   // location of the decl, otherwise use the location of the struct/union
14927   // keyword.
14928   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14929 
14930   // Otherwise, create a new declaration. If there is a previous
14931   // declaration of the same entity, the two will be linked via
14932   // PrevDecl.
14933   TagDecl *New;
14934 
14935   if (Kind == TTK_Enum) {
14936     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14937     // enum X { A, B, C } D;    D should chain to X.
14938     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14939                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14940                            ScopedEnumUsesClassTag, IsFixed);
14941 
14942     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14943       StdAlignValT = cast<EnumDecl>(New);
14944 
14945     // If this is an undefined enum, warn.
14946     if (TUK != TUK_Definition && !Invalid) {
14947       TagDecl *Def;
14948       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14949         // C++0x: 7.2p2: opaque-enum-declaration.
14950         // Conflicts are diagnosed above. Do nothing.
14951       }
14952       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14953         Diag(Loc, diag::ext_forward_ref_enum_def)
14954           << New;
14955         Diag(Def->getLocation(), diag::note_previous_definition);
14956       } else {
14957         unsigned DiagID = diag::ext_forward_ref_enum;
14958         if (getLangOpts().MSVCCompat)
14959           DiagID = diag::ext_ms_forward_ref_enum;
14960         else if (getLangOpts().CPlusPlus)
14961           DiagID = diag::err_forward_ref_enum;
14962         Diag(Loc, DiagID);
14963       }
14964     }
14965 
14966     if (EnumUnderlying) {
14967       EnumDecl *ED = cast<EnumDecl>(New);
14968       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14969         ED->setIntegerTypeSourceInfo(TI);
14970       else
14971         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14972       ED->setPromotionType(ED->getIntegerType());
14973       assert(ED->isComplete() && "enum with type should be complete");
14974     }
14975   } else {
14976     // struct/union/class
14977 
14978     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14979     // struct X { int A; } D;    D should chain to X.
14980     if (getLangOpts().CPlusPlus) {
14981       // FIXME: Look for a way to use RecordDecl for simple structs.
14982       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14983                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14984 
14985       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14986         StdBadAlloc = cast<CXXRecordDecl>(New);
14987     } else
14988       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14989                                cast_or_null<RecordDecl>(PrevDecl));
14990   }
14991 
14992   // C++11 [dcl.type]p3:
14993   //   A type-specifier-seq shall not define a class or enumeration [...].
14994   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14995       TUK == TUK_Definition) {
14996     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14997       << Context.getTagDeclType(New);
14998     Invalid = true;
14999   }
15000 
15001   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
15002       DC->getDeclKind() == Decl::Enum) {
15003     Diag(New->getLocation(), diag::err_type_defined_in_enum)
15004       << Context.getTagDeclType(New);
15005     Invalid = true;
15006   }
15007 
15008   // Maybe add qualifier info.
15009   if (SS.isNotEmpty()) {
15010     if (SS.isSet()) {
15011       // If this is either a declaration or a definition, check the
15012       // nested-name-specifier against the current context.
15013       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
15014           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
15015                                        isMemberSpecialization))
15016         Invalid = true;
15017 
15018       New->setQualifierInfo(SS.getWithLocInContext(Context));
15019       if (TemplateParameterLists.size() > 0) {
15020         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
15021       }
15022     }
15023     else
15024       Invalid = true;
15025   }
15026 
15027   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15028     // Add alignment attributes if necessary; these attributes are checked when
15029     // the ASTContext lays out the structure.
15030     //
15031     // It is important for implementing the correct semantics that this
15032     // happen here (in ActOnTag). The #pragma pack stack is
15033     // maintained as a result of parser callbacks which can occur at
15034     // many points during the parsing of a struct declaration (because
15035     // the #pragma tokens are effectively skipped over during the
15036     // parsing of the struct).
15037     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15038       AddAlignmentAttributesForRecord(RD);
15039       AddMsStructLayoutForRecord(RD);
15040     }
15041   }
15042 
15043   if (ModulePrivateLoc.isValid()) {
15044     if (isMemberSpecialization)
15045       Diag(New->getLocation(), diag::err_module_private_specialization)
15046         << 2
15047         << FixItHint::CreateRemoval(ModulePrivateLoc);
15048     // __module_private__ does not apply to local classes. However, we only
15049     // diagnose this as an error when the declaration specifiers are
15050     // freestanding. Here, we just ignore the __module_private__.
15051     else if (!SearchDC->isFunctionOrMethod())
15052       New->setModulePrivate();
15053   }
15054 
15055   // If this is a specialization of a member class (of a class template),
15056   // check the specialization.
15057   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
15058     Invalid = true;
15059 
15060   // If we're declaring or defining a tag in function prototype scope in C,
15061   // note that this type can only be used within the function and add it to
15062   // the list of decls to inject into the function definition scope.
15063   if ((Name || Kind == TTK_Enum) &&
15064       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
15065     if (getLangOpts().CPlusPlus) {
15066       // C++ [dcl.fct]p6:
15067       //   Types shall not be defined in return or parameter types.
15068       if (TUK == TUK_Definition && !IsTypeSpecifier) {
15069         Diag(Loc, diag::err_type_defined_in_param_type)
15070             << Name;
15071         Invalid = true;
15072       }
15073     } else if (!PrevDecl) {
15074       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
15075     }
15076   }
15077 
15078   if (Invalid)
15079     New->setInvalidDecl();
15080 
15081   // Set the lexical context. If the tag has a C++ scope specifier, the
15082   // lexical context will be different from the semantic context.
15083   New->setLexicalDeclContext(CurContext);
15084 
15085   // Mark this as a friend decl if applicable.
15086   // In Microsoft mode, a friend declaration also acts as a forward
15087   // declaration so we always pass true to setObjectOfFriendDecl to make
15088   // the tag name visible.
15089   if (TUK == TUK_Friend)
15090     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
15091 
15092   // Set the access specifier.
15093   if (!Invalid && SearchDC->isRecord())
15094     SetMemberAccessSpecifier(New, PrevDecl, AS);
15095 
15096   if (PrevDecl)
15097     CheckRedeclarationModuleOwnership(New, PrevDecl);
15098 
15099   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
15100     New->startDefinition();
15101 
15102   ProcessDeclAttributeList(S, New, Attrs);
15103   AddPragmaAttributes(S, New);
15104 
15105   // If this has an identifier, add it to the scope stack.
15106   if (TUK == TUK_Friend) {
15107     // We might be replacing an existing declaration in the lookup tables;
15108     // if so, borrow its access specifier.
15109     if (PrevDecl)
15110       New->setAccess(PrevDecl->getAccess());
15111 
15112     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15113     DC->makeDeclVisibleInContext(New);
15114     if (Name) // can be null along some error paths
15115       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15116         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15117   } else if (Name) {
15118     S = getNonFieldDeclScope(S);
15119     PushOnScopeChains(New, S, true);
15120   } else {
15121     CurContext->addDecl(New);
15122   }
15123 
15124   // If this is the C FILE type, notify the AST context.
15125   if (IdentifierInfo *II = New->getIdentifier())
15126     if (!New->isInvalidDecl() &&
15127         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15128         II->isStr("FILE"))
15129       Context.setFILEDecl(New);
15130 
15131   if (PrevDecl)
15132     mergeDeclAttributes(New, PrevDecl);
15133 
15134   // If there's a #pragma GCC visibility in scope, set the visibility of this
15135   // record.
15136   AddPushedVisibilityAttribute(New);
15137 
15138   if (isMemberSpecialization && !New->isInvalidDecl())
15139     CompleteMemberSpecialization(New, Previous);
15140 
15141   OwnedDecl = true;
15142   // In C++, don't return an invalid declaration. We can't recover well from
15143   // the cases where we make the type anonymous.
15144   if (Invalid && getLangOpts().CPlusPlus) {
15145     if (New->isBeingDefined())
15146       if (auto RD = dyn_cast<RecordDecl>(New))
15147         RD->completeDefinition();
15148     return nullptr;
15149   } else if (SkipBody && SkipBody->ShouldSkip) {
15150     return SkipBody->Previous;
15151   } else {
15152     return New;
15153   }
15154 }
15155 
15156 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15157   AdjustDeclIfTemplate(TagD);
15158   TagDecl *Tag = cast<TagDecl>(TagD);
15159 
15160   // Enter the tag context.
15161   PushDeclContext(S, Tag);
15162 
15163   ActOnDocumentableDecl(TagD);
15164 
15165   // If there's a #pragma GCC visibility in scope, set the visibility of this
15166   // record.
15167   AddPushedVisibilityAttribute(Tag);
15168 }
15169 
15170 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15171                                     SkipBodyInfo &SkipBody) {
15172   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15173     return false;
15174 
15175   // Make the previous decl visible.
15176   makeMergedDefinitionVisible(SkipBody.Previous);
15177   return true;
15178 }
15179 
15180 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15181   assert(isa<ObjCContainerDecl>(IDecl) &&
15182          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15183   DeclContext *OCD = cast<DeclContext>(IDecl);
15184   assert(getContainingDC(OCD) == CurContext &&
15185       "The next DeclContext should be lexically contained in the current one.");
15186   CurContext = OCD;
15187   return IDecl;
15188 }
15189 
15190 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15191                                            SourceLocation FinalLoc,
15192                                            bool IsFinalSpelledSealed,
15193                                            SourceLocation LBraceLoc) {
15194   AdjustDeclIfTemplate(TagD);
15195   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15196 
15197   FieldCollector->StartClass();
15198 
15199   if (!Record->getIdentifier())
15200     return;
15201 
15202   if (FinalLoc.isValid())
15203     Record->addAttr(new (Context)
15204                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15205 
15206   // C++ [class]p2:
15207   //   [...] The class-name is also inserted into the scope of the
15208   //   class itself; this is known as the injected-class-name. For
15209   //   purposes of access checking, the injected-class-name is treated
15210   //   as if it were a public member name.
15211   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15212       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15213       Record->getLocation(), Record->getIdentifier(),
15214       /*PrevDecl=*/nullptr,
15215       /*DelayTypeCreation=*/true);
15216   Context.getTypeDeclType(InjectedClassName, Record);
15217   InjectedClassName->setImplicit();
15218   InjectedClassName->setAccess(AS_public);
15219   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15220       InjectedClassName->setDescribedClassTemplate(Template);
15221   PushOnScopeChains(InjectedClassName, S);
15222   assert(InjectedClassName->isInjectedClassName() &&
15223          "Broken injected-class-name");
15224 }
15225 
15226 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15227                                     SourceRange BraceRange) {
15228   AdjustDeclIfTemplate(TagD);
15229   TagDecl *Tag = cast<TagDecl>(TagD);
15230   Tag->setBraceRange(BraceRange);
15231 
15232   // Make sure we "complete" the definition even it is invalid.
15233   if (Tag->isBeingDefined()) {
15234     assert(Tag->isInvalidDecl() && "We should already have completed it");
15235     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15236       RD->completeDefinition();
15237   }
15238 
15239   if (isa<CXXRecordDecl>(Tag)) {
15240     FieldCollector->FinishClass();
15241   }
15242 
15243   // Exit this scope of this tag's definition.
15244   PopDeclContext();
15245 
15246   if (getCurLexicalContext()->isObjCContainer() &&
15247       Tag->getDeclContext()->isFileContext())
15248     Tag->setTopLevelDeclInObjCContainer();
15249 
15250   // Notify the consumer that we've defined a tag.
15251   if (!Tag->isInvalidDecl())
15252     Consumer.HandleTagDeclDefinition(Tag);
15253 }
15254 
15255 void Sema::ActOnObjCContainerFinishDefinition() {
15256   // Exit this scope of this interface definition.
15257   PopDeclContext();
15258 }
15259 
15260 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15261   assert(DC == CurContext && "Mismatch of container contexts");
15262   OriginalLexicalContext = DC;
15263   ActOnObjCContainerFinishDefinition();
15264 }
15265 
15266 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15267   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15268   OriginalLexicalContext = nullptr;
15269 }
15270 
15271 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15272   AdjustDeclIfTemplate(TagD);
15273   TagDecl *Tag = cast<TagDecl>(TagD);
15274   Tag->setInvalidDecl();
15275 
15276   // Make sure we "complete" the definition even it is invalid.
15277   if (Tag->isBeingDefined()) {
15278     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15279       RD->completeDefinition();
15280   }
15281 
15282   // We're undoing ActOnTagStartDefinition here, not
15283   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15284   // the FieldCollector.
15285 
15286   PopDeclContext();
15287 }
15288 
15289 // Note that FieldName may be null for anonymous bitfields.
15290 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15291                                 IdentifierInfo *FieldName,
15292                                 QualType FieldTy, bool IsMsStruct,
15293                                 Expr *BitWidth, bool *ZeroWidth) {
15294   // Default to true; that shouldn't confuse checks for emptiness
15295   if (ZeroWidth)
15296     *ZeroWidth = true;
15297 
15298   // C99 6.7.2.1p4 - verify the field type.
15299   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15300   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15301     // Handle incomplete types with specific error.
15302     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15303       return ExprError();
15304     if (FieldName)
15305       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15306         << FieldName << FieldTy << BitWidth->getSourceRange();
15307     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15308       << FieldTy << BitWidth->getSourceRange();
15309   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15310                                              UPPC_BitFieldWidth))
15311     return ExprError();
15312 
15313   // If the bit-width is type- or value-dependent, don't try to check
15314   // it now.
15315   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15316     return BitWidth;
15317 
15318   llvm::APSInt Value;
15319   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15320   if (ICE.isInvalid())
15321     return ICE;
15322   BitWidth = ICE.get();
15323 
15324   if (Value != 0 && ZeroWidth)
15325     *ZeroWidth = false;
15326 
15327   // Zero-width bitfield is ok for anonymous field.
15328   if (Value == 0 && FieldName)
15329     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15330 
15331   if (Value.isSigned() && Value.isNegative()) {
15332     if (FieldName)
15333       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15334                << FieldName << Value.toString(10);
15335     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15336       << Value.toString(10);
15337   }
15338 
15339   if (!FieldTy->isDependentType()) {
15340     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15341     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15342     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15343 
15344     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15345     // ABI.
15346     bool CStdConstraintViolation =
15347         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15348     bool MSBitfieldViolation =
15349         Value.ugt(TypeStorageSize) &&
15350         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15351     if (CStdConstraintViolation || MSBitfieldViolation) {
15352       unsigned DiagWidth =
15353           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15354       if (FieldName)
15355         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15356                << FieldName << (unsigned)Value.getZExtValue()
15357                << !CStdConstraintViolation << DiagWidth;
15358 
15359       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15360              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15361              << DiagWidth;
15362     }
15363 
15364     // Warn on types where the user might conceivably expect to get all
15365     // specified bits as value bits: that's all integral types other than
15366     // 'bool'.
15367     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15368       if (FieldName)
15369         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15370             << FieldName << (unsigned)Value.getZExtValue()
15371             << (unsigned)TypeWidth;
15372       else
15373         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15374             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15375     }
15376   }
15377 
15378   return BitWidth;
15379 }
15380 
15381 /// ActOnField - Each field of a C struct/union is passed into this in order
15382 /// to create a FieldDecl object for it.
15383 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15384                        Declarator &D, Expr *BitfieldWidth) {
15385   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15386                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15387                                /*InitStyle=*/ICIS_NoInit, AS_public);
15388   return Res;
15389 }
15390 
15391 /// HandleField - Analyze a field of a C struct or a C++ data member.
15392 ///
15393 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15394                              SourceLocation DeclStart,
15395                              Declarator &D, Expr *BitWidth,
15396                              InClassInitStyle InitStyle,
15397                              AccessSpecifier AS) {
15398   if (D.isDecompositionDeclarator()) {
15399     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15400     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15401       << Decomp.getSourceRange();
15402     return nullptr;
15403   }
15404 
15405   IdentifierInfo *II = D.getIdentifier();
15406   SourceLocation Loc = DeclStart;
15407   if (II) Loc = D.getIdentifierLoc();
15408 
15409   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15410   QualType T = TInfo->getType();
15411   if (getLangOpts().CPlusPlus) {
15412     CheckExtraCXXDefaultArguments(D);
15413 
15414     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15415                                         UPPC_DataMemberType)) {
15416       D.setInvalidType();
15417       T = Context.IntTy;
15418       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15419     }
15420   }
15421 
15422   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15423 
15424   if (D.getDeclSpec().isInlineSpecified())
15425     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15426         << getLangOpts().CPlusPlus17;
15427   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15428     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15429          diag::err_invalid_thread)
15430       << DeclSpec::getSpecifierName(TSCS);
15431 
15432   // Check to see if this name was declared as a member previously
15433   NamedDecl *PrevDecl = nullptr;
15434   LookupResult Previous(*this, II, Loc, LookupMemberName,
15435                         ForVisibleRedeclaration);
15436   LookupName(Previous, S);
15437   switch (Previous.getResultKind()) {
15438     case LookupResult::Found:
15439     case LookupResult::FoundUnresolvedValue:
15440       PrevDecl = Previous.getAsSingle<NamedDecl>();
15441       break;
15442 
15443     case LookupResult::FoundOverloaded:
15444       PrevDecl = Previous.getRepresentativeDecl();
15445       break;
15446 
15447     case LookupResult::NotFound:
15448     case LookupResult::NotFoundInCurrentInstantiation:
15449     case LookupResult::Ambiguous:
15450       break;
15451   }
15452   Previous.suppressDiagnostics();
15453 
15454   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15455     // Maybe we will complain about the shadowed template parameter.
15456     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15457     // Just pretend that we didn't see the previous declaration.
15458     PrevDecl = nullptr;
15459   }
15460 
15461   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15462     PrevDecl = nullptr;
15463 
15464   bool Mutable
15465     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15466   SourceLocation TSSL = D.getBeginLoc();
15467   FieldDecl *NewFD
15468     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15469                      TSSL, AS, PrevDecl, &D);
15470 
15471   if (NewFD->isInvalidDecl())
15472     Record->setInvalidDecl();
15473 
15474   if (D.getDeclSpec().isModulePrivateSpecified())
15475     NewFD->setModulePrivate();
15476 
15477   if (NewFD->isInvalidDecl() && PrevDecl) {
15478     // Don't introduce NewFD into scope; there's already something
15479     // with the same name in the same scope.
15480   } else if (II) {
15481     PushOnScopeChains(NewFD, S);
15482   } else
15483     Record->addDecl(NewFD);
15484 
15485   return NewFD;
15486 }
15487 
15488 /// Build a new FieldDecl and check its well-formedness.
15489 ///
15490 /// This routine builds a new FieldDecl given the fields name, type,
15491 /// record, etc. \p PrevDecl should refer to any previous declaration
15492 /// with the same name and in the same scope as the field to be
15493 /// created.
15494 ///
15495 /// \returns a new FieldDecl.
15496 ///
15497 /// \todo The Declarator argument is a hack. It will be removed once
15498 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15499                                 TypeSourceInfo *TInfo,
15500                                 RecordDecl *Record, SourceLocation Loc,
15501                                 bool Mutable, Expr *BitWidth,
15502                                 InClassInitStyle InitStyle,
15503                                 SourceLocation TSSL,
15504                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15505                                 Declarator *D) {
15506   IdentifierInfo *II = Name.getAsIdentifierInfo();
15507   bool InvalidDecl = false;
15508   if (D) InvalidDecl = D->isInvalidType();
15509 
15510   // If we receive a broken type, recover by assuming 'int' and
15511   // marking this declaration as invalid.
15512   if (T.isNull()) {
15513     InvalidDecl = true;
15514     T = Context.IntTy;
15515   }
15516 
15517   QualType EltTy = Context.getBaseElementType(T);
15518   if (!EltTy->isDependentType()) {
15519     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15520       // Fields of incomplete type force their record to be invalid.
15521       Record->setInvalidDecl();
15522       InvalidDecl = true;
15523     } else {
15524       NamedDecl *Def;
15525       EltTy->isIncompleteType(&Def);
15526       if (Def && Def->isInvalidDecl()) {
15527         Record->setInvalidDecl();
15528         InvalidDecl = true;
15529       }
15530     }
15531   }
15532 
15533   // TR 18037 does not allow fields to be declared with address space
15534   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15535       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15536     Diag(Loc, diag::err_field_with_address_space);
15537     Record->setInvalidDecl();
15538     InvalidDecl = true;
15539   }
15540 
15541   if (LangOpts.OpenCL) {
15542     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15543     // used as structure or union field: image, sampler, event or block types.
15544     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15545         T->isBlockPointerType()) {
15546       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15547       Record->setInvalidDecl();
15548       InvalidDecl = true;
15549     }
15550     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15551     if (BitWidth) {
15552       Diag(Loc, diag::err_opencl_bitfields);
15553       InvalidDecl = true;
15554     }
15555   }
15556 
15557   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15558   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15559       T.hasQualifiers()) {
15560     InvalidDecl = true;
15561     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15562   }
15563 
15564   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15565   // than a variably modified type.
15566   if (!InvalidDecl && T->isVariablyModifiedType()) {
15567     bool SizeIsNegative;
15568     llvm::APSInt Oversized;
15569 
15570     TypeSourceInfo *FixedTInfo =
15571       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15572                                                     SizeIsNegative,
15573                                                     Oversized);
15574     if (FixedTInfo) {
15575       Diag(Loc, diag::warn_illegal_constant_array_size);
15576       TInfo = FixedTInfo;
15577       T = FixedTInfo->getType();
15578     } else {
15579       if (SizeIsNegative)
15580         Diag(Loc, diag::err_typecheck_negative_array_size);
15581       else if (Oversized.getBoolValue())
15582         Diag(Loc, diag::err_array_too_large)
15583           << Oversized.toString(10);
15584       else
15585         Diag(Loc, diag::err_typecheck_field_variable_size);
15586       InvalidDecl = true;
15587     }
15588   }
15589 
15590   // Fields can not have abstract class types
15591   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15592                                              diag::err_abstract_type_in_decl,
15593                                              AbstractFieldType))
15594     InvalidDecl = true;
15595 
15596   bool ZeroWidth = false;
15597   if (InvalidDecl)
15598     BitWidth = nullptr;
15599   // If this is declared as a bit-field, check the bit-field.
15600   if (BitWidth) {
15601     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15602                               &ZeroWidth).get();
15603     if (!BitWidth) {
15604       InvalidDecl = true;
15605       BitWidth = nullptr;
15606       ZeroWidth = false;
15607     }
15608   }
15609 
15610   // Check that 'mutable' is consistent with the type of the declaration.
15611   if (!InvalidDecl && Mutable) {
15612     unsigned DiagID = 0;
15613     if (T->isReferenceType())
15614       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15615                                         : diag::err_mutable_reference;
15616     else if (T.isConstQualified())
15617       DiagID = diag::err_mutable_const;
15618 
15619     if (DiagID) {
15620       SourceLocation ErrLoc = Loc;
15621       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15622         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15623       Diag(ErrLoc, DiagID);
15624       if (DiagID != diag::ext_mutable_reference) {
15625         Mutable = false;
15626         InvalidDecl = true;
15627       }
15628     }
15629   }
15630 
15631   // C++11 [class.union]p8 (DR1460):
15632   //   At most one variant member of a union may have a
15633   //   brace-or-equal-initializer.
15634   if (InitStyle != ICIS_NoInit)
15635     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15636 
15637   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15638                                        BitWidth, Mutable, InitStyle);
15639   if (InvalidDecl)
15640     NewFD->setInvalidDecl();
15641 
15642   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15643     Diag(Loc, diag::err_duplicate_member) << II;
15644     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15645     NewFD->setInvalidDecl();
15646   }
15647 
15648   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15649     if (Record->isUnion()) {
15650       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15651         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15652         if (RDecl->getDefinition()) {
15653           // C++ [class.union]p1: An object of a class with a non-trivial
15654           // constructor, a non-trivial copy constructor, a non-trivial
15655           // destructor, or a non-trivial copy assignment operator
15656           // cannot be a member of a union, nor can an array of such
15657           // objects.
15658           if (CheckNontrivialField(NewFD))
15659             NewFD->setInvalidDecl();
15660         }
15661       }
15662 
15663       // C++ [class.union]p1: If a union contains a member of reference type,
15664       // the program is ill-formed, except when compiling with MSVC extensions
15665       // enabled.
15666       if (EltTy->isReferenceType()) {
15667         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15668                                     diag::ext_union_member_of_reference_type :
15669                                     diag::err_union_member_of_reference_type)
15670           << NewFD->getDeclName() << EltTy;
15671         if (!getLangOpts().MicrosoftExt)
15672           NewFD->setInvalidDecl();
15673       }
15674     }
15675   }
15676 
15677   // FIXME: We need to pass in the attributes given an AST
15678   // representation, not a parser representation.
15679   if (D) {
15680     // FIXME: The current scope is almost... but not entirely... correct here.
15681     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15682 
15683     if (NewFD->hasAttrs())
15684       CheckAlignasUnderalignment(NewFD);
15685   }
15686 
15687   // In auto-retain/release, infer strong retension for fields of
15688   // retainable type.
15689   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15690     NewFD->setInvalidDecl();
15691 
15692   if (T.isObjCGCWeak())
15693     Diag(Loc, diag::warn_attribute_weak_on_field);
15694 
15695   NewFD->setAccess(AS);
15696   return NewFD;
15697 }
15698 
15699 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15700   assert(FD);
15701   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15702 
15703   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15704     return false;
15705 
15706   QualType EltTy = Context.getBaseElementType(FD->getType());
15707   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15708     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15709     if (RDecl->getDefinition()) {
15710       // We check for copy constructors before constructors
15711       // because otherwise we'll never get complaints about
15712       // copy constructors.
15713 
15714       CXXSpecialMember member = CXXInvalid;
15715       // We're required to check for any non-trivial constructors. Since the
15716       // implicit default constructor is suppressed if there are any
15717       // user-declared constructors, we just need to check that there is a
15718       // trivial default constructor and a trivial copy constructor. (We don't
15719       // worry about move constructors here, since this is a C++98 check.)
15720       if (RDecl->hasNonTrivialCopyConstructor())
15721         member = CXXCopyConstructor;
15722       else if (!RDecl->hasTrivialDefaultConstructor())
15723         member = CXXDefaultConstructor;
15724       else if (RDecl->hasNonTrivialCopyAssignment())
15725         member = CXXCopyAssignment;
15726       else if (RDecl->hasNonTrivialDestructor())
15727         member = CXXDestructor;
15728 
15729       if (member != CXXInvalid) {
15730         if (!getLangOpts().CPlusPlus11 &&
15731             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15732           // Objective-C++ ARC: it is an error to have a non-trivial field of
15733           // a union. However, system headers in Objective-C programs
15734           // occasionally have Objective-C lifetime objects within unions,
15735           // and rather than cause the program to fail, we make those
15736           // members unavailable.
15737           SourceLocation Loc = FD->getLocation();
15738           if (getSourceManager().isInSystemHeader(Loc)) {
15739             if (!FD->hasAttr<UnavailableAttr>())
15740               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15741                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15742             return false;
15743           }
15744         }
15745 
15746         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15747                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15748                diag::err_illegal_union_or_anon_struct_member)
15749           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15750         DiagnoseNontrivial(RDecl, member);
15751         return !getLangOpts().CPlusPlus11;
15752       }
15753     }
15754   }
15755 
15756   return false;
15757 }
15758 
15759 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15760 ///  AST enum value.
15761 static ObjCIvarDecl::AccessControl
15762 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15763   switch (ivarVisibility) {
15764   default: llvm_unreachable("Unknown visitibility kind");
15765   case tok::objc_private: return ObjCIvarDecl::Private;
15766   case tok::objc_public: return ObjCIvarDecl::Public;
15767   case tok::objc_protected: return ObjCIvarDecl::Protected;
15768   case tok::objc_package: return ObjCIvarDecl::Package;
15769   }
15770 }
15771 
15772 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15773 /// in order to create an IvarDecl object for it.
15774 Decl *Sema::ActOnIvar(Scope *S,
15775                                 SourceLocation DeclStart,
15776                                 Declarator &D, Expr *BitfieldWidth,
15777                                 tok::ObjCKeywordKind Visibility) {
15778 
15779   IdentifierInfo *II = D.getIdentifier();
15780   Expr *BitWidth = (Expr*)BitfieldWidth;
15781   SourceLocation Loc = DeclStart;
15782   if (II) Loc = D.getIdentifierLoc();
15783 
15784   // FIXME: Unnamed fields can be handled in various different ways, for
15785   // example, unnamed unions inject all members into the struct namespace!
15786 
15787   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15788   QualType T = TInfo->getType();
15789 
15790   if (BitWidth) {
15791     // 6.7.2.1p3, 6.7.2.1p4
15792     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15793     if (!BitWidth)
15794       D.setInvalidType();
15795   } else {
15796     // Not a bitfield.
15797 
15798     // validate II.
15799 
15800   }
15801   if (T->isReferenceType()) {
15802     Diag(Loc, diag::err_ivar_reference_type);
15803     D.setInvalidType();
15804   }
15805   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15806   // than a variably modified type.
15807   else if (T->isVariablyModifiedType()) {
15808     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15809     D.setInvalidType();
15810   }
15811 
15812   // Get the visibility (access control) for this ivar.
15813   ObjCIvarDecl::AccessControl ac =
15814     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15815                                         : ObjCIvarDecl::None;
15816   // Must set ivar's DeclContext to its enclosing interface.
15817   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15818   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15819     return nullptr;
15820   ObjCContainerDecl *EnclosingContext;
15821   if (ObjCImplementationDecl *IMPDecl =
15822       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15823     if (LangOpts.ObjCRuntime.isFragile()) {
15824     // Case of ivar declared in an implementation. Context is that of its class.
15825       EnclosingContext = IMPDecl->getClassInterface();
15826       assert(EnclosingContext && "Implementation has no class interface!");
15827     }
15828     else
15829       EnclosingContext = EnclosingDecl;
15830   } else {
15831     if (ObjCCategoryDecl *CDecl =
15832         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15833       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15834         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15835         return nullptr;
15836       }
15837     }
15838     EnclosingContext = EnclosingDecl;
15839   }
15840 
15841   // Construct the decl.
15842   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15843                                              DeclStart, Loc, II, T,
15844                                              TInfo, ac, (Expr *)BitfieldWidth);
15845 
15846   if (II) {
15847     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15848                                            ForVisibleRedeclaration);
15849     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15850         && !isa<TagDecl>(PrevDecl)) {
15851       Diag(Loc, diag::err_duplicate_member) << II;
15852       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15853       NewID->setInvalidDecl();
15854     }
15855   }
15856 
15857   // Process attributes attached to the ivar.
15858   ProcessDeclAttributes(S, NewID, D);
15859 
15860   if (D.isInvalidType())
15861     NewID->setInvalidDecl();
15862 
15863   // In ARC, infer 'retaining' for ivars of retainable type.
15864   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15865     NewID->setInvalidDecl();
15866 
15867   if (D.getDeclSpec().isModulePrivateSpecified())
15868     NewID->setModulePrivate();
15869 
15870   if (II) {
15871     // FIXME: When interfaces are DeclContexts, we'll need to add
15872     // these to the interface.
15873     S->AddDecl(NewID);
15874     IdResolver.AddDecl(NewID);
15875   }
15876 
15877   if (LangOpts.ObjCRuntime.isNonFragile() &&
15878       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15879     Diag(Loc, diag::warn_ivars_in_interface);
15880 
15881   return NewID;
15882 }
15883 
15884 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15885 /// class and class extensions. For every class \@interface and class
15886 /// extension \@interface, if the last ivar is a bitfield of any type,
15887 /// then add an implicit `char :0` ivar to the end of that interface.
15888 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15889                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15890   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15891     return;
15892 
15893   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15894   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15895 
15896   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15897     return;
15898   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15899   if (!ID) {
15900     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15901       if (!CD->IsClassExtension())
15902         return;
15903     }
15904     // No need to add this to end of @implementation.
15905     else
15906       return;
15907   }
15908   // All conditions are met. Add a new bitfield to the tail end of ivars.
15909   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15910   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15911 
15912   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15913                               DeclLoc, DeclLoc, nullptr,
15914                               Context.CharTy,
15915                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15916                                                                DeclLoc),
15917                               ObjCIvarDecl::Private, BW,
15918                               true);
15919   AllIvarDecls.push_back(Ivar);
15920 }
15921 
15922 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15923                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15924                        SourceLocation RBrac,
15925                        const ParsedAttributesView &Attrs) {
15926   assert(EnclosingDecl && "missing record or interface decl");
15927 
15928   // If this is an Objective-C @implementation or category and we have
15929   // new fields here we should reset the layout of the interface since
15930   // it will now change.
15931   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15932     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15933     switch (DC->getKind()) {
15934     default: break;
15935     case Decl::ObjCCategory:
15936       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15937       break;
15938     case Decl::ObjCImplementation:
15939       Context.
15940         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15941       break;
15942     }
15943   }
15944 
15945   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15946   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15947 
15948   // Start counting up the number of named members; make sure to include
15949   // members of anonymous structs and unions in the total.
15950   unsigned NumNamedMembers = 0;
15951   if (Record) {
15952     for (const auto *I : Record->decls()) {
15953       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15954         if (IFD->getDeclName())
15955           ++NumNamedMembers;
15956     }
15957   }
15958 
15959   // Verify that all the fields are okay.
15960   SmallVector<FieldDecl*, 32> RecFields;
15961 
15962   bool ObjCFieldLifetimeErrReported = false;
15963   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15964        i != end; ++i) {
15965     FieldDecl *FD = cast<FieldDecl>(*i);
15966 
15967     // Get the type for the field.
15968     const Type *FDTy = FD->getType().getTypePtr();
15969 
15970     if (!FD->isAnonymousStructOrUnion()) {
15971       // Remember all fields written by the user.
15972       RecFields.push_back(FD);
15973     }
15974 
15975     // If the field is already invalid for some reason, don't emit more
15976     // diagnostics about it.
15977     if (FD->isInvalidDecl()) {
15978       EnclosingDecl->setInvalidDecl();
15979       continue;
15980     }
15981 
15982     // C99 6.7.2.1p2:
15983     //   A structure or union shall not contain a member with
15984     //   incomplete or function type (hence, a structure shall not
15985     //   contain an instance of itself, but may contain a pointer to
15986     //   an instance of itself), except that the last member of a
15987     //   structure with more than one named member may have incomplete
15988     //   array type; such a structure (and any union containing,
15989     //   possibly recursively, a member that is such a structure)
15990     //   shall not be a member of a structure or an element of an
15991     //   array.
15992     bool IsLastField = (i + 1 == Fields.end());
15993     if (FDTy->isFunctionType()) {
15994       // Field declared as a function.
15995       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15996         << FD->getDeclName();
15997       FD->setInvalidDecl();
15998       EnclosingDecl->setInvalidDecl();
15999       continue;
16000     } else if (FDTy->isIncompleteArrayType() &&
16001                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
16002       if (Record) {
16003         // Flexible array member.
16004         // Microsoft and g++ is more permissive regarding flexible array.
16005         // It will accept flexible array in union and also
16006         // as the sole element of a struct/class.
16007         unsigned DiagID = 0;
16008         if (!Record->isUnion() && !IsLastField) {
16009           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
16010             << FD->getDeclName() << FD->getType() << Record->getTagKind();
16011           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
16012           FD->setInvalidDecl();
16013           EnclosingDecl->setInvalidDecl();
16014           continue;
16015         } else if (Record->isUnion())
16016           DiagID = getLangOpts().MicrosoftExt
16017                        ? diag::ext_flexible_array_union_ms
16018                        : getLangOpts().CPlusPlus
16019                              ? diag::ext_flexible_array_union_gnu
16020                              : diag::err_flexible_array_union;
16021         else if (NumNamedMembers < 1)
16022           DiagID = getLangOpts().MicrosoftExt
16023                        ? diag::ext_flexible_array_empty_aggregate_ms
16024                        : getLangOpts().CPlusPlus
16025                              ? diag::ext_flexible_array_empty_aggregate_gnu
16026                              : diag::err_flexible_array_empty_aggregate;
16027 
16028         if (DiagID)
16029           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
16030                                           << Record->getTagKind();
16031         // While the layout of types that contain virtual bases is not specified
16032         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
16033         // virtual bases after the derived members.  This would make a flexible
16034         // array member declared at the end of an object not adjacent to the end
16035         // of the type.
16036         if (CXXRecord && CXXRecord->getNumVBases() != 0)
16037           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
16038               << FD->getDeclName() << Record->getTagKind();
16039         if (!getLangOpts().C99)
16040           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
16041             << FD->getDeclName() << Record->getTagKind();
16042 
16043         // If the element type has a non-trivial destructor, we would not
16044         // implicitly destroy the elements, so disallow it for now.
16045         //
16046         // FIXME: GCC allows this. We should probably either implicitly delete
16047         // the destructor of the containing class, or just allow this.
16048         QualType BaseElem = Context.getBaseElementType(FD->getType());
16049         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
16050           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
16051             << FD->getDeclName() << FD->getType();
16052           FD->setInvalidDecl();
16053           EnclosingDecl->setInvalidDecl();
16054           continue;
16055         }
16056         // Okay, we have a legal flexible array member at the end of the struct.
16057         Record->setHasFlexibleArrayMember(true);
16058       } else {
16059         // In ObjCContainerDecl ivars with incomplete array type are accepted,
16060         // unless they are followed by another ivar. That check is done
16061         // elsewhere, after synthesized ivars are known.
16062       }
16063     } else if (!FDTy->isDependentType() &&
16064                RequireCompleteType(FD->getLocation(), FD->getType(),
16065                                    diag::err_field_incomplete)) {
16066       // Incomplete type
16067       FD->setInvalidDecl();
16068       EnclosingDecl->setInvalidDecl();
16069       continue;
16070     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
16071       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
16072         // A type which contains a flexible array member is considered to be a
16073         // flexible array member.
16074         Record->setHasFlexibleArrayMember(true);
16075         if (!Record->isUnion()) {
16076           // If this is a struct/class and this is not the last element, reject
16077           // it.  Note that GCC supports variable sized arrays in the middle of
16078           // structures.
16079           if (!IsLastField)
16080             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
16081               << FD->getDeclName() << FD->getType();
16082           else {
16083             // We support flexible arrays at the end of structs in
16084             // other structs as an extension.
16085             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
16086               << FD->getDeclName();
16087           }
16088         }
16089       }
16090       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
16091           RequireNonAbstractType(FD->getLocation(), FD->getType(),
16092                                  diag::err_abstract_type_in_decl,
16093                                  AbstractIvarType)) {
16094         // Ivars can not have abstract class types
16095         FD->setInvalidDecl();
16096       }
16097       if (Record && FDTTy->getDecl()->hasObjectMember())
16098         Record->setHasObjectMember(true);
16099       if (Record && FDTTy->getDecl()->hasVolatileMember())
16100         Record->setHasVolatileMember(true);
16101       if (Record && Record->isUnion() &&
16102           FD->getType().isNonTrivialPrimitiveCType(Context))
16103         Diag(FD->getLocation(),
16104              diag::err_nontrivial_primitive_type_in_union);
16105     } else if (FDTy->isObjCObjectType()) {
16106       /// A field cannot be an Objective-c object
16107       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16108         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16109       QualType T = Context.getObjCObjectPointerType(FD->getType());
16110       FD->setType(T);
16111     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
16112                Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
16113                !getLangOpts().CPlusPlus) {
16114       // It's an error in ARC or Weak if a field has lifetime.
16115       // We don't want to report this in a system header, though,
16116       // so we just make the field unavailable.
16117       // FIXME: that's really not sufficient; we need to make the type
16118       // itself invalid to, say, initialize or copy.
16119       QualType T = FD->getType();
16120       if (T.hasNonTrivialObjCLifetime()) {
16121         SourceLocation loc = FD->getLocation();
16122         if (getSourceManager().isInSystemHeader(loc)) {
16123           if (!FD->hasAttr<UnavailableAttr>()) {
16124             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16125                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
16126           }
16127         } else {
16128           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
16129             << T->isBlockPointerType() << Record->getTagKind();
16130         }
16131         ObjCFieldLifetimeErrReported = true;
16132       }
16133     } else if (getLangOpts().ObjC &&
16134                getLangOpts().getGC() != LangOptions::NonGC &&
16135                Record && !Record->hasObjectMember()) {
16136       if (FD->getType()->isObjCObjectPointerType() ||
16137           FD->getType().isObjCGCStrong())
16138         Record->setHasObjectMember(true);
16139       else if (Context.getAsArrayType(FD->getType())) {
16140         QualType BaseType = Context.getBaseElementType(FD->getType());
16141         if (BaseType->isRecordType() &&
16142             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16143           Record->setHasObjectMember(true);
16144         else if (BaseType->isObjCObjectPointerType() ||
16145                  BaseType.isObjCGCStrong())
16146                Record->setHasObjectMember(true);
16147       }
16148     }
16149 
16150     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16151       QualType FT = FD->getType();
16152       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
16153         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16154       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16155       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
16156         Record->setNonTrivialToPrimitiveCopy(true);
16157       if (FT.isDestructedType()) {
16158         Record->setNonTrivialToPrimitiveDestroy(true);
16159         Record->setParamDestroyedInCallee(true);
16160       }
16161 
16162       if (const auto *RT = FT->getAs<RecordType>()) {
16163         if (RT->getDecl()->getArgPassingRestrictions() ==
16164             RecordDecl::APK_CanNeverPassInRegs)
16165           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16166       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16167         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16168     }
16169 
16170     if (Record && FD->getType().isVolatileQualified())
16171       Record->setHasVolatileMember(true);
16172     // Keep track of the number of named members.
16173     if (FD->getIdentifier())
16174       ++NumNamedMembers;
16175   }
16176 
16177   // Okay, we successfully defined 'Record'.
16178   if (Record) {
16179     bool Completed = false;
16180     if (CXXRecord) {
16181       if (!CXXRecord->isInvalidDecl()) {
16182         // Set access bits correctly on the directly-declared conversions.
16183         for (CXXRecordDecl::conversion_iterator
16184                I = CXXRecord->conversion_begin(),
16185                E = CXXRecord->conversion_end(); I != E; ++I)
16186           I.setAccess((*I)->getAccess());
16187       }
16188 
16189       if (!CXXRecord->isDependentType()) {
16190         // Add any implicitly-declared members to this class.
16191         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16192 
16193         if (!CXXRecord->isInvalidDecl()) {
16194           // If we have virtual base classes, we may end up finding multiple
16195           // final overriders for a given virtual function. Check for this
16196           // problem now.
16197           if (CXXRecord->getNumVBases()) {
16198             CXXFinalOverriderMap FinalOverriders;
16199             CXXRecord->getFinalOverriders(FinalOverriders);
16200 
16201             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16202                                              MEnd = FinalOverriders.end();
16203                  M != MEnd; ++M) {
16204               for (OverridingMethods::iterator SO = M->second.begin(),
16205                                             SOEnd = M->second.end();
16206                    SO != SOEnd; ++SO) {
16207                 assert(SO->second.size() > 0 &&
16208                        "Virtual function without overriding functions?");
16209                 if (SO->second.size() == 1)
16210                   continue;
16211 
16212                 // C++ [class.virtual]p2:
16213                 //   In a derived class, if a virtual member function of a base
16214                 //   class subobject has more than one final overrider the
16215                 //   program is ill-formed.
16216                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16217                   << (const NamedDecl *)M->first << Record;
16218                 Diag(M->first->getLocation(),
16219                      diag::note_overridden_virtual_function);
16220                 for (OverridingMethods::overriding_iterator
16221                           OM = SO->second.begin(),
16222                        OMEnd = SO->second.end();
16223                      OM != OMEnd; ++OM)
16224                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16225                     << (const NamedDecl *)M->first << OM->Method->getParent();
16226 
16227                 Record->setInvalidDecl();
16228               }
16229             }
16230             CXXRecord->completeDefinition(&FinalOverriders);
16231             Completed = true;
16232           }
16233         }
16234       }
16235     }
16236 
16237     if (!Completed)
16238       Record->completeDefinition();
16239 
16240     // Handle attributes before checking the layout.
16241     ProcessDeclAttributeList(S, Record, Attrs);
16242 
16243     // We may have deferred checking for a deleted destructor. Check now.
16244     if (CXXRecord) {
16245       auto *Dtor = CXXRecord->getDestructor();
16246       if (Dtor && Dtor->isImplicit() &&
16247           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16248         CXXRecord->setImplicitDestructorIsDeleted();
16249         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16250       }
16251     }
16252 
16253     if (Record->hasAttrs()) {
16254       CheckAlignasUnderalignment(Record);
16255 
16256       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16257         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16258                                            IA->getRange(), IA->getBestCase(),
16259                                            IA->getSemanticSpelling());
16260     }
16261 
16262     // Check if the structure/union declaration is a type that can have zero
16263     // size in C. For C this is a language extension, for C++ it may cause
16264     // compatibility problems.
16265     bool CheckForZeroSize;
16266     if (!getLangOpts().CPlusPlus) {
16267       CheckForZeroSize = true;
16268     } else {
16269       // For C++ filter out types that cannot be referenced in C code.
16270       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16271       CheckForZeroSize =
16272           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16273           !CXXRecord->isDependentType() &&
16274           CXXRecord->isCLike();
16275     }
16276     if (CheckForZeroSize) {
16277       bool ZeroSize = true;
16278       bool IsEmpty = true;
16279       unsigned NonBitFields = 0;
16280       for (RecordDecl::field_iterator I = Record->field_begin(),
16281                                       E = Record->field_end();
16282            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16283         IsEmpty = false;
16284         if (I->isUnnamedBitfield()) {
16285           if (!I->isZeroLengthBitField(Context))
16286             ZeroSize = false;
16287         } else {
16288           ++NonBitFields;
16289           QualType FieldType = I->getType();
16290           if (FieldType->isIncompleteType() ||
16291               !Context.getTypeSizeInChars(FieldType).isZero())
16292             ZeroSize = false;
16293         }
16294       }
16295 
16296       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16297       // allowed in C++, but warn if its declaration is inside
16298       // extern "C" block.
16299       if (ZeroSize) {
16300         Diag(RecLoc, getLangOpts().CPlusPlus ?
16301                          diag::warn_zero_size_struct_union_in_extern_c :
16302                          diag::warn_zero_size_struct_union_compat)
16303           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16304       }
16305 
16306       // Structs without named members are extension in C (C99 6.7.2.1p7),
16307       // but are accepted by GCC.
16308       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16309         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16310                                diag::ext_no_named_members_in_struct_union)
16311           << Record->isUnion();
16312       }
16313     }
16314   } else {
16315     ObjCIvarDecl **ClsFields =
16316       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16317     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16318       ID->setEndOfDefinitionLoc(RBrac);
16319       // Add ivar's to class's DeclContext.
16320       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16321         ClsFields[i]->setLexicalDeclContext(ID);
16322         ID->addDecl(ClsFields[i]);
16323       }
16324       // Must enforce the rule that ivars in the base classes may not be
16325       // duplicates.
16326       if (ID->getSuperClass())
16327         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16328     } else if (ObjCImplementationDecl *IMPDecl =
16329                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16330       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16331       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16332         // Ivar declared in @implementation never belongs to the implementation.
16333         // Only it is in implementation's lexical context.
16334         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16335       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16336       IMPDecl->setIvarLBraceLoc(LBrac);
16337       IMPDecl->setIvarRBraceLoc(RBrac);
16338     } else if (ObjCCategoryDecl *CDecl =
16339                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16340       // case of ivars in class extension; all other cases have been
16341       // reported as errors elsewhere.
16342       // FIXME. Class extension does not have a LocEnd field.
16343       // CDecl->setLocEnd(RBrac);
16344       // Add ivar's to class extension's DeclContext.
16345       // Diagnose redeclaration of private ivars.
16346       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16347       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16348         if (IDecl) {
16349           if (const ObjCIvarDecl *ClsIvar =
16350               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16351             Diag(ClsFields[i]->getLocation(),
16352                  diag::err_duplicate_ivar_declaration);
16353             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16354             continue;
16355           }
16356           for (const auto *Ext : IDecl->known_extensions()) {
16357             if (const ObjCIvarDecl *ClsExtIvar
16358                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16359               Diag(ClsFields[i]->getLocation(),
16360                    diag::err_duplicate_ivar_declaration);
16361               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16362               continue;
16363             }
16364           }
16365         }
16366         ClsFields[i]->setLexicalDeclContext(CDecl);
16367         CDecl->addDecl(ClsFields[i]);
16368       }
16369       CDecl->setIvarLBraceLoc(LBrac);
16370       CDecl->setIvarRBraceLoc(RBrac);
16371     }
16372   }
16373 }
16374 
16375 /// Determine whether the given integral value is representable within
16376 /// the given type T.
16377 static bool isRepresentableIntegerValue(ASTContext &Context,
16378                                         llvm::APSInt &Value,
16379                                         QualType T) {
16380   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16381          "Integral type required!");
16382   unsigned BitWidth = Context.getIntWidth(T);
16383 
16384   if (Value.isUnsigned() || Value.isNonNegative()) {
16385     if (T->isSignedIntegerOrEnumerationType())
16386       --BitWidth;
16387     return Value.getActiveBits() <= BitWidth;
16388   }
16389   return Value.getMinSignedBits() <= BitWidth;
16390 }
16391 
16392 // Given an integral type, return the next larger integral type
16393 // (or a NULL type of no such type exists).
16394 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16395   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16396   // enum checking below.
16397   assert((T->isIntegralType(Context) ||
16398          T->isEnumeralType()) && "Integral type required!");
16399   const unsigned NumTypes = 4;
16400   QualType SignedIntegralTypes[NumTypes] = {
16401     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16402   };
16403   QualType UnsignedIntegralTypes[NumTypes] = {
16404     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16405     Context.UnsignedLongLongTy
16406   };
16407 
16408   unsigned BitWidth = Context.getTypeSize(T);
16409   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16410                                                         : UnsignedIntegralTypes;
16411   for (unsigned I = 0; I != NumTypes; ++I)
16412     if (Context.getTypeSize(Types[I]) > BitWidth)
16413       return Types[I];
16414 
16415   return QualType();
16416 }
16417 
16418 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16419                                           EnumConstantDecl *LastEnumConst,
16420                                           SourceLocation IdLoc,
16421                                           IdentifierInfo *Id,
16422                                           Expr *Val) {
16423   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16424   llvm::APSInt EnumVal(IntWidth);
16425   QualType EltTy;
16426 
16427   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16428     Val = nullptr;
16429 
16430   if (Val)
16431     Val = DefaultLvalueConversion(Val).get();
16432 
16433   if (Val) {
16434     if (Enum->isDependentType() || Val->isTypeDependent())
16435       EltTy = Context.DependentTy;
16436     else {
16437       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16438           !getLangOpts().MSVCCompat) {
16439         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16440         // constant-expression in the enumerator-definition shall be a converted
16441         // constant expression of the underlying type.
16442         EltTy = Enum->getIntegerType();
16443         ExprResult Converted =
16444           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16445                                            CCEK_Enumerator);
16446         if (Converted.isInvalid())
16447           Val = nullptr;
16448         else
16449           Val = Converted.get();
16450       } else if (!Val->isValueDependent() &&
16451                  !(Val = VerifyIntegerConstantExpression(Val,
16452                                                          &EnumVal).get())) {
16453         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16454       } else {
16455         if (Enum->isComplete()) {
16456           EltTy = Enum->getIntegerType();
16457 
16458           // In Obj-C and Microsoft mode, require the enumeration value to be
16459           // representable in the underlying type of the enumeration. In C++11,
16460           // we perform a non-narrowing conversion as part of converted constant
16461           // expression checking.
16462           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16463             if (getLangOpts().MSVCCompat) {
16464               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16465               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16466             } else
16467               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16468           } else
16469             Val = ImpCastExprToType(Val, EltTy,
16470                                     EltTy->isBooleanType() ?
16471                                     CK_IntegralToBoolean : CK_IntegralCast)
16472                     .get();
16473         } else if (getLangOpts().CPlusPlus) {
16474           // C++11 [dcl.enum]p5:
16475           //   If the underlying type is not fixed, the type of each enumerator
16476           //   is the type of its initializing value:
16477           //     - If an initializer is specified for an enumerator, the
16478           //       initializing value has the same type as the expression.
16479           EltTy = Val->getType();
16480         } else {
16481           // C99 6.7.2.2p2:
16482           //   The expression that defines the value of an enumeration constant
16483           //   shall be an integer constant expression that has a value
16484           //   representable as an int.
16485 
16486           // Complain if the value is not representable in an int.
16487           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16488             Diag(IdLoc, diag::ext_enum_value_not_int)
16489               << EnumVal.toString(10) << Val->getSourceRange()
16490               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16491           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16492             // Force the type of the expression to 'int'.
16493             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16494           }
16495           EltTy = Val->getType();
16496         }
16497       }
16498     }
16499   }
16500 
16501   if (!Val) {
16502     if (Enum->isDependentType())
16503       EltTy = Context.DependentTy;
16504     else if (!LastEnumConst) {
16505       // C++0x [dcl.enum]p5:
16506       //   If the underlying type is not fixed, the type of each enumerator
16507       //   is the type of its initializing value:
16508       //     - If no initializer is specified for the first enumerator, the
16509       //       initializing value has an unspecified integral type.
16510       //
16511       // GCC uses 'int' for its unspecified integral type, as does
16512       // C99 6.7.2.2p3.
16513       if (Enum->isFixed()) {
16514         EltTy = Enum->getIntegerType();
16515       }
16516       else {
16517         EltTy = Context.IntTy;
16518       }
16519     } else {
16520       // Assign the last value + 1.
16521       EnumVal = LastEnumConst->getInitVal();
16522       ++EnumVal;
16523       EltTy = LastEnumConst->getType();
16524 
16525       // Check for overflow on increment.
16526       if (EnumVal < LastEnumConst->getInitVal()) {
16527         // C++0x [dcl.enum]p5:
16528         //   If the underlying type is not fixed, the type of each enumerator
16529         //   is the type of its initializing value:
16530         //
16531         //     - Otherwise the type of the initializing value is the same as
16532         //       the type of the initializing value of the preceding enumerator
16533         //       unless the incremented value is not representable in that type,
16534         //       in which case the type is an unspecified integral type
16535         //       sufficient to contain the incremented value. If no such type
16536         //       exists, the program is ill-formed.
16537         QualType T = getNextLargerIntegralType(Context, EltTy);
16538         if (T.isNull() || Enum->isFixed()) {
16539           // There is no integral type larger enough to represent this
16540           // value. Complain, then allow the value to wrap around.
16541           EnumVal = LastEnumConst->getInitVal();
16542           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16543           ++EnumVal;
16544           if (Enum->isFixed())
16545             // When the underlying type is fixed, this is ill-formed.
16546             Diag(IdLoc, diag::err_enumerator_wrapped)
16547               << EnumVal.toString(10)
16548               << EltTy;
16549           else
16550             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16551               << EnumVal.toString(10);
16552         } else {
16553           EltTy = T;
16554         }
16555 
16556         // Retrieve the last enumerator's value, extent that type to the
16557         // type that is supposed to be large enough to represent the incremented
16558         // value, then increment.
16559         EnumVal = LastEnumConst->getInitVal();
16560         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16561         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16562         ++EnumVal;
16563 
16564         // If we're not in C++, diagnose the overflow of enumerator values,
16565         // which in C99 means that the enumerator value is not representable in
16566         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16567         // permits enumerator values that are representable in some larger
16568         // integral type.
16569         if (!getLangOpts().CPlusPlus && !T.isNull())
16570           Diag(IdLoc, diag::warn_enum_value_overflow);
16571       } else if (!getLangOpts().CPlusPlus &&
16572                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16573         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16574         Diag(IdLoc, diag::ext_enum_value_not_int)
16575           << EnumVal.toString(10) << 1;
16576       }
16577     }
16578   }
16579 
16580   if (!EltTy->isDependentType()) {
16581     // Make the enumerator value match the signedness and size of the
16582     // enumerator's type.
16583     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16584     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16585   }
16586 
16587   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16588                                   Val, EnumVal);
16589 }
16590 
16591 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16592                                                 SourceLocation IILoc) {
16593   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16594       !getLangOpts().CPlusPlus)
16595     return SkipBodyInfo();
16596 
16597   // We have an anonymous enum definition. Look up the first enumerator to
16598   // determine if we should merge the definition with an existing one and
16599   // skip the body.
16600   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16601                                          forRedeclarationInCurContext());
16602   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16603   if (!PrevECD)
16604     return SkipBodyInfo();
16605 
16606   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16607   NamedDecl *Hidden;
16608   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16609     SkipBodyInfo Skip;
16610     Skip.Previous = Hidden;
16611     return Skip;
16612   }
16613 
16614   return SkipBodyInfo();
16615 }
16616 
16617 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16618                               SourceLocation IdLoc, IdentifierInfo *Id,
16619                               const ParsedAttributesView &Attrs,
16620                               SourceLocation EqualLoc, Expr *Val) {
16621   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16622   EnumConstantDecl *LastEnumConst =
16623     cast_or_null<EnumConstantDecl>(lastEnumConst);
16624 
16625   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16626   // we find one that is.
16627   S = getNonFieldDeclScope(S);
16628 
16629   // Verify that there isn't already something declared with this name in this
16630   // scope.
16631   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16632   LookupName(R, S);
16633   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16634 
16635   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16636     // Maybe we will complain about the shadowed template parameter.
16637     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16638     // Just pretend that we didn't see the previous declaration.
16639     PrevDecl = nullptr;
16640   }
16641 
16642   // C++ [class.mem]p15:
16643   // If T is the name of a class, then each of the following shall have a name
16644   // different from T:
16645   // - every enumerator of every member of class T that is an unscoped
16646   // enumerated type
16647   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16648     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16649                             DeclarationNameInfo(Id, IdLoc));
16650 
16651   EnumConstantDecl *New =
16652     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16653   if (!New)
16654     return nullptr;
16655 
16656   if (PrevDecl) {
16657     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16658       // Check for other kinds of shadowing not already handled.
16659       CheckShadow(New, PrevDecl, R);
16660     }
16661 
16662     // When in C++, we may get a TagDecl with the same name; in this case the
16663     // enum constant will 'hide' the tag.
16664     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16665            "Received TagDecl when not in C++!");
16666     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16667       if (isa<EnumConstantDecl>(PrevDecl))
16668         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16669       else
16670         Diag(IdLoc, diag::err_redefinition) << Id;
16671       notePreviousDefinition(PrevDecl, IdLoc);
16672       return nullptr;
16673     }
16674   }
16675 
16676   // Process attributes.
16677   ProcessDeclAttributeList(S, New, Attrs);
16678   AddPragmaAttributes(S, New);
16679 
16680   // Register this decl in the current scope stack.
16681   New->setAccess(TheEnumDecl->getAccess());
16682   PushOnScopeChains(New, S);
16683 
16684   ActOnDocumentableDecl(New);
16685 
16686   return New;
16687 }
16688 
16689 // Returns true when the enum initial expression does not trigger the
16690 // duplicate enum warning.  A few common cases are exempted as follows:
16691 // Element2 = Element1
16692 // Element2 = Element1 + 1
16693 // Element2 = Element1 - 1
16694 // Where Element2 and Element1 are from the same enum.
16695 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16696   Expr *InitExpr = ECD->getInitExpr();
16697   if (!InitExpr)
16698     return true;
16699   InitExpr = InitExpr->IgnoreImpCasts();
16700 
16701   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16702     if (!BO->isAdditiveOp())
16703       return true;
16704     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16705     if (!IL)
16706       return true;
16707     if (IL->getValue() != 1)
16708       return true;
16709 
16710     InitExpr = BO->getLHS();
16711   }
16712 
16713   // This checks if the elements are from the same enum.
16714   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16715   if (!DRE)
16716     return true;
16717 
16718   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16719   if (!EnumConstant)
16720     return true;
16721 
16722   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16723       Enum)
16724     return true;
16725 
16726   return false;
16727 }
16728 
16729 // Emits a warning when an element is implicitly set a value that
16730 // a previous element has already been set to.
16731 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16732                                         EnumDecl *Enum, QualType EnumType) {
16733   // Avoid anonymous enums
16734   if (!Enum->getIdentifier())
16735     return;
16736 
16737   // Only check for small enums.
16738   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16739     return;
16740 
16741   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16742     return;
16743 
16744   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16745   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16746 
16747   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16748   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16749 
16750   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16751   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16752     llvm::APSInt Val = D->getInitVal();
16753     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16754   };
16755 
16756   DuplicatesVector DupVector;
16757   ValueToVectorMap EnumMap;
16758 
16759   // Populate the EnumMap with all values represented by enum constants without
16760   // an initializer.
16761   for (auto *Element : Elements) {
16762     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16763 
16764     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16765     // this constant.  Skip this enum since it may be ill-formed.
16766     if (!ECD) {
16767       return;
16768     }
16769 
16770     // Constants with initalizers are handled in the next loop.
16771     if (ECD->getInitExpr())
16772       continue;
16773 
16774     // Duplicate values are handled in the next loop.
16775     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16776   }
16777 
16778   if (EnumMap.size() == 0)
16779     return;
16780 
16781   // Create vectors for any values that has duplicates.
16782   for (auto *Element : Elements) {
16783     // The last loop returned if any constant was null.
16784     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16785     if (!ValidDuplicateEnum(ECD, Enum))
16786       continue;
16787 
16788     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16789     if (Iter == EnumMap.end())
16790       continue;
16791 
16792     DeclOrVector& Entry = Iter->second;
16793     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16794       // Ensure constants are different.
16795       if (D == ECD)
16796         continue;
16797 
16798       // Create new vector and push values onto it.
16799       auto Vec = llvm::make_unique<ECDVector>();
16800       Vec->push_back(D);
16801       Vec->push_back(ECD);
16802 
16803       // Update entry to point to the duplicates vector.
16804       Entry = Vec.get();
16805 
16806       // Store the vector somewhere we can consult later for quick emission of
16807       // diagnostics.
16808       DupVector.emplace_back(std::move(Vec));
16809       continue;
16810     }
16811 
16812     ECDVector *Vec = Entry.get<ECDVector*>();
16813     // Make sure constants are not added more than once.
16814     if (*Vec->begin() == ECD)
16815       continue;
16816 
16817     Vec->push_back(ECD);
16818   }
16819 
16820   // Emit diagnostics.
16821   for (const auto &Vec : DupVector) {
16822     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16823 
16824     // Emit warning for one enum constant.
16825     auto *FirstECD = Vec->front();
16826     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16827       << FirstECD << FirstECD->getInitVal().toString(10)
16828       << FirstECD->getSourceRange();
16829 
16830     // Emit one note for each of the remaining enum constants with
16831     // the same value.
16832     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16833       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16834         << ECD << ECD->getInitVal().toString(10)
16835         << ECD->getSourceRange();
16836   }
16837 }
16838 
16839 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16840                              bool AllowMask) const {
16841   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16842   assert(ED->isCompleteDefinition() && "expected enum definition");
16843 
16844   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16845   llvm::APInt &FlagBits = R.first->second;
16846 
16847   if (R.second) {
16848     for (auto *E : ED->enumerators()) {
16849       const auto &EVal = E->getInitVal();
16850       // Only single-bit enumerators introduce new flag values.
16851       if (EVal.isPowerOf2())
16852         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16853     }
16854   }
16855 
16856   // A value is in a flag enum if either its bits are a subset of the enum's
16857   // flag bits (the first condition) or we are allowing masks and the same is
16858   // true of its complement (the second condition). When masks are allowed, we
16859   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16860   //
16861   // While it's true that any value could be used as a mask, the assumption is
16862   // that a mask will have all of the insignificant bits set. Anything else is
16863   // likely a logic error.
16864   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16865   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16866 }
16867 
16868 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16869                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16870                          const ParsedAttributesView &Attrs) {
16871   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16872   QualType EnumType = Context.getTypeDeclType(Enum);
16873 
16874   ProcessDeclAttributeList(S, Enum, Attrs);
16875 
16876   if (Enum->isDependentType()) {
16877     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16878       EnumConstantDecl *ECD =
16879         cast_or_null<EnumConstantDecl>(Elements[i]);
16880       if (!ECD) continue;
16881 
16882       ECD->setType(EnumType);
16883     }
16884 
16885     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16886     return;
16887   }
16888 
16889   // TODO: If the result value doesn't fit in an int, it must be a long or long
16890   // long value.  ISO C does not support this, but GCC does as an extension,
16891   // emit a warning.
16892   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16893   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16894   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16895 
16896   // Verify that all the values are okay, compute the size of the values, and
16897   // reverse the list.
16898   unsigned NumNegativeBits = 0;
16899   unsigned NumPositiveBits = 0;
16900 
16901   // Keep track of whether all elements have type int.
16902   bool AllElementsInt = true;
16903 
16904   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16905     EnumConstantDecl *ECD =
16906       cast_or_null<EnumConstantDecl>(Elements[i]);
16907     if (!ECD) continue;  // Already issued a diagnostic.
16908 
16909     const llvm::APSInt &InitVal = ECD->getInitVal();
16910 
16911     // Keep track of the size of positive and negative values.
16912     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16913       NumPositiveBits = std::max(NumPositiveBits,
16914                                  (unsigned)InitVal.getActiveBits());
16915     else
16916       NumNegativeBits = std::max(NumNegativeBits,
16917                                  (unsigned)InitVal.getMinSignedBits());
16918 
16919     // Keep track of whether every enum element has type int (very common).
16920     if (AllElementsInt)
16921       AllElementsInt = ECD->getType() == Context.IntTy;
16922   }
16923 
16924   // Figure out the type that should be used for this enum.
16925   QualType BestType;
16926   unsigned BestWidth;
16927 
16928   // C++0x N3000 [conv.prom]p3:
16929   //   An rvalue of an unscoped enumeration type whose underlying
16930   //   type is not fixed can be converted to an rvalue of the first
16931   //   of the following types that can represent all the values of
16932   //   the enumeration: int, unsigned int, long int, unsigned long
16933   //   int, long long int, or unsigned long long int.
16934   // C99 6.4.4.3p2:
16935   //   An identifier declared as an enumeration constant has type int.
16936   // The C99 rule is modified by a gcc extension
16937   QualType BestPromotionType;
16938 
16939   bool Packed = Enum->hasAttr<PackedAttr>();
16940   // -fshort-enums is the equivalent to specifying the packed attribute on all
16941   // enum definitions.
16942   if (LangOpts.ShortEnums)
16943     Packed = true;
16944 
16945   // If the enum already has a type because it is fixed or dictated by the
16946   // target, promote that type instead of analyzing the enumerators.
16947   if (Enum->isComplete()) {
16948     BestType = Enum->getIntegerType();
16949     if (BestType->isPromotableIntegerType())
16950       BestPromotionType = Context.getPromotedIntegerType(BestType);
16951     else
16952       BestPromotionType = BestType;
16953 
16954     BestWidth = Context.getIntWidth(BestType);
16955   }
16956   else if (NumNegativeBits) {
16957     // If there is a negative value, figure out the smallest integer type (of
16958     // int/long/longlong) that fits.
16959     // If it's packed, check also if it fits a char or a short.
16960     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16961       BestType = Context.SignedCharTy;
16962       BestWidth = CharWidth;
16963     } else if (Packed && NumNegativeBits <= ShortWidth &&
16964                NumPositiveBits < ShortWidth) {
16965       BestType = Context.ShortTy;
16966       BestWidth = ShortWidth;
16967     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16968       BestType = Context.IntTy;
16969       BestWidth = IntWidth;
16970     } else {
16971       BestWidth = Context.getTargetInfo().getLongWidth();
16972 
16973       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16974         BestType = Context.LongTy;
16975       } else {
16976         BestWidth = Context.getTargetInfo().getLongLongWidth();
16977 
16978         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16979           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16980         BestType = Context.LongLongTy;
16981       }
16982     }
16983     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16984   } else {
16985     // If there is no negative value, figure out the smallest type that fits
16986     // all of the enumerator values.
16987     // If it's packed, check also if it fits a char or a short.
16988     if (Packed && NumPositiveBits <= CharWidth) {
16989       BestType = Context.UnsignedCharTy;
16990       BestPromotionType = Context.IntTy;
16991       BestWidth = CharWidth;
16992     } else if (Packed && NumPositiveBits <= ShortWidth) {
16993       BestType = Context.UnsignedShortTy;
16994       BestPromotionType = Context.IntTy;
16995       BestWidth = ShortWidth;
16996     } else if (NumPositiveBits <= IntWidth) {
16997       BestType = Context.UnsignedIntTy;
16998       BestWidth = IntWidth;
16999       BestPromotionType
17000         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17001                            ? Context.UnsignedIntTy : Context.IntTy;
17002     } else if (NumPositiveBits <=
17003                (BestWidth = Context.getTargetInfo().getLongWidth())) {
17004       BestType = Context.UnsignedLongTy;
17005       BestPromotionType
17006         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17007                            ? Context.UnsignedLongTy : Context.LongTy;
17008     } else {
17009       BestWidth = Context.getTargetInfo().getLongLongWidth();
17010       assert(NumPositiveBits <= BestWidth &&
17011              "How could an initializer get larger than ULL?");
17012       BestType = Context.UnsignedLongLongTy;
17013       BestPromotionType
17014         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
17015                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
17016     }
17017   }
17018 
17019   // Loop over all of the enumerator constants, changing their types to match
17020   // the type of the enum if needed.
17021   for (auto *D : Elements) {
17022     auto *ECD = cast_or_null<EnumConstantDecl>(D);
17023     if (!ECD) continue;  // Already issued a diagnostic.
17024 
17025     // Standard C says the enumerators have int type, but we allow, as an
17026     // extension, the enumerators to be larger than int size.  If each
17027     // enumerator value fits in an int, type it as an int, otherwise type it the
17028     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
17029     // that X has type 'int', not 'unsigned'.
17030 
17031     // Determine whether the value fits into an int.
17032     llvm::APSInt InitVal = ECD->getInitVal();
17033 
17034     // If it fits into an integer type, force it.  Otherwise force it to match
17035     // the enum decl type.
17036     QualType NewTy;
17037     unsigned NewWidth;
17038     bool NewSign;
17039     if (!getLangOpts().CPlusPlus &&
17040         !Enum->isFixed() &&
17041         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
17042       NewTy = Context.IntTy;
17043       NewWidth = IntWidth;
17044       NewSign = true;
17045     } else if (ECD->getType() == BestType) {
17046       // Already the right type!
17047       if (getLangOpts().CPlusPlus)
17048         // C++ [dcl.enum]p4: Following the closing brace of an
17049         // enum-specifier, each enumerator has the type of its
17050         // enumeration.
17051         ECD->setType(EnumType);
17052       continue;
17053     } else {
17054       NewTy = BestType;
17055       NewWidth = BestWidth;
17056       NewSign = BestType->isSignedIntegerOrEnumerationType();
17057     }
17058 
17059     // Adjust the APSInt value.
17060     InitVal = InitVal.extOrTrunc(NewWidth);
17061     InitVal.setIsSigned(NewSign);
17062     ECD->setInitVal(InitVal);
17063 
17064     // Adjust the Expr initializer and type.
17065     if (ECD->getInitExpr() &&
17066         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
17067       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
17068                                                 CK_IntegralCast,
17069                                                 ECD->getInitExpr(),
17070                                                 /*base paths*/ nullptr,
17071                                                 VK_RValue));
17072     if (getLangOpts().CPlusPlus)
17073       // C++ [dcl.enum]p4: Following the closing brace of an
17074       // enum-specifier, each enumerator has the type of its
17075       // enumeration.
17076       ECD->setType(EnumType);
17077     else
17078       ECD->setType(NewTy);
17079   }
17080 
17081   Enum->completeDefinition(BestType, BestPromotionType,
17082                            NumPositiveBits, NumNegativeBits);
17083 
17084   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
17085 
17086   if (Enum->isClosedFlag()) {
17087     for (Decl *D : Elements) {
17088       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
17089       if (!ECD) continue;  // Already issued a diagnostic.
17090 
17091       llvm::APSInt InitVal = ECD->getInitVal();
17092       if (InitVal != 0 && !InitVal.isPowerOf2() &&
17093           !IsValueInFlagEnum(Enum, InitVal, true))
17094         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
17095           << ECD << Enum;
17096     }
17097   }
17098 
17099   // Now that the enum type is defined, ensure it's not been underaligned.
17100   if (Enum->hasAttrs())
17101     CheckAlignasUnderalignment(Enum);
17102 }
17103 
17104 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17105                                   SourceLocation StartLoc,
17106                                   SourceLocation EndLoc) {
17107   StringLiteral *AsmString = cast<StringLiteral>(expr);
17108 
17109   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17110                                                    AsmString, StartLoc,
17111                                                    EndLoc);
17112   CurContext->addDecl(New);
17113   return New;
17114 }
17115 
17116 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17117                                       IdentifierInfo* AliasName,
17118                                       SourceLocation PragmaLoc,
17119                                       SourceLocation NameLoc,
17120                                       SourceLocation AliasNameLoc) {
17121   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17122                                          LookupOrdinaryName);
17123   AsmLabelAttr *Attr =
17124       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17125 
17126   // If a declaration that:
17127   // 1) declares a function or a variable
17128   // 2) has external linkage
17129   // already exists, add a label attribute to it.
17130   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17131     if (isDeclExternC(PrevDecl))
17132       PrevDecl->addAttr(Attr);
17133     else
17134       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17135           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17136   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17137   } else
17138     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17139 }
17140 
17141 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17142                              SourceLocation PragmaLoc,
17143                              SourceLocation NameLoc) {
17144   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17145 
17146   if (PrevDecl) {
17147     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17148   } else {
17149     (void)WeakUndeclaredIdentifiers.insert(
17150       std::pair<IdentifierInfo*,WeakInfo>
17151         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17152   }
17153 }
17154 
17155 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17156                                 IdentifierInfo* AliasName,
17157                                 SourceLocation PragmaLoc,
17158                                 SourceLocation NameLoc,
17159                                 SourceLocation AliasNameLoc) {
17160   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17161                                     LookupOrdinaryName);
17162   WeakInfo W = WeakInfo(Name, NameLoc);
17163 
17164   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17165     if (!PrevDecl->hasAttr<AliasAttr>())
17166       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17167         DeclApplyPragmaWeak(TUScope, ND, W);
17168   } else {
17169     (void)WeakUndeclaredIdentifiers.insert(
17170       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17171   }
17172 }
17173 
17174 Decl *Sema::getObjCDeclContext() const {
17175   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17176 }
17177