1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57   if (OwnedType) {
58     Decl *Group[2] = { OwnedType, Ptr };
59     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60   }
61 
62   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70                         bool AllowTemplates = false,
71                         bool AllowNonTemplates = true)
72        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74      WantExpressionKeywords = false;
75      WantCXXNamedCasts = false;
76      WantRemainingKeywords = false;
77   }
78 
79   bool ValidateCandidate(const TypoCorrection &candidate) override {
80     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81       if (!AllowInvalidDecl && ND->isInvalidDecl())
82         return false;
83 
84       if (getAsTypeTemplateDecl(ND))
85         return AllowTemplates;
86 
87       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88       if (!IsType)
89         return false;
90 
91       if (AllowNonTemplates)
92         return true;
93 
94       // An injected-class-name of a class template (specialization) is valid
95       // as a template or as a non-template.
96       if (AllowTemplates) {
97         auto *RD = dyn_cast<CXXRecordDecl>(ND);
98         if (!RD || !RD->isInjectedClassName())
99           return false;
100         RD = cast<CXXRecordDecl>(RD->getDeclContext());
101         return RD->getDescribedClassTemplate() ||
102                isa<ClassTemplateSpecializationDecl>(RD);
103       }
104 
105       return false;
106     }
107 
108     return !WantClassName && candidate.isKeyword();
109   }
110 
111   std::unique_ptr<CorrectionCandidateCallback> clone() override {
112     return std::make_unique<TypeNameValidatorCCC>(*this);
113   }
114 
115  private:
116   bool AllowInvalidDecl;
117   bool WantClassName;
118   bool AllowTemplates;
119   bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126   switch (Kind) {
127   // FIXME: Take into account the current language when deciding whether a
128   // token kind is a valid type specifier
129   case tok::kw_short:
130   case tok::kw_long:
131   case tok::kw___int64:
132   case tok::kw___int128:
133   case tok::kw_signed:
134   case tok::kw_unsigned:
135   case tok::kw_void:
136   case tok::kw_char:
137   case tok::kw_int:
138   case tok::kw_half:
139   case tok::kw_float:
140   case tok::kw_double:
141   case tok::kw___bf16:
142   case tok::kw__Float16:
143   case tok::kw___float128:
144   case tok::kw___ibm128:
145   case tok::kw_wchar_t:
146   case tok::kw_bool:
147   case tok::kw___underlying_type:
148   case tok::kw___auto_type:
149     return true;
150 
151   case tok::annot_typename:
152   case tok::kw_char16_t:
153   case tok::kw_char32_t:
154   case tok::kw_typeof:
155   case tok::annot_decltype:
156   case tok::kw_decltype:
157     return getLangOpts().CPlusPlus;
158 
159   case tok::kw_char8_t:
160     return getLangOpts().Char8;
161 
162   default:
163     break;
164   }
165 
166   return false;
167 }
168 
169 namespace {
170 enum class UnqualifiedTypeNameLookupResult {
171   NotFound,
172   FoundNonType,
173   FoundType
174 };
175 } // end anonymous namespace
176 
177 /// Tries to perform unqualified lookup of the type decls in bases for
178 /// dependent class.
179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
180 /// type decl, \a FoundType if only type decls are found.
181 static UnqualifiedTypeNameLookupResult
182 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
183                                 SourceLocation NameLoc,
184                                 const CXXRecordDecl *RD) {
185   if (!RD->hasDefinition())
186     return UnqualifiedTypeNameLookupResult::NotFound;
187   // Look for type decls in base classes.
188   UnqualifiedTypeNameLookupResult FoundTypeDecl =
189       UnqualifiedTypeNameLookupResult::NotFound;
190   for (const auto &Base : RD->bases()) {
191     const CXXRecordDecl *BaseRD = nullptr;
192     if (auto *BaseTT = Base.getType()->getAs<TagType>())
193       BaseRD = BaseTT->getAsCXXRecordDecl();
194     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
195       // Look for type decls in dependent base classes that have known primary
196       // templates.
197       if (!TST || !TST->isDependentType())
198         continue;
199       auto *TD = TST->getTemplateName().getAsTemplateDecl();
200       if (!TD)
201         continue;
202       if (auto *BasePrimaryTemplate =
203           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
204         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
205           BaseRD = BasePrimaryTemplate;
206         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207           if (const ClassTemplatePartialSpecializationDecl *PS =
208                   CTD->findPartialSpecialization(Base.getType()))
209             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
210               BaseRD = PS;
211         }
212       }
213     }
214     if (BaseRD) {
215       for (NamedDecl *ND : BaseRD->lookup(&II)) {
216         if (!isa<TypeDecl>(ND))
217           return UnqualifiedTypeNameLookupResult::FoundNonType;
218         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219       }
220       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
221         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
222         case UnqualifiedTypeNameLookupResult::FoundNonType:
223           return UnqualifiedTypeNameLookupResult::FoundNonType;
224         case UnqualifiedTypeNameLookupResult::FoundType:
225           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
226           break;
227         case UnqualifiedTypeNameLookupResult::NotFound:
228           break;
229         }
230       }
231     }
232   }
233 
234   return FoundTypeDecl;
235 }
236 
237 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
238                                                       const IdentifierInfo &II,
239                                                       SourceLocation NameLoc) {
240   // Lookup in the parent class template context, if any.
241   const CXXRecordDecl *RD = nullptr;
242   UnqualifiedTypeNameLookupResult FoundTypeDecl =
243       UnqualifiedTypeNameLookupResult::NotFound;
244   for (DeclContext *DC = S.CurContext;
245        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
246        DC = DC->getParent()) {
247     // Look for type decls in dependent base classes that have known primary
248     // templates.
249     RD = dyn_cast<CXXRecordDecl>(DC);
250     if (RD && RD->getDescribedClassTemplate())
251       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
252   }
253   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
254     return nullptr;
255 
256   // We found some types in dependent base classes.  Recover as if the user
257   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
258   // lookup during template instantiation.
259   S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
260 
261   ASTContext &Context = S.Context;
262   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
263                                           cast<Type>(Context.getRecordType(RD)));
264   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
265 
266   CXXScopeSpec SS;
267   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
268 
269   TypeLocBuilder Builder;
270   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
271   DepTL.setNameLoc(NameLoc);
272   DepTL.setElaboratedKeywordLoc(SourceLocation());
273   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
274   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
275 }
276 
277 /// If the identifier refers to a type name within this scope,
278 /// return the declaration of that type.
279 ///
280 /// This routine performs ordinary name lookup of the identifier II
281 /// within the given scope, with optional C++ scope specifier SS, to
282 /// determine whether the name refers to a type. If so, returns an
283 /// opaque pointer (actually a QualType) corresponding to that
284 /// type. Otherwise, returns NULL.
285 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
286                              Scope *S, CXXScopeSpec *SS,
287                              bool isClassName, bool HasTrailingDot,
288                              ParsedType ObjectTypePtr,
289                              bool IsCtorOrDtorName,
290                              bool WantNontrivialTypeSourceInfo,
291                              bool IsClassTemplateDeductionContext,
292                              IdentifierInfo **CorrectedII) {
293   // FIXME: Consider allowing this outside C++1z mode as an extension.
294   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
296                               !isClassName && !HasTrailingDot;
297 
298   // Determine where we will perform name lookup.
299   DeclContext *LookupCtx = nullptr;
300   if (ObjectTypePtr) {
301     QualType ObjectType = ObjectTypePtr.get();
302     if (ObjectType->isRecordType())
303       LookupCtx = computeDeclContext(ObjectType);
304   } else if (SS && SS->isNotEmpty()) {
305     LookupCtx = computeDeclContext(*SS, false);
306 
307     if (!LookupCtx) {
308       if (isDependentScopeSpecifier(*SS)) {
309         // C++ [temp.res]p3:
310         //   A qualified-id that refers to a type and in which the
311         //   nested-name-specifier depends on a template-parameter (14.6.2)
312         //   shall be prefixed by the keyword typename to indicate that the
313         //   qualified-id denotes a type, forming an
314         //   elaborated-type-specifier (7.1.5.3).
315         //
316         // We therefore do not perform any name lookup if the result would
317         // refer to a member of an unknown specialization.
318         if (!isClassName && !IsCtorOrDtorName)
319           return nullptr;
320 
321         // We know from the grammar that this name refers to a type,
322         // so build a dependent node to describe the type.
323         if (WantNontrivialTypeSourceInfo)
324           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
325 
326         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
327         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
328                                        II, NameLoc);
329         return ParsedType::make(T);
330       }
331 
332       return nullptr;
333     }
334 
335     if (!LookupCtx->isDependentContext() &&
336         RequireCompleteDeclContext(*SS, LookupCtx))
337       return nullptr;
338   }
339 
340   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
341   // lookup for class-names.
342   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
343                                       LookupOrdinaryName;
344   LookupResult Result(*this, &II, NameLoc, Kind);
345   if (LookupCtx) {
346     // Perform "qualified" name lookup into the declaration context we
347     // computed, which is either the type of the base of a member access
348     // expression or the declaration context associated with a prior
349     // nested-name-specifier.
350     LookupQualifiedName(Result, LookupCtx);
351 
352     if (ObjectTypePtr && Result.empty()) {
353       // C++ [basic.lookup.classref]p3:
354       //   If the unqualified-id is ~type-name, the type-name is looked up
355       //   in the context of the entire postfix-expression. If the type T of
356       //   the object expression is of a class type C, the type-name is also
357       //   looked up in the scope of class C. At least one of the lookups shall
358       //   find a name that refers to (possibly cv-qualified) T.
359       LookupName(Result, S);
360     }
361   } else {
362     // Perform unqualified name lookup.
363     LookupName(Result, S);
364 
365     // For unqualified lookup in a class template in MSVC mode, look into
366     // dependent base classes where the primary class template is known.
367     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
368       if (ParsedType TypeInBase =
369               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
370         return TypeInBase;
371     }
372   }
373 
374   NamedDecl *IIDecl = nullptr;
375   switch (Result.getResultKind()) {
376   case LookupResult::NotFound:
377   case LookupResult::NotFoundInCurrentInstantiation:
378     if (CorrectedII) {
379       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
380                                AllowDeducedTemplate);
381       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
382                                               S, SS, CCC, CTK_ErrorRecovery);
383       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
384       TemplateTy Template;
385       bool MemberOfUnknownSpecialization;
386       UnqualifiedId TemplateName;
387       TemplateName.setIdentifier(NewII, NameLoc);
388       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
389       CXXScopeSpec NewSS, *NewSSPtr = SS;
390       if (SS && NNS) {
391         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
392         NewSSPtr = &NewSS;
393       }
394       if (Correction && (NNS || NewII != &II) &&
395           // Ignore a correction to a template type as the to-be-corrected
396           // identifier is not a template (typo correction for template names
397           // is handled elsewhere).
398           !(getLangOpts().CPlusPlus && NewSSPtr &&
399             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
400                            Template, MemberOfUnknownSpecialization))) {
401         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
402                                     isClassName, HasTrailingDot, ObjectTypePtr,
403                                     IsCtorOrDtorName,
404                                     WantNontrivialTypeSourceInfo,
405                                     IsClassTemplateDeductionContext);
406         if (Ty) {
407           diagnoseTypo(Correction,
408                        PDiag(diag::err_unknown_type_or_class_name_suggest)
409                          << Result.getLookupName() << isClassName);
410           if (SS && NNS)
411             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
412           *CorrectedII = NewII;
413           return Ty;
414         }
415       }
416     }
417     // If typo correction failed or was not performed, fall through
418     LLVM_FALLTHROUGH;
419   case LookupResult::FoundOverloaded:
420   case LookupResult::FoundUnresolvedValue:
421     Result.suppressDiagnostics();
422     return nullptr;
423 
424   case LookupResult::Ambiguous:
425     // Recover from type-hiding ambiguities by hiding the type.  We'll
426     // do the lookup again when looking for an object, and we can
427     // diagnose the error then.  If we don't do this, then the error
428     // about hiding the type will be immediately followed by an error
429     // that only makes sense if the identifier was treated like a type.
430     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
431       Result.suppressDiagnostics();
432       return nullptr;
433     }
434 
435     // Look to see if we have a type anywhere in the list of results.
436     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
437          Res != ResEnd; ++Res) {
438       NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
439       if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
440               RealRes) ||
441           (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
442         if (!IIDecl ||
443             // Make the selection of the recovery decl deterministic.
444             RealRes->getLocation() < IIDecl->getLocation())
445           IIDecl = RealRes;
446       }
447     }
448 
449     if (!IIDecl) {
450       // None of the entities we found is a type, so there is no way
451       // to even assume that the result is a type. In this case, don't
452       // complain about the ambiguity. The parser will either try to
453       // perform this lookup again (e.g., as an object name), which
454       // will produce the ambiguity, or will complain that it expected
455       // a type name.
456       Result.suppressDiagnostics();
457       return nullptr;
458     }
459 
460     // We found a type within the ambiguous lookup; diagnose the
461     // ambiguity and then return that type. This might be the right
462     // answer, or it might not be, but it suppresses any attempt to
463     // perform the name lookup again.
464     break;
465 
466   case LookupResult::Found:
467     IIDecl = Result.getFoundDecl();
468     break;
469   }
470 
471   assert(IIDecl && "Didn't find decl");
472 
473   QualType T;
474   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
475     // C++ [class.qual]p2: A lookup that would find the injected-class-name
476     // instead names the constructors of the class, except when naming a class.
477     // This is ill-formed when we're not actually forming a ctor or dtor name.
478     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
479     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
480     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
481         FoundRD->isInjectedClassName() &&
482         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
483       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
484           << &II << /*Type*/1;
485 
486     DiagnoseUseOfDecl(IIDecl, NameLoc);
487 
488     T = Context.getTypeDeclType(TD);
489     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
490   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
491     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
492     if (!HasTrailingDot)
493       T = Context.getObjCInterfaceType(IDecl);
494   } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
495     (void)DiagnoseUseOfDecl(UD, NameLoc);
496     // Recover with 'int'
497     T = Context.IntTy;
498   } else if (AllowDeducedTemplate) {
499     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
500       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
501                                                        QualType(), false);
502   }
503 
504   if (T.isNull()) {
505     // If it's not plausibly a type, suppress diagnostics.
506     Result.suppressDiagnostics();
507     return nullptr;
508   }
509 
510   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
511   // constructor or destructor name (in such a case, the scope specifier
512   // will be attached to the enclosing Expr or Decl node).
513   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
514       !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
515     if (WantNontrivialTypeSourceInfo) {
516       // Construct a type with type-source information.
517       TypeLocBuilder Builder;
518       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
519 
520       T = getElaboratedType(ETK_None, *SS, T);
521       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
522       ElabTL.setElaboratedKeywordLoc(SourceLocation());
523       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
524       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
525     } else {
526       T = getElaboratedType(ETK_None, *SS, T);
527     }
528   }
529 
530   return ParsedType::make(T);
531 }
532 
533 // Builds a fake NNS for the given decl context.
534 static NestedNameSpecifier *
535 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
536   for (;; DC = DC->getLookupParent()) {
537     DC = DC->getPrimaryContext();
538     auto *ND = dyn_cast<NamespaceDecl>(DC);
539     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
540       return NestedNameSpecifier::Create(Context, nullptr, ND);
541     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
542       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
543                                          RD->getTypeForDecl());
544     else if (isa<TranslationUnitDecl>(DC))
545       return NestedNameSpecifier::GlobalSpecifier(Context);
546   }
547   llvm_unreachable("something isn't in TU scope?");
548 }
549 
550 /// Find the parent class with dependent bases of the innermost enclosing method
551 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
552 /// up allowing unqualified dependent type names at class-level, which MSVC
553 /// correctly rejects.
554 static const CXXRecordDecl *
555 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
556   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
557     DC = DC->getPrimaryContext();
558     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
559       if (MD->getParent()->hasAnyDependentBases())
560         return MD->getParent();
561   }
562   return nullptr;
563 }
564 
565 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
566                                           SourceLocation NameLoc,
567                                           bool IsTemplateTypeArg) {
568   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
569 
570   NestedNameSpecifier *NNS = nullptr;
571   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
572     // If we weren't able to parse a default template argument, delay lookup
573     // until instantiation time by making a non-dependent DependentTypeName. We
574     // pretend we saw a NestedNameSpecifier referring to the current scope, and
575     // lookup is retried.
576     // FIXME: This hurts our diagnostic quality, since we get errors like "no
577     // type named 'Foo' in 'current_namespace'" when the user didn't write any
578     // name specifiers.
579     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
580     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
581   } else if (const CXXRecordDecl *RD =
582                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
583     // Build a DependentNameType that will perform lookup into RD at
584     // instantiation time.
585     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
586                                       RD->getTypeForDecl());
587 
588     // Diagnose that this identifier was undeclared, and retry the lookup during
589     // template instantiation.
590     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
591                                                                       << RD;
592   } else {
593     // This is not a situation that we should recover from.
594     return ParsedType();
595   }
596 
597   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
598 
599   // Build type location information.  We synthesized the qualifier, so we have
600   // to build a fake NestedNameSpecifierLoc.
601   NestedNameSpecifierLocBuilder NNSLocBuilder;
602   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
603   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
604 
605   TypeLocBuilder Builder;
606   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
607   DepTL.setNameLoc(NameLoc);
608   DepTL.setElaboratedKeywordLoc(SourceLocation());
609   DepTL.setQualifierLoc(QualifierLoc);
610   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
611 }
612 
613 /// isTagName() - This method is called *for error recovery purposes only*
614 /// to determine if the specified name is a valid tag name ("struct foo").  If
615 /// so, this returns the TST for the tag corresponding to it (TST_enum,
616 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
617 /// cases in C where the user forgot to specify the tag.
618 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
619   // Do a tag name lookup in this scope.
620   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
621   LookupName(R, S, false);
622   R.suppressDiagnostics();
623   if (R.getResultKind() == LookupResult::Found)
624     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
625       switch (TD->getTagKind()) {
626       case TTK_Struct: return DeclSpec::TST_struct;
627       case TTK_Interface: return DeclSpec::TST_interface;
628       case TTK_Union:  return DeclSpec::TST_union;
629       case TTK_Class:  return DeclSpec::TST_class;
630       case TTK_Enum:   return DeclSpec::TST_enum;
631       }
632     }
633 
634   return DeclSpec::TST_unspecified;
635 }
636 
637 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
638 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
639 /// then downgrade the missing typename error to a warning.
640 /// This is needed for MSVC compatibility; Example:
641 /// @code
642 /// template<class T> class A {
643 /// public:
644 ///   typedef int TYPE;
645 /// };
646 /// template<class T> class B : public A<T> {
647 /// public:
648 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
649 /// };
650 /// @endcode
651 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
652   if (CurContext->isRecord()) {
653     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
654       return true;
655 
656     const Type *Ty = SS->getScopeRep()->getAsType();
657 
658     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
659     for (const auto &Base : RD->bases())
660       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
661         return true;
662     return S->isFunctionPrototypeScope();
663   }
664   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
665 }
666 
667 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
668                                    SourceLocation IILoc,
669                                    Scope *S,
670                                    CXXScopeSpec *SS,
671                                    ParsedType &SuggestedType,
672                                    bool IsTemplateName) {
673   // Don't report typename errors for editor placeholders.
674   if (II->isEditorPlaceholder())
675     return;
676   // We don't have anything to suggest (yet).
677   SuggestedType = nullptr;
678 
679   // There may have been a typo in the name of the type. Look up typo
680   // results, in case we have something that we can suggest.
681   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
682                            /*AllowTemplates=*/IsTemplateName,
683                            /*AllowNonTemplates=*/!IsTemplateName);
684   if (TypoCorrection Corrected =
685           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
686                       CCC, CTK_ErrorRecovery)) {
687     // FIXME: Support error recovery for the template-name case.
688     bool CanRecover = !IsTemplateName;
689     if (Corrected.isKeyword()) {
690       // We corrected to a keyword.
691       diagnoseTypo(Corrected,
692                    PDiag(IsTemplateName ? diag::err_no_template_suggest
693                                         : diag::err_unknown_typename_suggest)
694                        << II);
695       II = Corrected.getCorrectionAsIdentifierInfo();
696     } else {
697       // We found a similarly-named type or interface; suggest that.
698       if (!SS || !SS->isSet()) {
699         diagnoseTypo(Corrected,
700                      PDiag(IsTemplateName ? diag::err_no_template_suggest
701                                           : diag::err_unknown_typename_suggest)
702                          << II, CanRecover);
703       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
704         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
705         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
706                                 II->getName().equals(CorrectedStr);
707         diagnoseTypo(Corrected,
708                      PDiag(IsTemplateName
709                                ? diag::err_no_member_template_suggest
710                                : diag::err_unknown_nested_typename_suggest)
711                          << II << DC << DroppedSpecifier << SS->getRange(),
712                      CanRecover);
713       } else {
714         llvm_unreachable("could not have corrected a typo here");
715       }
716 
717       if (!CanRecover)
718         return;
719 
720       CXXScopeSpec tmpSS;
721       if (Corrected.getCorrectionSpecifier())
722         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
723                           SourceRange(IILoc));
724       // FIXME: Support class template argument deduction here.
725       SuggestedType =
726           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
727                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
728                       /*IsCtorOrDtorName=*/false,
729                       /*WantNontrivialTypeSourceInfo=*/true);
730     }
731     return;
732   }
733 
734   if (getLangOpts().CPlusPlus && !IsTemplateName) {
735     // See if II is a class template that the user forgot to pass arguments to.
736     UnqualifiedId Name;
737     Name.setIdentifier(II, IILoc);
738     CXXScopeSpec EmptySS;
739     TemplateTy TemplateResult;
740     bool MemberOfUnknownSpecialization;
741     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
742                        Name, nullptr, true, TemplateResult,
743                        MemberOfUnknownSpecialization) == TNK_Type_template) {
744       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
745       return;
746     }
747   }
748 
749   // FIXME: Should we move the logic that tries to recover from a missing tag
750   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
751 
752   if (!SS || (!SS->isSet() && !SS->isInvalid()))
753     Diag(IILoc, IsTemplateName ? diag::err_no_template
754                                : diag::err_unknown_typename)
755         << II;
756   else if (DeclContext *DC = computeDeclContext(*SS, false))
757     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
758                                : diag::err_typename_nested_not_found)
759         << II << DC << SS->getRange();
760   else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
761     SuggestedType =
762         ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
763   } else if (isDependentScopeSpecifier(*SS)) {
764     unsigned DiagID = diag::err_typename_missing;
765     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
766       DiagID = diag::ext_typename_missing;
767 
768     Diag(SS->getRange().getBegin(), DiagID)
769       << SS->getScopeRep() << II->getName()
770       << SourceRange(SS->getRange().getBegin(), IILoc)
771       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
772     SuggestedType = ActOnTypenameType(S, SourceLocation(),
773                                       *SS, *II, IILoc).get();
774   } else {
775     assert(SS && SS->isInvalid() &&
776            "Invalid scope specifier has already been diagnosed");
777   }
778 }
779 
780 /// Determine whether the given result set contains either a type name
781 /// or
782 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
783   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
784                        NextToken.is(tok::less);
785 
786   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
787     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
788       return true;
789 
790     if (CheckTemplate && isa<TemplateDecl>(*I))
791       return true;
792   }
793 
794   return false;
795 }
796 
797 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
798                                     Scope *S, CXXScopeSpec &SS,
799                                     IdentifierInfo *&Name,
800                                     SourceLocation NameLoc) {
801   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
802   SemaRef.LookupParsedName(R, S, &SS);
803   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
804     StringRef FixItTagName;
805     switch (Tag->getTagKind()) {
806       case TTK_Class:
807         FixItTagName = "class ";
808         break;
809 
810       case TTK_Enum:
811         FixItTagName = "enum ";
812         break;
813 
814       case TTK_Struct:
815         FixItTagName = "struct ";
816         break;
817 
818       case TTK_Interface:
819         FixItTagName = "__interface ";
820         break;
821 
822       case TTK_Union:
823         FixItTagName = "union ";
824         break;
825     }
826 
827     StringRef TagName = FixItTagName.drop_back();
828     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
829       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
830       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
831 
832     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
833          I != IEnd; ++I)
834       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
835         << Name << TagName;
836 
837     // Replace lookup results with just the tag decl.
838     Result.clear(Sema::LookupTagName);
839     SemaRef.LookupParsedName(Result, S, &SS);
840     return true;
841   }
842 
843   return false;
844 }
845 
846 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
847 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
848                                   QualType T, SourceLocation NameLoc) {
849   ASTContext &Context = S.Context;
850 
851   TypeLocBuilder Builder;
852   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
853 
854   T = S.getElaboratedType(ETK_None, SS, T);
855   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
856   ElabTL.setElaboratedKeywordLoc(SourceLocation());
857   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
858   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
859 }
860 
861 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
862                                             IdentifierInfo *&Name,
863                                             SourceLocation NameLoc,
864                                             const Token &NextToken,
865                                             CorrectionCandidateCallback *CCC) {
866   DeclarationNameInfo NameInfo(Name, NameLoc);
867   ObjCMethodDecl *CurMethod = getCurMethodDecl();
868 
869   assert(NextToken.isNot(tok::coloncolon) &&
870          "parse nested name specifiers before calling ClassifyName");
871   if (getLangOpts().CPlusPlus && SS.isSet() &&
872       isCurrentClassName(*Name, S, &SS)) {
873     // Per [class.qual]p2, this names the constructors of SS, not the
874     // injected-class-name. We don't have a classification for that.
875     // There's not much point caching this result, since the parser
876     // will reject it later.
877     return NameClassification::Unknown();
878   }
879 
880   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
881   LookupParsedName(Result, S, &SS, !CurMethod);
882 
883   if (SS.isInvalid())
884     return NameClassification::Error();
885 
886   // For unqualified lookup in a class template in MSVC mode, look into
887   // dependent base classes where the primary class template is known.
888   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
889     if (ParsedType TypeInBase =
890             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
891       return TypeInBase;
892   }
893 
894   // Perform lookup for Objective-C instance variables (including automatically
895   // synthesized instance variables), if we're in an Objective-C method.
896   // FIXME: This lookup really, really needs to be folded in to the normal
897   // unqualified lookup mechanism.
898   if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
899     DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
900     if (Ivar.isInvalid())
901       return NameClassification::Error();
902     if (Ivar.isUsable())
903       return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
904 
905     // We defer builtin creation until after ivar lookup inside ObjC methods.
906     if (Result.empty())
907       LookupBuiltin(Result);
908   }
909 
910   bool SecondTry = false;
911   bool IsFilteredTemplateName = false;
912 
913 Corrected:
914   switch (Result.getResultKind()) {
915   case LookupResult::NotFound:
916     // If an unqualified-id is followed by a '(', then we have a function
917     // call.
918     if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
919       // In C++, this is an ADL-only call.
920       // FIXME: Reference?
921       if (getLangOpts().CPlusPlus)
922         return NameClassification::UndeclaredNonType();
923 
924       // C90 6.3.2.2:
925       //   If the expression that precedes the parenthesized argument list in a
926       //   function call consists solely of an identifier, and if no
927       //   declaration is visible for this identifier, the identifier is
928       //   implicitly declared exactly as if, in the innermost block containing
929       //   the function call, the declaration
930       //
931       //     extern int identifier ();
932       //
933       //   appeared.
934       //
935       // We also allow this in C99 as an extension.
936       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
937         return NameClassification::NonType(D);
938     }
939 
940     if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
941       // In C++20 onwards, this could be an ADL-only call to a function
942       // template, and we're required to assume that this is a template name.
943       //
944       // FIXME: Find a way to still do typo correction in this case.
945       TemplateName Template =
946           Context.getAssumedTemplateName(NameInfo.getName());
947       return NameClassification::UndeclaredTemplate(Template);
948     }
949 
950     // In C, we first see whether there is a tag type by the same name, in
951     // which case it's likely that the user just forgot to write "enum",
952     // "struct", or "union".
953     if (!getLangOpts().CPlusPlus && !SecondTry &&
954         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
955       break;
956     }
957 
958     // Perform typo correction to determine if there is another name that is
959     // close to this name.
960     if (!SecondTry && CCC) {
961       SecondTry = true;
962       if (TypoCorrection Corrected =
963               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
964                           &SS, *CCC, CTK_ErrorRecovery)) {
965         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
966         unsigned QualifiedDiag = diag::err_no_member_suggest;
967 
968         NamedDecl *FirstDecl = Corrected.getFoundDecl();
969         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
970         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
971             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
972           UnqualifiedDiag = diag::err_no_template_suggest;
973           QualifiedDiag = diag::err_no_member_template_suggest;
974         } else if (UnderlyingFirstDecl &&
975                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
976                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
977                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
978           UnqualifiedDiag = diag::err_unknown_typename_suggest;
979           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
980         }
981 
982         if (SS.isEmpty()) {
983           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
984         } else {// FIXME: is this even reachable? Test it.
985           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
986           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
987                                   Name->getName().equals(CorrectedStr);
988           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
989                                     << Name << computeDeclContext(SS, false)
990                                     << DroppedSpecifier << SS.getRange());
991         }
992 
993         // Update the name, so that the caller has the new name.
994         Name = Corrected.getCorrectionAsIdentifierInfo();
995 
996         // Typo correction corrected to a keyword.
997         if (Corrected.isKeyword())
998           return Name;
999 
1000         // Also update the LookupResult...
1001         // FIXME: This should probably go away at some point
1002         Result.clear();
1003         Result.setLookupName(Corrected.getCorrection());
1004         if (FirstDecl)
1005           Result.addDecl(FirstDecl);
1006 
1007         // If we found an Objective-C instance variable, let
1008         // LookupInObjCMethod build the appropriate expression to
1009         // reference the ivar.
1010         // FIXME: This is a gross hack.
1011         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1012           DeclResult R =
1013               LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1014           if (R.isInvalid())
1015             return NameClassification::Error();
1016           if (R.isUsable())
1017             return NameClassification::NonType(Ivar);
1018         }
1019 
1020         goto Corrected;
1021       }
1022     }
1023 
1024     // We failed to correct; just fall through and let the parser deal with it.
1025     Result.suppressDiagnostics();
1026     return NameClassification::Unknown();
1027 
1028   case LookupResult::NotFoundInCurrentInstantiation: {
1029     // We performed name lookup into the current instantiation, and there were
1030     // dependent bases, so we treat this result the same way as any other
1031     // dependent nested-name-specifier.
1032 
1033     // C++ [temp.res]p2:
1034     //   A name used in a template declaration or definition and that is
1035     //   dependent on a template-parameter is assumed not to name a type
1036     //   unless the applicable name lookup finds a type name or the name is
1037     //   qualified by the keyword typename.
1038     //
1039     // FIXME: If the next token is '<', we might want to ask the parser to
1040     // perform some heroics to see if we actually have a
1041     // template-argument-list, which would indicate a missing 'template'
1042     // keyword here.
1043     return NameClassification::DependentNonType();
1044   }
1045 
1046   case LookupResult::Found:
1047   case LookupResult::FoundOverloaded:
1048   case LookupResult::FoundUnresolvedValue:
1049     break;
1050 
1051   case LookupResult::Ambiguous:
1052     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1053         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1054                                       /*AllowDependent=*/false)) {
1055       // C++ [temp.local]p3:
1056       //   A lookup that finds an injected-class-name (10.2) can result in an
1057       //   ambiguity in certain cases (for example, if it is found in more than
1058       //   one base class). If all of the injected-class-names that are found
1059       //   refer to specializations of the same class template, and if the name
1060       //   is followed by a template-argument-list, the reference refers to the
1061       //   class template itself and not a specialization thereof, and is not
1062       //   ambiguous.
1063       //
1064       // This filtering can make an ambiguous result into an unambiguous one,
1065       // so try again after filtering out template names.
1066       FilterAcceptableTemplateNames(Result);
1067       if (!Result.isAmbiguous()) {
1068         IsFilteredTemplateName = true;
1069         break;
1070       }
1071     }
1072 
1073     // Diagnose the ambiguity and return an error.
1074     return NameClassification::Error();
1075   }
1076 
1077   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1078       (IsFilteredTemplateName ||
1079        hasAnyAcceptableTemplateNames(
1080            Result, /*AllowFunctionTemplates=*/true,
1081            /*AllowDependent=*/false,
1082            /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1083                getLangOpts().CPlusPlus20))) {
1084     // C++ [temp.names]p3:
1085     //   After name lookup (3.4) finds that a name is a template-name or that
1086     //   an operator-function-id or a literal- operator-id refers to a set of
1087     //   overloaded functions any member of which is a function template if
1088     //   this is followed by a <, the < is always taken as the delimiter of a
1089     //   template-argument-list and never as the less-than operator.
1090     // C++2a [temp.names]p2:
1091     //   A name is also considered to refer to a template if it is an
1092     //   unqualified-id followed by a < and name lookup finds either one
1093     //   or more functions or finds nothing.
1094     if (!IsFilteredTemplateName)
1095       FilterAcceptableTemplateNames(Result);
1096 
1097     bool IsFunctionTemplate;
1098     bool IsVarTemplate;
1099     TemplateName Template;
1100     if (Result.end() - Result.begin() > 1) {
1101       IsFunctionTemplate = true;
1102       Template = Context.getOverloadedTemplateName(Result.begin(),
1103                                                    Result.end());
1104     } else if (!Result.empty()) {
1105       auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1106           *Result.begin(), /*AllowFunctionTemplates=*/true,
1107           /*AllowDependent=*/false));
1108       IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1109       IsVarTemplate = isa<VarTemplateDecl>(TD);
1110 
1111       if (SS.isNotEmpty())
1112         Template =
1113             Context.getQualifiedTemplateName(SS.getScopeRep(),
1114                                              /*TemplateKeyword=*/false, TD);
1115       else
1116         Template = TemplateName(TD);
1117     } else {
1118       // All results were non-template functions. This is a function template
1119       // name.
1120       IsFunctionTemplate = true;
1121       Template = Context.getAssumedTemplateName(NameInfo.getName());
1122     }
1123 
1124     if (IsFunctionTemplate) {
1125       // Function templates always go through overload resolution, at which
1126       // point we'll perform the various checks (e.g., accessibility) we need
1127       // to based on which function we selected.
1128       Result.suppressDiagnostics();
1129 
1130       return NameClassification::FunctionTemplate(Template);
1131     }
1132 
1133     return IsVarTemplate ? NameClassification::VarTemplate(Template)
1134                          : NameClassification::TypeTemplate(Template);
1135   }
1136 
1137   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1138   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1139     DiagnoseUseOfDecl(Type, NameLoc);
1140     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1148   if (!Class) {
1149     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1150     if (ObjCCompatibleAliasDecl *Alias =
1151             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1152       Class = Alias->getClassInterface();
1153   }
1154 
1155   if (Class) {
1156     DiagnoseUseOfDecl(Class, NameLoc);
1157 
1158     if (NextToken.is(tok::period)) {
1159       // Interface. <something> is parsed as a property reference expression.
1160       // Just return "unknown" as a fall-through for now.
1161       Result.suppressDiagnostics();
1162       return NameClassification::Unknown();
1163     }
1164 
1165     QualType T = Context.getObjCInterfaceType(Class);
1166     return ParsedType::make(T);
1167   }
1168 
1169   if (isa<ConceptDecl>(FirstDecl))
1170     return NameClassification::Concept(
1171         TemplateName(cast<TemplateDecl>(FirstDecl)));
1172 
1173   if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1174     (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1175     return NameClassification::Error();
1176   }
1177 
1178   // We can have a type template here if we're classifying a template argument.
1179   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1180       !isa<VarTemplateDecl>(FirstDecl))
1181     return NameClassification::TypeTemplate(
1182         TemplateName(cast<TemplateDecl>(FirstDecl)));
1183 
1184   // Check for a tag type hidden by a non-type decl in a few cases where it
1185   // seems likely a type is wanted instead of the non-type that was found.
1186   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1187   if ((NextToken.is(tok::identifier) ||
1188        (NextIsOp &&
1189         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1190       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1191     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1192     DiagnoseUseOfDecl(Type, NameLoc);
1193     QualType T = Context.getTypeDeclType(Type);
1194     if (SS.isNotEmpty())
1195       return buildNestedType(*this, SS, T, NameLoc);
1196     return ParsedType::make(T);
1197   }
1198 
1199   // If we already know which single declaration is referenced, just annotate
1200   // that declaration directly. Defer resolving even non-overloaded class
1201   // member accesses, as we need to defer certain access checks until we know
1202   // the context.
1203   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1204   if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1205     return NameClassification::NonType(Result.getRepresentativeDecl());
1206 
1207   // Otherwise, this is an overload set that we will need to resolve later.
1208   Result.suppressDiagnostics();
1209   return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1210       Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1211       Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1212       Result.begin(), Result.end()));
1213 }
1214 
1215 ExprResult
1216 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1217                                              SourceLocation NameLoc) {
1218   assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1219   CXXScopeSpec SS;
1220   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1221   return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1222 }
1223 
1224 ExprResult
1225 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1226                                             IdentifierInfo *Name,
1227                                             SourceLocation NameLoc,
1228                                             bool IsAddressOfOperand) {
1229   DeclarationNameInfo NameInfo(Name, NameLoc);
1230   return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1231                                     NameInfo, IsAddressOfOperand,
1232                                     /*TemplateArgs=*/nullptr);
1233 }
1234 
1235 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1236                                               NamedDecl *Found,
1237                                               SourceLocation NameLoc,
1238                                               const Token &NextToken) {
1239   if (getCurMethodDecl() && SS.isEmpty())
1240     if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1241       return BuildIvarRefExpr(S, NameLoc, Ivar);
1242 
1243   // Reconstruct the lookup result.
1244   LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1245   Result.addDecl(Found);
1246   Result.resolveKind();
1247 
1248   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1249   return BuildDeclarationNameExpr(SS, Result, ADL);
1250 }
1251 
1252 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1253   // For an implicit class member access, transform the result into a member
1254   // access expression if necessary.
1255   auto *ULE = cast<UnresolvedLookupExpr>(E);
1256   if ((*ULE->decls_begin())->isCXXClassMember()) {
1257     CXXScopeSpec SS;
1258     SS.Adopt(ULE->getQualifierLoc());
1259 
1260     // Reconstruct the lookup result.
1261     LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1262                         LookupOrdinaryName);
1263     Result.setNamingClass(ULE->getNamingClass());
1264     for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1265       Result.addDecl(*I, I.getAccess());
1266     Result.resolveKind();
1267     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1268                                            nullptr, S);
1269   }
1270 
1271   // Otherwise, this is already in the form we needed, and no further checks
1272   // are necessary.
1273   return ULE;
1274 }
1275 
1276 Sema::TemplateNameKindForDiagnostics
1277 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1278   auto *TD = Name.getAsTemplateDecl();
1279   if (!TD)
1280     return TemplateNameKindForDiagnostics::DependentTemplate;
1281   if (isa<ClassTemplateDecl>(TD))
1282     return TemplateNameKindForDiagnostics::ClassTemplate;
1283   if (isa<FunctionTemplateDecl>(TD))
1284     return TemplateNameKindForDiagnostics::FunctionTemplate;
1285   if (isa<VarTemplateDecl>(TD))
1286     return TemplateNameKindForDiagnostics::VarTemplate;
1287   if (isa<TypeAliasTemplateDecl>(TD))
1288     return TemplateNameKindForDiagnostics::AliasTemplate;
1289   if (isa<TemplateTemplateParmDecl>(TD))
1290     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1291   if (isa<ConceptDecl>(TD))
1292     return TemplateNameKindForDiagnostics::Concept;
1293   return TemplateNameKindForDiagnostics::DependentTemplate;
1294 }
1295 
1296 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1297   assert(DC->getLexicalParent() == CurContext &&
1298       "The next DeclContext should be lexically contained in the current one.");
1299   CurContext = DC;
1300   S->setEntity(DC);
1301 }
1302 
1303 void Sema::PopDeclContext() {
1304   assert(CurContext && "DeclContext imbalance!");
1305 
1306   CurContext = CurContext->getLexicalParent();
1307   assert(CurContext && "Popped translation unit!");
1308 }
1309 
1310 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1311                                                                     Decl *D) {
1312   // Unlike PushDeclContext, the context to which we return is not necessarily
1313   // the containing DC of TD, because the new context will be some pre-existing
1314   // TagDecl definition instead of a fresh one.
1315   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1316   CurContext = cast<TagDecl>(D)->getDefinition();
1317   assert(CurContext && "skipping definition of undefined tag");
1318   // Start lookups from the parent of the current context; we don't want to look
1319   // into the pre-existing complete definition.
1320   S->setEntity(CurContext->getLookupParent());
1321   return Result;
1322 }
1323 
1324 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1325   CurContext = static_cast<decltype(CurContext)>(Context);
1326 }
1327 
1328 /// EnterDeclaratorContext - Used when we must lookup names in the context
1329 /// of a declarator's nested name specifier.
1330 ///
1331 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1332   // C++0x [basic.lookup.unqual]p13:
1333   //   A name used in the definition of a static data member of class
1334   //   X (after the qualified-id of the static member) is looked up as
1335   //   if the name was used in a member function of X.
1336   // C++0x [basic.lookup.unqual]p14:
1337   //   If a variable member of a namespace is defined outside of the
1338   //   scope of its namespace then any name used in the definition of
1339   //   the variable member (after the declarator-id) is looked up as
1340   //   if the definition of the variable member occurred in its
1341   //   namespace.
1342   // Both of these imply that we should push a scope whose context
1343   // is the semantic context of the declaration.  We can't use
1344   // PushDeclContext here because that context is not necessarily
1345   // lexically contained in the current context.  Fortunately,
1346   // the containing scope should have the appropriate information.
1347 
1348   assert(!S->getEntity() && "scope already has entity");
1349 
1350 #ifndef NDEBUG
1351   Scope *Ancestor = S->getParent();
1352   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1353   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1354 #endif
1355 
1356   CurContext = DC;
1357   S->setEntity(DC);
1358 
1359   if (S->getParent()->isTemplateParamScope()) {
1360     // Also set the corresponding entities for all immediately-enclosing
1361     // template parameter scopes.
1362     EnterTemplatedContext(S->getParent(), DC);
1363   }
1364 }
1365 
1366 void Sema::ExitDeclaratorContext(Scope *S) {
1367   assert(S->getEntity() == CurContext && "Context imbalance!");
1368 
1369   // Switch back to the lexical context.  The safety of this is
1370   // enforced by an assert in EnterDeclaratorContext.
1371   Scope *Ancestor = S->getParent();
1372   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1373   CurContext = Ancestor->getEntity();
1374 
1375   // We don't need to do anything with the scope, which is going to
1376   // disappear.
1377 }
1378 
1379 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1380   assert(S->isTemplateParamScope() &&
1381          "expected to be initializing a template parameter scope");
1382 
1383   // C++20 [temp.local]p7:
1384   //   In the definition of a member of a class template that appears outside
1385   //   of the class template definition, the name of a member of the class
1386   //   template hides the name of a template-parameter of any enclosing class
1387   //   templates (but not a template-parameter of the member if the member is a
1388   //   class or function template).
1389   // C++20 [temp.local]p9:
1390   //   In the definition of a class template or in the definition of a member
1391   //   of such a template that appears outside of the template definition, for
1392   //   each non-dependent base class (13.8.2.1), if the name of the base class
1393   //   or the name of a member of the base class is the same as the name of a
1394   //   template-parameter, the base class name or member name hides the
1395   //   template-parameter name (6.4.10).
1396   //
1397   // This means that a template parameter scope should be searched immediately
1398   // after searching the DeclContext for which it is a template parameter
1399   // scope. For example, for
1400   //   template<typename T> template<typename U> template<typename V>
1401   //     void N::A<T>::B<U>::f(...)
1402   // we search V then B<U> (and base classes) then U then A<T> (and base
1403   // classes) then T then N then ::.
1404   unsigned ScopeDepth = getTemplateDepth(S);
1405   for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1406     DeclContext *SearchDCAfterScope = DC;
1407     for (; DC; DC = DC->getLookupParent()) {
1408       if (const TemplateParameterList *TPL =
1409               cast<Decl>(DC)->getDescribedTemplateParams()) {
1410         unsigned DCDepth = TPL->getDepth() + 1;
1411         if (DCDepth > ScopeDepth)
1412           continue;
1413         if (ScopeDepth == DCDepth)
1414           SearchDCAfterScope = DC = DC->getLookupParent();
1415         break;
1416       }
1417     }
1418     S->setLookupEntity(SearchDCAfterScope);
1419   }
1420 }
1421 
1422 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1423   // We assume that the caller has already called
1424   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1425   FunctionDecl *FD = D->getAsFunction();
1426   if (!FD)
1427     return;
1428 
1429   // Same implementation as PushDeclContext, but enters the context
1430   // from the lexical parent, rather than the top-level class.
1431   assert(CurContext == FD->getLexicalParent() &&
1432     "The next DeclContext should be lexically contained in the current one.");
1433   CurContext = FD;
1434   S->setEntity(CurContext);
1435 
1436   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1437     ParmVarDecl *Param = FD->getParamDecl(P);
1438     // If the parameter has an identifier, then add it to the scope
1439     if (Param->getIdentifier()) {
1440       S->AddDecl(Param);
1441       IdResolver.AddDecl(Param);
1442     }
1443   }
1444 }
1445 
1446 void Sema::ActOnExitFunctionContext() {
1447   // Same implementation as PopDeclContext, but returns to the lexical parent,
1448   // rather than the top-level class.
1449   assert(CurContext && "DeclContext imbalance!");
1450   CurContext = CurContext->getLexicalParent();
1451   assert(CurContext && "Popped translation unit!");
1452 }
1453 
1454 /// Determine whether we allow overloading of the function
1455 /// PrevDecl with another declaration.
1456 ///
1457 /// This routine determines whether overloading is possible, not
1458 /// whether some new function is actually an overload. It will return
1459 /// true in C++ (where we can always provide overloads) or, as an
1460 /// extension, in C when the previous function is already an
1461 /// overloaded function declaration or has the "overloadable"
1462 /// attribute.
1463 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1464                                        ASTContext &Context,
1465                                        const FunctionDecl *New) {
1466   if (Context.getLangOpts().CPlusPlus)
1467     return true;
1468 
1469   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1470     return true;
1471 
1472   return Previous.getResultKind() == LookupResult::Found &&
1473          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1474           New->hasAttr<OverloadableAttr>());
1475 }
1476 
1477 /// Add this decl to the scope shadowed decl chains.
1478 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1479   // Move up the scope chain until we find the nearest enclosing
1480   // non-transparent context. The declaration will be introduced into this
1481   // scope.
1482   while (S->getEntity() && S->getEntity()->isTransparentContext())
1483     S = S->getParent();
1484 
1485   // Add scoped declarations into their context, so that they can be
1486   // found later. Declarations without a context won't be inserted
1487   // into any context.
1488   if (AddToContext)
1489     CurContext->addDecl(D);
1490 
1491   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1492   // are function-local declarations.
1493   if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1494     return;
1495 
1496   // Template instantiations should also not be pushed into scope.
1497   if (isa<FunctionDecl>(D) &&
1498       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1499     return;
1500 
1501   // If this replaces anything in the current scope,
1502   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1503                                IEnd = IdResolver.end();
1504   for (; I != IEnd; ++I) {
1505     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1506       S->RemoveDecl(*I);
1507       IdResolver.RemoveDecl(*I);
1508 
1509       // Should only need to replace one decl.
1510       break;
1511     }
1512   }
1513 
1514   S->AddDecl(D);
1515 
1516   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1517     // Implicitly-generated labels may end up getting generated in an order that
1518     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1519     // the label at the appropriate place in the identifier chain.
1520     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1521       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1522       if (IDC == CurContext) {
1523         if (!S->isDeclScope(*I))
1524           continue;
1525       } else if (IDC->Encloses(CurContext))
1526         break;
1527     }
1528 
1529     IdResolver.InsertDeclAfter(I, D);
1530   } else {
1531     IdResolver.AddDecl(D);
1532   }
1533   warnOnReservedIdentifier(D);
1534 }
1535 
1536 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1537                          bool AllowInlineNamespace) {
1538   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1539 }
1540 
1541 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1542   DeclContext *TargetDC = DC->getPrimaryContext();
1543   do {
1544     if (DeclContext *ScopeDC = S->getEntity())
1545       if (ScopeDC->getPrimaryContext() == TargetDC)
1546         return S;
1547   } while ((S = S->getParent()));
1548 
1549   return nullptr;
1550 }
1551 
1552 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1553                                             DeclContext*,
1554                                             ASTContext&);
1555 
1556 /// Filters out lookup results that don't fall within the given scope
1557 /// as determined by isDeclInScope.
1558 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1559                                 bool ConsiderLinkage,
1560                                 bool AllowInlineNamespace) {
1561   LookupResult::Filter F = R.makeFilter();
1562   while (F.hasNext()) {
1563     NamedDecl *D = F.next();
1564 
1565     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1566       continue;
1567 
1568     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1569       continue;
1570 
1571     F.erase();
1572   }
1573 
1574   F.done();
1575 }
1576 
1577 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1578 /// have compatible owning modules.
1579 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1580   // FIXME: The Modules TS is not clear about how friend declarations are
1581   // to be treated. It's not meaningful to have different owning modules for
1582   // linkage in redeclarations of the same entity, so for now allow the
1583   // redeclaration and change the owning modules to match.
1584   if (New->getFriendObjectKind() &&
1585       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1586     New->setLocalOwningModule(Old->getOwningModule());
1587     makeMergedDefinitionVisible(New);
1588     return false;
1589   }
1590 
1591   Module *NewM = New->getOwningModule();
1592   Module *OldM = Old->getOwningModule();
1593 
1594   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1595     NewM = NewM->Parent;
1596   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1597     OldM = OldM->Parent;
1598 
1599   if (NewM == OldM)
1600     return false;
1601 
1602   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1603   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1604   if (NewIsModuleInterface || OldIsModuleInterface) {
1605     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1606     //   if a declaration of D [...] appears in the purview of a module, all
1607     //   other such declarations shall appear in the purview of the same module
1608     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1609       << New
1610       << NewIsModuleInterface
1611       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1612       << OldIsModuleInterface
1613       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1614     Diag(Old->getLocation(), diag::note_previous_declaration);
1615     New->setInvalidDecl();
1616     return true;
1617   }
1618 
1619   return false;
1620 }
1621 
1622 static bool isUsingDecl(NamedDecl *D) {
1623   return isa<UsingShadowDecl>(D) ||
1624          isa<UnresolvedUsingTypenameDecl>(D) ||
1625          isa<UnresolvedUsingValueDecl>(D);
1626 }
1627 
1628 /// Removes using shadow declarations from the lookup results.
1629 static void RemoveUsingDecls(LookupResult &R) {
1630   LookupResult::Filter F = R.makeFilter();
1631   while (F.hasNext())
1632     if (isUsingDecl(F.next()))
1633       F.erase();
1634 
1635   F.done();
1636 }
1637 
1638 /// Check for this common pattern:
1639 /// @code
1640 /// class S {
1641 ///   S(const S&); // DO NOT IMPLEMENT
1642 ///   void operator=(const S&); // DO NOT IMPLEMENT
1643 /// };
1644 /// @endcode
1645 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1646   // FIXME: Should check for private access too but access is set after we get
1647   // the decl here.
1648   if (D->doesThisDeclarationHaveABody())
1649     return false;
1650 
1651   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1652     return CD->isCopyConstructor();
1653   return D->isCopyAssignmentOperator();
1654 }
1655 
1656 // We need this to handle
1657 //
1658 // typedef struct {
1659 //   void *foo() { return 0; }
1660 // } A;
1661 //
1662 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1663 // for example. If 'A', foo will have external linkage. If we have '*A',
1664 // foo will have no linkage. Since we can't know until we get to the end
1665 // of the typedef, this function finds out if D might have non-external linkage.
1666 // Callers should verify at the end of the TU if it D has external linkage or
1667 // not.
1668 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1669   const DeclContext *DC = D->getDeclContext();
1670   while (!DC->isTranslationUnit()) {
1671     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1672       if (!RD->hasNameForLinkage())
1673         return true;
1674     }
1675     DC = DC->getParent();
1676   }
1677 
1678   return !D->isExternallyVisible();
1679 }
1680 
1681 // FIXME: This needs to be refactored; some other isInMainFile users want
1682 // these semantics.
1683 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1684   if (S.TUKind != TU_Complete)
1685     return false;
1686   return S.SourceMgr.isInMainFile(Loc);
1687 }
1688 
1689 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1690   assert(D);
1691 
1692   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1693     return false;
1694 
1695   // Ignore all entities declared within templates, and out-of-line definitions
1696   // of members of class templates.
1697   if (D->getDeclContext()->isDependentContext() ||
1698       D->getLexicalDeclContext()->isDependentContext())
1699     return false;
1700 
1701   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1702     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1703       return false;
1704     // A non-out-of-line declaration of a member specialization was implicitly
1705     // instantiated; it's the out-of-line declaration that we're interested in.
1706     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1707         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1708       return false;
1709 
1710     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1711       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1712         return false;
1713     } else {
1714       // 'static inline' functions are defined in headers; don't warn.
1715       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1716         return false;
1717     }
1718 
1719     if (FD->doesThisDeclarationHaveABody() &&
1720         Context.DeclMustBeEmitted(FD))
1721       return false;
1722   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1723     // Constants and utility variables are defined in headers with internal
1724     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1725     // like "inline".)
1726     if (!isMainFileLoc(*this, VD->getLocation()))
1727       return false;
1728 
1729     if (Context.DeclMustBeEmitted(VD))
1730       return false;
1731 
1732     if (VD->isStaticDataMember() &&
1733         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1734       return false;
1735     if (VD->isStaticDataMember() &&
1736         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1737         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1738       return false;
1739 
1740     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1741       return false;
1742   } else {
1743     return false;
1744   }
1745 
1746   // Only warn for unused decls internal to the translation unit.
1747   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1748   // for inline functions defined in the main source file, for instance.
1749   return mightHaveNonExternalLinkage(D);
1750 }
1751 
1752 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1753   if (!D)
1754     return;
1755 
1756   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1757     const FunctionDecl *First = FD->getFirstDecl();
1758     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1759       return; // First should already be in the vector.
1760   }
1761 
1762   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1763     const VarDecl *First = VD->getFirstDecl();
1764     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1765       return; // First should already be in the vector.
1766   }
1767 
1768   if (ShouldWarnIfUnusedFileScopedDecl(D))
1769     UnusedFileScopedDecls.push_back(D);
1770 }
1771 
1772 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1773   if (D->isInvalidDecl())
1774     return false;
1775 
1776   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1777     // For a decomposition declaration, warn if none of the bindings are
1778     // referenced, instead of if the variable itself is referenced (which
1779     // it is, by the bindings' expressions).
1780     for (auto *BD : DD->bindings())
1781       if (BD->isReferenced())
1782         return false;
1783   } else if (!D->getDeclName()) {
1784     return false;
1785   } else if (D->isReferenced() || D->isUsed()) {
1786     return false;
1787   }
1788 
1789   if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1790     return false;
1791 
1792   if (isa<LabelDecl>(D))
1793     return true;
1794 
1795   // Except for labels, we only care about unused decls that are local to
1796   // functions.
1797   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1798   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1799     // For dependent types, the diagnostic is deferred.
1800     WithinFunction =
1801         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1802   if (!WithinFunction)
1803     return false;
1804 
1805   if (isa<TypedefNameDecl>(D))
1806     return true;
1807 
1808   // White-list anything that isn't a local variable.
1809   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1810     return false;
1811 
1812   // Types of valid local variables should be complete, so this should succeed.
1813   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1814 
1815     // White-list anything with an __attribute__((unused)) type.
1816     const auto *Ty = VD->getType().getTypePtr();
1817 
1818     // Only look at the outermost level of typedef.
1819     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1820       if (TT->getDecl()->hasAttr<UnusedAttr>())
1821         return false;
1822     }
1823 
1824     // If we failed to complete the type for some reason, or if the type is
1825     // dependent, don't diagnose the variable.
1826     if (Ty->isIncompleteType() || Ty->isDependentType())
1827       return false;
1828 
1829     // Look at the element type to ensure that the warning behaviour is
1830     // consistent for both scalars and arrays.
1831     Ty = Ty->getBaseElementTypeUnsafe();
1832 
1833     if (const TagType *TT = Ty->getAs<TagType>()) {
1834       const TagDecl *Tag = TT->getDecl();
1835       if (Tag->hasAttr<UnusedAttr>())
1836         return false;
1837 
1838       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1839         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1840           return false;
1841 
1842         if (const Expr *Init = VD->getInit()) {
1843           if (const ExprWithCleanups *Cleanups =
1844                   dyn_cast<ExprWithCleanups>(Init))
1845             Init = Cleanups->getSubExpr();
1846           const CXXConstructExpr *Construct =
1847             dyn_cast<CXXConstructExpr>(Init);
1848           if (Construct && !Construct->isElidable()) {
1849             CXXConstructorDecl *CD = Construct->getConstructor();
1850             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1851                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1852               return false;
1853           }
1854 
1855           // Suppress the warning if we don't know how this is constructed, and
1856           // it could possibly be non-trivial constructor.
1857           if (Init->isTypeDependent())
1858             for (const CXXConstructorDecl *Ctor : RD->ctors())
1859               if (!Ctor->isTrivial())
1860                 return false;
1861         }
1862       }
1863     }
1864 
1865     // TODO: __attribute__((unused)) templates?
1866   }
1867 
1868   return true;
1869 }
1870 
1871 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1872                                      FixItHint &Hint) {
1873   if (isa<LabelDecl>(D)) {
1874     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1875         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1876         true);
1877     if (AfterColon.isInvalid())
1878       return;
1879     Hint = FixItHint::CreateRemoval(
1880         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1881   }
1882 }
1883 
1884 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1885   if (D->getTypeForDecl()->isDependentType())
1886     return;
1887 
1888   for (auto *TmpD : D->decls()) {
1889     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1890       DiagnoseUnusedDecl(T);
1891     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1892       DiagnoseUnusedNestedTypedefs(R);
1893   }
1894 }
1895 
1896 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1897 /// unless they are marked attr(unused).
1898 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1899   if (!ShouldDiagnoseUnusedDecl(D))
1900     return;
1901 
1902   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1903     // typedefs can be referenced later on, so the diagnostics are emitted
1904     // at end-of-translation-unit.
1905     UnusedLocalTypedefNameCandidates.insert(TD);
1906     return;
1907   }
1908 
1909   FixItHint Hint;
1910   GenerateFixForUnusedDecl(D, Context, Hint);
1911 
1912   unsigned DiagID;
1913   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1914     DiagID = diag::warn_unused_exception_param;
1915   else if (isa<LabelDecl>(D))
1916     DiagID = diag::warn_unused_label;
1917   else
1918     DiagID = diag::warn_unused_variable;
1919 
1920   Diag(D->getLocation(), DiagID) << D << Hint;
1921 }
1922 
1923 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1924   // If it's not referenced, it can't be set. If it has the Cleanup attribute,
1925   // it's not really unused.
1926   if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
1927       VD->hasAttr<CleanupAttr>())
1928     return;
1929 
1930   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1931 
1932   if (Ty->isReferenceType() || Ty->isDependentType())
1933     return;
1934 
1935   if (const TagType *TT = Ty->getAs<TagType>()) {
1936     const TagDecl *Tag = TT->getDecl();
1937     if (Tag->hasAttr<UnusedAttr>())
1938       return;
1939     // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1940     // mimic gcc's behavior.
1941     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1942       if (!RD->hasAttr<WarnUnusedAttr>())
1943         return;
1944     }
1945   }
1946 
1947   // Don't warn about __block Objective-C pointer variables, as they might
1948   // be assigned in the block but not used elsewhere for the purpose of lifetime
1949   // extension.
1950   if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
1951     return;
1952 
1953   auto iter = RefsMinusAssignments.find(VD);
1954   if (iter == RefsMinusAssignments.end())
1955     return;
1956 
1957   assert(iter->getSecond() >= 0 &&
1958          "Found a negative number of references to a VarDecl");
1959   if (iter->getSecond() != 0)
1960     return;
1961   unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1962                                          : diag::warn_unused_but_set_variable;
1963   Diag(VD->getLocation(), DiagID) << VD;
1964 }
1965 
1966 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1967   // Verify that we have no forward references left.  If so, there was a goto
1968   // or address of a label taken, but no definition of it.  Label fwd
1969   // definitions are indicated with a null substmt which is also not a resolved
1970   // MS inline assembly label name.
1971   bool Diagnose = false;
1972   if (L->isMSAsmLabel())
1973     Diagnose = !L->isResolvedMSAsmLabel();
1974   else
1975     Diagnose = L->getStmt() == nullptr;
1976   if (Diagnose)
1977     S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1978 }
1979 
1980 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1981   S->mergeNRVOIntoParent();
1982 
1983   if (S->decl_empty()) return;
1984   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1985          "Scope shouldn't contain decls!");
1986 
1987   for (auto *TmpD : S->decls()) {
1988     assert(TmpD && "This decl didn't get pushed??");
1989 
1990     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1991     NamedDecl *D = cast<NamedDecl>(TmpD);
1992 
1993     // Diagnose unused variables in this scope.
1994     if (!S->hasUnrecoverableErrorOccurred()) {
1995       DiagnoseUnusedDecl(D);
1996       if (const auto *RD = dyn_cast<RecordDecl>(D))
1997         DiagnoseUnusedNestedTypedefs(RD);
1998       if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1999         DiagnoseUnusedButSetDecl(VD);
2000         RefsMinusAssignments.erase(VD);
2001       }
2002     }
2003 
2004     if (!D->getDeclName()) continue;
2005 
2006     // If this was a forward reference to a label, verify it was defined.
2007     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2008       CheckPoppedLabel(LD, *this);
2009 
2010     // Remove this name from our lexical scope, and warn on it if we haven't
2011     // already.
2012     IdResolver.RemoveDecl(D);
2013     auto ShadowI = ShadowingDecls.find(D);
2014     if (ShadowI != ShadowingDecls.end()) {
2015       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2016         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2017             << D << FD << FD->getParent();
2018         Diag(FD->getLocation(), diag::note_previous_declaration);
2019       }
2020       ShadowingDecls.erase(ShadowI);
2021     }
2022   }
2023 }
2024 
2025 /// Look for an Objective-C class in the translation unit.
2026 ///
2027 /// \param Id The name of the Objective-C class we're looking for. If
2028 /// typo-correction fixes this name, the Id will be updated
2029 /// to the fixed name.
2030 ///
2031 /// \param IdLoc The location of the name in the translation unit.
2032 ///
2033 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2034 /// if there is no class with the given name.
2035 ///
2036 /// \returns The declaration of the named Objective-C class, or NULL if the
2037 /// class could not be found.
2038 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2039                                               SourceLocation IdLoc,
2040                                               bool DoTypoCorrection) {
2041   // The third "scope" argument is 0 since we aren't enabling lazy built-in
2042   // creation from this context.
2043   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2044 
2045   if (!IDecl && DoTypoCorrection) {
2046     // Perform typo correction at the given location, but only if we
2047     // find an Objective-C class name.
2048     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2049     if (TypoCorrection C =
2050             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2051                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2052       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2053       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2054       Id = IDecl->getIdentifier();
2055     }
2056   }
2057   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2058   // This routine must always return a class definition, if any.
2059   if (Def && Def->getDefinition())
2060       Def = Def->getDefinition();
2061   return Def;
2062 }
2063 
2064 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2065 /// from S, where a non-field would be declared. This routine copes
2066 /// with the difference between C and C++ scoping rules in structs and
2067 /// unions. For example, the following code is well-formed in C but
2068 /// ill-formed in C++:
2069 /// @code
2070 /// struct S6 {
2071 ///   enum { BAR } e;
2072 /// };
2073 ///
2074 /// void test_S6() {
2075 ///   struct S6 a;
2076 ///   a.e = BAR;
2077 /// }
2078 /// @endcode
2079 /// For the declaration of BAR, this routine will return a different
2080 /// scope. The scope S will be the scope of the unnamed enumeration
2081 /// within S6. In C++, this routine will return the scope associated
2082 /// with S6, because the enumeration's scope is a transparent
2083 /// context but structures can contain non-field names. In C, this
2084 /// routine will return the translation unit scope, since the
2085 /// enumeration's scope is a transparent context and structures cannot
2086 /// contain non-field names.
2087 Scope *Sema::getNonFieldDeclScope(Scope *S) {
2088   while (((S->getFlags() & Scope::DeclScope) == 0) ||
2089          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2090          (S->isClassScope() && !getLangOpts().CPlusPlus))
2091     S = S->getParent();
2092   return S;
2093 }
2094 
2095 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2096                                ASTContext::GetBuiltinTypeError Error) {
2097   switch (Error) {
2098   case ASTContext::GE_None:
2099     return "";
2100   case ASTContext::GE_Missing_type:
2101     return BuiltinInfo.getHeaderName(ID);
2102   case ASTContext::GE_Missing_stdio:
2103     return "stdio.h";
2104   case ASTContext::GE_Missing_setjmp:
2105     return "setjmp.h";
2106   case ASTContext::GE_Missing_ucontext:
2107     return "ucontext.h";
2108   }
2109   llvm_unreachable("unhandled error kind");
2110 }
2111 
2112 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2113                                   unsigned ID, SourceLocation Loc) {
2114   DeclContext *Parent = Context.getTranslationUnitDecl();
2115 
2116   if (getLangOpts().CPlusPlus) {
2117     LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2118         Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2119     CLinkageDecl->setImplicit();
2120     Parent->addDecl(CLinkageDecl);
2121     Parent = CLinkageDecl;
2122   }
2123 
2124   FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2125                                            /*TInfo=*/nullptr, SC_Extern,
2126                                            getCurFPFeatures().isFPConstrained(),
2127                                            false, Type->isFunctionProtoType());
2128   New->setImplicit();
2129   New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2130 
2131   // Create Decl objects for each parameter, adding them to the
2132   // FunctionDecl.
2133   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2134     SmallVector<ParmVarDecl *, 16> Params;
2135     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2136       ParmVarDecl *parm = ParmVarDecl::Create(
2137           Context, New, SourceLocation(), SourceLocation(), nullptr,
2138           FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2139       parm->setScopeInfo(0, i);
2140       Params.push_back(parm);
2141     }
2142     New->setParams(Params);
2143   }
2144 
2145   AddKnownFunctionAttributes(New);
2146   return New;
2147 }
2148 
2149 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2150 /// file scope.  lazily create a decl for it. ForRedeclaration is true
2151 /// if we're creating this built-in in anticipation of redeclaring the
2152 /// built-in.
2153 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2154                                      Scope *S, bool ForRedeclaration,
2155                                      SourceLocation Loc) {
2156   LookupNecessaryTypesForBuiltin(S, ID);
2157 
2158   ASTContext::GetBuiltinTypeError Error;
2159   QualType R = Context.GetBuiltinType(ID, Error);
2160   if (Error) {
2161     if (!ForRedeclaration)
2162       return nullptr;
2163 
2164     // If we have a builtin without an associated type we should not emit a
2165     // warning when we were not able to find a type for it.
2166     if (Error == ASTContext::GE_Missing_type ||
2167         Context.BuiltinInfo.allowTypeMismatch(ID))
2168       return nullptr;
2169 
2170     // If we could not find a type for setjmp it is because the jmp_buf type was
2171     // not defined prior to the setjmp declaration.
2172     if (Error == ASTContext::GE_Missing_setjmp) {
2173       Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2174           << Context.BuiltinInfo.getName(ID);
2175       return nullptr;
2176     }
2177 
2178     // Generally, we emit a warning that the declaration requires the
2179     // appropriate header.
2180     Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2181         << getHeaderName(Context.BuiltinInfo, ID, Error)
2182         << Context.BuiltinInfo.getName(ID);
2183     return nullptr;
2184   }
2185 
2186   if (!ForRedeclaration &&
2187       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2188        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2189     Diag(Loc, diag::ext_implicit_lib_function_decl)
2190         << Context.BuiltinInfo.getName(ID) << R;
2191     if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2192       Diag(Loc, diag::note_include_header_or_declare)
2193           << Header << Context.BuiltinInfo.getName(ID);
2194   }
2195 
2196   if (R.isNull())
2197     return nullptr;
2198 
2199   FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2200   RegisterLocallyScopedExternCDecl(New, S);
2201 
2202   // TUScope is the translation-unit scope to insert this function into.
2203   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2204   // relate Scopes to DeclContexts, and probably eliminate CurContext
2205   // entirely, but we're not there yet.
2206   DeclContext *SavedContext = CurContext;
2207   CurContext = New->getDeclContext();
2208   PushOnScopeChains(New, TUScope);
2209   CurContext = SavedContext;
2210   return New;
2211 }
2212 
2213 /// Typedef declarations don't have linkage, but they still denote the same
2214 /// entity if their types are the same.
2215 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2216 /// isSameEntity.
2217 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2218                                                      TypedefNameDecl *Decl,
2219                                                      LookupResult &Previous) {
2220   // This is only interesting when modules are enabled.
2221   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2222     return;
2223 
2224   // Empty sets are uninteresting.
2225   if (Previous.empty())
2226     return;
2227 
2228   LookupResult::Filter Filter = Previous.makeFilter();
2229   while (Filter.hasNext()) {
2230     NamedDecl *Old = Filter.next();
2231 
2232     // Non-hidden declarations are never ignored.
2233     if (S.isVisible(Old))
2234       continue;
2235 
2236     // Declarations of the same entity are not ignored, even if they have
2237     // different linkages.
2238     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2239       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2240                                 Decl->getUnderlyingType()))
2241         continue;
2242 
2243       // If both declarations give a tag declaration a typedef name for linkage
2244       // purposes, then they declare the same entity.
2245       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2246           Decl->getAnonDeclWithTypedefName())
2247         continue;
2248     }
2249 
2250     Filter.erase();
2251   }
2252 
2253   Filter.done();
2254 }
2255 
2256 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2257   QualType OldType;
2258   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2259     OldType = OldTypedef->getUnderlyingType();
2260   else
2261     OldType = Context.getTypeDeclType(Old);
2262   QualType NewType = New->getUnderlyingType();
2263 
2264   if (NewType->isVariablyModifiedType()) {
2265     // Must not redefine a typedef with a variably-modified type.
2266     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2267     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2268       << Kind << NewType;
2269     if (Old->getLocation().isValid())
2270       notePreviousDefinition(Old, New->getLocation());
2271     New->setInvalidDecl();
2272     return true;
2273   }
2274 
2275   if (OldType != NewType &&
2276       !OldType->isDependentType() &&
2277       !NewType->isDependentType() &&
2278       !Context.hasSameType(OldType, NewType)) {
2279     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2280     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2281       << Kind << NewType << OldType;
2282     if (Old->getLocation().isValid())
2283       notePreviousDefinition(Old, New->getLocation());
2284     New->setInvalidDecl();
2285     return true;
2286   }
2287   return false;
2288 }
2289 
2290 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2291 /// same name and scope as a previous declaration 'Old'.  Figure out
2292 /// how to resolve this situation, merging decls or emitting
2293 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2294 ///
2295 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2296                                 LookupResult &OldDecls) {
2297   // If the new decl is known invalid already, don't bother doing any
2298   // merging checks.
2299   if (New->isInvalidDecl()) return;
2300 
2301   // Allow multiple definitions for ObjC built-in typedefs.
2302   // FIXME: Verify the underlying types are equivalent!
2303   if (getLangOpts().ObjC) {
2304     const IdentifierInfo *TypeID = New->getIdentifier();
2305     switch (TypeID->getLength()) {
2306     default: break;
2307     case 2:
2308       {
2309         if (!TypeID->isStr("id"))
2310           break;
2311         QualType T = New->getUnderlyingType();
2312         if (!T->isPointerType())
2313           break;
2314         if (!T->isVoidPointerType()) {
2315           QualType PT = T->castAs<PointerType>()->getPointeeType();
2316           if (!PT->isStructureType())
2317             break;
2318         }
2319         Context.setObjCIdRedefinitionType(T);
2320         // Install the built-in type for 'id', ignoring the current definition.
2321         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2322         return;
2323       }
2324     case 5:
2325       if (!TypeID->isStr("Class"))
2326         break;
2327       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2328       // Install the built-in type for 'Class', ignoring the current definition.
2329       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2330       return;
2331     case 3:
2332       if (!TypeID->isStr("SEL"))
2333         break;
2334       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2335       // Install the built-in type for 'SEL', ignoring the current definition.
2336       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2337       return;
2338     }
2339     // Fall through - the typedef name was not a builtin type.
2340   }
2341 
2342   // Verify the old decl was also a type.
2343   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2344   if (!Old) {
2345     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2346       << New->getDeclName();
2347 
2348     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2349     if (OldD->getLocation().isValid())
2350       notePreviousDefinition(OldD, New->getLocation());
2351 
2352     return New->setInvalidDecl();
2353   }
2354 
2355   // If the old declaration is invalid, just give up here.
2356   if (Old->isInvalidDecl())
2357     return New->setInvalidDecl();
2358 
2359   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2360     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2361     auto *NewTag = New->getAnonDeclWithTypedefName();
2362     NamedDecl *Hidden = nullptr;
2363     if (OldTag && NewTag &&
2364         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2365         !hasVisibleDefinition(OldTag, &Hidden)) {
2366       // There is a definition of this tag, but it is not visible. Use it
2367       // instead of our tag.
2368       New->setTypeForDecl(OldTD->getTypeForDecl());
2369       if (OldTD->isModed())
2370         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2371                                     OldTD->getUnderlyingType());
2372       else
2373         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2374 
2375       // Make the old tag definition visible.
2376       makeMergedDefinitionVisible(Hidden);
2377 
2378       // If this was an unscoped enumeration, yank all of its enumerators
2379       // out of the scope.
2380       if (isa<EnumDecl>(NewTag)) {
2381         Scope *EnumScope = getNonFieldDeclScope(S);
2382         for (auto *D : NewTag->decls()) {
2383           auto *ED = cast<EnumConstantDecl>(D);
2384           assert(EnumScope->isDeclScope(ED));
2385           EnumScope->RemoveDecl(ED);
2386           IdResolver.RemoveDecl(ED);
2387           ED->getLexicalDeclContext()->removeDecl(ED);
2388         }
2389       }
2390     }
2391   }
2392 
2393   // If the typedef types are not identical, reject them in all languages and
2394   // with any extensions enabled.
2395   if (isIncompatibleTypedef(Old, New))
2396     return;
2397 
2398   // The types match.  Link up the redeclaration chain and merge attributes if
2399   // the old declaration was a typedef.
2400   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2401     New->setPreviousDecl(Typedef);
2402     mergeDeclAttributes(New, Old);
2403   }
2404 
2405   if (getLangOpts().MicrosoftExt)
2406     return;
2407 
2408   if (getLangOpts().CPlusPlus) {
2409     // C++ [dcl.typedef]p2:
2410     //   In a given non-class scope, a typedef specifier can be used to
2411     //   redefine the name of any type declared in that scope to refer
2412     //   to the type to which it already refers.
2413     if (!isa<CXXRecordDecl>(CurContext))
2414       return;
2415 
2416     // C++0x [dcl.typedef]p4:
2417     //   In a given class scope, a typedef specifier can be used to redefine
2418     //   any class-name declared in that scope that is not also a typedef-name
2419     //   to refer to the type to which it already refers.
2420     //
2421     // This wording came in via DR424, which was a correction to the
2422     // wording in DR56, which accidentally banned code like:
2423     //
2424     //   struct S {
2425     //     typedef struct A { } A;
2426     //   };
2427     //
2428     // in the C++03 standard. We implement the C++0x semantics, which
2429     // allow the above but disallow
2430     //
2431     //   struct S {
2432     //     typedef int I;
2433     //     typedef int I;
2434     //   };
2435     //
2436     // since that was the intent of DR56.
2437     if (!isa<TypedefNameDecl>(Old))
2438       return;
2439 
2440     Diag(New->getLocation(), diag::err_redefinition)
2441       << New->getDeclName();
2442     notePreviousDefinition(Old, New->getLocation());
2443     return New->setInvalidDecl();
2444   }
2445 
2446   // Modules always permit redefinition of typedefs, as does C11.
2447   if (getLangOpts().Modules || getLangOpts().C11)
2448     return;
2449 
2450   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2451   // is normally mapped to an error, but can be controlled with
2452   // -Wtypedef-redefinition.  If either the original or the redefinition is
2453   // in a system header, don't emit this for compatibility with GCC.
2454   if (getDiagnostics().getSuppressSystemWarnings() &&
2455       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2456       (Old->isImplicit() ||
2457        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2458        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2459     return;
2460 
2461   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2462     << New->getDeclName();
2463   notePreviousDefinition(Old, New->getLocation());
2464 }
2465 
2466 /// DeclhasAttr - returns true if decl Declaration already has the target
2467 /// attribute.
2468 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2469   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2470   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2471   for (const auto *i : D->attrs())
2472     if (i->getKind() == A->getKind()) {
2473       if (Ann) {
2474         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2475           return true;
2476         continue;
2477       }
2478       // FIXME: Don't hardcode this check
2479       if (OA && isa<OwnershipAttr>(i))
2480         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2481       return true;
2482     }
2483 
2484   return false;
2485 }
2486 
2487 static bool isAttributeTargetADefinition(Decl *D) {
2488   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2489     return VD->isThisDeclarationADefinition();
2490   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2491     return TD->isCompleteDefinition() || TD->isBeingDefined();
2492   return true;
2493 }
2494 
2495 /// Merge alignment attributes from \p Old to \p New, taking into account the
2496 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2497 ///
2498 /// \return \c true if any attributes were added to \p New.
2499 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2500   // Look for alignas attributes on Old, and pick out whichever attribute
2501   // specifies the strictest alignment requirement.
2502   AlignedAttr *OldAlignasAttr = nullptr;
2503   AlignedAttr *OldStrictestAlignAttr = nullptr;
2504   unsigned OldAlign = 0;
2505   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2506     // FIXME: We have no way of representing inherited dependent alignments
2507     // in a case like:
2508     //   template<int A, int B> struct alignas(A) X;
2509     //   template<int A, int B> struct alignas(B) X {};
2510     // For now, we just ignore any alignas attributes which are not on the
2511     // definition in such a case.
2512     if (I->isAlignmentDependent())
2513       return false;
2514 
2515     if (I->isAlignas())
2516       OldAlignasAttr = I;
2517 
2518     unsigned Align = I->getAlignment(S.Context);
2519     if (Align > OldAlign) {
2520       OldAlign = Align;
2521       OldStrictestAlignAttr = I;
2522     }
2523   }
2524 
2525   // Look for alignas attributes on New.
2526   AlignedAttr *NewAlignasAttr = nullptr;
2527   unsigned NewAlign = 0;
2528   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2529     if (I->isAlignmentDependent())
2530       return false;
2531 
2532     if (I->isAlignas())
2533       NewAlignasAttr = I;
2534 
2535     unsigned Align = I->getAlignment(S.Context);
2536     if (Align > NewAlign)
2537       NewAlign = Align;
2538   }
2539 
2540   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2541     // Both declarations have 'alignas' attributes. We require them to match.
2542     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2543     // fall short. (If two declarations both have alignas, they must both match
2544     // every definition, and so must match each other if there is a definition.)
2545 
2546     // If either declaration only contains 'alignas(0)' specifiers, then it
2547     // specifies the natural alignment for the type.
2548     if (OldAlign == 0 || NewAlign == 0) {
2549       QualType Ty;
2550       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2551         Ty = VD->getType();
2552       else
2553         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2554 
2555       if (OldAlign == 0)
2556         OldAlign = S.Context.getTypeAlign(Ty);
2557       if (NewAlign == 0)
2558         NewAlign = S.Context.getTypeAlign(Ty);
2559     }
2560 
2561     if (OldAlign != NewAlign) {
2562       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2563         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2564         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2565       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2566     }
2567   }
2568 
2569   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2570     // C++11 [dcl.align]p6:
2571     //   if any declaration of an entity has an alignment-specifier,
2572     //   every defining declaration of that entity shall specify an
2573     //   equivalent alignment.
2574     // C11 6.7.5/7:
2575     //   If the definition of an object does not have an alignment
2576     //   specifier, any other declaration of that object shall also
2577     //   have no alignment specifier.
2578     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2579       << OldAlignasAttr;
2580     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2581       << OldAlignasAttr;
2582   }
2583 
2584   bool AnyAdded = false;
2585 
2586   // Ensure we have an attribute representing the strictest alignment.
2587   if (OldAlign > NewAlign) {
2588     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2589     Clone->setInherited(true);
2590     New->addAttr(Clone);
2591     AnyAdded = true;
2592   }
2593 
2594   // Ensure we have an alignas attribute if the old declaration had one.
2595   if (OldAlignasAttr && !NewAlignasAttr &&
2596       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2597     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2598     Clone->setInherited(true);
2599     New->addAttr(Clone);
2600     AnyAdded = true;
2601   }
2602 
2603   return AnyAdded;
2604 }
2605 
2606 #define WANT_DECL_MERGE_LOGIC
2607 #include "clang/Sema/AttrParsedAttrImpl.inc"
2608 #undef WANT_DECL_MERGE_LOGIC
2609 
2610 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2611                                const InheritableAttr *Attr,
2612                                Sema::AvailabilityMergeKind AMK) {
2613   // Diagnose any mutual exclusions between the attribute that we want to add
2614   // and attributes that already exist on the declaration.
2615   if (!DiagnoseMutualExclusions(S, D, Attr))
2616     return false;
2617 
2618   // This function copies an attribute Attr from a previous declaration to the
2619   // new declaration D if the new declaration doesn't itself have that attribute
2620   // yet or if that attribute allows duplicates.
2621   // If you're adding a new attribute that requires logic different from
2622   // "use explicit attribute on decl if present, else use attribute from
2623   // previous decl", for example if the attribute needs to be consistent
2624   // between redeclarations, you need to call a custom merge function here.
2625   InheritableAttr *NewAttr = nullptr;
2626   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2627     NewAttr = S.mergeAvailabilityAttr(
2628         D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2629         AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2630         AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2631         AA->getPriority());
2632   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2633     NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2634   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2635     NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2636   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2637     NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2638   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2639     NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2640   else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2641     NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2642   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2643     NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2644                                 FA->getFirstArg());
2645   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2646     NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2647   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2648     NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2649   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2650     NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2651                                        IA->getInheritanceModel());
2652   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2653     NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2654                                       &S.Context.Idents.get(AA->getSpelling()));
2655   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2656            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2657             isa<CUDAGlobalAttr>(Attr))) {
2658     // CUDA target attributes are part of function signature for
2659     // overloading purposes and must not be merged.
2660     return false;
2661   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2662     NewAttr = S.mergeMinSizeAttr(D, *MA);
2663   else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2664     NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2665   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2666     NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2667   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2668     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2669   else if (isa<AlignedAttr>(Attr))
2670     // AlignedAttrs are handled separately, because we need to handle all
2671     // such attributes on a declaration at the same time.
2672     NewAttr = nullptr;
2673   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2674            (AMK == Sema::AMK_Override ||
2675             AMK == Sema::AMK_ProtocolImplementation ||
2676             AMK == Sema::AMK_OptionalProtocolImplementation))
2677     NewAttr = nullptr;
2678   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2679     NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2680   else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2681     NewAttr = S.mergeImportModuleAttr(D, *IMA);
2682   else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2683     NewAttr = S.mergeImportNameAttr(D, *INA);
2684   else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2685     NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2686   else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2687     NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2688   else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2689     NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2690   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2691     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2692 
2693   if (NewAttr) {
2694     NewAttr->setInherited(true);
2695     D->addAttr(NewAttr);
2696     if (isa<MSInheritanceAttr>(NewAttr))
2697       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2698     return true;
2699   }
2700 
2701   return false;
2702 }
2703 
2704 static const NamedDecl *getDefinition(const Decl *D) {
2705   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2706     return TD->getDefinition();
2707   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2708     const VarDecl *Def = VD->getDefinition();
2709     if (Def)
2710       return Def;
2711     return VD->getActingDefinition();
2712   }
2713   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2714     const FunctionDecl *Def = nullptr;
2715     if (FD->isDefined(Def, true))
2716       return Def;
2717   }
2718   return nullptr;
2719 }
2720 
2721 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2722   for (const auto *Attribute : D->attrs())
2723     if (Attribute->getKind() == Kind)
2724       return true;
2725   return false;
2726 }
2727 
2728 /// checkNewAttributesAfterDef - If we already have a definition, check that
2729 /// there are no new attributes in this declaration.
2730 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2731   if (!New->hasAttrs())
2732     return;
2733 
2734   const NamedDecl *Def = getDefinition(Old);
2735   if (!Def || Def == New)
2736     return;
2737 
2738   AttrVec &NewAttributes = New->getAttrs();
2739   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2740     const Attr *NewAttribute = NewAttributes[I];
2741 
2742     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2743       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2744         Sema::SkipBodyInfo SkipBody;
2745         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2746 
2747         // If we're skipping this definition, drop the "alias" attribute.
2748         if (SkipBody.ShouldSkip) {
2749           NewAttributes.erase(NewAttributes.begin() + I);
2750           --E;
2751           continue;
2752         }
2753       } else {
2754         VarDecl *VD = cast<VarDecl>(New);
2755         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2756                                 VarDecl::TentativeDefinition
2757                             ? diag::err_alias_after_tentative
2758                             : diag::err_redefinition;
2759         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2760         if (Diag == diag::err_redefinition)
2761           S.notePreviousDefinition(Def, VD->getLocation());
2762         else
2763           S.Diag(Def->getLocation(), diag::note_previous_definition);
2764         VD->setInvalidDecl();
2765       }
2766       ++I;
2767       continue;
2768     }
2769 
2770     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2771       // Tentative definitions are only interesting for the alias check above.
2772       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2773         ++I;
2774         continue;
2775       }
2776     }
2777 
2778     if (hasAttribute(Def, NewAttribute->getKind())) {
2779       ++I;
2780       continue; // regular attr merging will take care of validating this.
2781     }
2782 
2783     if (isa<C11NoReturnAttr>(NewAttribute)) {
2784       // C's _Noreturn is allowed to be added to a function after it is defined.
2785       ++I;
2786       continue;
2787     } else if (isa<UuidAttr>(NewAttribute)) {
2788       // msvc will allow a subsequent definition to add an uuid to a class
2789       ++I;
2790       continue;
2791     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2792       if (AA->isAlignas()) {
2793         // C++11 [dcl.align]p6:
2794         //   if any declaration of an entity has an alignment-specifier,
2795         //   every defining declaration of that entity shall specify an
2796         //   equivalent alignment.
2797         // C11 6.7.5/7:
2798         //   If the definition of an object does not have an alignment
2799         //   specifier, any other declaration of that object shall also
2800         //   have no alignment specifier.
2801         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2802           << AA;
2803         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2804           << AA;
2805         NewAttributes.erase(NewAttributes.begin() + I);
2806         --E;
2807         continue;
2808       }
2809     } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2810       // If there is a C definition followed by a redeclaration with this
2811       // attribute then there are two different definitions. In C++, prefer the
2812       // standard diagnostics.
2813       if (!S.getLangOpts().CPlusPlus) {
2814         S.Diag(NewAttribute->getLocation(),
2815                diag::err_loader_uninitialized_redeclaration);
2816         S.Diag(Def->getLocation(), diag::note_previous_definition);
2817         NewAttributes.erase(NewAttributes.begin() + I);
2818         --E;
2819         continue;
2820       }
2821     } else if (isa<SelectAnyAttr>(NewAttribute) &&
2822                cast<VarDecl>(New)->isInline() &&
2823                !cast<VarDecl>(New)->isInlineSpecified()) {
2824       // Don't warn about applying selectany to implicitly inline variables.
2825       // Older compilers and language modes would require the use of selectany
2826       // to make such variables inline, and it would have no effect if we
2827       // honored it.
2828       ++I;
2829       continue;
2830     } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2831       // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2832       // declarations after defintions.
2833       ++I;
2834       continue;
2835     }
2836 
2837     S.Diag(NewAttribute->getLocation(),
2838            diag::warn_attribute_precede_definition);
2839     S.Diag(Def->getLocation(), diag::note_previous_definition);
2840     NewAttributes.erase(NewAttributes.begin() + I);
2841     --E;
2842   }
2843 }
2844 
2845 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2846                                      const ConstInitAttr *CIAttr,
2847                                      bool AttrBeforeInit) {
2848   SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2849 
2850   // Figure out a good way to write this specifier on the old declaration.
2851   // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2852   // enough of the attribute list spelling information to extract that without
2853   // heroics.
2854   std::string SuitableSpelling;
2855   if (S.getLangOpts().CPlusPlus20)
2856     SuitableSpelling = std::string(
2857         S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2858   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2859     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2860         InsertLoc, {tok::l_square, tok::l_square,
2861                     S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2862                     S.PP.getIdentifierInfo("require_constant_initialization"),
2863                     tok::r_square, tok::r_square}));
2864   if (SuitableSpelling.empty())
2865     SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2866         InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2867                     S.PP.getIdentifierInfo("require_constant_initialization"),
2868                     tok::r_paren, tok::r_paren}));
2869   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2870     SuitableSpelling = "constinit";
2871   if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2872     SuitableSpelling = "[[clang::require_constant_initialization]]";
2873   if (SuitableSpelling.empty())
2874     SuitableSpelling = "__attribute__((require_constant_initialization))";
2875   SuitableSpelling += " ";
2876 
2877   if (AttrBeforeInit) {
2878     // extern constinit int a;
2879     // int a = 0; // error (missing 'constinit'), accepted as extension
2880     assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
2881     S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2882         << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2883     S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2884   } else {
2885     // int a = 0;
2886     // constinit extern int a; // error (missing 'constinit')
2887     S.Diag(CIAttr->getLocation(),
2888            CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2889                                  : diag::warn_require_const_init_added_too_late)
2890         << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2891     S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2892         << CIAttr->isConstinit()
2893         << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2894   }
2895 }
2896 
2897 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2898 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2899                                AvailabilityMergeKind AMK) {
2900   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2901     UsedAttr *NewAttr = OldAttr->clone(Context);
2902     NewAttr->setInherited(true);
2903     New->addAttr(NewAttr);
2904   }
2905   if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2906     RetainAttr *NewAttr = OldAttr->clone(Context);
2907     NewAttr->setInherited(true);
2908     New->addAttr(NewAttr);
2909   }
2910 
2911   if (!Old->hasAttrs() && !New->hasAttrs())
2912     return;
2913 
2914   // [dcl.constinit]p1:
2915   //   If the [constinit] specifier is applied to any declaration of a
2916   //   variable, it shall be applied to the initializing declaration.
2917   const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2918   const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2919   if (bool(OldConstInit) != bool(NewConstInit)) {
2920     const auto *OldVD = cast<VarDecl>(Old);
2921     auto *NewVD = cast<VarDecl>(New);
2922 
2923     // Find the initializing declaration. Note that we might not have linked
2924     // the new declaration into the redeclaration chain yet.
2925     const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2926     if (!InitDecl &&
2927         (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2928       InitDecl = NewVD;
2929 
2930     if (InitDecl == NewVD) {
2931       // This is the initializing declaration. If it would inherit 'constinit',
2932       // that's ill-formed. (Note that we do not apply this to the attribute
2933       // form).
2934       if (OldConstInit && OldConstInit->isConstinit())
2935         diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2936                                  /*AttrBeforeInit=*/true);
2937     } else if (NewConstInit) {
2938       // This is the first time we've been told that this declaration should
2939       // have a constant initializer. If we already saw the initializing
2940       // declaration, this is too late.
2941       if (InitDecl && InitDecl != NewVD) {
2942         diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2943                                  /*AttrBeforeInit=*/false);
2944         NewVD->dropAttr<ConstInitAttr>();
2945       }
2946     }
2947   }
2948 
2949   // Attributes declared post-definition are currently ignored.
2950   checkNewAttributesAfterDef(*this, New, Old);
2951 
2952   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2953     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2954       if (!OldA->isEquivalent(NewA)) {
2955         // This redeclaration changes __asm__ label.
2956         Diag(New->getLocation(), diag::err_different_asm_label);
2957         Diag(OldA->getLocation(), diag::note_previous_declaration);
2958       }
2959     } else if (Old->isUsed()) {
2960       // This redeclaration adds an __asm__ label to a declaration that has
2961       // already been ODR-used.
2962       Diag(New->getLocation(), diag::err_late_asm_label_name)
2963         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2964     }
2965   }
2966 
2967   // Re-declaration cannot add abi_tag's.
2968   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2969     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2970       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2971         if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
2972           Diag(NewAbiTagAttr->getLocation(),
2973                diag::err_new_abi_tag_on_redeclaration)
2974               << NewTag;
2975           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2976         }
2977       }
2978     } else {
2979       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2980       Diag(Old->getLocation(), diag::note_previous_declaration);
2981     }
2982   }
2983 
2984   // This redeclaration adds a section attribute.
2985   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2986     if (auto *VD = dyn_cast<VarDecl>(New)) {
2987       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2988         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2989         Diag(Old->getLocation(), diag::note_previous_declaration);
2990       }
2991     }
2992   }
2993 
2994   // Redeclaration adds code-seg attribute.
2995   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2996   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2997       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2998     Diag(New->getLocation(), diag::warn_mismatched_section)
2999          << 0 /*codeseg*/;
3000     Diag(Old->getLocation(), diag::note_previous_declaration);
3001   }
3002 
3003   if (!Old->hasAttrs())
3004     return;
3005 
3006   bool foundAny = New->hasAttrs();
3007 
3008   // Ensure that any moving of objects within the allocated map is done before
3009   // we process them.
3010   if (!foundAny) New->setAttrs(AttrVec());
3011 
3012   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3013     // Ignore deprecated/unavailable/availability attributes if requested.
3014     AvailabilityMergeKind LocalAMK = AMK_None;
3015     if (isa<DeprecatedAttr>(I) ||
3016         isa<UnavailableAttr>(I) ||
3017         isa<AvailabilityAttr>(I)) {
3018       switch (AMK) {
3019       case AMK_None:
3020         continue;
3021 
3022       case AMK_Redeclaration:
3023       case AMK_Override:
3024       case AMK_ProtocolImplementation:
3025       case AMK_OptionalProtocolImplementation:
3026         LocalAMK = AMK;
3027         break;
3028       }
3029     }
3030 
3031     // Already handled.
3032     if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3033       continue;
3034 
3035     if (mergeDeclAttribute(*this, New, I, LocalAMK))
3036       foundAny = true;
3037   }
3038 
3039   if (mergeAlignedAttrs(*this, New, Old))
3040     foundAny = true;
3041 
3042   if (!foundAny) New->dropAttrs();
3043 }
3044 
3045 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3046 /// to the new one.
3047 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3048                                      const ParmVarDecl *oldDecl,
3049                                      Sema &S) {
3050   // C++11 [dcl.attr.depend]p2:
3051   //   The first declaration of a function shall specify the
3052   //   carries_dependency attribute for its declarator-id if any declaration
3053   //   of the function specifies the carries_dependency attribute.
3054   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3055   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3056     S.Diag(CDA->getLocation(),
3057            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3058     // Find the first declaration of the parameter.
3059     // FIXME: Should we build redeclaration chains for function parameters?
3060     const FunctionDecl *FirstFD =
3061       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3062     const ParmVarDecl *FirstVD =
3063       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3064     S.Diag(FirstVD->getLocation(),
3065            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3066   }
3067 
3068   if (!oldDecl->hasAttrs())
3069     return;
3070 
3071   bool foundAny = newDecl->hasAttrs();
3072 
3073   // Ensure that any moving of objects within the allocated map is
3074   // done before we process them.
3075   if (!foundAny) newDecl->setAttrs(AttrVec());
3076 
3077   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3078     if (!DeclHasAttr(newDecl, I)) {
3079       InheritableAttr *newAttr =
3080         cast<InheritableParamAttr>(I->clone(S.Context));
3081       newAttr->setInherited(true);
3082       newDecl->addAttr(newAttr);
3083       foundAny = true;
3084     }
3085   }
3086 
3087   if (!foundAny) newDecl->dropAttrs();
3088 }
3089 
3090 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3091                                 const ParmVarDecl *OldParam,
3092                                 Sema &S) {
3093   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3094     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3095       if (*Oldnullability != *Newnullability) {
3096         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3097           << DiagNullabilityKind(
3098                *Newnullability,
3099                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3100                 != 0))
3101           << DiagNullabilityKind(
3102                *Oldnullability,
3103                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3104                 != 0));
3105         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3106       }
3107     } else {
3108       QualType NewT = NewParam->getType();
3109       NewT = S.Context.getAttributedType(
3110                          AttributedType::getNullabilityAttrKind(*Oldnullability),
3111                          NewT, NewT);
3112       NewParam->setType(NewT);
3113     }
3114   }
3115 }
3116 
3117 namespace {
3118 
3119 /// Used in MergeFunctionDecl to keep track of function parameters in
3120 /// C.
3121 struct GNUCompatibleParamWarning {
3122   ParmVarDecl *OldParm;
3123   ParmVarDecl *NewParm;
3124   QualType PromotedType;
3125 };
3126 
3127 } // end anonymous namespace
3128 
3129 // Determine whether the previous declaration was a definition, implicit
3130 // declaration, or a declaration.
3131 template <typename T>
3132 static std::pair<diag::kind, SourceLocation>
3133 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3134   diag::kind PrevDiag;
3135   SourceLocation OldLocation = Old->getLocation();
3136   if (Old->isThisDeclarationADefinition())
3137     PrevDiag = diag::note_previous_definition;
3138   else if (Old->isImplicit()) {
3139     PrevDiag = diag::note_previous_implicit_declaration;
3140     if (OldLocation.isInvalid())
3141       OldLocation = New->getLocation();
3142   } else
3143     PrevDiag = diag::note_previous_declaration;
3144   return std::make_pair(PrevDiag, OldLocation);
3145 }
3146 
3147 /// canRedefineFunction - checks if a function can be redefined. Currently,
3148 /// only extern inline functions can be redefined, and even then only in
3149 /// GNU89 mode.
3150 static bool canRedefineFunction(const FunctionDecl *FD,
3151                                 const LangOptions& LangOpts) {
3152   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3153           !LangOpts.CPlusPlus &&
3154           FD->isInlineSpecified() &&
3155           FD->getStorageClass() == SC_Extern);
3156 }
3157 
3158 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3159   const AttributedType *AT = T->getAs<AttributedType>();
3160   while (AT && !AT->isCallingConv())
3161     AT = AT->getModifiedType()->getAs<AttributedType>();
3162   return AT;
3163 }
3164 
3165 template <typename T>
3166 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3167   const DeclContext *DC = Old->getDeclContext();
3168   if (DC->isRecord())
3169     return false;
3170 
3171   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3172   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3173     return true;
3174   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3175     return true;
3176   return false;
3177 }
3178 
3179 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3180 static bool isExternC(VarTemplateDecl *) { return false; }
3181 static bool isExternC(FunctionTemplateDecl *) { return false; }
3182 
3183 /// Check whether a redeclaration of an entity introduced by a
3184 /// using-declaration is valid, given that we know it's not an overload
3185 /// (nor a hidden tag declaration).
3186 template<typename ExpectedDecl>
3187 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3188                                    ExpectedDecl *New) {
3189   // C++11 [basic.scope.declarative]p4:
3190   //   Given a set of declarations in a single declarative region, each of
3191   //   which specifies the same unqualified name,
3192   //   -- they shall all refer to the same entity, or all refer to functions
3193   //      and function templates; or
3194   //   -- exactly one declaration shall declare a class name or enumeration
3195   //      name that is not a typedef name and the other declarations shall all
3196   //      refer to the same variable or enumerator, or all refer to functions
3197   //      and function templates; in this case the class name or enumeration
3198   //      name is hidden (3.3.10).
3199 
3200   // C++11 [namespace.udecl]p14:
3201   //   If a function declaration in namespace scope or block scope has the
3202   //   same name and the same parameter-type-list as a function introduced
3203   //   by a using-declaration, and the declarations do not declare the same
3204   //   function, the program is ill-formed.
3205 
3206   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3207   if (Old &&
3208       !Old->getDeclContext()->getRedeclContext()->Equals(
3209           New->getDeclContext()->getRedeclContext()) &&
3210       !(isExternC(Old) && isExternC(New)))
3211     Old = nullptr;
3212 
3213   if (!Old) {
3214     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3215     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3216     S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3217     return true;
3218   }
3219   return false;
3220 }
3221 
3222 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3223                                             const FunctionDecl *B) {
3224   assert(A->getNumParams() == B->getNumParams());
3225 
3226   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3227     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3228     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3229     if (AttrA == AttrB)
3230       return true;
3231     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3232            AttrA->isDynamic() == AttrB->isDynamic();
3233   };
3234 
3235   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3236 }
3237 
3238 /// If necessary, adjust the semantic declaration context for a qualified
3239 /// declaration to name the correct inline namespace within the qualifier.
3240 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3241                                                DeclaratorDecl *OldD) {
3242   // The only case where we need to update the DeclContext is when
3243   // redeclaration lookup for a qualified name finds a declaration
3244   // in an inline namespace within the context named by the qualifier:
3245   //
3246   //   inline namespace N { int f(); }
3247   //   int ::f(); // Sema DC needs adjusting from :: to N::.
3248   //
3249   // For unqualified declarations, the semantic context *can* change
3250   // along the redeclaration chain (for local extern declarations,
3251   // extern "C" declarations, and friend declarations in particular).
3252   if (!NewD->getQualifier())
3253     return;
3254 
3255   // NewD is probably already in the right context.
3256   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3257   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3258   if (NamedDC->Equals(SemaDC))
3259     return;
3260 
3261   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3262           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3263          "unexpected context for redeclaration");
3264 
3265   auto *LexDC = NewD->getLexicalDeclContext();
3266   auto FixSemaDC = [=](NamedDecl *D) {
3267     if (!D)
3268       return;
3269     D->setDeclContext(SemaDC);
3270     D->setLexicalDeclContext(LexDC);
3271   };
3272 
3273   FixSemaDC(NewD);
3274   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3275     FixSemaDC(FD->getDescribedFunctionTemplate());
3276   else if (auto *VD = dyn_cast<VarDecl>(NewD))
3277     FixSemaDC(VD->getDescribedVarTemplate());
3278 }
3279 
3280 /// MergeFunctionDecl - We just parsed a function 'New' from
3281 /// declarator D which has the same name and scope as a previous
3282 /// declaration 'Old'.  Figure out how to resolve this situation,
3283 /// merging decls or emitting diagnostics as appropriate.
3284 ///
3285 /// In C++, New and Old must be declarations that are not
3286 /// overloaded. Use IsOverload to determine whether New and Old are
3287 /// overloaded, and to select the Old declaration that New should be
3288 /// merged with.
3289 ///
3290 /// Returns true if there was an error, false otherwise.
3291 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3292                              Scope *S, bool MergeTypeWithOld) {
3293   // Verify the old decl was also a function.
3294   FunctionDecl *Old = OldD->getAsFunction();
3295   if (!Old) {
3296     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3297       if (New->getFriendObjectKind()) {
3298         Diag(New->getLocation(), diag::err_using_decl_friend);
3299         Diag(Shadow->getTargetDecl()->getLocation(),
3300              diag::note_using_decl_target);
3301         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3302             << 0;
3303         return true;
3304       }
3305 
3306       // Check whether the two declarations might declare the same function or
3307       // function template.
3308       if (FunctionTemplateDecl *NewTemplate =
3309               New->getDescribedFunctionTemplate()) {
3310         if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3311                                                          NewTemplate))
3312           return true;
3313         OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3314                          ->getAsFunction();
3315       } else {
3316         if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3317           return true;
3318         OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3319       }
3320     } else {
3321       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3322         << New->getDeclName();
3323       notePreviousDefinition(OldD, New->getLocation());
3324       return true;
3325     }
3326   }
3327 
3328   // If the old declaration was found in an inline namespace and the new
3329   // declaration was qualified, update the DeclContext to match.
3330   adjustDeclContextForDeclaratorDecl(New, Old);
3331 
3332   // If the old declaration is invalid, just give up here.
3333   if (Old->isInvalidDecl())
3334     return true;
3335 
3336   // Disallow redeclaration of some builtins.
3337   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3338     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3339     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3340         << Old << Old->getType();
3341     return true;
3342   }
3343 
3344   diag::kind PrevDiag;
3345   SourceLocation OldLocation;
3346   std::tie(PrevDiag, OldLocation) =
3347       getNoteDiagForInvalidRedeclaration(Old, New);
3348 
3349   // Don't complain about this if we're in GNU89 mode and the old function
3350   // is an extern inline function.
3351   // Don't complain about specializations. They are not supposed to have
3352   // storage classes.
3353   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3354       New->getStorageClass() == SC_Static &&
3355       Old->hasExternalFormalLinkage() &&
3356       !New->getTemplateSpecializationInfo() &&
3357       !canRedefineFunction(Old, getLangOpts())) {
3358     if (getLangOpts().MicrosoftExt) {
3359       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3360       Diag(OldLocation, PrevDiag);
3361     } else {
3362       Diag(New->getLocation(), diag::err_static_non_static) << New;
3363       Diag(OldLocation, PrevDiag);
3364       return true;
3365     }
3366   }
3367 
3368   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3369     if (!Old->hasAttr<InternalLinkageAttr>()) {
3370       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3371           << ILA;
3372       Diag(Old->getLocation(), diag::note_previous_declaration);
3373       New->dropAttr<InternalLinkageAttr>();
3374     }
3375 
3376   if (auto *EA = New->getAttr<ErrorAttr>()) {
3377     if (!Old->hasAttr<ErrorAttr>()) {
3378       Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3379       Diag(Old->getLocation(), diag::note_previous_declaration);
3380       New->dropAttr<ErrorAttr>();
3381     }
3382   }
3383 
3384   if (CheckRedeclarationModuleOwnership(New, Old))
3385     return true;
3386 
3387   if (!getLangOpts().CPlusPlus) {
3388     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3389     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3390       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3391         << New << OldOvl;
3392 
3393       // Try our best to find a decl that actually has the overloadable
3394       // attribute for the note. In most cases (e.g. programs with only one
3395       // broken declaration/definition), this won't matter.
3396       //
3397       // FIXME: We could do this if we juggled some extra state in
3398       // OverloadableAttr, rather than just removing it.
3399       const Decl *DiagOld = Old;
3400       if (OldOvl) {
3401         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3402           const auto *A = D->getAttr<OverloadableAttr>();
3403           return A && !A->isImplicit();
3404         });
3405         // If we've implicitly added *all* of the overloadable attrs to this
3406         // chain, emitting a "previous redecl" note is pointless.
3407         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3408       }
3409 
3410       if (DiagOld)
3411         Diag(DiagOld->getLocation(),
3412              diag::note_attribute_overloadable_prev_overload)
3413           << OldOvl;
3414 
3415       if (OldOvl)
3416         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3417       else
3418         New->dropAttr<OverloadableAttr>();
3419     }
3420   }
3421 
3422   // If a function is first declared with a calling convention, but is later
3423   // declared or defined without one, all following decls assume the calling
3424   // convention of the first.
3425   //
3426   // It's OK if a function is first declared without a calling convention,
3427   // but is later declared or defined with the default calling convention.
3428   //
3429   // To test if either decl has an explicit calling convention, we look for
3430   // AttributedType sugar nodes on the type as written.  If they are missing or
3431   // were canonicalized away, we assume the calling convention was implicit.
3432   //
3433   // Note also that we DO NOT return at this point, because we still have
3434   // other tests to run.
3435   QualType OldQType = Context.getCanonicalType(Old->getType());
3436   QualType NewQType = Context.getCanonicalType(New->getType());
3437   const FunctionType *OldType = cast<FunctionType>(OldQType);
3438   const FunctionType *NewType = cast<FunctionType>(NewQType);
3439   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3440   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3441   bool RequiresAdjustment = false;
3442 
3443   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3444     FunctionDecl *First = Old->getFirstDecl();
3445     const FunctionType *FT =
3446         First->getType().getCanonicalType()->castAs<FunctionType>();
3447     FunctionType::ExtInfo FI = FT->getExtInfo();
3448     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3449     if (!NewCCExplicit) {
3450       // Inherit the CC from the previous declaration if it was specified
3451       // there but not here.
3452       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3453       RequiresAdjustment = true;
3454     } else if (Old->getBuiltinID()) {
3455       // Builtin attribute isn't propagated to the new one yet at this point,
3456       // so we check if the old one is a builtin.
3457 
3458       // Calling Conventions on a Builtin aren't really useful and setting a
3459       // default calling convention and cdecl'ing some builtin redeclarations is
3460       // common, so warn and ignore the calling convention on the redeclaration.
3461       Diag(New->getLocation(), diag::warn_cconv_unsupported)
3462           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3463           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3464       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3465       RequiresAdjustment = true;
3466     } else {
3467       // Calling conventions aren't compatible, so complain.
3468       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3469       Diag(New->getLocation(), diag::err_cconv_change)
3470         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3471         << !FirstCCExplicit
3472         << (!FirstCCExplicit ? "" :
3473             FunctionType::getNameForCallConv(FI.getCC()));
3474 
3475       // Put the note on the first decl, since it is the one that matters.
3476       Diag(First->getLocation(), diag::note_previous_declaration);
3477       return true;
3478     }
3479   }
3480 
3481   // FIXME: diagnose the other way around?
3482   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3483     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3484     RequiresAdjustment = true;
3485   }
3486 
3487   // Merge regparm attribute.
3488   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3489       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3490     if (NewTypeInfo.getHasRegParm()) {
3491       Diag(New->getLocation(), diag::err_regparm_mismatch)
3492         << NewType->getRegParmType()
3493         << OldType->getRegParmType();
3494       Diag(OldLocation, diag::note_previous_declaration);
3495       return true;
3496     }
3497 
3498     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3499     RequiresAdjustment = true;
3500   }
3501 
3502   // Merge ns_returns_retained attribute.
3503   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3504     if (NewTypeInfo.getProducesResult()) {
3505       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3506           << "'ns_returns_retained'";
3507       Diag(OldLocation, diag::note_previous_declaration);
3508       return true;
3509     }
3510 
3511     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3512     RequiresAdjustment = true;
3513   }
3514 
3515   if (OldTypeInfo.getNoCallerSavedRegs() !=
3516       NewTypeInfo.getNoCallerSavedRegs()) {
3517     if (NewTypeInfo.getNoCallerSavedRegs()) {
3518       AnyX86NoCallerSavedRegistersAttr *Attr =
3519         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3520       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3521       Diag(OldLocation, diag::note_previous_declaration);
3522       return true;
3523     }
3524 
3525     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3526     RequiresAdjustment = true;
3527   }
3528 
3529   if (RequiresAdjustment) {
3530     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3531     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3532     New->setType(QualType(AdjustedType, 0));
3533     NewQType = Context.getCanonicalType(New->getType());
3534   }
3535 
3536   // If this redeclaration makes the function inline, we may need to add it to
3537   // UndefinedButUsed.
3538   if (!Old->isInlined() && New->isInlined() &&
3539       !New->hasAttr<GNUInlineAttr>() &&
3540       !getLangOpts().GNUInline &&
3541       Old->isUsed(false) &&
3542       !Old->isDefined() && !New->isThisDeclarationADefinition())
3543     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3544                                            SourceLocation()));
3545 
3546   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3547   // about it.
3548   if (New->hasAttr<GNUInlineAttr>() &&
3549       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3550     UndefinedButUsed.erase(Old->getCanonicalDecl());
3551   }
3552 
3553   // If pass_object_size params don't match up perfectly, this isn't a valid
3554   // redeclaration.
3555   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3556       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3557     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3558         << New->getDeclName();
3559     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3560     return true;
3561   }
3562 
3563   if (getLangOpts().CPlusPlus) {
3564     // C++1z [over.load]p2
3565     //   Certain function declarations cannot be overloaded:
3566     //     -- Function declarations that differ only in the return type,
3567     //        the exception specification, or both cannot be overloaded.
3568 
3569     // Check the exception specifications match. This may recompute the type of
3570     // both Old and New if it resolved exception specifications, so grab the
3571     // types again after this. Because this updates the type, we do this before
3572     // any of the other checks below, which may update the "de facto" NewQType
3573     // but do not necessarily update the type of New.
3574     if (CheckEquivalentExceptionSpec(Old, New))
3575       return true;
3576     OldQType = Context.getCanonicalType(Old->getType());
3577     NewQType = Context.getCanonicalType(New->getType());
3578 
3579     // Go back to the type source info to compare the declared return types,
3580     // per C++1y [dcl.type.auto]p13:
3581     //   Redeclarations or specializations of a function or function template
3582     //   with a declared return type that uses a placeholder type shall also
3583     //   use that placeholder, not a deduced type.
3584     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3585     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3586     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3587         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3588                                        OldDeclaredReturnType)) {
3589       QualType ResQT;
3590       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3591           OldDeclaredReturnType->isObjCObjectPointerType())
3592         // FIXME: This does the wrong thing for a deduced return type.
3593         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3594       if (ResQT.isNull()) {
3595         if (New->isCXXClassMember() && New->isOutOfLine())
3596           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3597               << New << New->getReturnTypeSourceRange();
3598         else
3599           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3600               << New->getReturnTypeSourceRange();
3601         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3602                                     << Old->getReturnTypeSourceRange();
3603         return true;
3604       }
3605       else
3606         NewQType = ResQT;
3607     }
3608 
3609     QualType OldReturnType = OldType->getReturnType();
3610     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3611     if (OldReturnType != NewReturnType) {
3612       // If this function has a deduced return type and has already been
3613       // defined, copy the deduced value from the old declaration.
3614       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3615       if (OldAT && OldAT->isDeduced()) {
3616         New->setType(
3617             SubstAutoType(New->getType(),
3618                           OldAT->isDependentType() ? Context.DependentTy
3619                                                    : OldAT->getDeducedType()));
3620         NewQType = Context.getCanonicalType(
3621             SubstAutoType(NewQType,
3622                           OldAT->isDependentType() ? Context.DependentTy
3623                                                    : OldAT->getDeducedType()));
3624       }
3625     }
3626 
3627     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3628     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3629     if (OldMethod && NewMethod) {
3630       // Preserve triviality.
3631       NewMethod->setTrivial(OldMethod->isTrivial());
3632 
3633       // MSVC allows explicit template specialization at class scope:
3634       // 2 CXXMethodDecls referring to the same function will be injected.
3635       // We don't want a redeclaration error.
3636       bool IsClassScopeExplicitSpecialization =
3637                               OldMethod->isFunctionTemplateSpecialization() &&
3638                               NewMethod->isFunctionTemplateSpecialization();
3639       bool isFriend = NewMethod->getFriendObjectKind();
3640 
3641       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3642           !IsClassScopeExplicitSpecialization) {
3643         //    -- Member function declarations with the same name and the
3644         //       same parameter types cannot be overloaded if any of them
3645         //       is a static member function declaration.
3646         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3647           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3648           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3649           return true;
3650         }
3651 
3652         // C++ [class.mem]p1:
3653         //   [...] A member shall not be declared twice in the
3654         //   member-specification, except that a nested class or member
3655         //   class template can be declared and then later defined.
3656         if (!inTemplateInstantiation()) {
3657           unsigned NewDiag;
3658           if (isa<CXXConstructorDecl>(OldMethod))
3659             NewDiag = diag::err_constructor_redeclared;
3660           else if (isa<CXXDestructorDecl>(NewMethod))
3661             NewDiag = diag::err_destructor_redeclared;
3662           else if (isa<CXXConversionDecl>(NewMethod))
3663             NewDiag = diag::err_conv_function_redeclared;
3664           else
3665             NewDiag = diag::err_member_redeclared;
3666 
3667           Diag(New->getLocation(), NewDiag);
3668         } else {
3669           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3670             << New << New->getType();
3671         }
3672         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3673         return true;
3674 
3675       // Complain if this is an explicit declaration of a special
3676       // member that was initially declared implicitly.
3677       //
3678       // As an exception, it's okay to befriend such methods in order
3679       // to permit the implicit constructor/destructor/operator calls.
3680       } else if (OldMethod->isImplicit()) {
3681         if (isFriend) {
3682           NewMethod->setImplicit();
3683         } else {
3684           Diag(NewMethod->getLocation(),
3685                diag::err_definition_of_implicitly_declared_member)
3686             << New << getSpecialMember(OldMethod);
3687           return true;
3688         }
3689       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3690         Diag(NewMethod->getLocation(),
3691              diag::err_definition_of_explicitly_defaulted_member)
3692           << getSpecialMember(OldMethod);
3693         return true;
3694       }
3695     }
3696 
3697     // C++11 [dcl.attr.noreturn]p1:
3698     //   The first declaration of a function shall specify the noreturn
3699     //   attribute if any declaration of that function specifies the noreturn
3700     //   attribute.
3701     if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3702       if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3703         Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3704             << NRA;
3705         Diag(Old->getLocation(), diag::note_previous_declaration);
3706       }
3707 
3708     // C++11 [dcl.attr.depend]p2:
3709     //   The first declaration of a function shall specify the
3710     //   carries_dependency attribute for its declarator-id if any declaration
3711     //   of the function specifies the carries_dependency attribute.
3712     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3713     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3714       Diag(CDA->getLocation(),
3715            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3716       Diag(Old->getFirstDecl()->getLocation(),
3717            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3718     }
3719 
3720     // (C++98 8.3.5p3):
3721     //   All declarations for a function shall agree exactly in both the
3722     //   return type and the parameter-type-list.
3723     // We also want to respect all the extended bits except noreturn.
3724 
3725     // noreturn should now match unless the old type info didn't have it.
3726     QualType OldQTypeForComparison = OldQType;
3727     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3728       auto *OldType = OldQType->castAs<FunctionProtoType>();
3729       const FunctionType *OldTypeForComparison
3730         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3731       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3732       assert(OldQTypeForComparison.isCanonical());
3733     }
3734 
3735     if (haveIncompatibleLanguageLinkages(Old, New)) {
3736       // As a special case, retain the language linkage from previous
3737       // declarations of a friend function as an extension.
3738       //
3739       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3740       // and is useful because there's otherwise no way to specify language
3741       // linkage within class scope.
3742       //
3743       // Check cautiously as the friend object kind isn't yet complete.
3744       if (New->getFriendObjectKind() != Decl::FOK_None) {
3745         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3746         Diag(OldLocation, PrevDiag);
3747       } else {
3748         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3749         Diag(OldLocation, PrevDiag);
3750         return true;
3751       }
3752     }
3753 
3754     // If the function types are compatible, merge the declarations. Ignore the
3755     // exception specifier because it was already checked above in
3756     // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3757     // about incompatible types under -fms-compatibility.
3758     if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3759                                                          NewQType))
3760       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3761 
3762     // If the types are imprecise (due to dependent constructs in friends or
3763     // local extern declarations), it's OK if they differ. We'll check again
3764     // during instantiation.
3765     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3766       return false;
3767 
3768     // Fall through for conflicting redeclarations and redefinitions.
3769   }
3770 
3771   // C: Function types need to be compatible, not identical. This handles
3772   // duplicate function decls like "void f(int); void f(enum X);" properly.
3773   if (!getLangOpts().CPlusPlus &&
3774       Context.typesAreCompatible(OldQType, NewQType)) {
3775     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3776     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3777     const FunctionProtoType *OldProto = nullptr;
3778     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3779         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3780       // The old declaration provided a function prototype, but the
3781       // new declaration does not. Merge in the prototype.
3782       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3783       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3784       NewQType =
3785           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3786                                   OldProto->getExtProtoInfo());
3787       New->setType(NewQType);
3788       New->setHasInheritedPrototype();
3789 
3790       // Synthesize parameters with the same types.
3791       SmallVector<ParmVarDecl*, 16> Params;
3792       for (const auto &ParamType : OldProto->param_types()) {
3793         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3794                                                  SourceLocation(), nullptr,
3795                                                  ParamType, /*TInfo=*/nullptr,
3796                                                  SC_None, nullptr);
3797         Param->setScopeInfo(0, Params.size());
3798         Param->setImplicit();
3799         Params.push_back(Param);
3800       }
3801 
3802       New->setParams(Params);
3803     }
3804 
3805     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3806   }
3807 
3808   // Check if the function types are compatible when pointer size address
3809   // spaces are ignored.
3810   if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3811     return false;
3812 
3813   // GNU C permits a K&R definition to follow a prototype declaration
3814   // if the declared types of the parameters in the K&R definition
3815   // match the types in the prototype declaration, even when the
3816   // promoted types of the parameters from the K&R definition differ
3817   // from the types in the prototype. GCC then keeps the types from
3818   // the prototype.
3819   //
3820   // If a variadic prototype is followed by a non-variadic K&R definition,
3821   // the K&R definition becomes variadic.  This is sort of an edge case, but
3822   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3823   // C99 6.9.1p8.
3824   if (!getLangOpts().CPlusPlus &&
3825       Old->hasPrototype() && !New->hasPrototype() &&
3826       New->getType()->getAs<FunctionProtoType>() &&
3827       Old->getNumParams() == New->getNumParams()) {
3828     SmallVector<QualType, 16> ArgTypes;
3829     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3830     const FunctionProtoType *OldProto
3831       = Old->getType()->getAs<FunctionProtoType>();
3832     const FunctionProtoType *NewProto
3833       = New->getType()->getAs<FunctionProtoType>();
3834 
3835     // Determine whether this is the GNU C extension.
3836     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3837                                                NewProto->getReturnType());
3838     bool LooseCompatible = !MergedReturn.isNull();
3839     for (unsigned Idx = 0, End = Old->getNumParams();
3840          LooseCompatible && Idx != End; ++Idx) {
3841       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3842       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3843       if (Context.typesAreCompatible(OldParm->getType(),
3844                                      NewProto->getParamType(Idx))) {
3845         ArgTypes.push_back(NewParm->getType());
3846       } else if (Context.typesAreCompatible(OldParm->getType(),
3847                                             NewParm->getType(),
3848                                             /*CompareUnqualified=*/true)) {
3849         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3850                                            NewProto->getParamType(Idx) };
3851         Warnings.push_back(Warn);
3852         ArgTypes.push_back(NewParm->getType());
3853       } else
3854         LooseCompatible = false;
3855     }
3856 
3857     if (LooseCompatible) {
3858       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3859         Diag(Warnings[Warn].NewParm->getLocation(),
3860              diag::ext_param_promoted_not_compatible_with_prototype)
3861           << Warnings[Warn].PromotedType
3862           << Warnings[Warn].OldParm->getType();
3863         if (Warnings[Warn].OldParm->getLocation().isValid())
3864           Diag(Warnings[Warn].OldParm->getLocation(),
3865                diag::note_previous_declaration);
3866       }
3867 
3868       if (MergeTypeWithOld)
3869         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3870                                              OldProto->getExtProtoInfo()));
3871       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3872     }
3873 
3874     // Fall through to diagnose conflicting types.
3875   }
3876 
3877   // A function that has already been declared has been redeclared or
3878   // defined with a different type; show an appropriate diagnostic.
3879 
3880   // If the previous declaration was an implicitly-generated builtin
3881   // declaration, then at the very least we should use a specialized note.
3882   unsigned BuiltinID;
3883   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3884     // If it's actually a library-defined builtin function like 'malloc'
3885     // or 'printf', just warn about the incompatible redeclaration.
3886     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3887       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3888       Diag(OldLocation, diag::note_previous_builtin_declaration)
3889         << Old << Old->getType();
3890       return false;
3891     }
3892 
3893     PrevDiag = diag::note_previous_builtin_declaration;
3894   }
3895 
3896   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3897   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3898   return true;
3899 }
3900 
3901 /// Completes the merge of two function declarations that are
3902 /// known to be compatible.
3903 ///
3904 /// This routine handles the merging of attributes and other
3905 /// properties of function declarations from the old declaration to
3906 /// the new declaration, once we know that New is in fact a
3907 /// redeclaration of Old.
3908 ///
3909 /// \returns false
3910 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3911                                         Scope *S, bool MergeTypeWithOld) {
3912   // Merge the attributes
3913   mergeDeclAttributes(New, Old);
3914 
3915   // Merge "pure" flag.
3916   if (Old->isPure())
3917     New->setPure();
3918 
3919   // Merge "used" flag.
3920   if (Old->getMostRecentDecl()->isUsed(false))
3921     New->setIsUsed();
3922 
3923   // Merge attributes from the parameters.  These can mismatch with K&R
3924   // declarations.
3925   if (New->getNumParams() == Old->getNumParams())
3926       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3927         ParmVarDecl *NewParam = New->getParamDecl(i);
3928         ParmVarDecl *OldParam = Old->getParamDecl(i);
3929         mergeParamDeclAttributes(NewParam, OldParam, *this);
3930         mergeParamDeclTypes(NewParam, OldParam, *this);
3931       }
3932 
3933   if (getLangOpts().CPlusPlus)
3934     return MergeCXXFunctionDecl(New, Old, S);
3935 
3936   // Merge the function types so the we get the composite types for the return
3937   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3938   // was visible.
3939   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3940   if (!Merged.isNull() && MergeTypeWithOld)
3941     New->setType(Merged);
3942 
3943   return false;
3944 }
3945 
3946 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3947                                 ObjCMethodDecl *oldMethod) {
3948   // Merge the attributes, including deprecated/unavailable
3949   AvailabilityMergeKind MergeKind =
3950       isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3951           ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3952                                      : AMK_ProtocolImplementation)
3953           : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3954                                                            : AMK_Override;
3955 
3956   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3957 
3958   // Merge attributes from the parameters.
3959   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3960                                        oe = oldMethod->param_end();
3961   for (ObjCMethodDecl::param_iterator
3962          ni = newMethod->param_begin(), ne = newMethod->param_end();
3963        ni != ne && oi != oe; ++ni, ++oi)
3964     mergeParamDeclAttributes(*ni, *oi, *this);
3965 
3966   CheckObjCMethodOverride(newMethod, oldMethod);
3967 }
3968 
3969 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3970   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3971 
3972   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3973          ? diag::err_redefinition_different_type
3974          : diag::err_redeclaration_different_type)
3975     << New->getDeclName() << New->getType() << Old->getType();
3976 
3977   diag::kind PrevDiag;
3978   SourceLocation OldLocation;
3979   std::tie(PrevDiag, OldLocation)
3980     = getNoteDiagForInvalidRedeclaration(Old, New);
3981   S.Diag(OldLocation, PrevDiag);
3982   New->setInvalidDecl();
3983 }
3984 
3985 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3986 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3987 /// emitting diagnostics as appropriate.
3988 ///
3989 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3990 /// to here in AddInitializerToDecl. We can't check them before the initializer
3991 /// is attached.
3992 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3993                              bool MergeTypeWithOld) {
3994   if (New->isInvalidDecl() || Old->isInvalidDecl())
3995     return;
3996 
3997   QualType MergedT;
3998   if (getLangOpts().CPlusPlus) {
3999     if (New->getType()->isUndeducedType()) {
4000       // We don't know what the new type is until the initializer is attached.
4001       return;
4002     } else if (Context.hasSameType(New->getType(), Old->getType())) {
4003       // These could still be something that needs exception specs checked.
4004       return MergeVarDeclExceptionSpecs(New, Old);
4005     }
4006     // C++ [basic.link]p10:
4007     //   [...] the types specified by all declarations referring to a given
4008     //   object or function shall be identical, except that declarations for an
4009     //   array object can specify array types that differ by the presence or
4010     //   absence of a major array bound (8.3.4).
4011     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4012       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4013       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4014 
4015       // We are merging a variable declaration New into Old. If it has an array
4016       // bound, and that bound differs from Old's bound, we should diagnose the
4017       // mismatch.
4018       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4019         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4020              PrevVD = PrevVD->getPreviousDecl()) {
4021           QualType PrevVDTy = PrevVD->getType();
4022           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4023             continue;
4024 
4025           if (!Context.hasSameType(New->getType(), PrevVDTy))
4026             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4027         }
4028       }
4029 
4030       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4031         if (Context.hasSameType(OldArray->getElementType(),
4032                                 NewArray->getElementType()))
4033           MergedT = New->getType();
4034       }
4035       // FIXME: Check visibility. New is hidden but has a complete type. If New
4036       // has no array bound, it should not inherit one from Old, if Old is not
4037       // visible.
4038       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4039         if (Context.hasSameType(OldArray->getElementType(),
4040                                 NewArray->getElementType()))
4041           MergedT = Old->getType();
4042       }
4043     }
4044     else if (New->getType()->isObjCObjectPointerType() &&
4045                Old->getType()->isObjCObjectPointerType()) {
4046       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4047                                               Old->getType());
4048     }
4049   } else {
4050     // C 6.2.7p2:
4051     //   All declarations that refer to the same object or function shall have
4052     //   compatible type.
4053     MergedT = Context.mergeTypes(New->getType(), Old->getType());
4054   }
4055   if (MergedT.isNull()) {
4056     // It's OK if we couldn't merge types if either type is dependent, for a
4057     // block-scope variable. In other cases (static data members of class
4058     // templates, variable templates, ...), we require the types to be
4059     // equivalent.
4060     // FIXME: The C++ standard doesn't say anything about this.
4061     if ((New->getType()->isDependentType() ||
4062          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4063       // If the old type was dependent, we can't merge with it, so the new type
4064       // becomes dependent for now. We'll reproduce the original type when we
4065       // instantiate the TypeSourceInfo for the variable.
4066       if (!New->getType()->isDependentType() && MergeTypeWithOld)
4067         New->setType(Context.DependentTy);
4068       return;
4069     }
4070     return diagnoseVarDeclTypeMismatch(*this, New, Old);
4071   }
4072 
4073   // Don't actually update the type on the new declaration if the old
4074   // declaration was an extern declaration in a different scope.
4075   if (MergeTypeWithOld)
4076     New->setType(MergedT);
4077 }
4078 
4079 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4080                                   LookupResult &Previous) {
4081   // C11 6.2.7p4:
4082   //   For an identifier with internal or external linkage declared
4083   //   in a scope in which a prior declaration of that identifier is
4084   //   visible, if the prior declaration specifies internal or
4085   //   external linkage, the type of the identifier at the later
4086   //   declaration becomes the composite type.
4087   //
4088   // If the variable isn't visible, we do not merge with its type.
4089   if (Previous.isShadowed())
4090     return false;
4091 
4092   if (S.getLangOpts().CPlusPlus) {
4093     // C++11 [dcl.array]p3:
4094     //   If there is a preceding declaration of the entity in the same
4095     //   scope in which the bound was specified, an omitted array bound
4096     //   is taken to be the same as in that earlier declaration.
4097     return NewVD->isPreviousDeclInSameBlockScope() ||
4098            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4099             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4100   } else {
4101     // If the old declaration was function-local, don't merge with its
4102     // type unless we're in the same function.
4103     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4104            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4105   }
4106 }
4107 
4108 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4109 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
4110 /// situation, merging decls or emitting diagnostics as appropriate.
4111 ///
4112 /// Tentative definition rules (C99 6.9.2p2) are checked by
4113 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4114 /// definitions here, since the initializer hasn't been attached.
4115 ///
4116 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4117   // If the new decl is already invalid, don't do any other checking.
4118   if (New->isInvalidDecl())
4119     return;
4120 
4121   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4122     return;
4123 
4124   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4125 
4126   // Verify the old decl was also a variable or variable template.
4127   VarDecl *Old = nullptr;
4128   VarTemplateDecl *OldTemplate = nullptr;
4129   if (Previous.isSingleResult()) {
4130     if (NewTemplate) {
4131       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4132       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4133 
4134       if (auto *Shadow =
4135               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4136         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4137           return New->setInvalidDecl();
4138     } else {
4139       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4140 
4141       if (auto *Shadow =
4142               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4143         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4144           return New->setInvalidDecl();
4145     }
4146   }
4147   if (!Old) {
4148     Diag(New->getLocation(), diag::err_redefinition_different_kind)
4149         << New->getDeclName();
4150     notePreviousDefinition(Previous.getRepresentativeDecl(),
4151                            New->getLocation());
4152     return New->setInvalidDecl();
4153   }
4154 
4155   // If the old declaration was found in an inline namespace and the new
4156   // declaration was qualified, update the DeclContext to match.
4157   adjustDeclContextForDeclaratorDecl(New, Old);
4158 
4159   // Ensure the template parameters are compatible.
4160   if (NewTemplate &&
4161       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4162                                       OldTemplate->getTemplateParameters(),
4163                                       /*Complain=*/true, TPL_TemplateMatch))
4164     return New->setInvalidDecl();
4165 
4166   // C++ [class.mem]p1:
4167   //   A member shall not be declared twice in the member-specification [...]
4168   //
4169   // Here, we need only consider static data members.
4170   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4171     Diag(New->getLocation(), diag::err_duplicate_member)
4172       << New->getIdentifier();
4173     Diag(Old->getLocation(), diag::note_previous_declaration);
4174     New->setInvalidDecl();
4175   }
4176 
4177   mergeDeclAttributes(New, Old);
4178   // Warn if an already-declared variable is made a weak_import in a subsequent
4179   // declaration
4180   if (New->hasAttr<WeakImportAttr>() &&
4181       Old->getStorageClass() == SC_None &&
4182       !Old->hasAttr<WeakImportAttr>()) {
4183     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4184     Diag(Old->getLocation(), diag::note_previous_declaration);
4185     // Remove weak_import attribute on new declaration.
4186     New->dropAttr<WeakImportAttr>();
4187   }
4188 
4189   if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4190     if (!Old->hasAttr<InternalLinkageAttr>()) {
4191       Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4192           << ILA;
4193       Diag(Old->getLocation(), diag::note_previous_declaration);
4194       New->dropAttr<InternalLinkageAttr>();
4195     }
4196 
4197   // Merge the types.
4198   VarDecl *MostRecent = Old->getMostRecentDecl();
4199   if (MostRecent != Old) {
4200     MergeVarDeclTypes(New, MostRecent,
4201                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4202     if (New->isInvalidDecl())
4203       return;
4204   }
4205 
4206   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4207   if (New->isInvalidDecl())
4208     return;
4209 
4210   diag::kind PrevDiag;
4211   SourceLocation OldLocation;
4212   std::tie(PrevDiag, OldLocation) =
4213       getNoteDiagForInvalidRedeclaration(Old, New);
4214 
4215   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4216   if (New->getStorageClass() == SC_Static &&
4217       !New->isStaticDataMember() &&
4218       Old->hasExternalFormalLinkage()) {
4219     if (getLangOpts().MicrosoftExt) {
4220       Diag(New->getLocation(), diag::ext_static_non_static)
4221           << New->getDeclName();
4222       Diag(OldLocation, PrevDiag);
4223     } else {
4224       Diag(New->getLocation(), diag::err_static_non_static)
4225           << New->getDeclName();
4226       Diag(OldLocation, PrevDiag);
4227       return New->setInvalidDecl();
4228     }
4229   }
4230   // C99 6.2.2p4:
4231   //   For an identifier declared with the storage-class specifier
4232   //   extern in a scope in which a prior declaration of that
4233   //   identifier is visible,23) if the prior declaration specifies
4234   //   internal or external linkage, the linkage of the identifier at
4235   //   the later declaration is the same as the linkage specified at
4236   //   the prior declaration. If no prior declaration is visible, or
4237   //   if the prior declaration specifies no linkage, then the
4238   //   identifier has external linkage.
4239   if (New->hasExternalStorage() && Old->hasLinkage())
4240     /* Okay */;
4241   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4242            !New->isStaticDataMember() &&
4243            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4244     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4245     Diag(OldLocation, PrevDiag);
4246     return New->setInvalidDecl();
4247   }
4248 
4249   // Check if extern is followed by non-extern and vice-versa.
4250   if (New->hasExternalStorage() &&
4251       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4252     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4253     Diag(OldLocation, PrevDiag);
4254     return New->setInvalidDecl();
4255   }
4256   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4257       !New->hasExternalStorage()) {
4258     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4259     Diag(OldLocation, PrevDiag);
4260     return New->setInvalidDecl();
4261   }
4262 
4263   if (CheckRedeclarationModuleOwnership(New, Old))
4264     return;
4265 
4266   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4267 
4268   // FIXME: The test for external storage here seems wrong? We still
4269   // need to check for mismatches.
4270   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4271       // Don't complain about out-of-line definitions of static members.
4272       !(Old->getLexicalDeclContext()->isRecord() &&
4273         !New->getLexicalDeclContext()->isRecord())) {
4274     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4275     Diag(OldLocation, PrevDiag);
4276     return New->setInvalidDecl();
4277   }
4278 
4279   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4280     if (VarDecl *Def = Old->getDefinition()) {
4281       // C++1z [dcl.fcn.spec]p4:
4282       //   If the definition of a variable appears in a translation unit before
4283       //   its first declaration as inline, the program is ill-formed.
4284       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4285       Diag(Def->getLocation(), diag::note_previous_definition);
4286     }
4287   }
4288 
4289   // If this redeclaration makes the variable inline, we may need to add it to
4290   // UndefinedButUsed.
4291   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4292       !Old->getDefinition() && !New->isThisDeclarationADefinition())
4293     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4294                                            SourceLocation()));
4295 
4296   if (New->getTLSKind() != Old->getTLSKind()) {
4297     if (!Old->getTLSKind()) {
4298       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4299       Diag(OldLocation, PrevDiag);
4300     } else if (!New->getTLSKind()) {
4301       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4302       Diag(OldLocation, PrevDiag);
4303     } else {
4304       // Do not allow redeclaration to change the variable between requiring
4305       // static and dynamic initialization.
4306       // FIXME: GCC allows this, but uses the TLS keyword on the first
4307       // declaration to determine the kind. Do we need to be compatible here?
4308       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4309         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4310       Diag(OldLocation, PrevDiag);
4311     }
4312   }
4313 
4314   // C++ doesn't have tentative definitions, so go right ahead and check here.
4315   if (getLangOpts().CPlusPlus &&
4316       New->isThisDeclarationADefinition() == VarDecl::Definition) {
4317     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4318         Old->getCanonicalDecl()->isConstexpr()) {
4319       // This definition won't be a definition any more once it's been merged.
4320       Diag(New->getLocation(),
4321            diag::warn_deprecated_redundant_constexpr_static_def);
4322     } else if (VarDecl *Def = Old->getDefinition()) {
4323       if (checkVarDeclRedefinition(Def, New))
4324         return;
4325     }
4326   }
4327 
4328   if (haveIncompatibleLanguageLinkages(Old, New)) {
4329     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4330     Diag(OldLocation, PrevDiag);
4331     New->setInvalidDecl();
4332     return;
4333   }
4334 
4335   // Merge "used" flag.
4336   if (Old->getMostRecentDecl()->isUsed(false))
4337     New->setIsUsed();
4338 
4339   // Keep a chain of previous declarations.
4340   New->setPreviousDecl(Old);
4341   if (NewTemplate)
4342     NewTemplate->setPreviousDecl(OldTemplate);
4343 
4344   // Inherit access appropriately.
4345   New->setAccess(Old->getAccess());
4346   if (NewTemplate)
4347     NewTemplate->setAccess(New->getAccess());
4348 
4349   if (Old->isInline())
4350     New->setImplicitlyInline();
4351 }
4352 
4353 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4354   SourceManager &SrcMgr = getSourceManager();
4355   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4356   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4357   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4358   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4359   auto &HSI = PP.getHeaderSearchInfo();
4360   StringRef HdrFilename =
4361       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4362 
4363   auto noteFromModuleOrInclude = [&](Module *Mod,
4364                                      SourceLocation IncLoc) -> bool {
4365     // Redefinition errors with modules are common with non modular mapped
4366     // headers, example: a non-modular header H in module A that also gets
4367     // included directly in a TU. Pointing twice to the same header/definition
4368     // is confusing, try to get better diagnostics when modules is on.
4369     if (IncLoc.isValid()) {
4370       if (Mod) {
4371         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4372             << HdrFilename.str() << Mod->getFullModuleName();
4373         if (!Mod->DefinitionLoc.isInvalid())
4374           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4375               << Mod->getFullModuleName();
4376       } else {
4377         Diag(IncLoc, diag::note_redefinition_include_same_file)
4378             << HdrFilename.str();
4379       }
4380       return true;
4381     }
4382 
4383     return false;
4384   };
4385 
4386   // Is it the same file and same offset? Provide more information on why
4387   // this leads to a redefinition error.
4388   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4389     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4390     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4391     bool EmittedDiag =
4392         noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4393     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4394 
4395     // If the header has no guards, emit a note suggesting one.
4396     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4397       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4398 
4399     if (EmittedDiag)
4400       return;
4401   }
4402 
4403   // Redefinition coming from different files or couldn't do better above.
4404   if (Old->getLocation().isValid())
4405     Diag(Old->getLocation(), diag::note_previous_definition);
4406 }
4407 
4408 /// We've just determined that \p Old and \p New both appear to be definitions
4409 /// of the same variable. Either diagnose or fix the problem.
4410 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4411   if (!hasVisibleDefinition(Old) &&
4412       (New->getFormalLinkage() == InternalLinkage ||
4413        New->isInline() ||
4414        New->getDescribedVarTemplate() ||
4415        New->getNumTemplateParameterLists() ||
4416        New->getDeclContext()->isDependentContext())) {
4417     // The previous definition is hidden, and multiple definitions are
4418     // permitted (in separate TUs). Demote this to a declaration.
4419     New->demoteThisDefinitionToDeclaration();
4420 
4421     // Make the canonical definition visible.
4422     if (auto *OldTD = Old->getDescribedVarTemplate())
4423       makeMergedDefinitionVisible(OldTD);
4424     makeMergedDefinitionVisible(Old);
4425     return false;
4426   } else {
4427     Diag(New->getLocation(), diag::err_redefinition) << New;
4428     notePreviousDefinition(Old, New->getLocation());
4429     New->setInvalidDecl();
4430     return true;
4431   }
4432 }
4433 
4434 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4435 /// no declarator (e.g. "struct foo;") is parsed.
4436 Decl *
4437 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4438                                  RecordDecl *&AnonRecord) {
4439   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4440                                     AnonRecord);
4441 }
4442 
4443 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4444 // disambiguate entities defined in different scopes.
4445 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4446 // compatibility.
4447 // We will pick our mangling number depending on which version of MSVC is being
4448 // targeted.
4449 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4450   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4451              ? S->getMSCurManglingNumber()
4452              : S->getMSLastManglingNumber();
4453 }
4454 
4455 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4456   if (!Context.getLangOpts().CPlusPlus)
4457     return;
4458 
4459   if (isa<CXXRecordDecl>(Tag->getParent())) {
4460     // If this tag is the direct child of a class, number it if
4461     // it is anonymous.
4462     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4463       return;
4464     MangleNumberingContext &MCtx =
4465         Context.getManglingNumberContext(Tag->getParent());
4466     Context.setManglingNumber(
4467         Tag, MCtx.getManglingNumber(
4468                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4469     return;
4470   }
4471 
4472   // If this tag isn't a direct child of a class, number it if it is local.
4473   MangleNumberingContext *MCtx;
4474   Decl *ManglingContextDecl;
4475   std::tie(MCtx, ManglingContextDecl) =
4476       getCurrentMangleNumberContext(Tag->getDeclContext());
4477   if (MCtx) {
4478     Context.setManglingNumber(
4479         Tag, MCtx->getManglingNumber(
4480                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4481   }
4482 }
4483 
4484 namespace {
4485 struct NonCLikeKind {
4486   enum {
4487     None,
4488     BaseClass,
4489     DefaultMemberInit,
4490     Lambda,
4491     Friend,
4492     OtherMember,
4493     Invalid,
4494   } Kind = None;
4495   SourceRange Range;
4496 
4497   explicit operator bool() { return Kind != None; }
4498 };
4499 }
4500 
4501 /// Determine whether a class is C-like, according to the rules of C++
4502 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4503 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4504   if (RD->isInvalidDecl())
4505     return {NonCLikeKind::Invalid, {}};
4506 
4507   // C++ [dcl.typedef]p9: [P1766R1]
4508   //   An unnamed class with a typedef name for linkage purposes shall not
4509   //
4510   //    -- have any base classes
4511   if (RD->getNumBases())
4512     return {NonCLikeKind::BaseClass,
4513             SourceRange(RD->bases_begin()->getBeginLoc(),
4514                         RD->bases_end()[-1].getEndLoc())};
4515   bool Invalid = false;
4516   for (Decl *D : RD->decls()) {
4517     // Don't complain about things we already diagnosed.
4518     if (D->isInvalidDecl()) {
4519       Invalid = true;
4520       continue;
4521     }
4522 
4523     //  -- have any [...] default member initializers
4524     if (auto *FD = dyn_cast<FieldDecl>(D)) {
4525       if (FD->hasInClassInitializer()) {
4526         auto *Init = FD->getInClassInitializer();
4527         return {NonCLikeKind::DefaultMemberInit,
4528                 Init ? Init->getSourceRange() : D->getSourceRange()};
4529       }
4530       continue;
4531     }
4532 
4533     // FIXME: We don't allow friend declarations. This violates the wording of
4534     // P1766, but not the intent.
4535     if (isa<FriendDecl>(D))
4536       return {NonCLikeKind::Friend, D->getSourceRange()};
4537 
4538     //  -- declare any members other than non-static data members, member
4539     //     enumerations, or member classes,
4540     if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4541         isa<EnumDecl>(D))
4542       continue;
4543     auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4544     if (!MemberRD) {
4545       if (D->isImplicit())
4546         continue;
4547       return {NonCLikeKind::OtherMember, D->getSourceRange()};
4548     }
4549 
4550     //  -- contain a lambda-expression,
4551     if (MemberRD->isLambda())
4552       return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4553 
4554     //  and all member classes shall also satisfy these requirements
4555     //  (recursively).
4556     if (MemberRD->isThisDeclarationADefinition()) {
4557       if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4558         return Kind;
4559     }
4560   }
4561 
4562   return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4563 }
4564 
4565 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4566                                         TypedefNameDecl *NewTD) {
4567   if (TagFromDeclSpec->isInvalidDecl())
4568     return;
4569 
4570   // Do nothing if the tag already has a name for linkage purposes.
4571   if (TagFromDeclSpec->hasNameForLinkage())
4572     return;
4573 
4574   // A well-formed anonymous tag must always be a TUK_Definition.
4575   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4576 
4577   // The type must match the tag exactly;  no qualifiers allowed.
4578   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4579                            Context.getTagDeclType(TagFromDeclSpec))) {
4580     if (getLangOpts().CPlusPlus)
4581       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4582     return;
4583   }
4584 
4585   // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4586   //   An unnamed class with a typedef name for linkage purposes shall [be
4587   //   C-like].
4588   //
4589   // FIXME: Also diagnose if we've already computed the linkage. That ideally
4590   // shouldn't happen, but there are constructs that the language rule doesn't
4591   // disallow for which we can't reasonably avoid computing linkage early.
4592   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4593   NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4594                              : NonCLikeKind();
4595   bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4596   if (NonCLike || ChangesLinkage) {
4597     if (NonCLike.Kind == NonCLikeKind::Invalid)
4598       return;
4599 
4600     unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4601     if (ChangesLinkage) {
4602       // If the linkage changes, we can't accept this as an extension.
4603       if (NonCLike.Kind == NonCLikeKind::None)
4604         DiagID = diag::err_typedef_changes_linkage;
4605       else
4606         DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4607     }
4608 
4609     SourceLocation FixitLoc =
4610         getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4611     llvm::SmallString<40> TextToInsert;
4612     TextToInsert += ' ';
4613     TextToInsert += NewTD->getIdentifier()->getName();
4614 
4615     Diag(FixitLoc, DiagID)
4616       << isa<TypeAliasDecl>(NewTD)
4617       << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4618     if (NonCLike.Kind != NonCLikeKind::None) {
4619       Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4620         << NonCLike.Kind - 1 << NonCLike.Range;
4621     }
4622     Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4623       << NewTD << isa<TypeAliasDecl>(NewTD);
4624 
4625     if (ChangesLinkage)
4626       return;
4627   }
4628 
4629   // Otherwise, set this as the anon-decl typedef for the tag.
4630   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4631 }
4632 
4633 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4634   switch (T) {
4635   case DeclSpec::TST_class:
4636     return 0;
4637   case DeclSpec::TST_struct:
4638     return 1;
4639   case DeclSpec::TST_interface:
4640     return 2;
4641   case DeclSpec::TST_union:
4642     return 3;
4643   case DeclSpec::TST_enum:
4644     return 4;
4645   default:
4646     llvm_unreachable("unexpected type specifier");
4647   }
4648 }
4649 
4650 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4651 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4652 /// parameters to cope with template friend declarations.
4653 Decl *
4654 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4655                                  MultiTemplateParamsArg TemplateParams,
4656                                  bool IsExplicitInstantiation,
4657                                  RecordDecl *&AnonRecord) {
4658   Decl *TagD = nullptr;
4659   TagDecl *Tag = nullptr;
4660   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4661       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4662       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4663       DS.getTypeSpecType() == DeclSpec::TST_union ||
4664       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4665     TagD = DS.getRepAsDecl();
4666 
4667     if (!TagD) // We probably had an error
4668       return nullptr;
4669 
4670     // Note that the above type specs guarantee that the
4671     // type rep is a Decl, whereas in many of the others
4672     // it's a Type.
4673     if (isa<TagDecl>(TagD))
4674       Tag = cast<TagDecl>(TagD);
4675     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4676       Tag = CTD->getTemplatedDecl();
4677   }
4678 
4679   if (Tag) {
4680     handleTagNumbering(Tag, S);
4681     Tag->setFreeStanding();
4682     if (Tag->isInvalidDecl())
4683       return Tag;
4684   }
4685 
4686   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4687     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4688     // or incomplete types shall not be restrict-qualified."
4689     if (TypeQuals & DeclSpec::TQ_restrict)
4690       Diag(DS.getRestrictSpecLoc(),
4691            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4692            << DS.getSourceRange();
4693   }
4694 
4695   if (DS.isInlineSpecified())
4696     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4697         << getLangOpts().CPlusPlus17;
4698 
4699   if (DS.hasConstexprSpecifier()) {
4700     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4701     // and definitions of functions and variables.
4702     // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4703     // the declaration of a function or function template
4704     if (Tag)
4705       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4706           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4707           << static_cast<int>(DS.getConstexprSpecifier());
4708     else
4709       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4710           << static_cast<int>(DS.getConstexprSpecifier());
4711     // Don't emit warnings after this error.
4712     return TagD;
4713   }
4714 
4715   DiagnoseFunctionSpecifiers(DS);
4716 
4717   if (DS.isFriendSpecified()) {
4718     // If we're dealing with a decl but not a TagDecl, assume that
4719     // whatever routines created it handled the friendship aspect.
4720     if (TagD && !Tag)
4721       return nullptr;
4722     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4723   }
4724 
4725   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4726   bool IsExplicitSpecialization =
4727     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4728   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4729       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4730       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4731     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4732     // nested-name-specifier unless it is an explicit instantiation
4733     // or an explicit specialization.
4734     //
4735     // FIXME: We allow class template partial specializations here too, per the
4736     // obvious intent of DR1819.
4737     //
4738     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4739     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4740         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4741     return nullptr;
4742   }
4743 
4744   // Track whether this decl-specifier declares anything.
4745   bool DeclaresAnything = true;
4746 
4747   // Handle anonymous struct definitions.
4748   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4749     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4750         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4751       if (getLangOpts().CPlusPlus ||
4752           Record->getDeclContext()->isRecord()) {
4753         // If CurContext is a DeclContext that can contain statements,
4754         // RecursiveASTVisitor won't visit the decls that
4755         // BuildAnonymousStructOrUnion() will put into CurContext.
4756         // Also store them here so that they can be part of the
4757         // DeclStmt that gets created in this case.
4758         // FIXME: Also return the IndirectFieldDecls created by
4759         // BuildAnonymousStructOr union, for the same reason?
4760         if (CurContext->isFunctionOrMethod())
4761           AnonRecord = Record;
4762         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4763                                            Context.getPrintingPolicy());
4764       }
4765 
4766       DeclaresAnything = false;
4767     }
4768   }
4769 
4770   // C11 6.7.2.1p2:
4771   //   A struct-declaration that does not declare an anonymous structure or
4772   //   anonymous union shall contain a struct-declarator-list.
4773   //
4774   // This rule also existed in C89 and C99; the grammar for struct-declaration
4775   // did not permit a struct-declaration without a struct-declarator-list.
4776   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4777       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4778     // Check for Microsoft C extension: anonymous struct/union member.
4779     // Handle 2 kinds of anonymous struct/union:
4780     //   struct STRUCT;
4781     //   union UNION;
4782     // and
4783     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4784     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4785     if ((Tag && Tag->getDeclName()) ||
4786         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4787       RecordDecl *Record = nullptr;
4788       if (Tag)
4789         Record = dyn_cast<RecordDecl>(Tag);
4790       else if (const RecordType *RT =
4791                    DS.getRepAsType().get()->getAsStructureType())
4792         Record = RT->getDecl();
4793       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4794         Record = UT->getDecl();
4795 
4796       if (Record && getLangOpts().MicrosoftExt) {
4797         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4798             << Record->isUnion() << DS.getSourceRange();
4799         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4800       }
4801 
4802       DeclaresAnything = false;
4803     }
4804   }
4805 
4806   // Skip all the checks below if we have a type error.
4807   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4808       (TagD && TagD->isInvalidDecl()))
4809     return TagD;
4810 
4811   if (getLangOpts().CPlusPlus &&
4812       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4813     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4814       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4815           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4816         DeclaresAnything = false;
4817 
4818   if (!DS.isMissingDeclaratorOk()) {
4819     // Customize diagnostic for a typedef missing a name.
4820     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4821       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4822           << DS.getSourceRange();
4823     else
4824       DeclaresAnything = false;
4825   }
4826 
4827   if (DS.isModulePrivateSpecified() &&
4828       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4829     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4830       << Tag->getTagKind()
4831       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4832 
4833   ActOnDocumentableDecl(TagD);
4834 
4835   // C 6.7/2:
4836   //   A declaration [...] shall declare at least a declarator [...], a tag,
4837   //   or the members of an enumeration.
4838   // C++ [dcl.dcl]p3:
4839   //   [If there are no declarators], and except for the declaration of an
4840   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4841   //   names into the program, or shall redeclare a name introduced by a
4842   //   previous declaration.
4843   if (!DeclaresAnything) {
4844     // In C, we allow this as a (popular) extension / bug. Don't bother
4845     // producing further diagnostics for redundant qualifiers after this.
4846     Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4847                                ? diag::err_no_declarators
4848                                : diag::ext_no_declarators)
4849         << DS.getSourceRange();
4850     return TagD;
4851   }
4852 
4853   // C++ [dcl.stc]p1:
4854   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4855   //   init-declarator-list of the declaration shall not be empty.
4856   // C++ [dcl.fct.spec]p1:
4857   //   If a cv-qualifier appears in a decl-specifier-seq, the
4858   //   init-declarator-list of the declaration shall not be empty.
4859   //
4860   // Spurious qualifiers here appear to be valid in C.
4861   unsigned DiagID = diag::warn_standalone_specifier;
4862   if (getLangOpts().CPlusPlus)
4863     DiagID = diag::ext_standalone_specifier;
4864 
4865   // Note that a linkage-specification sets a storage class, but
4866   // 'extern "C" struct foo;' is actually valid and not theoretically
4867   // useless.
4868   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4869     if (SCS == DeclSpec::SCS_mutable)
4870       // Since mutable is not a viable storage class specifier in C, there is
4871       // no reason to treat it as an extension. Instead, diagnose as an error.
4872       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4873     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4874       Diag(DS.getStorageClassSpecLoc(), DiagID)
4875         << DeclSpec::getSpecifierName(SCS);
4876   }
4877 
4878   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4879     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4880       << DeclSpec::getSpecifierName(TSCS);
4881   if (DS.getTypeQualifiers()) {
4882     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4883       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4884     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4885       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4886     // Restrict is covered above.
4887     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4888       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4889     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4890       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4891   }
4892 
4893   // Warn about ignored type attributes, for example:
4894   // __attribute__((aligned)) struct A;
4895   // Attributes should be placed after tag to apply to type declaration.
4896   if (!DS.getAttributes().empty()) {
4897     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4898     if (TypeSpecType == DeclSpec::TST_class ||
4899         TypeSpecType == DeclSpec::TST_struct ||
4900         TypeSpecType == DeclSpec::TST_interface ||
4901         TypeSpecType == DeclSpec::TST_union ||
4902         TypeSpecType == DeclSpec::TST_enum) {
4903       for (const ParsedAttr &AL : DS.getAttributes())
4904         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4905             << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4906     }
4907   }
4908 
4909   return TagD;
4910 }
4911 
4912 /// We are trying to inject an anonymous member into the given scope;
4913 /// check if there's an existing declaration that can't be overloaded.
4914 ///
4915 /// \return true if this is a forbidden redeclaration
4916 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4917                                          Scope *S,
4918                                          DeclContext *Owner,
4919                                          DeclarationName Name,
4920                                          SourceLocation NameLoc,
4921                                          bool IsUnion) {
4922   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4923                  Sema::ForVisibleRedeclaration);
4924   if (!SemaRef.LookupName(R, S)) return false;
4925 
4926   // Pick a representative declaration.
4927   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4928   assert(PrevDecl && "Expected a non-null Decl");
4929 
4930   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4931     return false;
4932 
4933   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4934     << IsUnion << Name;
4935   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4936 
4937   return true;
4938 }
4939 
4940 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4941 /// anonymous struct or union AnonRecord into the owning context Owner
4942 /// and scope S. This routine will be invoked just after we realize
4943 /// that an unnamed union or struct is actually an anonymous union or
4944 /// struct, e.g.,
4945 ///
4946 /// @code
4947 /// union {
4948 ///   int i;
4949 ///   float f;
4950 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4951 ///    // f into the surrounding scope.x
4952 /// @endcode
4953 ///
4954 /// This routine is recursive, injecting the names of nested anonymous
4955 /// structs/unions into the owning context and scope as well.
4956 static bool
4957 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4958                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4959                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4960   bool Invalid = false;
4961 
4962   // Look every FieldDecl and IndirectFieldDecl with a name.
4963   for (auto *D : AnonRecord->decls()) {
4964     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4965         cast<NamedDecl>(D)->getDeclName()) {
4966       ValueDecl *VD = cast<ValueDecl>(D);
4967       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4968                                        VD->getLocation(),
4969                                        AnonRecord->isUnion())) {
4970         // C++ [class.union]p2:
4971         //   The names of the members of an anonymous union shall be
4972         //   distinct from the names of any other entity in the
4973         //   scope in which the anonymous union is declared.
4974         Invalid = true;
4975       } else {
4976         // C++ [class.union]p2:
4977         //   For the purpose of name lookup, after the anonymous union
4978         //   definition, the members of the anonymous union are
4979         //   considered to have been defined in the scope in which the
4980         //   anonymous union is declared.
4981         unsigned OldChainingSize = Chaining.size();
4982         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4983           Chaining.append(IF->chain_begin(), IF->chain_end());
4984         else
4985           Chaining.push_back(VD);
4986 
4987         assert(Chaining.size() >= 2);
4988         NamedDecl **NamedChain =
4989           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4990         for (unsigned i = 0; i < Chaining.size(); i++)
4991           NamedChain[i] = Chaining[i];
4992 
4993         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4994             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4995             VD->getType(), {NamedChain, Chaining.size()});
4996 
4997         for (const auto *Attr : VD->attrs())
4998           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4999 
5000         IndirectField->setAccess(AS);
5001         IndirectField->setImplicit();
5002         SemaRef.PushOnScopeChains(IndirectField, S);
5003 
5004         // That includes picking up the appropriate access specifier.
5005         if (AS != AS_none) IndirectField->setAccess(AS);
5006 
5007         Chaining.resize(OldChainingSize);
5008       }
5009     }
5010   }
5011 
5012   return Invalid;
5013 }
5014 
5015 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5016 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5017 /// illegal input values are mapped to SC_None.
5018 static StorageClass
5019 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
5020   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5021   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5022          "Parser allowed 'typedef' as storage class VarDecl.");
5023   switch (StorageClassSpec) {
5024   case DeclSpec::SCS_unspecified:    return SC_None;
5025   case DeclSpec::SCS_extern:
5026     if (DS.isExternInLinkageSpec())
5027       return SC_None;
5028     return SC_Extern;
5029   case DeclSpec::SCS_static:         return SC_Static;
5030   case DeclSpec::SCS_auto:           return SC_Auto;
5031   case DeclSpec::SCS_register:       return SC_Register;
5032   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5033     // Illegal SCSs map to None: error reporting is up to the caller.
5034   case DeclSpec::SCS_mutable:        // Fall through.
5035   case DeclSpec::SCS_typedef:        return SC_None;
5036   }
5037   llvm_unreachable("unknown storage class specifier");
5038 }
5039 
5040 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5041   assert(Record->hasInClassInitializer());
5042 
5043   for (const auto *I : Record->decls()) {
5044     const auto *FD = dyn_cast<FieldDecl>(I);
5045     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5046       FD = IFD->getAnonField();
5047     if (FD && FD->hasInClassInitializer())
5048       return FD->getLocation();
5049   }
5050 
5051   llvm_unreachable("couldn't find in-class initializer");
5052 }
5053 
5054 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5055                                       SourceLocation DefaultInitLoc) {
5056   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5057     return;
5058 
5059   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5060   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5061 }
5062 
5063 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5064                                       CXXRecordDecl *AnonUnion) {
5065   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5066     return;
5067 
5068   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5069 }
5070 
5071 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5072 /// anonymous structure or union. Anonymous unions are a C++ feature
5073 /// (C++ [class.union]) and a C11 feature; anonymous structures
5074 /// are a C11 feature and GNU C++ extension.
5075 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5076                                         AccessSpecifier AS,
5077                                         RecordDecl *Record,
5078                                         const PrintingPolicy &Policy) {
5079   DeclContext *Owner = Record->getDeclContext();
5080 
5081   // Diagnose whether this anonymous struct/union is an extension.
5082   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5083     Diag(Record->getLocation(), diag::ext_anonymous_union);
5084   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5085     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5086   else if (!Record->isUnion() && !getLangOpts().C11)
5087     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5088 
5089   // C and C++ require different kinds of checks for anonymous
5090   // structs/unions.
5091   bool Invalid = false;
5092   if (getLangOpts().CPlusPlus) {
5093     const char *PrevSpec = nullptr;
5094     if (Record->isUnion()) {
5095       // C++ [class.union]p6:
5096       // C++17 [class.union.anon]p2:
5097       //   Anonymous unions declared in a named namespace or in the
5098       //   global namespace shall be declared static.
5099       unsigned DiagID;
5100       DeclContext *OwnerScope = Owner->getRedeclContext();
5101       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5102           (OwnerScope->isTranslationUnit() ||
5103            (OwnerScope->isNamespace() &&
5104             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5105         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5106           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5107 
5108         // Recover by adding 'static'.
5109         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5110                                PrevSpec, DiagID, Policy);
5111       }
5112       // C++ [class.union]p6:
5113       //   A storage class is not allowed in a declaration of an
5114       //   anonymous union in a class scope.
5115       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5116                isa<RecordDecl>(Owner)) {
5117         Diag(DS.getStorageClassSpecLoc(),
5118              diag::err_anonymous_union_with_storage_spec)
5119           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5120 
5121         // Recover by removing the storage specifier.
5122         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5123                                SourceLocation(),
5124                                PrevSpec, DiagID, Context.getPrintingPolicy());
5125       }
5126     }
5127 
5128     // Ignore const/volatile/restrict qualifiers.
5129     if (DS.getTypeQualifiers()) {
5130       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5131         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5132           << Record->isUnion() << "const"
5133           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5134       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5135         Diag(DS.getVolatileSpecLoc(),
5136              diag::ext_anonymous_struct_union_qualified)
5137           << Record->isUnion() << "volatile"
5138           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5139       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5140         Diag(DS.getRestrictSpecLoc(),
5141              diag::ext_anonymous_struct_union_qualified)
5142           << Record->isUnion() << "restrict"
5143           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5144       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5145         Diag(DS.getAtomicSpecLoc(),
5146              diag::ext_anonymous_struct_union_qualified)
5147           << Record->isUnion() << "_Atomic"
5148           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5149       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5150         Diag(DS.getUnalignedSpecLoc(),
5151              diag::ext_anonymous_struct_union_qualified)
5152           << Record->isUnion() << "__unaligned"
5153           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5154 
5155       DS.ClearTypeQualifiers();
5156     }
5157 
5158     // C++ [class.union]p2:
5159     //   The member-specification of an anonymous union shall only
5160     //   define non-static data members. [Note: nested types and
5161     //   functions cannot be declared within an anonymous union. ]
5162     for (auto *Mem : Record->decls()) {
5163       // Ignore invalid declarations; we already diagnosed them.
5164       if (Mem->isInvalidDecl())
5165         continue;
5166 
5167       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5168         // C++ [class.union]p3:
5169         //   An anonymous union shall not have private or protected
5170         //   members (clause 11).
5171         assert(FD->getAccess() != AS_none);
5172         if (FD->getAccess() != AS_public) {
5173           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5174             << Record->isUnion() << (FD->getAccess() == AS_protected);
5175           Invalid = true;
5176         }
5177 
5178         // C++ [class.union]p1
5179         //   An object of a class with a non-trivial constructor, a non-trivial
5180         //   copy constructor, a non-trivial destructor, or a non-trivial copy
5181         //   assignment operator cannot be a member of a union, nor can an
5182         //   array of such objects.
5183         if (CheckNontrivialField(FD))
5184           Invalid = true;
5185       } else if (Mem->isImplicit()) {
5186         // Any implicit members are fine.
5187       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5188         // This is a type that showed up in an
5189         // elaborated-type-specifier inside the anonymous struct or
5190         // union, but which actually declares a type outside of the
5191         // anonymous struct or union. It's okay.
5192       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5193         if (!MemRecord->isAnonymousStructOrUnion() &&
5194             MemRecord->getDeclName()) {
5195           // Visual C++ allows type definition in anonymous struct or union.
5196           if (getLangOpts().MicrosoftExt)
5197             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5198               << Record->isUnion();
5199           else {
5200             // This is a nested type declaration.
5201             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5202               << Record->isUnion();
5203             Invalid = true;
5204           }
5205         } else {
5206           // This is an anonymous type definition within another anonymous type.
5207           // This is a popular extension, provided by Plan9, MSVC and GCC, but
5208           // not part of standard C++.
5209           Diag(MemRecord->getLocation(),
5210                diag::ext_anonymous_record_with_anonymous_type)
5211             << Record->isUnion();
5212         }
5213       } else if (isa<AccessSpecDecl>(Mem)) {
5214         // Any access specifier is fine.
5215       } else if (isa<StaticAssertDecl>(Mem)) {
5216         // In C++1z, static_assert declarations are also fine.
5217       } else {
5218         // We have something that isn't a non-static data
5219         // member. Complain about it.
5220         unsigned DK = diag::err_anonymous_record_bad_member;
5221         if (isa<TypeDecl>(Mem))
5222           DK = diag::err_anonymous_record_with_type;
5223         else if (isa<FunctionDecl>(Mem))
5224           DK = diag::err_anonymous_record_with_function;
5225         else if (isa<VarDecl>(Mem))
5226           DK = diag::err_anonymous_record_with_static;
5227 
5228         // Visual C++ allows type definition in anonymous struct or union.
5229         if (getLangOpts().MicrosoftExt &&
5230             DK == diag::err_anonymous_record_with_type)
5231           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5232             << Record->isUnion();
5233         else {
5234           Diag(Mem->getLocation(), DK) << Record->isUnion();
5235           Invalid = true;
5236         }
5237       }
5238     }
5239 
5240     // C++11 [class.union]p8 (DR1460):
5241     //   At most one variant member of a union may have a
5242     //   brace-or-equal-initializer.
5243     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5244         Owner->isRecord())
5245       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5246                                 cast<CXXRecordDecl>(Record));
5247   }
5248 
5249   if (!Record->isUnion() && !Owner->isRecord()) {
5250     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5251       << getLangOpts().CPlusPlus;
5252     Invalid = true;
5253   }
5254 
5255   // C++ [dcl.dcl]p3:
5256   //   [If there are no declarators], and except for the declaration of an
5257   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
5258   //   names into the program
5259   // C++ [class.mem]p2:
5260   //   each such member-declaration shall either declare at least one member
5261   //   name of the class or declare at least one unnamed bit-field
5262   //
5263   // For C this is an error even for a named struct, and is diagnosed elsewhere.
5264   if (getLangOpts().CPlusPlus && Record->field_empty())
5265     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5266 
5267   // Mock up a declarator.
5268   Declarator Dc(DS, DeclaratorContext::Member);
5269   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5270   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5271 
5272   // Create a declaration for this anonymous struct/union.
5273   NamedDecl *Anon = nullptr;
5274   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5275     Anon = FieldDecl::Create(
5276         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5277         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5278         /*BitWidth=*/nullptr, /*Mutable=*/false,
5279         /*InitStyle=*/ICIS_NoInit);
5280     Anon->setAccess(AS);
5281     ProcessDeclAttributes(S, Anon, Dc);
5282 
5283     if (getLangOpts().CPlusPlus)
5284       FieldCollector->Add(cast<FieldDecl>(Anon));
5285   } else {
5286     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5287     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5288     if (SCSpec == DeclSpec::SCS_mutable) {
5289       // mutable can only appear on non-static class members, so it's always
5290       // an error here
5291       Diag(Record->getLocation(), diag::err_mutable_nonmember);
5292       Invalid = true;
5293       SC = SC_None;
5294     }
5295 
5296     assert(DS.getAttributes().empty() && "No attribute expected");
5297     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5298                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
5299                            Context.getTypeDeclType(Record), TInfo, SC);
5300 
5301     // Default-initialize the implicit variable. This initialization will be
5302     // trivial in almost all cases, except if a union member has an in-class
5303     // initializer:
5304     //   union { int n = 0; };
5305     ActOnUninitializedDecl(Anon);
5306   }
5307   Anon->setImplicit();
5308 
5309   // Mark this as an anonymous struct/union type.
5310   Record->setAnonymousStructOrUnion(true);
5311 
5312   // Add the anonymous struct/union object to the current
5313   // context. We'll be referencing this object when we refer to one of
5314   // its members.
5315   Owner->addDecl(Anon);
5316 
5317   // Inject the members of the anonymous struct/union into the owning
5318   // context and into the identifier resolver chain for name lookup
5319   // purposes.
5320   SmallVector<NamedDecl*, 2> Chain;
5321   Chain.push_back(Anon);
5322 
5323   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5324     Invalid = true;
5325 
5326   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5327     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5328       MangleNumberingContext *MCtx;
5329       Decl *ManglingContextDecl;
5330       std::tie(MCtx, ManglingContextDecl) =
5331           getCurrentMangleNumberContext(NewVD->getDeclContext());
5332       if (MCtx) {
5333         Context.setManglingNumber(
5334             NewVD, MCtx->getManglingNumber(
5335                        NewVD, getMSManglingNumber(getLangOpts(), S)));
5336         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5337       }
5338     }
5339   }
5340 
5341   if (Invalid)
5342     Anon->setInvalidDecl();
5343 
5344   return Anon;
5345 }
5346 
5347 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5348 /// Microsoft C anonymous structure.
5349 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5350 /// Example:
5351 ///
5352 /// struct A { int a; };
5353 /// struct B { struct A; int b; };
5354 ///
5355 /// void foo() {
5356 ///   B var;
5357 ///   var.a = 3;
5358 /// }
5359 ///
5360 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5361                                            RecordDecl *Record) {
5362   assert(Record && "expected a record!");
5363 
5364   // Mock up a declarator.
5365   Declarator Dc(DS, DeclaratorContext::TypeName);
5366   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5367   assert(TInfo && "couldn't build declarator info for anonymous struct");
5368 
5369   auto *ParentDecl = cast<RecordDecl>(CurContext);
5370   QualType RecTy = Context.getTypeDeclType(Record);
5371 
5372   // Create a declaration for this anonymous struct.
5373   NamedDecl *Anon =
5374       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5375                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5376                         /*BitWidth=*/nullptr, /*Mutable=*/false,
5377                         /*InitStyle=*/ICIS_NoInit);
5378   Anon->setImplicit();
5379 
5380   // Add the anonymous struct object to the current context.
5381   CurContext->addDecl(Anon);
5382 
5383   // Inject the members of the anonymous struct into the current
5384   // context and into the identifier resolver chain for name lookup
5385   // purposes.
5386   SmallVector<NamedDecl*, 2> Chain;
5387   Chain.push_back(Anon);
5388 
5389   RecordDecl *RecordDef = Record->getDefinition();
5390   if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5391                                diag::err_field_incomplete_or_sizeless) ||
5392       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5393                                           AS_none, Chain)) {
5394     Anon->setInvalidDecl();
5395     ParentDecl->setInvalidDecl();
5396   }
5397 
5398   return Anon;
5399 }
5400 
5401 /// GetNameForDeclarator - Determine the full declaration name for the
5402 /// given Declarator.
5403 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5404   return GetNameFromUnqualifiedId(D.getName());
5405 }
5406 
5407 /// Retrieves the declaration name from a parsed unqualified-id.
5408 DeclarationNameInfo
5409 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5410   DeclarationNameInfo NameInfo;
5411   NameInfo.setLoc(Name.StartLocation);
5412 
5413   switch (Name.getKind()) {
5414 
5415   case UnqualifiedIdKind::IK_ImplicitSelfParam:
5416   case UnqualifiedIdKind::IK_Identifier:
5417     NameInfo.setName(Name.Identifier);
5418     return NameInfo;
5419 
5420   case UnqualifiedIdKind::IK_DeductionGuideName: {
5421     // C++ [temp.deduct.guide]p3:
5422     //   The simple-template-id shall name a class template specialization.
5423     //   The template-name shall be the same identifier as the template-name
5424     //   of the simple-template-id.
5425     // These together intend to imply that the template-name shall name a
5426     // class template.
5427     // FIXME: template<typename T> struct X {};
5428     //        template<typename T> using Y = X<T>;
5429     //        Y(int) -> Y<int>;
5430     //   satisfies these rules but does not name a class template.
5431     TemplateName TN = Name.TemplateName.get().get();
5432     auto *Template = TN.getAsTemplateDecl();
5433     if (!Template || !isa<ClassTemplateDecl>(Template)) {
5434       Diag(Name.StartLocation,
5435            diag::err_deduction_guide_name_not_class_template)
5436         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5437       if (Template)
5438         Diag(Template->getLocation(), diag::note_template_decl_here);
5439       return DeclarationNameInfo();
5440     }
5441 
5442     NameInfo.setName(
5443         Context.DeclarationNames.getCXXDeductionGuideName(Template));
5444     return NameInfo;
5445   }
5446 
5447   case UnqualifiedIdKind::IK_OperatorFunctionId:
5448     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5449                                            Name.OperatorFunctionId.Operator));
5450     NameInfo.setCXXOperatorNameRange(SourceRange(
5451         Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5452     return NameInfo;
5453 
5454   case UnqualifiedIdKind::IK_LiteralOperatorId:
5455     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5456                                                            Name.Identifier));
5457     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5458     return NameInfo;
5459 
5460   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5461     TypeSourceInfo *TInfo;
5462     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5463     if (Ty.isNull())
5464       return DeclarationNameInfo();
5465     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5466                                                Context.getCanonicalType(Ty)));
5467     NameInfo.setNamedTypeInfo(TInfo);
5468     return NameInfo;
5469   }
5470 
5471   case UnqualifiedIdKind::IK_ConstructorName: {
5472     TypeSourceInfo *TInfo;
5473     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5474     if (Ty.isNull())
5475       return DeclarationNameInfo();
5476     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5477                                               Context.getCanonicalType(Ty)));
5478     NameInfo.setNamedTypeInfo(TInfo);
5479     return NameInfo;
5480   }
5481 
5482   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5483     // In well-formed code, we can only have a constructor
5484     // template-id that refers to the current context, so go there
5485     // to find the actual type being constructed.
5486     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5487     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5488       return DeclarationNameInfo();
5489 
5490     // Determine the type of the class being constructed.
5491     QualType CurClassType = Context.getTypeDeclType(CurClass);
5492 
5493     // FIXME: Check two things: that the template-id names the same type as
5494     // CurClassType, and that the template-id does not occur when the name
5495     // was qualified.
5496 
5497     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5498                                     Context.getCanonicalType(CurClassType)));
5499     // FIXME: should we retrieve TypeSourceInfo?
5500     NameInfo.setNamedTypeInfo(nullptr);
5501     return NameInfo;
5502   }
5503 
5504   case UnqualifiedIdKind::IK_DestructorName: {
5505     TypeSourceInfo *TInfo;
5506     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5507     if (Ty.isNull())
5508       return DeclarationNameInfo();
5509     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5510                                               Context.getCanonicalType(Ty)));
5511     NameInfo.setNamedTypeInfo(TInfo);
5512     return NameInfo;
5513   }
5514 
5515   case UnqualifiedIdKind::IK_TemplateId: {
5516     TemplateName TName = Name.TemplateId->Template.get();
5517     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5518     return Context.getNameForTemplate(TName, TNameLoc);
5519   }
5520 
5521   } // switch (Name.getKind())
5522 
5523   llvm_unreachable("Unknown name kind");
5524 }
5525 
5526 static QualType getCoreType(QualType Ty) {
5527   do {
5528     if (Ty->isPointerType() || Ty->isReferenceType())
5529       Ty = Ty->getPointeeType();
5530     else if (Ty->isArrayType())
5531       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5532     else
5533       return Ty.withoutLocalFastQualifiers();
5534   } while (true);
5535 }
5536 
5537 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5538 /// and Definition have "nearly" matching parameters. This heuristic is
5539 /// used to improve diagnostics in the case where an out-of-line function
5540 /// definition doesn't match any declaration within the class or namespace.
5541 /// Also sets Params to the list of indices to the parameters that differ
5542 /// between the declaration and the definition. If hasSimilarParameters
5543 /// returns true and Params is empty, then all of the parameters match.
5544 static bool hasSimilarParameters(ASTContext &Context,
5545                                      FunctionDecl *Declaration,
5546                                      FunctionDecl *Definition,
5547                                      SmallVectorImpl<unsigned> &Params) {
5548   Params.clear();
5549   if (Declaration->param_size() != Definition->param_size())
5550     return false;
5551   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5552     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5553     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5554 
5555     // The parameter types are identical
5556     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5557       continue;
5558 
5559     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5560     QualType DefParamBaseTy = getCoreType(DefParamTy);
5561     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5562     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5563 
5564     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5565         (DeclTyName && DeclTyName == DefTyName))
5566       Params.push_back(Idx);
5567     else  // The two parameters aren't even close
5568       return false;
5569   }
5570 
5571   return true;
5572 }
5573 
5574 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5575 /// declarator needs to be rebuilt in the current instantiation.
5576 /// Any bits of declarator which appear before the name are valid for
5577 /// consideration here.  That's specifically the type in the decl spec
5578 /// and the base type in any member-pointer chunks.
5579 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5580                                                     DeclarationName Name) {
5581   // The types we specifically need to rebuild are:
5582   //   - typenames, typeofs, and decltypes
5583   //   - types which will become injected class names
5584   // Of course, we also need to rebuild any type referencing such a
5585   // type.  It's safest to just say "dependent", but we call out a
5586   // few cases here.
5587 
5588   DeclSpec &DS = D.getMutableDeclSpec();
5589   switch (DS.getTypeSpecType()) {
5590   case DeclSpec::TST_typename:
5591   case DeclSpec::TST_typeofType:
5592   case DeclSpec::TST_underlyingType:
5593   case DeclSpec::TST_atomic: {
5594     // Grab the type from the parser.
5595     TypeSourceInfo *TSI = nullptr;
5596     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5597     if (T.isNull() || !T->isInstantiationDependentType()) break;
5598 
5599     // Make sure there's a type source info.  This isn't really much
5600     // of a waste; most dependent types should have type source info
5601     // attached already.
5602     if (!TSI)
5603       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5604 
5605     // Rebuild the type in the current instantiation.
5606     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5607     if (!TSI) return true;
5608 
5609     // Store the new type back in the decl spec.
5610     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5611     DS.UpdateTypeRep(LocType);
5612     break;
5613   }
5614 
5615   case DeclSpec::TST_decltype:
5616   case DeclSpec::TST_typeofExpr: {
5617     Expr *E = DS.getRepAsExpr();
5618     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5619     if (Result.isInvalid()) return true;
5620     DS.UpdateExprRep(Result.get());
5621     break;
5622   }
5623 
5624   default:
5625     // Nothing to do for these decl specs.
5626     break;
5627   }
5628 
5629   // It doesn't matter what order we do this in.
5630   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5631     DeclaratorChunk &Chunk = D.getTypeObject(I);
5632 
5633     // The only type information in the declarator which can come
5634     // before the declaration name is the base type of a member
5635     // pointer.
5636     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5637       continue;
5638 
5639     // Rebuild the scope specifier in-place.
5640     CXXScopeSpec &SS = Chunk.Mem.Scope();
5641     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5642       return true;
5643   }
5644 
5645   return false;
5646 }
5647 
5648 void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5649   // Avoid warning twice on the same identifier, and don't warn on redeclaration
5650   // of system decl.
5651   if (D->getPreviousDecl() || D->isImplicit())
5652     return;
5653   ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5654   if (Status != ReservedIdentifierStatus::NotReserved &&
5655       !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5656     Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5657         << D << static_cast<int>(Status);
5658 }
5659 
5660 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5661   D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5662   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5663 
5664   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5665       Dcl && Dcl->getDeclContext()->isFileContext())
5666     Dcl->setTopLevelDeclInObjCContainer();
5667 
5668   return Dcl;
5669 }
5670 
5671 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5672 ///   If T is the name of a class, then each of the following shall have a
5673 ///   name different from T:
5674 ///     - every static data member of class T;
5675 ///     - every member function of class T
5676 ///     - every member of class T that is itself a type;
5677 /// \returns true if the declaration name violates these rules.
5678 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5679                                    DeclarationNameInfo NameInfo) {
5680   DeclarationName Name = NameInfo.getName();
5681 
5682   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5683   while (Record && Record->isAnonymousStructOrUnion())
5684     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5685   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5686     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5687     return true;
5688   }
5689 
5690   return false;
5691 }
5692 
5693 /// Diagnose a declaration whose declarator-id has the given
5694 /// nested-name-specifier.
5695 ///
5696 /// \param SS The nested-name-specifier of the declarator-id.
5697 ///
5698 /// \param DC The declaration context to which the nested-name-specifier
5699 /// resolves.
5700 ///
5701 /// \param Name The name of the entity being declared.
5702 ///
5703 /// \param Loc The location of the name of the entity being declared.
5704 ///
5705 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5706 /// we're declaring an explicit / partial specialization / instantiation.
5707 ///
5708 /// \returns true if we cannot safely recover from this error, false otherwise.
5709 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5710                                         DeclarationName Name,
5711                                         SourceLocation Loc, bool IsTemplateId) {
5712   DeclContext *Cur = CurContext;
5713   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5714     Cur = Cur->getParent();
5715 
5716   // If the user provided a superfluous scope specifier that refers back to the
5717   // class in which the entity is already declared, diagnose and ignore it.
5718   //
5719   // class X {
5720   //   void X::f();
5721   // };
5722   //
5723   // Note, it was once ill-formed to give redundant qualification in all
5724   // contexts, but that rule was removed by DR482.
5725   if (Cur->Equals(DC)) {
5726     if (Cur->isRecord()) {
5727       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5728                                       : diag::err_member_extra_qualification)
5729         << Name << FixItHint::CreateRemoval(SS.getRange());
5730       SS.clear();
5731     } else {
5732       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5733     }
5734     return false;
5735   }
5736 
5737   // Check whether the qualifying scope encloses the scope of the original
5738   // declaration. For a template-id, we perform the checks in
5739   // CheckTemplateSpecializationScope.
5740   if (!Cur->Encloses(DC) && !IsTemplateId) {
5741     if (Cur->isRecord())
5742       Diag(Loc, diag::err_member_qualification)
5743         << Name << SS.getRange();
5744     else if (isa<TranslationUnitDecl>(DC))
5745       Diag(Loc, diag::err_invalid_declarator_global_scope)
5746         << Name << SS.getRange();
5747     else if (isa<FunctionDecl>(Cur))
5748       Diag(Loc, diag::err_invalid_declarator_in_function)
5749         << Name << SS.getRange();
5750     else if (isa<BlockDecl>(Cur))
5751       Diag(Loc, diag::err_invalid_declarator_in_block)
5752         << Name << SS.getRange();
5753     else
5754       Diag(Loc, diag::err_invalid_declarator_scope)
5755       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5756 
5757     return true;
5758   }
5759 
5760   if (Cur->isRecord()) {
5761     // Cannot qualify members within a class.
5762     Diag(Loc, diag::err_member_qualification)
5763       << Name << SS.getRange();
5764     SS.clear();
5765 
5766     // C++ constructors and destructors with incorrect scopes can break
5767     // our AST invariants by having the wrong underlying types. If
5768     // that's the case, then drop this declaration entirely.
5769     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5770          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5771         !Context.hasSameType(Name.getCXXNameType(),
5772                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5773       return true;
5774 
5775     return false;
5776   }
5777 
5778   // C++11 [dcl.meaning]p1:
5779   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5780   //   not begin with a decltype-specifer"
5781   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5782   while (SpecLoc.getPrefix())
5783     SpecLoc = SpecLoc.getPrefix();
5784   if (isa_and_nonnull<DecltypeType>(
5785           SpecLoc.getNestedNameSpecifier()->getAsType()))
5786     Diag(Loc, diag::err_decltype_in_declarator)
5787       << SpecLoc.getTypeLoc().getSourceRange();
5788 
5789   return false;
5790 }
5791 
5792 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5793                                   MultiTemplateParamsArg TemplateParamLists) {
5794   // TODO: consider using NameInfo for diagnostic.
5795   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5796   DeclarationName Name = NameInfo.getName();
5797 
5798   // All of these full declarators require an identifier.  If it doesn't have
5799   // one, the ParsedFreeStandingDeclSpec action should be used.
5800   if (D.isDecompositionDeclarator()) {
5801     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5802   } else if (!Name) {
5803     if (!D.isInvalidType())  // Reject this if we think it is valid.
5804       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5805           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5806     return nullptr;
5807   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5808     return nullptr;
5809 
5810   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5811   // we find one that is.
5812   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5813          (S->getFlags() & Scope::TemplateParamScope) != 0)
5814     S = S->getParent();
5815 
5816   DeclContext *DC = CurContext;
5817   if (D.getCXXScopeSpec().isInvalid())
5818     D.setInvalidType();
5819   else if (D.getCXXScopeSpec().isSet()) {
5820     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5821                                         UPPC_DeclarationQualifier))
5822       return nullptr;
5823 
5824     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5825     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5826     if (!DC || isa<EnumDecl>(DC)) {
5827       // If we could not compute the declaration context, it's because the
5828       // declaration context is dependent but does not refer to a class,
5829       // class template, or class template partial specialization. Complain
5830       // and return early, to avoid the coming semantic disaster.
5831       Diag(D.getIdentifierLoc(),
5832            diag::err_template_qualified_declarator_no_match)
5833         << D.getCXXScopeSpec().getScopeRep()
5834         << D.getCXXScopeSpec().getRange();
5835       return nullptr;
5836     }
5837     bool IsDependentContext = DC->isDependentContext();
5838 
5839     if (!IsDependentContext &&
5840         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5841       return nullptr;
5842 
5843     // If a class is incomplete, do not parse entities inside it.
5844     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5845       Diag(D.getIdentifierLoc(),
5846            diag::err_member_def_undefined_record)
5847         << Name << DC << D.getCXXScopeSpec().getRange();
5848       return nullptr;
5849     }
5850     if (!D.getDeclSpec().isFriendSpecified()) {
5851       if (diagnoseQualifiedDeclaration(
5852               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5853               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5854         if (DC->isRecord())
5855           return nullptr;
5856 
5857         D.setInvalidType();
5858       }
5859     }
5860 
5861     // Check whether we need to rebuild the type of the given
5862     // declaration in the current instantiation.
5863     if (EnteringContext && IsDependentContext &&
5864         TemplateParamLists.size() != 0) {
5865       ContextRAII SavedContext(*this, DC);
5866       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5867         D.setInvalidType();
5868     }
5869   }
5870 
5871   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5872   QualType R = TInfo->getType();
5873 
5874   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5875                                       UPPC_DeclarationType))
5876     D.setInvalidType();
5877 
5878   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5879                         forRedeclarationInCurContext());
5880 
5881   // See if this is a redefinition of a variable in the same scope.
5882   if (!D.getCXXScopeSpec().isSet()) {
5883     bool IsLinkageLookup = false;
5884     bool CreateBuiltins = false;
5885 
5886     // If the declaration we're planning to build will be a function
5887     // or object with linkage, then look for another declaration with
5888     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5889     //
5890     // If the declaration we're planning to build will be declared with
5891     // external linkage in the translation unit, create any builtin with
5892     // the same name.
5893     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5894       /* Do nothing*/;
5895     else if (CurContext->isFunctionOrMethod() &&
5896              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5897               R->isFunctionType())) {
5898       IsLinkageLookup = true;
5899       CreateBuiltins =
5900           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5901     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5902                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5903       CreateBuiltins = true;
5904 
5905     if (IsLinkageLookup) {
5906       Previous.clear(LookupRedeclarationWithLinkage);
5907       Previous.setRedeclarationKind(ForExternalRedeclaration);
5908     }
5909 
5910     LookupName(Previous, S, CreateBuiltins);
5911   } else { // Something like "int foo::x;"
5912     LookupQualifiedName(Previous, DC);
5913 
5914     // C++ [dcl.meaning]p1:
5915     //   When the declarator-id is qualified, the declaration shall refer to a
5916     //  previously declared member of the class or namespace to which the
5917     //  qualifier refers (or, in the case of a namespace, of an element of the
5918     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5919     //  thereof; [...]
5920     //
5921     // Note that we already checked the context above, and that we do not have
5922     // enough information to make sure that Previous contains the declaration
5923     // we want to match. For example, given:
5924     //
5925     //   class X {
5926     //     void f();
5927     //     void f(float);
5928     //   };
5929     //
5930     //   void X::f(int) { } // ill-formed
5931     //
5932     // In this case, Previous will point to the overload set
5933     // containing the two f's declared in X, but neither of them
5934     // matches.
5935 
5936     // C++ [dcl.meaning]p1:
5937     //   [...] the member shall not merely have been introduced by a
5938     //   using-declaration in the scope of the class or namespace nominated by
5939     //   the nested-name-specifier of the declarator-id.
5940     RemoveUsingDecls(Previous);
5941   }
5942 
5943   if (Previous.isSingleResult() &&
5944       Previous.getFoundDecl()->isTemplateParameter()) {
5945     // Maybe we will complain about the shadowed template parameter.
5946     if (!D.isInvalidType())
5947       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5948                                       Previous.getFoundDecl());
5949 
5950     // Just pretend that we didn't see the previous declaration.
5951     Previous.clear();
5952   }
5953 
5954   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5955     // Forget that the previous declaration is the injected-class-name.
5956     Previous.clear();
5957 
5958   // In C++, the previous declaration we find might be a tag type
5959   // (class or enum). In this case, the new declaration will hide the
5960   // tag type. Note that this applies to functions, function templates, and
5961   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5962   if (Previous.isSingleTagDecl() &&
5963       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5964       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5965     Previous.clear();
5966 
5967   // Check that there are no default arguments other than in the parameters
5968   // of a function declaration (C++ only).
5969   if (getLangOpts().CPlusPlus)
5970     CheckExtraCXXDefaultArguments(D);
5971 
5972   NamedDecl *New;
5973 
5974   bool AddToScope = true;
5975   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5976     if (TemplateParamLists.size()) {
5977       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5978       return nullptr;
5979     }
5980 
5981     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5982   } else if (R->isFunctionType()) {
5983     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5984                                   TemplateParamLists,
5985                                   AddToScope);
5986   } else {
5987     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5988                                   AddToScope);
5989   }
5990 
5991   if (!New)
5992     return nullptr;
5993 
5994   // If this has an identifier and is not a function template specialization,
5995   // add it to the scope stack.
5996   if (New->getDeclName() && AddToScope)
5997     PushOnScopeChains(New, S);
5998 
5999   if (isInOpenMPDeclareTargetContext())
6000     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6001 
6002   return New;
6003 }
6004 
6005 /// Helper method to turn variable array types into constant array
6006 /// types in certain situations which would otherwise be errors (for
6007 /// GCC compatibility).
6008 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
6009                                                     ASTContext &Context,
6010                                                     bool &SizeIsNegative,
6011                                                     llvm::APSInt &Oversized) {
6012   // This method tries to turn a variable array into a constant
6013   // array even when the size isn't an ICE.  This is necessary
6014   // for compatibility with code that depends on gcc's buggy
6015   // constant expression folding, like struct {char x[(int)(char*)2];}
6016   SizeIsNegative = false;
6017   Oversized = 0;
6018 
6019   if (T->isDependentType())
6020     return QualType();
6021 
6022   QualifierCollector Qs;
6023   const Type *Ty = Qs.strip(T);
6024 
6025   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6026     QualType Pointee = PTy->getPointeeType();
6027     QualType FixedType =
6028         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6029                                             Oversized);
6030     if (FixedType.isNull()) return FixedType;
6031     FixedType = Context.getPointerType(FixedType);
6032     return Qs.apply(Context, FixedType);
6033   }
6034   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6035     QualType Inner = PTy->getInnerType();
6036     QualType FixedType =
6037         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6038                                             Oversized);
6039     if (FixedType.isNull()) return FixedType;
6040     FixedType = Context.getParenType(FixedType);
6041     return Qs.apply(Context, FixedType);
6042   }
6043 
6044   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6045   if (!VLATy)
6046     return QualType();
6047 
6048   QualType ElemTy = VLATy->getElementType();
6049   if (ElemTy->isVariablyModifiedType()) {
6050     ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6051                                                  SizeIsNegative, Oversized);
6052     if (ElemTy.isNull())
6053       return QualType();
6054   }
6055 
6056   Expr::EvalResult Result;
6057   if (!VLATy->getSizeExpr() ||
6058       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6059     return QualType();
6060 
6061   llvm::APSInt Res = Result.Val.getInt();
6062 
6063   // Check whether the array size is negative.
6064   if (Res.isSigned() && Res.isNegative()) {
6065     SizeIsNegative = true;
6066     return QualType();
6067   }
6068 
6069   // Check whether the array is too large to be addressed.
6070   unsigned ActiveSizeBits =
6071       (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6072        !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6073           ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6074           : Res.getActiveBits();
6075   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6076     Oversized = Res;
6077     return QualType();
6078   }
6079 
6080   QualType FoldedArrayType = Context.getConstantArrayType(
6081       ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6082   return Qs.apply(Context, FoldedArrayType);
6083 }
6084 
6085 static void
6086 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6087   SrcTL = SrcTL.getUnqualifiedLoc();
6088   DstTL = DstTL.getUnqualifiedLoc();
6089   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6090     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6091     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6092                                       DstPTL.getPointeeLoc());
6093     DstPTL.setStarLoc(SrcPTL.getStarLoc());
6094     return;
6095   }
6096   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6097     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6098     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6099                                       DstPTL.getInnerLoc());
6100     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6101     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6102     return;
6103   }
6104   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6105   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6106   TypeLoc SrcElemTL = SrcATL.getElementLoc();
6107   TypeLoc DstElemTL = DstATL.getElementLoc();
6108   if (VariableArrayTypeLoc SrcElemATL =
6109           SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6110     ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6111     FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6112   } else {
6113     DstElemTL.initializeFullCopy(SrcElemTL);
6114   }
6115   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6116   DstATL.setSizeExpr(SrcATL.getSizeExpr());
6117   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6118 }
6119 
6120 /// Helper method to turn variable array types into constant array
6121 /// types in certain situations which would otherwise be errors (for
6122 /// GCC compatibility).
6123 static TypeSourceInfo*
6124 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6125                                               ASTContext &Context,
6126                                               bool &SizeIsNegative,
6127                                               llvm::APSInt &Oversized) {
6128   QualType FixedTy
6129     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6130                                           SizeIsNegative, Oversized);
6131   if (FixedTy.isNull())
6132     return nullptr;
6133   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6134   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6135                                     FixedTInfo->getTypeLoc());
6136   return FixedTInfo;
6137 }
6138 
6139 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6140 /// true if we were successful.
6141 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6142                                            QualType &T, SourceLocation Loc,
6143                                            unsigned FailedFoldDiagID) {
6144   bool SizeIsNegative;
6145   llvm::APSInt Oversized;
6146   TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6147       TInfo, Context, SizeIsNegative, Oversized);
6148   if (FixedTInfo) {
6149     Diag(Loc, diag::ext_vla_folded_to_constant);
6150     TInfo = FixedTInfo;
6151     T = FixedTInfo->getType();
6152     return true;
6153   }
6154 
6155   if (SizeIsNegative)
6156     Diag(Loc, diag::err_typecheck_negative_array_size);
6157   else if (Oversized.getBoolValue())
6158     Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6159   else if (FailedFoldDiagID)
6160     Diag(Loc, FailedFoldDiagID);
6161   return false;
6162 }
6163 
6164 /// Register the given locally-scoped extern "C" declaration so
6165 /// that it can be found later for redeclarations. We include any extern "C"
6166 /// declaration that is not visible in the translation unit here, not just
6167 /// function-scope declarations.
6168 void
6169 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6170   if (!getLangOpts().CPlusPlus &&
6171       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6172     // Don't need to track declarations in the TU in C.
6173     return;
6174 
6175   // Note that we have a locally-scoped external with this name.
6176   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6177 }
6178 
6179 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6180   // FIXME: We can have multiple results via __attribute__((overloadable)).
6181   auto Result = Context.getExternCContextDecl()->lookup(Name);
6182   return Result.empty() ? nullptr : *Result.begin();
6183 }
6184 
6185 /// Diagnose function specifiers on a declaration of an identifier that
6186 /// does not identify a function.
6187 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6188   // FIXME: We should probably indicate the identifier in question to avoid
6189   // confusion for constructs like "virtual int a(), b;"
6190   if (DS.isVirtualSpecified())
6191     Diag(DS.getVirtualSpecLoc(),
6192          diag::err_virtual_non_function);
6193 
6194   if (DS.hasExplicitSpecifier())
6195     Diag(DS.getExplicitSpecLoc(),
6196          diag::err_explicit_non_function);
6197 
6198   if (DS.isNoreturnSpecified())
6199     Diag(DS.getNoreturnSpecLoc(),
6200          diag::err_noreturn_non_function);
6201 }
6202 
6203 NamedDecl*
6204 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6205                              TypeSourceInfo *TInfo, LookupResult &Previous) {
6206   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6207   if (D.getCXXScopeSpec().isSet()) {
6208     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6209       << D.getCXXScopeSpec().getRange();
6210     D.setInvalidType();
6211     // Pretend we didn't see the scope specifier.
6212     DC = CurContext;
6213     Previous.clear();
6214   }
6215 
6216   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6217 
6218   if (D.getDeclSpec().isInlineSpecified())
6219     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6220         << getLangOpts().CPlusPlus17;
6221   if (D.getDeclSpec().hasConstexprSpecifier())
6222     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6223         << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6224 
6225   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6226     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6227       Diag(D.getName().StartLocation,
6228            diag::err_deduction_guide_invalid_specifier)
6229           << "typedef";
6230     else
6231       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6232           << D.getName().getSourceRange();
6233     return nullptr;
6234   }
6235 
6236   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6237   if (!NewTD) return nullptr;
6238 
6239   // Handle attributes prior to checking for duplicates in MergeVarDecl
6240   ProcessDeclAttributes(S, NewTD, D);
6241 
6242   CheckTypedefForVariablyModifiedType(S, NewTD);
6243 
6244   bool Redeclaration = D.isRedeclaration();
6245   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6246   D.setRedeclaration(Redeclaration);
6247   return ND;
6248 }
6249 
6250 void
6251 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6252   // C99 6.7.7p2: If a typedef name specifies a variably modified type
6253   // then it shall have block scope.
6254   // Note that variably modified types must be fixed before merging the decl so
6255   // that redeclarations will match.
6256   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6257   QualType T = TInfo->getType();
6258   if (T->isVariablyModifiedType()) {
6259     setFunctionHasBranchProtectedScope();
6260 
6261     if (S->getFnParent() == nullptr) {
6262       bool SizeIsNegative;
6263       llvm::APSInt Oversized;
6264       TypeSourceInfo *FixedTInfo =
6265         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6266                                                       SizeIsNegative,
6267                                                       Oversized);
6268       if (FixedTInfo) {
6269         Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6270         NewTD->setTypeSourceInfo(FixedTInfo);
6271       } else {
6272         if (SizeIsNegative)
6273           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6274         else if (T->isVariableArrayType())
6275           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6276         else if (Oversized.getBoolValue())
6277           Diag(NewTD->getLocation(), diag::err_array_too_large)
6278             << toString(Oversized, 10);
6279         else
6280           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6281         NewTD->setInvalidDecl();
6282       }
6283     }
6284   }
6285 }
6286 
6287 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6288 /// declares a typedef-name, either using the 'typedef' type specifier or via
6289 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6290 NamedDecl*
6291 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6292                            LookupResult &Previous, bool &Redeclaration) {
6293 
6294   // Find the shadowed declaration before filtering for scope.
6295   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6296 
6297   // Merge the decl with the existing one if appropriate. If the decl is
6298   // in an outer scope, it isn't the same thing.
6299   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6300                        /*AllowInlineNamespace*/false);
6301   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6302   if (!Previous.empty()) {
6303     Redeclaration = true;
6304     MergeTypedefNameDecl(S, NewTD, Previous);
6305   } else {
6306     inferGslPointerAttribute(NewTD);
6307   }
6308 
6309   if (ShadowedDecl && !Redeclaration)
6310     CheckShadow(NewTD, ShadowedDecl, Previous);
6311 
6312   // If this is the C FILE type, notify the AST context.
6313   if (IdentifierInfo *II = NewTD->getIdentifier())
6314     if (!NewTD->isInvalidDecl() &&
6315         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6316       if (II->isStr("FILE"))
6317         Context.setFILEDecl(NewTD);
6318       else if (II->isStr("jmp_buf"))
6319         Context.setjmp_bufDecl(NewTD);
6320       else if (II->isStr("sigjmp_buf"))
6321         Context.setsigjmp_bufDecl(NewTD);
6322       else if (II->isStr("ucontext_t"))
6323         Context.setucontext_tDecl(NewTD);
6324     }
6325 
6326   return NewTD;
6327 }
6328 
6329 /// Determines whether the given declaration is an out-of-scope
6330 /// previous declaration.
6331 ///
6332 /// This routine should be invoked when name lookup has found a
6333 /// previous declaration (PrevDecl) that is not in the scope where a
6334 /// new declaration by the same name is being introduced. If the new
6335 /// declaration occurs in a local scope, previous declarations with
6336 /// linkage may still be considered previous declarations (C99
6337 /// 6.2.2p4-5, C++ [basic.link]p6).
6338 ///
6339 /// \param PrevDecl the previous declaration found by name
6340 /// lookup
6341 ///
6342 /// \param DC the context in which the new declaration is being
6343 /// declared.
6344 ///
6345 /// \returns true if PrevDecl is an out-of-scope previous declaration
6346 /// for a new delcaration with the same name.
6347 static bool
6348 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6349                                 ASTContext &Context) {
6350   if (!PrevDecl)
6351     return false;
6352 
6353   if (!PrevDecl->hasLinkage())
6354     return false;
6355 
6356   if (Context.getLangOpts().CPlusPlus) {
6357     // C++ [basic.link]p6:
6358     //   If there is a visible declaration of an entity with linkage
6359     //   having the same name and type, ignoring entities declared
6360     //   outside the innermost enclosing namespace scope, the block
6361     //   scope declaration declares that same entity and receives the
6362     //   linkage of the previous declaration.
6363     DeclContext *OuterContext = DC->getRedeclContext();
6364     if (!OuterContext->isFunctionOrMethod())
6365       // This rule only applies to block-scope declarations.
6366       return false;
6367 
6368     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6369     if (PrevOuterContext->isRecord())
6370       // We found a member function: ignore it.
6371       return false;
6372 
6373     // Find the innermost enclosing namespace for the new and
6374     // previous declarations.
6375     OuterContext = OuterContext->getEnclosingNamespaceContext();
6376     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6377 
6378     // The previous declaration is in a different namespace, so it
6379     // isn't the same function.
6380     if (!OuterContext->Equals(PrevOuterContext))
6381       return false;
6382   }
6383 
6384   return true;
6385 }
6386 
6387 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6388   CXXScopeSpec &SS = D.getCXXScopeSpec();
6389   if (!SS.isSet()) return;
6390   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6391 }
6392 
6393 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6394   QualType type = decl->getType();
6395   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6396   if (lifetime == Qualifiers::OCL_Autoreleasing) {
6397     // Various kinds of declaration aren't allowed to be __autoreleasing.
6398     unsigned kind = -1U;
6399     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6400       if (var->hasAttr<BlocksAttr>())
6401         kind = 0; // __block
6402       else if (!var->hasLocalStorage())
6403         kind = 1; // global
6404     } else if (isa<ObjCIvarDecl>(decl)) {
6405       kind = 3; // ivar
6406     } else if (isa<FieldDecl>(decl)) {
6407       kind = 2; // field
6408     }
6409 
6410     if (kind != -1U) {
6411       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6412         << kind;
6413     }
6414   } else if (lifetime == Qualifiers::OCL_None) {
6415     // Try to infer lifetime.
6416     if (!type->isObjCLifetimeType())
6417       return false;
6418 
6419     lifetime = type->getObjCARCImplicitLifetime();
6420     type = Context.getLifetimeQualifiedType(type, lifetime);
6421     decl->setType(type);
6422   }
6423 
6424   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6425     // Thread-local variables cannot have lifetime.
6426     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6427         var->getTLSKind()) {
6428       Diag(var->getLocation(), diag::err_arc_thread_ownership)
6429         << var->getType();
6430       return true;
6431     }
6432   }
6433 
6434   return false;
6435 }
6436 
6437 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6438   if (Decl->getType().hasAddressSpace())
6439     return;
6440   if (Decl->getType()->isDependentType())
6441     return;
6442   if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6443     QualType Type = Var->getType();
6444     if (Type->isSamplerT() || Type->isVoidType())
6445       return;
6446     LangAS ImplAS = LangAS::opencl_private;
6447     // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6448     // __opencl_c_program_scope_global_variables feature, the address space
6449     // for a variable at program scope or a static or extern variable inside
6450     // a function are inferred to be __global.
6451     if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6452         Var->hasGlobalStorage())
6453       ImplAS = LangAS::opencl_global;
6454     // If the original type from a decayed type is an array type and that array
6455     // type has no address space yet, deduce it now.
6456     if (auto DT = dyn_cast<DecayedType>(Type)) {
6457       auto OrigTy = DT->getOriginalType();
6458       if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6459         // Add the address space to the original array type and then propagate
6460         // that to the element type through `getAsArrayType`.
6461         OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6462         OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6463         // Re-generate the decayed type.
6464         Type = Context.getDecayedType(OrigTy);
6465       }
6466     }
6467     Type = Context.getAddrSpaceQualType(Type, ImplAS);
6468     // Apply any qualifiers (including address space) from the array type to
6469     // the element type. This implements C99 6.7.3p8: "If the specification of
6470     // an array type includes any type qualifiers, the element type is so
6471     // qualified, not the array type."
6472     if (Type->isArrayType())
6473       Type = QualType(Context.getAsArrayType(Type), 0);
6474     Decl->setType(Type);
6475   }
6476 }
6477 
6478 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6479   // Ensure that an auto decl is deduced otherwise the checks below might cache
6480   // the wrong linkage.
6481   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6482 
6483   // 'weak' only applies to declarations with external linkage.
6484   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6485     if (!ND.isExternallyVisible()) {
6486       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6487       ND.dropAttr<WeakAttr>();
6488     }
6489   }
6490   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6491     if (ND.isExternallyVisible()) {
6492       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6493       ND.dropAttr<WeakRefAttr>();
6494       ND.dropAttr<AliasAttr>();
6495     }
6496   }
6497 
6498   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6499     if (VD->hasInit()) {
6500       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6501         assert(VD->isThisDeclarationADefinition() &&
6502                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6503         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6504         VD->dropAttr<AliasAttr>();
6505       }
6506     }
6507   }
6508 
6509   // 'selectany' only applies to externally visible variable declarations.
6510   // It does not apply to functions.
6511   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6512     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6513       S.Diag(Attr->getLocation(),
6514              diag::err_attribute_selectany_non_extern_data);
6515       ND.dropAttr<SelectAnyAttr>();
6516     }
6517   }
6518 
6519   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6520     auto *VD = dyn_cast<VarDecl>(&ND);
6521     bool IsAnonymousNS = false;
6522     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6523     if (VD) {
6524       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6525       while (NS && !IsAnonymousNS) {
6526         IsAnonymousNS = NS->isAnonymousNamespace();
6527         NS = dyn_cast<NamespaceDecl>(NS->getParent());
6528       }
6529     }
6530     // dll attributes require external linkage. Static locals may have external
6531     // linkage but still cannot be explicitly imported or exported.
6532     // In Microsoft mode, a variable defined in anonymous namespace must have
6533     // external linkage in order to be exported.
6534     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6535     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6536         (!AnonNSInMicrosoftMode &&
6537          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6538       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6539         << &ND << Attr;
6540       ND.setInvalidDecl();
6541     }
6542   }
6543 
6544   // Check the attributes on the function type, if any.
6545   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6546     // Don't declare this variable in the second operand of the for-statement;
6547     // GCC miscompiles that by ending its lifetime before evaluating the
6548     // third operand. See gcc.gnu.org/PR86769.
6549     AttributedTypeLoc ATL;
6550     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6551          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6552          TL = ATL.getModifiedLoc()) {
6553       // The [[lifetimebound]] attribute can be applied to the implicit object
6554       // parameter of a non-static member function (other than a ctor or dtor)
6555       // by applying it to the function type.
6556       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6557         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6558         if (!MD || MD->isStatic()) {
6559           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6560               << !MD << A->getRange();
6561         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6562           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6563               << isa<CXXDestructorDecl>(MD) << A->getRange();
6564         }
6565       }
6566     }
6567   }
6568 }
6569 
6570 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6571                                            NamedDecl *NewDecl,
6572                                            bool IsSpecialization,
6573                                            bool IsDefinition) {
6574   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6575     return;
6576 
6577   bool IsTemplate = false;
6578   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6579     OldDecl = OldTD->getTemplatedDecl();
6580     IsTemplate = true;
6581     if (!IsSpecialization)
6582       IsDefinition = false;
6583   }
6584   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6585     NewDecl = NewTD->getTemplatedDecl();
6586     IsTemplate = true;
6587   }
6588 
6589   if (!OldDecl || !NewDecl)
6590     return;
6591 
6592   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6593   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6594   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6595   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6596 
6597   // dllimport and dllexport are inheritable attributes so we have to exclude
6598   // inherited attribute instances.
6599   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6600                     (NewExportAttr && !NewExportAttr->isInherited());
6601 
6602   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6603   // the only exception being explicit specializations.
6604   // Implicitly generated declarations are also excluded for now because there
6605   // is no other way to switch these to use dllimport or dllexport.
6606   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6607 
6608   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6609     // Allow with a warning for free functions and global variables.
6610     bool JustWarn = false;
6611     if (!OldDecl->isCXXClassMember()) {
6612       auto *VD = dyn_cast<VarDecl>(OldDecl);
6613       if (VD && !VD->getDescribedVarTemplate())
6614         JustWarn = true;
6615       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6616       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6617         JustWarn = true;
6618     }
6619 
6620     // We cannot change a declaration that's been used because IR has already
6621     // been emitted. Dllimported functions will still work though (modulo
6622     // address equality) as they can use the thunk.
6623     if (OldDecl->isUsed())
6624       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6625         JustWarn = false;
6626 
6627     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6628                                : diag::err_attribute_dll_redeclaration;
6629     S.Diag(NewDecl->getLocation(), DiagID)
6630         << NewDecl
6631         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6632     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6633     if (!JustWarn) {
6634       NewDecl->setInvalidDecl();
6635       return;
6636     }
6637   }
6638 
6639   // A redeclaration is not allowed to drop a dllimport attribute, the only
6640   // exceptions being inline function definitions (except for function
6641   // templates), local extern declarations, qualified friend declarations or
6642   // special MSVC extension: in the last case, the declaration is treated as if
6643   // it were marked dllexport.
6644   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6645   bool IsMicrosoftABI  = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6646   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6647     // Ignore static data because out-of-line definitions are diagnosed
6648     // separately.
6649     IsStaticDataMember = VD->isStaticDataMember();
6650     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6651                    VarDecl::DeclarationOnly;
6652   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6653     IsInline = FD->isInlined();
6654     IsQualifiedFriend = FD->getQualifier() &&
6655                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6656   }
6657 
6658   if (OldImportAttr && !HasNewAttr &&
6659       (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6660       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6661     if (IsMicrosoftABI && IsDefinition) {
6662       S.Diag(NewDecl->getLocation(),
6663              diag::warn_redeclaration_without_import_attribute)
6664           << NewDecl;
6665       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6666       NewDecl->dropAttr<DLLImportAttr>();
6667       NewDecl->addAttr(
6668           DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6669     } else {
6670       S.Diag(NewDecl->getLocation(),
6671              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6672           << NewDecl << OldImportAttr;
6673       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6674       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6675       OldDecl->dropAttr<DLLImportAttr>();
6676       NewDecl->dropAttr<DLLImportAttr>();
6677     }
6678   } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6679     // In MinGW, seeing a function declared inline drops the dllimport
6680     // attribute.
6681     OldDecl->dropAttr<DLLImportAttr>();
6682     NewDecl->dropAttr<DLLImportAttr>();
6683     S.Diag(NewDecl->getLocation(),
6684            diag::warn_dllimport_dropped_from_inline_function)
6685         << NewDecl << OldImportAttr;
6686   }
6687 
6688   // A specialization of a class template member function is processed here
6689   // since it's a redeclaration. If the parent class is dllexport, the
6690   // specialization inherits that attribute. This doesn't happen automatically
6691   // since the parent class isn't instantiated until later.
6692   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6693     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6694         !NewImportAttr && !NewExportAttr) {
6695       if (const DLLExportAttr *ParentExportAttr =
6696               MD->getParent()->getAttr<DLLExportAttr>()) {
6697         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6698         NewAttr->setInherited(true);
6699         NewDecl->addAttr(NewAttr);
6700       }
6701     }
6702   }
6703 }
6704 
6705 /// Given that we are within the definition of the given function,
6706 /// will that definition behave like C99's 'inline', where the
6707 /// definition is discarded except for optimization purposes?
6708 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6709   // Try to avoid calling GetGVALinkageForFunction.
6710 
6711   // All cases of this require the 'inline' keyword.
6712   if (!FD->isInlined()) return false;
6713 
6714   // This is only possible in C++ with the gnu_inline attribute.
6715   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6716     return false;
6717 
6718   // Okay, go ahead and call the relatively-more-expensive function.
6719   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6720 }
6721 
6722 /// Determine whether a variable is extern "C" prior to attaching
6723 /// an initializer. We can't just call isExternC() here, because that
6724 /// will also compute and cache whether the declaration is externally
6725 /// visible, which might change when we attach the initializer.
6726 ///
6727 /// This can only be used if the declaration is known to not be a
6728 /// redeclaration of an internal linkage declaration.
6729 ///
6730 /// For instance:
6731 ///
6732 ///   auto x = []{};
6733 ///
6734 /// Attaching the initializer here makes this declaration not externally
6735 /// visible, because its type has internal linkage.
6736 ///
6737 /// FIXME: This is a hack.
6738 template<typename T>
6739 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6740   if (S.getLangOpts().CPlusPlus) {
6741     // In C++, the overloadable attribute negates the effects of extern "C".
6742     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6743       return false;
6744 
6745     // So do CUDA's host/device attributes.
6746     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6747                                  D->template hasAttr<CUDAHostAttr>()))
6748       return false;
6749   }
6750   return D->isExternC();
6751 }
6752 
6753 static bool shouldConsiderLinkage(const VarDecl *VD) {
6754   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6755   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6756       isa<OMPDeclareMapperDecl>(DC))
6757     return VD->hasExternalStorage();
6758   if (DC->isFileContext())
6759     return true;
6760   if (DC->isRecord())
6761     return false;
6762   if (isa<RequiresExprBodyDecl>(DC))
6763     return false;
6764   llvm_unreachable("Unexpected context");
6765 }
6766 
6767 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6768   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6769   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6770       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6771     return true;
6772   if (DC->isRecord())
6773     return false;
6774   llvm_unreachable("Unexpected context");
6775 }
6776 
6777 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6778                           ParsedAttr::Kind Kind) {
6779   // Check decl attributes on the DeclSpec.
6780   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6781     return true;
6782 
6783   // Walk the declarator structure, checking decl attributes that were in a type
6784   // position to the decl itself.
6785   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6786     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6787       return true;
6788   }
6789 
6790   // Finally, check attributes on the decl itself.
6791   return PD.getAttributes().hasAttribute(Kind);
6792 }
6793 
6794 /// Adjust the \c DeclContext for a function or variable that might be a
6795 /// function-local external declaration.
6796 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6797   if (!DC->isFunctionOrMethod())
6798     return false;
6799 
6800   // If this is a local extern function or variable declared within a function
6801   // template, don't add it into the enclosing namespace scope until it is
6802   // instantiated; it might have a dependent type right now.
6803   if (DC->isDependentContext())
6804     return true;
6805 
6806   // C++11 [basic.link]p7:
6807   //   When a block scope declaration of an entity with linkage is not found to
6808   //   refer to some other declaration, then that entity is a member of the
6809   //   innermost enclosing namespace.
6810   //
6811   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6812   // semantically-enclosing namespace, not a lexically-enclosing one.
6813   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6814     DC = DC->getParent();
6815   return true;
6816 }
6817 
6818 /// Returns true if given declaration has external C language linkage.
6819 static bool isDeclExternC(const Decl *D) {
6820   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6821     return FD->isExternC();
6822   if (const auto *VD = dyn_cast<VarDecl>(D))
6823     return VD->isExternC();
6824 
6825   llvm_unreachable("Unknown type of decl!");
6826 }
6827 
6828 /// Returns true if there hasn't been any invalid type diagnosed.
6829 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6830   DeclContext *DC = NewVD->getDeclContext();
6831   QualType R = NewVD->getType();
6832 
6833   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6834   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6835   // argument.
6836   if (R->isImageType() || R->isPipeType()) {
6837     Se.Diag(NewVD->getLocation(),
6838             diag::err_opencl_type_can_only_be_used_as_function_parameter)
6839         << R;
6840     NewVD->setInvalidDecl();
6841     return false;
6842   }
6843 
6844   // OpenCL v1.2 s6.9.r:
6845   // The event type cannot be used to declare a program scope variable.
6846   // OpenCL v2.0 s6.9.q:
6847   // The clk_event_t and reserve_id_t types cannot be declared in program
6848   // scope.
6849   if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6850     if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6851       Se.Diag(NewVD->getLocation(),
6852               diag::err_invalid_type_for_program_scope_var)
6853           << R;
6854       NewVD->setInvalidDecl();
6855       return false;
6856     }
6857   }
6858 
6859   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6860   if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6861                                                Se.getLangOpts())) {
6862     QualType NR = R.getCanonicalType();
6863     while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6864            NR->isReferenceType()) {
6865       if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6866           NR->isFunctionReferenceType()) {
6867         Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6868             << NR->isReferenceType();
6869         NewVD->setInvalidDecl();
6870         return false;
6871       }
6872       NR = NR->getPointeeType();
6873     }
6874   }
6875 
6876   if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6877                                                Se.getLangOpts())) {
6878     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6879     // half array type (unless the cl_khr_fp16 extension is enabled).
6880     if (Se.Context.getBaseElementType(R)->isHalfType()) {
6881       Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6882       NewVD->setInvalidDecl();
6883       return false;
6884     }
6885   }
6886 
6887   // OpenCL v1.2 s6.9.r:
6888   // The event type cannot be used with the __local, __constant and __global
6889   // address space qualifiers.
6890   if (R->isEventT()) {
6891     if (R.getAddressSpace() != LangAS::opencl_private) {
6892       Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6893       NewVD->setInvalidDecl();
6894       return false;
6895     }
6896   }
6897 
6898   if (R->isSamplerT()) {
6899     // OpenCL v1.2 s6.9.b p4:
6900     // The sampler type cannot be used with the __local and __global address
6901     // space qualifiers.
6902     if (R.getAddressSpace() == LangAS::opencl_local ||
6903         R.getAddressSpace() == LangAS::opencl_global) {
6904       Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6905       NewVD->setInvalidDecl();
6906     }
6907 
6908     // OpenCL v1.2 s6.12.14.1:
6909     // A global sampler must be declared with either the constant address
6910     // space qualifier or with the const qualifier.
6911     if (DC->isTranslationUnit() &&
6912         !(R.getAddressSpace() == LangAS::opencl_constant ||
6913           R.isConstQualified())) {
6914       Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6915       NewVD->setInvalidDecl();
6916     }
6917     if (NewVD->isInvalidDecl())
6918       return false;
6919   }
6920 
6921   return true;
6922 }
6923 
6924 template <typename AttrTy>
6925 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6926   const TypedefNameDecl *TND = TT->getDecl();
6927   if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6928     AttrTy *Clone = Attribute->clone(S.Context);
6929     Clone->setInherited(true);
6930     D->addAttr(Clone);
6931   }
6932 }
6933 
6934 NamedDecl *Sema::ActOnVariableDeclarator(
6935     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6936     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6937     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6938   QualType R = TInfo->getType();
6939   DeclarationName Name = GetNameForDeclarator(D).getName();
6940 
6941   IdentifierInfo *II = Name.getAsIdentifierInfo();
6942 
6943   if (D.isDecompositionDeclarator()) {
6944     // Take the name of the first declarator as our name for diagnostic
6945     // purposes.
6946     auto &Decomp = D.getDecompositionDeclarator();
6947     if (!Decomp.bindings().empty()) {
6948       II = Decomp.bindings()[0].Name;
6949       Name = II;
6950     }
6951   } else if (!II) {
6952     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6953     return nullptr;
6954   }
6955 
6956 
6957   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6958   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6959 
6960   // dllimport globals without explicit storage class are treated as extern. We
6961   // have to change the storage class this early to get the right DeclContext.
6962   if (SC == SC_None && !DC->isRecord() &&
6963       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6964       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6965     SC = SC_Extern;
6966 
6967   DeclContext *OriginalDC = DC;
6968   bool IsLocalExternDecl = SC == SC_Extern &&
6969                            adjustContextForLocalExternDecl(DC);
6970 
6971   if (SCSpec == DeclSpec::SCS_mutable) {
6972     // mutable can only appear on non-static class members, so it's always
6973     // an error here
6974     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6975     D.setInvalidType();
6976     SC = SC_None;
6977   }
6978 
6979   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6980       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6981                               D.getDeclSpec().getStorageClassSpecLoc())) {
6982     // In C++11, the 'register' storage class specifier is deprecated.
6983     // Suppress the warning in system macros, it's used in macros in some
6984     // popular C system headers, such as in glibc's htonl() macro.
6985     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6986          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6987                                    : diag::warn_deprecated_register)
6988       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6989   }
6990 
6991   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6992 
6993   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6994     // C99 6.9p2: The storage-class specifiers auto and register shall not
6995     // appear in the declaration specifiers in an external declaration.
6996     // Global Register+Asm is a GNU extension we support.
6997     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6998       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6999       D.setInvalidType();
7000     }
7001   }
7002 
7003   // If this variable has a VLA type and an initializer, try to
7004   // fold to a constant-sized type. This is otherwise invalid.
7005   if (D.hasInitializer() && R->isVariableArrayType())
7006     tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7007                                     /*DiagID=*/0);
7008 
7009   bool IsMemberSpecialization = false;
7010   bool IsVariableTemplateSpecialization = false;
7011   bool IsPartialSpecialization = false;
7012   bool IsVariableTemplate = false;
7013   VarDecl *NewVD = nullptr;
7014   VarTemplateDecl *NewTemplate = nullptr;
7015   TemplateParameterList *TemplateParams = nullptr;
7016   if (!getLangOpts().CPlusPlus) {
7017     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7018                             II, R, TInfo, SC);
7019 
7020     if (R->getContainedDeducedType())
7021       ParsingInitForAutoVars.insert(NewVD);
7022 
7023     if (D.isInvalidType())
7024       NewVD->setInvalidDecl();
7025 
7026     if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7027         NewVD->hasLocalStorage())
7028       checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7029                             NTCUC_AutoVar, NTCUK_Destruct);
7030   } else {
7031     bool Invalid = false;
7032 
7033     if (DC->isRecord() && !CurContext->isRecord()) {
7034       // This is an out-of-line definition of a static data member.
7035       switch (SC) {
7036       case SC_None:
7037         break;
7038       case SC_Static:
7039         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7040              diag::err_static_out_of_line)
7041           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7042         break;
7043       case SC_Auto:
7044       case SC_Register:
7045       case SC_Extern:
7046         // [dcl.stc] p2: The auto or register specifiers shall be applied only
7047         // to names of variables declared in a block or to function parameters.
7048         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7049         // of class members
7050 
7051         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7052              diag::err_storage_class_for_static_member)
7053           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7054         break;
7055       case SC_PrivateExtern:
7056         llvm_unreachable("C storage class in c++!");
7057       }
7058     }
7059 
7060     if (SC == SC_Static && CurContext->isRecord()) {
7061       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7062         // Walk up the enclosing DeclContexts to check for any that are
7063         // incompatible with static data members.
7064         const DeclContext *FunctionOrMethod = nullptr;
7065         const CXXRecordDecl *AnonStruct = nullptr;
7066         for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7067           if (Ctxt->isFunctionOrMethod()) {
7068             FunctionOrMethod = Ctxt;
7069             break;
7070           }
7071           const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7072           if (ParentDecl && !ParentDecl->getDeclName()) {
7073             AnonStruct = ParentDecl;
7074             break;
7075           }
7076         }
7077         if (FunctionOrMethod) {
7078           // C++ [class.static.data]p5: A local class shall not have static data
7079           // members.
7080           Diag(D.getIdentifierLoc(),
7081                diag::err_static_data_member_not_allowed_in_local_class)
7082             << Name << RD->getDeclName() << RD->getTagKind();
7083         } else if (AnonStruct) {
7084           // C++ [class.static.data]p4: Unnamed classes and classes contained
7085           // directly or indirectly within unnamed classes shall not contain
7086           // static data members.
7087           Diag(D.getIdentifierLoc(),
7088                diag::err_static_data_member_not_allowed_in_anon_struct)
7089             << Name << AnonStruct->getTagKind();
7090           Invalid = true;
7091         } else if (RD->isUnion()) {
7092           // C++98 [class.union]p1: If a union contains a static data member,
7093           // the program is ill-formed. C++11 drops this restriction.
7094           Diag(D.getIdentifierLoc(),
7095                getLangOpts().CPlusPlus11
7096                  ? diag::warn_cxx98_compat_static_data_member_in_union
7097                  : diag::ext_static_data_member_in_union) << Name;
7098         }
7099       }
7100     }
7101 
7102     // Match up the template parameter lists with the scope specifier, then
7103     // determine whether we have a template or a template specialization.
7104     bool InvalidScope = false;
7105     TemplateParams = MatchTemplateParametersToScopeSpecifier(
7106         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7107         D.getCXXScopeSpec(),
7108         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7109             ? D.getName().TemplateId
7110             : nullptr,
7111         TemplateParamLists,
7112         /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7113     Invalid |= InvalidScope;
7114 
7115     if (TemplateParams) {
7116       if (!TemplateParams->size() &&
7117           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7118         // There is an extraneous 'template<>' for this variable. Complain
7119         // about it, but allow the declaration of the variable.
7120         Diag(TemplateParams->getTemplateLoc(),
7121              diag::err_template_variable_noparams)
7122           << II
7123           << SourceRange(TemplateParams->getTemplateLoc(),
7124                          TemplateParams->getRAngleLoc());
7125         TemplateParams = nullptr;
7126       } else {
7127         // Check that we can declare a template here.
7128         if (CheckTemplateDeclScope(S, TemplateParams))
7129           return nullptr;
7130 
7131         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7132           // This is an explicit specialization or a partial specialization.
7133           IsVariableTemplateSpecialization = true;
7134           IsPartialSpecialization = TemplateParams->size() > 0;
7135         } else { // if (TemplateParams->size() > 0)
7136           // This is a template declaration.
7137           IsVariableTemplate = true;
7138 
7139           // Only C++1y supports variable templates (N3651).
7140           Diag(D.getIdentifierLoc(),
7141                getLangOpts().CPlusPlus14
7142                    ? diag::warn_cxx11_compat_variable_template
7143                    : diag::ext_variable_template);
7144         }
7145       }
7146     } else {
7147       // Check that we can declare a member specialization here.
7148       if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7149           CheckTemplateDeclScope(S, TemplateParamLists.back()))
7150         return nullptr;
7151       assert((Invalid ||
7152               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7153              "should have a 'template<>' for this decl");
7154     }
7155 
7156     if (IsVariableTemplateSpecialization) {
7157       SourceLocation TemplateKWLoc =
7158           TemplateParamLists.size() > 0
7159               ? TemplateParamLists[0]->getTemplateLoc()
7160               : SourceLocation();
7161       DeclResult Res = ActOnVarTemplateSpecialization(
7162           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7163           IsPartialSpecialization);
7164       if (Res.isInvalid())
7165         return nullptr;
7166       NewVD = cast<VarDecl>(Res.get());
7167       AddToScope = false;
7168     } else if (D.isDecompositionDeclarator()) {
7169       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7170                                         D.getIdentifierLoc(), R, TInfo, SC,
7171                                         Bindings);
7172     } else
7173       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7174                               D.getIdentifierLoc(), II, R, TInfo, SC);
7175 
7176     // If this is supposed to be a variable template, create it as such.
7177     if (IsVariableTemplate) {
7178       NewTemplate =
7179           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7180                                   TemplateParams, NewVD);
7181       NewVD->setDescribedVarTemplate(NewTemplate);
7182     }
7183 
7184     // If this decl has an auto type in need of deduction, make a note of the
7185     // Decl so we can diagnose uses of it in its own initializer.
7186     if (R->getContainedDeducedType())
7187       ParsingInitForAutoVars.insert(NewVD);
7188 
7189     if (D.isInvalidType() || Invalid) {
7190       NewVD->setInvalidDecl();
7191       if (NewTemplate)
7192         NewTemplate->setInvalidDecl();
7193     }
7194 
7195     SetNestedNameSpecifier(*this, NewVD, D);
7196 
7197     // If we have any template parameter lists that don't directly belong to
7198     // the variable (matching the scope specifier), store them.
7199     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7200     if (TemplateParamLists.size() > VDTemplateParamLists)
7201       NewVD->setTemplateParameterListsInfo(
7202           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7203   }
7204 
7205   if (D.getDeclSpec().isInlineSpecified()) {
7206     if (!getLangOpts().CPlusPlus) {
7207       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7208           << 0;
7209     } else if (CurContext->isFunctionOrMethod()) {
7210       // 'inline' is not allowed on block scope variable declaration.
7211       Diag(D.getDeclSpec().getInlineSpecLoc(),
7212            diag::err_inline_declaration_block_scope) << Name
7213         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7214     } else {
7215       Diag(D.getDeclSpec().getInlineSpecLoc(),
7216            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7217                                      : diag::ext_inline_variable);
7218       NewVD->setInlineSpecified();
7219     }
7220   }
7221 
7222   // Set the lexical context. If the declarator has a C++ scope specifier, the
7223   // lexical context will be different from the semantic context.
7224   NewVD->setLexicalDeclContext(CurContext);
7225   if (NewTemplate)
7226     NewTemplate->setLexicalDeclContext(CurContext);
7227 
7228   if (IsLocalExternDecl) {
7229     if (D.isDecompositionDeclarator())
7230       for (auto *B : Bindings)
7231         B->setLocalExternDecl();
7232     else
7233       NewVD->setLocalExternDecl();
7234   }
7235 
7236   bool EmitTLSUnsupportedError = false;
7237   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7238     // C++11 [dcl.stc]p4:
7239     //   When thread_local is applied to a variable of block scope the
7240     //   storage-class-specifier static is implied if it does not appear
7241     //   explicitly.
7242     // Core issue: 'static' is not implied if the variable is declared
7243     //   'extern'.
7244     if (NewVD->hasLocalStorage() &&
7245         (SCSpec != DeclSpec::SCS_unspecified ||
7246          TSCS != DeclSpec::TSCS_thread_local ||
7247          !DC->isFunctionOrMethod()))
7248       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7249            diag::err_thread_non_global)
7250         << DeclSpec::getSpecifierName(TSCS);
7251     else if (!Context.getTargetInfo().isTLSSupported()) {
7252       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7253           getLangOpts().SYCLIsDevice) {
7254         // Postpone error emission until we've collected attributes required to
7255         // figure out whether it's a host or device variable and whether the
7256         // error should be ignored.
7257         EmitTLSUnsupportedError = true;
7258         // We still need to mark the variable as TLS so it shows up in AST with
7259         // proper storage class for other tools to use even if we're not going
7260         // to emit any code for it.
7261         NewVD->setTSCSpec(TSCS);
7262       } else
7263         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7264              diag::err_thread_unsupported);
7265     } else
7266       NewVD->setTSCSpec(TSCS);
7267   }
7268 
7269   switch (D.getDeclSpec().getConstexprSpecifier()) {
7270   case ConstexprSpecKind::Unspecified:
7271     break;
7272 
7273   case ConstexprSpecKind::Consteval:
7274     Diag(D.getDeclSpec().getConstexprSpecLoc(),
7275          diag::err_constexpr_wrong_decl_kind)
7276         << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7277     LLVM_FALLTHROUGH;
7278 
7279   case ConstexprSpecKind::Constexpr:
7280     NewVD->setConstexpr(true);
7281     // C++1z [dcl.spec.constexpr]p1:
7282     //   A static data member declared with the constexpr specifier is
7283     //   implicitly an inline variable.
7284     if (NewVD->isStaticDataMember() &&
7285         (getLangOpts().CPlusPlus17 ||
7286          Context.getTargetInfo().getCXXABI().isMicrosoft()))
7287       NewVD->setImplicitlyInline();
7288     break;
7289 
7290   case ConstexprSpecKind::Constinit:
7291     if (!NewVD->hasGlobalStorage())
7292       Diag(D.getDeclSpec().getConstexprSpecLoc(),
7293            diag::err_constinit_local_variable);
7294     else
7295       NewVD->addAttr(ConstInitAttr::Create(
7296           Context, D.getDeclSpec().getConstexprSpecLoc(),
7297           AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7298     break;
7299   }
7300 
7301   // C99 6.7.4p3
7302   //   An inline definition of a function with external linkage shall
7303   //   not contain a definition of a modifiable object with static or
7304   //   thread storage duration...
7305   // We only apply this when the function is required to be defined
7306   // elsewhere, i.e. when the function is not 'extern inline'.  Note
7307   // that a local variable with thread storage duration still has to
7308   // be marked 'static'.  Also note that it's possible to get these
7309   // semantics in C++ using __attribute__((gnu_inline)).
7310   if (SC == SC_Static && S->getFnParent() != nullptr &&
7311       !NewVD->getType().isConstQualified()) {
7312     FunctionDecl *CurFD = getCurFunctionDecl();
7313     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7314       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7315            diag::warn_static_local_in_extern_inline);
7316       MaybeSuggestAddingStaticToDecl(CurFD);
7317     }
7318   }
7319 
7320   if (D.getDeclSpec().isModulePrivateSpecified()) {
7321     if (IsVariableTemplateSpecialization)
7322       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7323           << (IsPartialSpecialization ? 1 : 0)
7324           << FixItHint::CreateRemoval(
7325                  D.getDeclSpec().getModulePrivateSpecLoc());
7326     else if (IsMemberSpecialization)
7327       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7328         << 2
7329         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7330     else if (NewVD->hasLocalStorage())
7331       Diag(NewVD->getLocation(), diag::err_module_private_local)
7332           << 0 << NewVD
7333           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7334           << FixItHint::CreateRemoval(
7335                  D.getDeclSpec().getModulePrivateSpecLoc());
7336     else {
7337       NewVD->setModulePrivate();
7338       if (NewTemplate)
7339         NewTemplate->setModulePrivate();
7340       for (auto *B : Bindings)
7341         B->setModulePrivate();
7342     }
7343   }
7344 
7345   if (getLangOpts().OpenCL) {
7346     deduceOpenCLAddressSpace(NewVD);
7347 
7348     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7349     if (TSC != TSCS_unspecified) {
7350       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7351            diag::err_opencl_unknown_type_specifier)
7352           << getLangOpts().getOpenCLVersionString()
7353           << DeclSpec::getSpecifierName(TSC) << 1;
7354       NewVD->setInvalidDecl();
7355     }
7356   }
7357 
7358   // Handle attributes prior to checking for duplicates in MergeVarDecl
7359   ProcessDeclAttributes(S, NewVD, D);
7360 
7361   // FIXME: This is probably the wrong location to be doing this and we should
7362   // probably be doing this for more attributes (especially for function
7363   // pointer attributes such as format, warn_unused_result, etc.). Ideally
7364   // the code to copy attributes would be generated by TableGen.
7365   if (R->isFunctionPointerType())
7366     if (const auto *TT = R->getAs<TypedefType>())
7367       copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7368 
7369   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7370       getLangOpts().SYCLIsDevice) {
7371     if (EmitTLSUnsupportedError &&
7372         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7373          (getLangOpts().OpenMPIsDevice &&
7374           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7375       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7376            diag::err_thread_unsupported);
7377 
7378     if (EmitTLSUnsupportedError &&
7379         (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7380       targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7381     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7382     // storage [duration]."
7383     if (SC == SC_None && S->getFnParent() != nullptr &&
7384         (NewVD->hasAttr<CUDASharedAttr>() ||
7385          NewVD->hasAttr<CUDAConstantAttr>())) {
7386       NewVD->setStorageClass(SC_Static);
7387     }
7388   }
7389 
7390   // Ensure that dllimport globals without explicit storage class are treated as
7391   // extern. The storage class is set above using parsed attributes. Now we can
7392   // check the VarDecl itself.
7393   assert(!NewVD->hasAttr<DLLImportAttr>() ||
7394          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7395          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7396 
7397   // In auto-retain/release, infer strong retension for variables of
7398   // retainable type.
7399   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7400     NewVD->setInvalidDecl();
7401 
7402   // Handle GNU asm-label extension (encoded as an attribute).
7403   if (Expr *E = (Expr*)D.getAsmLabel()) {
7404     // The parser guarantees this is a string.
7405     StringLiteral *SE = cast<StringLiteral>(E);
7406     StringRef Label = SE->getString();
7407     if (S->getFnParent() != nullptr) {
7408       switch (SC) {
7409       case SC_None:
7410       case SC_Auto:
7411         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7412         break;
7413       case SC_Register:
7414         // Local Named register
7415         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7416             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7417           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7418         break;
7419       case SC_Static:
7420       case SC_Extern:
7421       case SC_PrivateExtern:
7422         break;
7423       }
7424     } else if (SC == SC_Register) {
7425       // Global Named register
7426       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7427         const auto &TI = Context.getTargetInfo();
7428         bool HasSizeMismatch;
7429 
7430         if (!TI.isValidGCCRegisterName(Label))
7431           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7432         else if (!TI.validateGlobalRegisterVariable(Label,
7433                                                     Context.getTypeSize(R),
7434                                                     HasSizeMismatch))
7435           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7436         else if (HasSizeMismatch)
7437           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7438       }
7439 
7440       if (!R->isIntegralType(Context) && !R->isPointerType()) {
7441         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7442         NewVD->setInvalidDecl(true);
7443       }
7444     }
7445 
7446     NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7447                                         /*IsLiteralLabel=*/true,
7448                                         SE->getStrTokenLoc(0)));
7449   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7450     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7451       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7452     if (I != ExtnameUndeclaredIdentifiers.end()) {
7453       if (isDeclExternC(NewVD)) {
7454         NewVD->addAttr(I->second);
7455         ExtnameUndeclaredIdentifiers.erase(I);
7456       } else
7457         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7458             << /*Variable*/1 << NewVD;
7459     }
7460   }
7461 
7462   // Find the shadowed declaration before filtering for scope.
7463   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7464                                 ? getShadowedDeclaration(NewVD, Previous)
7465                                 : nullptr;
7466 
7467   // Don't consider existing declarations that are in a different
7468   // scope and are out-of-semantic-context declarations (if the new
7469   // declaration has linkage).
7470   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7471                        D.getCXXScopeSpec().isNotEmpty() ||
7472                        IsMemberSpecialization ||
7473                        IsVariableTemplateSpecialization);
7474 
7475   // Check whether the previous declaration is in the same block scope. This
7476   // affects whether we merge types with it, per C++11 [dcl.array]p3.
7477   if (getLangOpts().CPlusPlus &&
7478       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7479     NewVD->setPreviousDeclInSameBlockScope(
7480         Previous.isSingleResult() && !Previous.isShadowed() &&
7481         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7482 
7483   if (!getLangOpts().CPlusPlus) {
7484     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7485   } else {
7486     // If this is an explicit specialization of a static data member, check it.
7487     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7488         CheckMemberSpecialization(NewVD, Previous))
7489       NewVD->setInvalidDecl();
7490 
7491     // Merge the decl with the existing one if appropriate.
7492     if (!Previous.empty()) {
7493       if (Previous.isSingleResult() &&
7494           isa<FieldDecl>(Previous.getFoundDecl()) &&
7495           D.getCXXScopeSpec().isSet()) {
7496         // The user tried to define a non-static data member
7497         // out-of-line (C++ [dcl.meaning]p1).
7498         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7499           << D.getCXXScopeSpec().getRange();
7500         Previous.clear();
7501         NewVD->setInvalidDecl();
7502       }
7503     } else if (D.getCXXScopeSpec().isSet()) {
7504       // No previous declaration in the qualifying scope.
7505       Diag(D.getIdentifierLoc(), diag::err_no_member)
7506         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7507         << D.getCXXScopeSpec().getRange();
7508       NewVD->setInvalidDecl();
7509     }
7510 
7511     if (!IsVariableTemplateSpecialization)
7512       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7513 
7514     if (NewTemplate) {
7515       VarTemplateDecl *PrevVarTemplate =
7516           NewVD->getPreviousDecl()
7517               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7518               : nullptr;
7519 
7520       // Check the template parameter list of this declaration, possibly
7521       // merging in the template parameter list from the previous variable
7522       // template declaration.
7523       if (CheckTemplateParameterList(
7524               TemplateParams,
7525               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7526                               : nullptr,
7527               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7528                DC->isDependentContext())
7529                   ? TPC_ClassTemplateMember
7530                   : TPC_VarTemplate))
7531         NewVD->setInvalidDecl();
7532 
7533       // If we are providing an explicit specialization of a static variable
7534       // template, make a note of that.
7535       if (PrevVarTemplate &&
7536           PrevVarTemplate->getInstantiatedFromMemberTemplate())
7537         PrevVarTemplate->setMemberSpecialization();
7538     }
7539   }
7540 
7541   // Diagnose shadowed variables iff this isn't a redeclaration.
7542   if (ShadowedDecl && !D.isRedeclaration())
7543     CheckShadow(NewVD, ShadowedDecl, Previous);
7544 
7545   ProcessPragmaWeak(S, NewVD);
7546 
7547   // If this is the first declaration of an extern C variable, update
7548   // the map of such variables.
7549   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7550       isIncompleteDeclExternC(*this, NewVD))
7551     RegisterLocallyScopedExternCDecl(NewVD, S);
7552 
7553   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7554     MangleNumberingContext *MCtx;
7555     Decl *ManglingContextDecl;
7556     std::tie(MCtx, ManglingContextDecl) =
7557         getCurrentMangleNumberContext(NewVD->getDeclContext());
7558     if (MCtx) {
7559       Context.setManglingNumber(
7560           NewVD, MCtx->getManglingNumber(
7561                      NewVD, getMSManglingNumber(getLangOpts(), S)));
7562       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7563     }
7564   }
7565 
7566   // Special handling of variable named 'main'.
7567   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7568       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7569       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7570 
7571     // C++ [basic.start.main]p3
7572     // A program that declares a variable main at global scope is ill-formed.
7573     if (getLangOpts().CPlusPlus)
7574       Diag(D.getBeginLoc(), diag::err_main_global_variable);
7575 
7576     // In C, and external-linkage variable named main results in undefined
7577     // behavior.
7578     else if (NewVD->hasExternalFormalLinkage())
7579       Diag(D.getBeginLoc(), diag::warn_main_redefined);
7580   }
7581 
7582   if (D.isRedeclaration() && !Previous.empty()) {
7583     NamedDecl *Prev = Previous.getRepresentativeDecl();
7584     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7585                                    D.isFunctionDefinition());
7586   }
7587 
7588   if (NewTemplate) {
7589     if (NewVD->isInvalidDecl())
7590       NewTemplate->setInvalidDecl();
7591     ActOnDocumentableDecl(NewTemplate);
7592     return NewTemplate;
7593   }
7594 
7595   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7596     CompleteMemberSpecialization(NewVD, Previous);
7597 
7598   return NewVD;
7599 }
7600 
7601 /// Enum describing the %select options in diag::warn_decl_shadow.
7602 enum ShadowedDeclKind {
7603   SDK_Local,
7604   SDK_Global,
7605   SDK_StaticMember,
7606   SDK_Field,
7607   SDK_Typedef,
7608   SDK_Using,
7609   SDK_StructuredBinding
7610 };
7611 
7612 /// Determine what kind of declaration we're shadowing.
7613 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7614                                                 const DeclContext *OldDC) {
7615   if (isa<TypeAliasDecl>(ShadowedDecl))
7616     return SDK_Using;
7617   else if (isa<TypedefDecl>(ShadowedDecl))
7618     return SDK_Typedef;
7619   else if (isa<BindingDecl>(ShadowedDecl))
7620     return SDK_StructuredBinding;
7621   else if (isa<RecordDecl>(OldDC))
7622     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7623 
7624   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7625 }
7626 
7627 /// Return the location of the capture if the given lambda captures the given
7628 /// variable \p VD, or an invalid source location otherwise.
7629 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7630                                          const VarDecl *VD) {
7631   for (const Capture &Capture : LSI->Captures) {
7632     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7633       return Capture.getLocation();
7634   }
7635   return SourceLocation();
7636 }
7637 
7638 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7639                                      const LookupResult &R) {
7640   // Only diagnose if we're shadowing an unambiguous field or variable.
7641   if (R.getResultKind() != LookupResult::Found)
7642     return false;
7643 
7644   // Return false if warning is ignored.
7645   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7646 }
7647 
7648 /// Return the declaration shadowed by the given variable \p D, or null
7649 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7650 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7651                                         const LookupResult &R) {
7652   if (!shouldWarnIfShadowedDecl(Diags, R))
7653     return nullptr;
7654 
7655   // Don't diagnose declarations at file scope.
7656   if (D->hasGlobalStorage())
7657     return nullptr;
7658 
7659   NamedDecl *ShadowedDecl = R.getFoundDecl();
7660   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7661                                                             : nullptr;
7662 }
7663 
7664 /// Return the declaration shadowed by the given typedef \p D, or null
7665 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7666 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7667                                         const LookupResult &R) {
7668   // Don't warn if typedef declaration is part of a class
7669   if (D->getDeclContext()->isRecord())
7670     return nullptr;
7671 
7672   if (!shouldWarnIfShadowedDecl(Diags, R))
7673     return nullptr;
7674 
7675   NamedDecl *ShadowedDecl = R.getFoundDecl();
7676   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7677 }
7678 
7679 /// Return the declaration shadowed by the given variable \p D, or null
7680 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7681 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7682                                         const LookupResult &R) {
7683   if (!shouldWarnIfShadowedDecl(Diags, R))
7684     return nullptr;
7685 
7686   NamedDecl *ShadowedDecl = R.getFoundDecl();
7687   return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7688                                                             : nullptr;
7689 }
7690 
7691 /// Diagnose variable or built-in function shadowing.  Implements
7692 /// -Wshadow.
7693 ///
7694 /// This method is called whenever a VarDecl is added to a "useful"
7695 /// scope.
7696 ///
7697 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7698 /// \param R the lookup of the name
7699 ///
7700 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7701                        const LookupResult &R) {
7702   DeclContext *NewDC = D->getDeclContext();
7703 
7704   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7705     // Fields are not shadowed by variables in C++ static methods.
7706     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7707       if (MD->isStatic())
7708         return;
7709 
7710     // Fields shadowed by constructor parameters are a special case. Usually
7711     // the constructor initializes the field with the parameter.
7712     if (isa<CXXConstructorDecl>(NewDC))
7713       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7714         // Remember that this was shadowed so we can either warn about its
7715         // modification or its existence depending on warning settings.
7716         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7717         return;
7718       }
7719   }
7720 
7721   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7722     if (shadowedVar->isExternC()) {
7723       // For shadowing external vars, make sure that we point to the global
7724       // declaration, not a locally scoped extern declaration.
7725       for (auto I : shadowedVar->redecls())
7726         if (I->isFileVarDecl()) {
7727           ShadowedDecl = I;
7728           break;
7729         }
7730     }
7731 
7732   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7733 
7734   unsigned WarningDiag = diag::warn_decl_shadow;
7735   SourceLocation CaptureLoc;
7736   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7737       isa<CXXMethodDecl>(NewDC)) {
7738     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7739       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7740         if (RD->getLambdaCaptureDefault() == LCD_None) {
7741           // Try to avoid warnings for lambdas with an explicit capture list.
7742           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7743           // Warn only when the lambda captures the shadowed decl explicitly.
7744           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7745           if (CaptureLoc.isInvalid())
7746             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7747         } else {
7748           // Remember that this was shadowed so we can avoid the warning if the
7749           // shadowed decl isn't captured and the warning settings allow it.
7750           cast<LambdaScopeInfo>(getCurFunction())
7751               ->ShadowingDecls.push_back(
7752                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7753           return;
7754         }
7755       }
7756 
7757       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7758         // A variable can't shadow a local variable in an enclosing scope, if
7759         // they are separated by a non-capturing declaration context.
7760         for (DeclContext *ParentDC = NewDC;
7761              ParentDC && !ParentDC->Equals(OldDC);
7762              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7763           // Only block literals, captured statements, and lambda expressions
7764           // can capture; other scopes don't.
7765           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7766               !isLambdaCallOperator(ParentDC)) {
7767             return;
7768           }
7769         }
7770       }
7771     }
7772   }
7773 
7774   // Only warn about certain kinds of shadowing for class members.
7775   if (NewDC && NewDC->isRecord()) {
7776     // In particular, don't warn about shadowing non-class members.
7777     if (!OldDC->isRecord())
7778       return;
7779 
7780     // TODO: should we warn about static data members shadowing
7781     // static data members from base classes?
7782 
7783     // TODO: don't diagnose for inaccessible shadowed members.
7784     // This is hard to do perfectly because we might friend the
7785     // shadowing context, but that's just a false negative.
7786   }
7787 
7788 
7789   DeclarationName Name = R.getLookupName();
7790 
7791   // Emit warning and note.
7792   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7793     return;
7794   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7795   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7796   if (!CaptureLoc.isInvalid())
7797     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7798         << Name << /*explicitly*/ 1;
7799   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7800 }
7801 
7802 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7803 /// when these variables are captured by the lambda.
7804 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7805   for (const auto &Shadow : LSI->ShadowingDecls) {
7806     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7807     // Try to avoid the warning when the shadowed decl isn't captured.
7808     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7809     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7810     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7811                                        ? diag::warn_decl_shadow_uncaptured_local
7812                                        : diag::warn_decl_shadow)
7813         << Shadow.VD->getDeclName()
7814         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7815     if (!CaptureLoc.isInvalid())
7816       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7817           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7818     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7819   }
7820 }
7821 
7822 /// Check -Wshadow without the advantage of a previous lookup.
7823 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7824   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7825     return;
7826 
7827   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7828                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7829   LookupName(R, S);
7830   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7831     CheckShadow(D, ShadowedDecl, R);
7832 }
7833 
7834 /// Check if 'E', which is an expression that is about to be modified, refers
7835 /// to a constructor parameter that shadows a field.
7836 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7837   // Quickly ignore expressions that can't be shadowing ctor parameters.
7838   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7839     return;
7840   E = E->IgnoreParenImpCasts();
7841   auto *DRE = dyn_cast<DeclRefExpr>(E);
7842   if (!DRE)
7843     return;
7844   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7845   auto I = ShadowingDecls.find(D);
7846   if (I == ShadowingDecls.end())
7847     return;
7848   const NamedDecl *ShadowedDecl = I->second;
7849   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7850   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7851   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7852   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7853 
7854   // Avoid issuing multiple warnings about the same decl.
7855   ShadowingDecls.erase(I);
7856 }
7857 
7858 /// Check for conflict between this global or extern "C" declaration and
7859 /// previous global or extern "C" declarations. This is only used in C++.
7860 template<typename T>
7861 static bool checkGlobalOrExternCConflict(
7862     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7863   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7864   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7865 
7866   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7867     // The common case: this global doesn't conflict with any extern "C"
7868     // declaration.
7869     return false;
7870   }
7871 
7872   if (Prev) {
7873     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7874       // Both the old and new declarations have C language linkage. This is a
7875       // redeclaration.
7876       Previous.clear();
7877       Previous.addDecl(Prev);
7878       return true;
7879     }
7880 
7881     // This is a global, non-extern "C" declaration, and there is a previous
7882     // non-global extern "C" declaration. Diagnose if this is a variable
7883     // declaration.
7884     if (!isa<VarDecl>(ND))
7885       return false;
7886   } else {
7887     // The declaration is extern "C". Check for any declaration in the
7888     // translation unit which might conflict.
7889     if (IsGlobal) {
7890       // We have already performed the lookup into the translation unit.
7891       IsGlobal = false;
7892       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7893            I != E; ++I) {
7894         if (isa<VarDecl>(*I)) {
7895           Prev = *I;
7896           break;
7897         }
7898       }
7899     } else {
7900       DeclContext::lookup_result R =
7901           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7902       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7903            I != E; ++I) {
7904         if (isa<VarDecl>(*I)) {
7905           Prev = *I;
7906           break;
7907         }
7908         // FIXME: If we have any other entity with this name in global scope,
7909         // the declaration is ill-formed, but that is a defect: it breaks the
7910         // 'stat' hack, for instance. Only variables can have mangled name
7911         // clashes with extern "C" declarations, so only they deserve a
7912         // diagnostic.
7913       }
7914     }
7915 
7916     if (!Prev)
7917       return false;
7918   }
7919 
7920   // Use the first declaration's location to ensure we point at something which
7921   // is lexically inside an extern "C" linkage-spec.
7922   assert(Prev && "should have found a previous declaration to diagnose");
7923   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7924     Prev = FD->getFirstDecl();
7925   else
7926     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7927 
7928   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7929     << IsGlobal << ND;
7930   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7931     << IsGlobal;
7932   return false;
7933 }
7934 
7935 /// Apply special rules for handling extern "C" declarations. Returns \c true
7936 /// if we have found that this is a redeclaration of some prior entity.
7937 ///
7938 /// Per C++ [dcl.link]p6:
7939 ///   Two declarations [for a function or variable] with C language linkage
7940 ///   with the same name that appear in different scopes refer to the same
7941 ///   [entity]. An entity with C language linkage shall not be declared with
7942 ///   the same name as an entity in global scope.
7943 template<typename T>
7944 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7945                                                   LookupResult &Previous) {
7946   if (!S.getLangOpts().CPlusPlus) {
7947     // In C, when declaring a global variable, look for a corresponding 'extern'
7948     // variable declared in function scope. We don't need this in C++, because
7949     // we find local extern decls in the surrounding file-scope DeclContext.
7950     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7951       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7952         Previous.clear();
7953         Previous.addDecl(Prev);
7954         return true;
7955       }
7956     }
7957     return false;
7958   }
7959 
7960   // A declaration in the translation unit can conflict with an extern "C"
7961   // declaration.
7962   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7963     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7964 
7965   // An extern "C" declaration can conflict with a declaration in the
7966   // translation unit or can be a redeclaration of an extern "C" declaration
7967   // in another scope.
7968   if (isIncompleteDeclExternC(S,ND))
7969     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7970 
7971   // Neither global nor extern "C": nothing to do.
7972   return false;
7973 }
7974 
7975 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7976   // If the decl is already known invalid, don't check it.
7977   if (NewVD->isInvalidDecl())
7978     return;
7979 
7980   QualType T = NewVD->getType();
7981 
7982   // Defer checking an 'auto' type until its initializer is attached.
7983   if (T->isUndeducedType())
7984     return;
7985 
7986   if (NewVD->hasAttrs())
7987     CheckAlignasUnderalignment(NewVD);
7988 
7989   if (T->isObjCObjectType()) {
7990     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7991       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7992     T = Context.getObjCObjectPointerType(T);
7993     NewVD->setType(T);
7994   }
7995 
7996   // Emit an error if an address space was applied to decl with local storage.
7997   // This includes arrays of objects with address space qualifiers, but not
7998   // automatic variables that point to other address spaces.
7999   // ISO/IEC TR 18037 S5.1.2
8000   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8001       T.getAddressSpace() != LangAS::Default) {
8002     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8003     NewVD->setInvalidDecl();
8004     return;
8005   }
8006 
8007   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8008   // scope.
8009   if (getLangOpts().OpenCLVersion == 120 &&
8010       !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8011                                             getLangOpts()) &&
8012       NewVD->isStaticLocal()) {
8013     Diag(NewVD->getLocation(), diag::err_static_function_scope);
8014     NewVD->setInvalidDecl();
8015     return;
8016   }
8017 
8018   if (getLangOpts().OpenCL) {
8019     if (!diagnoseOpenCLTypes(*this, NewVD))
8020       return;
8021 
8022     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8023     if (NewVD->hasAttr<BlocksAttr>()) {
8024       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8025       return;
8026     }
8027 
8028     if (T->isBlockPointerType()) {
8029       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8030       // can't use 'extern' storage class.
8031       if (!T.isConstQualified()) {
8032         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8033             << 0 /*const*/;
8034         NewVD->setInvalidDecl();
8035         return;
8036       }
8037       if (NewVD->hasExternalStorage()) {
8038         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8039         NewVD->setInvalidDecl();
8040         return;
8041       }
8042     }
8043 
8044     // FIXME: Adding local AS in C++ for OpenCL might make sense.
8045     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8046         NewVD->hasExternalStorage()) {
8047       if (!T->isSamplerT() && !T->isDependentType() &&
8048           !(T.getAddressSpace() == LangAS::opencl_constant ||
8049             (T.getAddressSpace() == LangAS::opencl_global &&
8050              getOpenCLOptions().areProgramScopeVariablesSupported(
8051                  getLangOpts())))) {
8052         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8053         if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8054           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8055               << Scope << "global or constant";
8056         else
8057           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8058               << Scope << "constant";
8059         NewVD->setInvalidDecl();
8060         return;
8061       }
8062     } else {
8063       if (T.getAddressSpace() == LangAS::opencl_global) {
8064         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8065             << 1 /*is any function*/ << "global";
8066         NewVD->setInvalidDecl();
8067         return;
8068       }
8069       if (T.getAddressSpace() == LangAS::opencl_constant ||
8070           T.getAddressSpace() == LangAS::opencl_local) {
8071         FunctionDecl *FD = getCurFunctionDecl();
8072         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8073         // in functions.
8074         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8075           if (T.getAddressSpace() == LangAS::opencl_constant)
8076             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8077                 << 0 /*non-kernel only*/ << "constant";
8078           else
8079             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8080                 << 0 /*non-kernel only*/ << "local";
8081           NewVD->setInvalidDecl();
8082           return;
8083         }
8084         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8085         // in the outermost scope of a kernel function.
8086         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8087           if (!getCurScope()->isFunctionScope()) {
8088             if (T.getAddressSpace() == LangAS::opencl_constant)
8089               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8090                   << "constant";
8091             else
8092               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8093                   << "local";
8094             NewVD->setInvalidDecl();
8095             return;
8096           }
8097         }
8098       } else if (T.getAddressSpace() != LangAS::opencl_private &&
8099                  // If we are parsing a template we didn't deduce an addr
8100                  // space yet.
8101                  T.getAddressSpace() != LangAS::Default) {
8102         // Do not allow other address spaces on automatic variable.
8103         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8104         NewVD->setInvalidDecl();
8105         return;
8106       }
8107     }
8108   }
8109 
8110   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8111       && !NewVD->hasAttr<BlocksAttr>()) {
8112     if (getLangOpts().getGC() != LangOptions::NonGC)
8113       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8114     else {
8115       assert(!getLangOpts().ObjCAutoRefCount);
8116       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8117     }
8118   }
8119 
8120   bool isVM = T->isVariablyModifiedType();
8121   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8122       NewVD->hasAttr<BlocksAttr>())
8123     setFunctionHasBranchProtectedScope();
8124 
8125   if ((isVM && NewVD->hasLinkage()) ||
8126       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8127     bool SizeIsNegative;
8128     llvm::APSInt Oversized;
8129     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8130         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8131     QualType FixedT;
8132     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
8133       FixedT = FixedTInfo->getType();
8134     else if (FixedTInfo) {
8135       // Type and type-as-written are canonically different. We need to fix up
8136       // both types separately.
8137       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8138                                                    Oversized);
8139     }
8140     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8141       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8142       // FIXME: This won't give the correct result for
8143       // int a[10][n];
8144       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8145 
8146       if (NewVD->isFileVarDecl())
8147         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8148         << SizeRange;
8149       else if (NewVD->isStaticLocal())
8150         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8151         << SizeRange;
8152       else
8153         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8154         << SizeRange;
8155       NewVD->setInvalidDecl();
8156       return;
8157     }
8158 
8159     if (!FixedTInfo) {
8160       if (NewVD->isFileVarDecl())
8161         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8162       else
8163         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8164       NewVD->setInvalidDecl();
8165       return;
8166     }
8167 
8168     Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8169     NewVD->setType(FixedT);
8170     NewVD->setTypeSourceInfo(FixedTInfo);
8171   }
8172 
8173   if (T->isVoidType()) {
8174     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8175     //                    of objects and functions.
8176     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8177       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8178         << T;
8179       NewVD->setInvalidDecl();
8180       return;
8181     }
8182   }
8183 
8184   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8185     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8186     NewVD->setInvalidDecl();
8187     return;
8188   }
8189 
8190   if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8191     Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8192     NewVD->setInvalidDecl();
8193     return;
8194   }
8195 
8196   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8197     Diag(NewVD->getLocation(), diag::err_block_on_vm);
8198     NewVD->setInvalidDecl();
8199     return;
8200   }
8201 
8202   if (NewVD->isConstexpr() && !T->isDependentType() &&
8203       RequireLiteralType(NewVD->getLocation(), T,
8204                          diag::err_constexpr_var_non_literal)) {
8205     NewVD->setInvalidDecl();
8206     return;
8207   }
8208 
8209   // PPC MMA non-pointer types are not allowed as non-local variable types.
8210   if (Context.getTargetInfo().getTriple().isPPC64() &&
8211       !NewVD->isLocalVarDecl() &&
8212       CheckPPCMMAType(T, NewVD->getLocation())) {
8213     NewVD->setInvalidDecl();
8214     return;
8215   }
8216 }
8217 
8218 /// Perform semantic checking on a newly-created variable
8219 /// declaration.
8220 ///
8221 /// This routine performs all of the type-checking required for a
8222 /// variable declaration once it has been built. It is used both to
8223 /// check variables after they have been parsed and their declarators
8224 /// have been translated into a declaration, and to check variables
8225 /// that have been instantiated from a template.
8226 ///
8227 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8228 ///
8229 /// Returns true if the variable declaration is a redeclaration.
8230 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8231   CheckVariableDeclarationType(NewVD);
8232 
8233   // If the decl is already known invalid, don't check it.
8234   if (NewVD->isInvalidDecl())
8235     return false;
8236 
8237   // If we did not find anything by this name, look for a non-visible
8238   // extern "C" declaration with the same name.
8239   if (Previous.empty() &&
8240       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8241     Previous.setShadowed();
8242 
8243   if (!Previous.empty()) {
8244     MergeVarDecl(NewVD, Previous);
8245     return true;
8246   }
8247   return false;
8248 }
8249 
8250 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8251 /// and if so, check that it's a valid override and remember it.
8252 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8253   llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8254 
8255   // Look for methods in base classes that this method might override.
8256   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8257                      /*DetectVirtual=*/false);
8258   auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8259     CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8260     DeclarationName Name = MD->getDeclName();
8261 
8262     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8263       // We really want to find the base class destructor here.
8264       QualType T = Context.getTypeDeclType(BaseRecord);
8265       CanQualType CT = Context.getCanonicalType(T);
8266       Name = Context.DeclarationNames.getCXXDestructorName(CT);
8267     }
8268 
8269     for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8270       CXXMethodDecl *BaseMD =
8271           dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8272       if (!BaseMD || !BaseMD->isVirtual() ||
8273           IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8274                      /*ConsiderCudaAttrs=*/true,
8275                      // C++2a [class.virtual]p2 does not consider requires
8276                      // clauses when overriding.
8277                      /*ConsiderRequiresClauses=*/false))
8278         continue;
8279 
8280       if (Overridden.insert(BaseMD).second) {
8281         MD->addOverriddenMethod(BaseMD);
8282         CheckOverridingFunctionReturnType(MD, BaseMD);
8283         CheckOverridingFunctionAttributes(MD, BaseMD);
8284         CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8285         CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8286       }
8287 
8288       // A method can only override one function from each base class. We
8289       // don't track indirectly overridden methods from bases of bases.
8290       return true;
8291     }
8292 
8293     return false;
8294   };
8295 
8296   DC->lookupInBases(VisitBase, Paths);
8297   return !Overridden.empty();
8298 }
8299 
8300 namespace {
8301   // Struct for holding all of the extra arguments needed by
8302   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8303   struct ActOnFDArgs {
8304     Scope *S;
8305     Declarator &D;
8306     MultiTemplateParamsArg TemplateParamLists;
8307     bool AddToScope;
8308   };
8309 } // end anonymous namespace
8310 
8311 namespace {
8312 
8313 // Callback to only accept typo corrections that have a non-zero edit distance.
8314 // Also only accept corrections that have the same parent decl.
8315 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8316  public:
8317   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8318                             CXXRecordDecl *Parent)
8319       : Context(Context), OriginalFD(TypoFD),
8320         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8321 
8322   bool ValidateCandidate(const TypoCorrection &candidate) override {
8323     if (candidate.getEditDistance() == 0)
8324       return false;
8325 
8326     SmallVector<unsigned, 1> MismatchedParams;
8327     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8328                                           CDeclEnd = candidate.end();
8329          CDecl != CDeclEnd; ++CDecl) {
8330       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8331 
8332       if (FD && !FD->hasBody() &&
8333           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8334         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8335           CXXRecordDecl *Parent = MD->getParent();
8336           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8337             return true;
8338         } else if (!ExpectedParent) {
8339           return true;
8340         }
8341       }
8342     }
8343 
8344     return false;
8345   }
8346 
8347   std::unique_ptr<CorrectionCandidateCallback> clone() override {
8348     return std::make_unique<DifferentNameValidatorCCC>(*this);
8349   }
8350 
8351  private:
8352   ASTContext &Context;
8353   FunctionDecl *OriginalFD;
8354   CXXRecordDecl *ExpectedParent;
8355 };
8356 
8357 } // end anonymous namespace
8358 
8359 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8360   TypoCorrectedFunctionDefinitions.insert(F);
8361 }
8362 
8363 /// Generate diagnostics for an invalid function redeclaration.
8364 ///
8365 /// This routine handles generating the diagnostic messages for an invalid
8366 /// function redeclaration, including finding possible similar declarations
8367 /// or performing typo correction if there are no previous declarations with
8368 /// the same name.
8369 ///
8370 /// Returns a NamedDecl iff typo correction was performed and substituting in
8371 /// the new declaration name does not cause new errors.
8372 static NamedDecl *DiagnoseInvalidRedeclaration(
8373     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8374     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8375   DeclarationName Name = NewFD->getDeclName();
8376   DeclContext *NewDC = NewFD->getDeclContext();
8377   SmallVector<unsigned, 1> MismatchedParams;
8378   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8379   TypoCorrection Correction;
8380   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8381   unsigned DiagMsg =
8382     IsLocalFriend ? diag::err_no_matching_local_friend :
8383     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8384     diag::err_member_decl_does_not_match;
8385   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8386                     IsLocalFriend ? Sema::LookupLocalFriendName
8387                                   : Sema::LookupOrdinaryName,
8388                     Sema::ForVisibleRedeclaration);
8389 
8390   NewFD->setInvalidDecl();
8391   if (IsLocalFriend)
8392     SemaRef.LookupName(Prev, S);
8393   else
8394     SemaRef.LookupQualifiedName(Prev, NewDC);
8395   assert(!Prev.isAmbiguous() &&
8396          "Cannot have an ambiguity in previous-declaration lookup");
8397   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8398   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8399                                 MD ? MD->getParent() : nullptr);
8400   if (!Prev.empty()) {
8401     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8402          Func != FuncEnd; ++Func) {
8403       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8404       if (FD &&
8405           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8406         // Add 1 to the index so that 0 can mean the mismatch didn't
8407         // involve a parameter
8408         unsigned ParamNum =
8409             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8410         NearMatches.push_back(std::make_pair(FD, ParamNum));
8411       }
8412     }
8413   // If the qualified name lookup yielded nothing, try typo correction
8414   } else if ((Correction = SemaRef.CorrectTypo(
8415                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8416                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8417                   IsLocalFriend ? nullptr : NewDC))) {
8418     // Set up everything for the call to ActOnFunctionDeclarator
8419     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8420                               ExtraArgs.D.getIdentifierLoc());
8421     Previous.clear();
8422     Previous.setLookupName(Correction.getCorrection());
8423     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8424                                     CDeclEnd = Correction.end();
8425          CDecl != CDeclEnd; ++CDecl) {
8426       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8427       if (FD && !FD->hasBody() &&
8428           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8429         Previous.addDecl(FD);
8430       }
8431     }
8432     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8433 
8434     NamedDecl *Result;
8435     // Retry building the function declaration with the new previous
8436     // declarations, and with errors suppressed.
8437     {
8438       // Trap errors.
8439       Sema::SFINAETrap Trap(SemaRef);
8440 
8441       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8442       // pieces need to verify the typo-corrected C++ declaration and hopefully
8443       // eliminate the need for the parameter pack ExtraArgs.
8444       Result = SemaRef.ActOnFunctionDeclarator(
8445           ExtraArgs.S, ExtraArgs.D,
8446           Correction.getCorrectionDecl()->getDeclContext(),
8447           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8448           ExtraArgs.AddToScope);
8449 
8450       if (Trap.hasErrorOccurred())
8451         Result = nullptr;
8452     }
8453 
8454     if (Result) {
8455       // Determine which correction we picked.
8456       Decl *Canonical = Result->getCanonicalDecl();
8457       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8458            I != E; ++I)
8459         if ((*I)->getCanonicalDecl() == Canonical)
8460           Correction.setCorrectionDecl(*I);
8461 
8462       // Let Sema know about the correction.
8463       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8464       SemaRef.diagnoseTypo(
8465           Correction,
8466           SemaRef.PDiag(IsLocalFriend
8467                           ? diag::err_no_matching_local_friend_suggest
8468                           : diag::err_member_decl_does_not_match_suggest)
8469             << Name << NewDC << IsDefinition);
8470       return Result;
8471     }
8472 
8473     // Pretend the typo correction never occurred
8474     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8475                               ExtraArgs.D.getIdentifierLoc());
8476     ExtraArgs.D.setRedeclaration(wasRedeclaration);
8477     Previous.clear();
8478     Previous.setLookupName(Name);
8479   }
8480 
8481   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8482       << Name << NewDC << IsDefinition << NewFD->getLocation();
8483 
8484   bool NewFDisConst = false;
8485   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8486     NewFDisConst = NewMD->isConst();
8487 
8488   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8489        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8490        NearMatch != NearMatchEnd; ++NearMatch) {
8491     FunctionDecl *FD = NearMatch->first;
8492     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8493     bool FDisConst = MD && MD->isConst();
8494     bool IsMember = MD || !IsLocalFriend;
8495 
8496     // FIXME: These notes are poorly worded for the local friend case.
8497     if (unsigned Idx = NearMatch->second) {
8498       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8499       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8500       if (Loc.isInvalid()) Loc = FD->getLocation();
8501       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8502                                  : diag::note_local_decl_close_param_match)
8503         << Idx << FDParam->getType()
8504         << NewFD->getParamDecl(Idx - 1)->getType();
8505     } else if (FDisConst != NewFDisConst) {
8506       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8507           << NewFDisConst << FD->getSourceRange().getEnd();
8508     } else
8509       SemaRef.Diag(FD->getLocation(),
8510                    IsMember ? diag::note_member_def_close_match
8511                             : diag::note_local_decl_close_match);
8512   }
8513   return nullptr;
8514 }
8515 
8516 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8517   switch (D.getDeclSpec().getStorageClassSpec()) {
8518   default: llvm_unreachable("Unknown storage class!");
8519   case DeclSpec::SCS_auto:
8520   case DeclSpec::SCS_register:
8521   case DeclSpec::SCS_mutable:
8522     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8523                  diag::err_typecheck_sclass_func);
8524     D.getMutableDeclSpec().ClearStorageClassSpecs();
8525     D.setInvalidType();
8526     break;
8527   case DeclSpec::SCS_unspecified: break;
8528   case DeclSpec::SCS_extern:
8529     if (D.getDeclSpec().isExternInLinkageSpec())
8530       return SC_None;
8531     return SC_Extern;
8532   case DeclSpec::SCS_static: {
8533     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8534       // C99 6.7.1p5:
8535       //   The declaration of an identifier for a function that has
8536       //   block scope shall have no explicit storage-class specifier
8537       //   other than extern
8538       // See also (C++ [dcl.stc]p4).
8539       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8540                    diag::err_static_block_func);
8541       break;
8542     } else
8543       return SC_Static;
8544   }
8545   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8546   }
8547 
8548   // No explicit storage class has already been returned
8549   return SC_None;
8550 }
8551 
8552 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8553                                            DeclContext *DC, QualType &R,
8554                                            TypeSourceInfo *TInfo,
8555                                            StorageClass SC,
8556                                            bool &IsVirtualOkay) {
8557   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8558   DeclarationName Name = NameInfo.getName();
8559 
8560   FunctionDecl *NewFD = nullptr;
8561   bool isInline = D.getDeclSpec().isInlineSpecified();
8562 
8563   if (!SemaRef.getLangOpts().CPlusPlus) {
8564     // Determine whether the function was written with a
8565     // prototype. This true when:
8566     //   - there is a prototype in the declarator, or
8567     //   - the type R of the function is some kind of typedef or other non-
8568     //     attributed reference to a type name (which eventually refers to a
8569     //     function type).
8570     bool HasPrototype =
8571       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8572       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8573 
8574     NewFD = FunctionDecl::Create(
8575         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8576         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8577         ConstexprSpecKind::Unspecified,
8578         /*TrailingRequiresClause=*/nullptr);
8579     if (D.isInvalidType())
8580       NewFD->setInvalidDecl();
8581 
8582     return NewFD;
8583   }
8584 
8585   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8586 
8587   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8588   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8589     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8590                  diag::err_constexpr_wrong_decl_kind)
8591         << static_cast<int>(ConstexprKind);
8592     ConstexprKind = ConstexprSpecKind::Unspecified;
8593     D.getMutableDeclSpec().ClearConstexprSpec();
8594   }
8595   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8596 
8597   // Check that the return type is not an abstract class type.
8598   // For record types, this is done by the AbstractClassUsageDiagnoser once
8599   // the class has been completely parsed.
8600   if (!DC->isRecord() &&
8601       SemaRef.RequireNonAbstractType(
8602           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8603           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8604     D.setInvalidType();
8605 
8606   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8607     // This is a C++ constructor declaration.
8608     assert(DC->isRecord() &&
8609            "Constructors can only be declared in a member context");
8610 
8611     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8612     return CXXConstructorDecl::Create(
8613         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8614         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8615         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8616         InheritedConstructor(), TrailingRequiresClause);
8617 
8618   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8619     // This is a C++ destructor declaration.
8620     if (DC->isRecord()) {
8621       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8622       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8623       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8624           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8625           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8626           /*isImplicitlyDeclared=*/false, ConstexprKind,
8627           TrailingRequiresClause);
8628 
8629       // If the destructor needs an implicit exception specification, set it
8630       // now. FIXME: It'd be nice to be able to create the right type to start
8631       // with, but the type needs to reference the destructor declaration.
8632       if (SemaRef.getLangOpts().CPlusPlus11)
8633         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8634 
8635       IsVirtualOkay = true;
8636       return NewDD;
8637 
8638     } else {
8639       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8640       D.setInvalidType();
8641 
8642       // Create a FunctionDecl to satisfy the function definition parsing
8643       // code path.
8644       return FunctionDecl::Create(
8645           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8646           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8647           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8648     }
8649 
8650   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8651     if (!DC->isRecord()) {
8652       SemaRef.Diag(D.getIdentifierLoc(),
8653            diag::err_conv_function_not_member);
8654       return nullptr;
8655     }
8656 
8657     SemaRef.CheckConversionDeclarator(D, R, SC);
8658     if (D.isInvalidType())
8659       return nullptr;
8660 
8661     IsVirtualOkay = true;
8662     return CXXConversionDecl::Create(
8663         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8664         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8665         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8666         TrailingRequiresClause);
8667 
8668   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8669     if (TrailingRequiresClause)
8670       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8671                    diag::err_trailing_requires_clause_on_deduction_guide)
8672           << TrailingRequiresClause->getSourceRange();
8673     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8674 
8675     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8676                                          ExplicitSpecifier, NameInfo, R, TInfo,
8677                                          D.getEndLoc());
8678   } else if (DC->isRecord()) {
8679     // If the name of the function is the same as the name of the record,
8680     // then this must be an invalid constructor that has a return type.
8681     // (The parser checks for a return type and makes the declarator a
8682     // constructor if it has no return type).
8683     if (Name.getAsIdentifierInfo() &&
8684         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8685       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8686         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8687         << SourceRange(D.getIdentifierLoc());
8688       return nullptr;
8689     }
8690 
8691     // This is a C++ method declaration.
8692     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8693         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8694         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8695         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8696     IsVirtualOkay = !Ret->isStatic();
8697     return Ret;
8698   } else {
8699     bool isFriend =
8700         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8701     if (!isFriend && SemaRef.CurContext->isRecord())
8702       return nullptr;
8703 
8704     // Determine whether the function was written with a
8705     // prototype. This true when:
8706     //   - we're in C++ (where every function has a prototype),
8707     return FunctionDecl::Create(
8708         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8709         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8710         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8711   }
8712 }
8713 
8714 enum OpenCLParamType {
8715   ValidKernelParam,
8716   PtrPtrKernelParam,
8717   PtrKernelParam,
8718   InvalidAddrSpacePtrKernelParam,
8719   InvalidKernelParam,
8720   RecordKernelParam
8721 };
8722 
8723 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8724   // Size dependent types are just typedefs to normal integer types
8725   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8726   // integers other than by their names.
8727   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8728 
8729   // Remove typedefs one by one until we reach a typedef
8730   // for a size dependent type.
8731   QualType DesugaredTy = Ty;
8732   do {
8733     ArrayRef<StringRef> Names(SizeTypeNames);
8734     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8735     if (Names.end() != Match)
8736       return true;
8737 
8738     Ty = DesugaredTy;
8739     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8740   } while (DesugaredTy != Ty);
8741 
8742   return false;
8743 }
8744 
8745 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8746   if (PT->isDependentType())
8747     return InvalidKernelParam;
8748 
8749   if (PT->isPointerType() || PT->isReferenceType()) {
8750     QualType PointeeType = PT->getPointeeType();
8751     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8752         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8753         PointeeType.getAddressSpace() == LangAS::Default)
8754       return InvalidAddrSpacePtrKernelParam;
8755 
8756     if (PointeeType->isPointerType()) {
8757       // This is a pointer to pointer parameter.
8758       // Recursively check inner type.
8759       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8760       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8761           ParamKind == InvalidKernelParam)
8762         return ParamKind;
8763 
8764       return PtrPtrKernelParam;
8765     }
8766 
8767     // C++ for OpenCL v1.0 s2.4:
8768     // Moreover the types used in parameters of the kernel functions must be:
8769     // Standard layout types for pointer parameters. The same applies to
8770     // reference if an implementation supports them in kernel parameters.
8771     if (S.getLangOpts().OpenCLCPlusPlus &&
8772         !S.getOpenCLOptions().isAvailableOption(
8773             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8774         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8775         !PointeeType->isStandardLayoutType())
8776       return InvalidKernelParam;
8777 
8778     return PtrKernelParam;
8779   }
8780 
8781   // OpenCL v1.2 s6.9.k:
8782   // Arguments to kernel functions in a program cannot be declared with the
8783   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8784   // uintptr_t or a struct and/or union that contain fields declared to be one
8785   // of these built-in scalar types.
8786   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8787     return InvalidKernelParam;
8788 
8789   if (PT->isImageType())
8790     return PtrKernelParam;
8791 
8792   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8793     return InvalidKernelParam;
8794 
8795   // OpenCL extension spec v1.2 s9.5:
8796   // This extension adds support for half scalar and vector types as built-in
8797   // types that can be used for arithmetic operations, conversions etc.
8798   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8799       PT->isHalfType())
8800     return InvalidKernelParam;
8801 
8802   // Look into an array argument to check if it has a forbidden type.
8803   if (PT->isArrayType()) {
8804     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8805     // Call ourself to check an underlying type of an array. Since the
8806     // getPointeeOrArrayElementType returns an innermost type which is not an
8807     // array, this recursive call only happens once.
8808     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8809   }
8810 
8811   // C++ for OpenCL v1.0 s2.4:
8812   // Moreover the types used in parameters of the kernel functions must be:
8813   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8814   // types) for parameters passed by value;
8815   if (S.getLangOpts().OpenCLCPlusPlus &&
8816       !S.getOpenCLOptions().isAvailableOption(
8817           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8818       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8819     return InvalidKernelParam;
8820 
8821   if (PT->isRecordType())
8822     return RecordKernelParam;
8823 
8824   return ValidKernelParam;
8825 }
8826 
8827 static void checkIsValidOpenCLKernelParameter(
8828   Sema &S,
8829   Declarator &D,
8830   ParmVarDecl *Param,
8831   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8832   QualType PT = Param->getType();
8833 
8834   // Cache the valid types we encounter to avoid rechecking structs that are
8835   // used again
8836   if (ValidTypes.count(PT.getTypePtr()))
8837     return;
8838 
8839   switch (getOpenCLKernelParameterType(S, PT)) {
8840   case PtrPtrKernelParam:
8841     // OpenCL v3.0 s6.11.a:
8842     // A kernel function argument cannot be declared as a pointer to a pointer
8843     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8844     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8845       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8846       D.setInvalidType();
8847       return;
8848     }
8849 
8850     ValidTypes.insert(PT.getTypePtr());
8851     return;
8852 
8853   case InvalidAddrSpacePtrKernelParam:
8854     // OpenCL v1.0 s6.5:
8855     // __kernel function arguments declared to be a pointer of a type can point
8856     // to one of the following address spaces only : __global, __local or
8857     // __constant.
8858     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8859     D.setInvalidType();
8860     return;
8861 
8862     // OpenCL v1.2 s6.9.k:
8863     // Arguments to kernel functions in a program cannot be declared with the
8864     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8865     // uintptr_t or a struct and/or union that contain fields declared to be
8866     // one of these built-in scalar types.
8867 
8868   case InvalidKernelParam:
8869     // OpenCL v1.2 s6.8 n:
8870     // A kernel function argument cannot be declared
8871     // of event_t type.
8872     // Do not diagnose half type since it is diagnosed as invalid argument
8873     // type for any function elsewhere.
8874     if (!PT->isHalfType()) {
8875       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8876 
8877       // Explain what typedefs are involved.
8878       const TypedefType *Typedef = nullptr;
8879       while ((Typedef = PT->getAs<TypedefType>())) {
8880         SourceLocation Loc = Typedef->getDecl()->getLocation();
8881         // SourceLocation may be invalid for a built-in type.
8882         if (Loc.isValid())
8883           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8884         PT = Typedef->desugar();
8885       }
8886     }
8887 
8888     D.setInvalidType();
8889     return;
8890 
8891   case PtrKernelParam:
8892   case ValidKernelParam:
8893     ValidTypes.insert(PT.getTypePtr());
8894     return;
8895 
8896   case RecordKernelParam:
8897     break;
8898   }
8899 
8900   // Track nested structs we will inspect
8901   SmallVector<const Decl *, 4> VisitStack;
8902 
8903   // Track where we are in the nested structs. Items will migrate from
8904   // VisitStack to HistoryStack as we do the DFS for bad field.
8905   SmallVector<const FieldDecl *, 4> HistoryStack;
8906   HistoryStack.push_back(nullptr);
8907 
8908   // At this point we already handled everything except of a RecordType or
8909   // an ArrayType of a RecordType.
8910   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8911   const RecordType *RecTy =
8912       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8913   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8914 
8915   VisitStack.push_back(RecTy->getDecl());
8916   assert(VisitStack.back() && "First decl null?");
8917 
8918   do {
8919     const Decl *Next = VisitStack.pop_back_val();
8920     if (!Next) {
8921       assert(!HistoryStack.empty());
8922       // Found a marker, we have gone up a level
8923       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8924         ValidTypes.insert(Hist->getType().getTypePtr());
8925 
8926       continue;
8927     }
8928 
8929     // Adds everything except the original parameter declaration (which is not a
8930     // field itself) to the history stack.
8931     const RecordDecl *RD;
8932     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8933       HistoryStack.push_back(Field);
8934 
8935       QualType FieldTy = Field->getType();
8936       // Other field types (known to be valid or invalid) are handled while we
8937       // walk around RecordDecl::fields().
8938       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8939              "Unexpected type.");
8940       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8941 
8942       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8943     } else {
8944       RD = cast<RecordDecl>(Next);
8945     }
8946 
8947     // Add a null marker so we know when we've gone back up a level
8948     VisitStack.push_back(nullptr);
8949 
8950     for (const auto *FD : RD->fields()) {
8951       QualType QT = FD->getType();
8952 
8953       if (ValidTypes.count(QT.getTypePtr()))
8954         continue;
8955 
8956       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8957       if (ParamType == ValidKernelParam)
8958         continue;
8959 
8960       if (ParamType == RecordKernelParam) {
8961         VisitStack.push_back(FD);
8962         continue;
8963       }
8964 
8965       // OpenCL v1.2 s6.9.p:
8966       // Arguments to kernel functions that are declared to be a struct or union
8967       // do not allow OpenCL objects to be passed as elements of the struct or
8968       // union.
8969       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8970           ParamType == InvalidAddrSpacePtrKernelParam) {
8971         S.Diag(Param->getLocation(),
8972                diag::err_record_with_pointers_kernel_param)
8973           << PT->isUnionType()
8974           << PT;
8975       } else {
8976         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8977       }
8978 
8979       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8980           << OrigRecDecl->getDeclName();
8981 
8982       // We have an error, now let's go back up through history and show where
8983       // the offending field came from
8984       for (ArrayRef<const FieldDecl *>::const_iterator
8985                I = HistoryStack.begin() + 1,
8986                E = HistoryStack.end();
8987            I != E; ++I) {
8988         const FieldDecl *OuterField = *I;
8989         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8990           << OuterField->getType();
8991       }
8992 
8993       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8994         << QT->isPointerType()
8995         << QT;
8996       D.setInvalidType();
8997       return;
8998     }
8999   } while (!VisitStack.empty());
9000 }
9001 
9002 /// Find the DeclContext in which a tag is implicitly declared if we see an
9003 /// elaborated type specifier in the specified context, and lookup finds
9004 /// nothing.
9005 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9006   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9007     DC = DC->getParent();
9008   return DC;
9009 }
9010 
9011 /// Find the Scope in which a tag is implicitly declared if we see an
9012 /// elaborated type specifier in the specified context, and lookup finds
9013 /// nothing.
9014 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9015   while (S->isClassScope() ||
9016          (LangOpts.CPlusPlus &&
9017           S->isFunctionPrototypeScope()) ||
9018          ((S->getFlags() & Scope::DeclScope) == 0) ||
9019          (S->getEntity() && S->getEntity()->isTransparentContext()))
9020     S = S->getParent();
9021   return S;
9022 }
9023 
9024 NamedDecl*
9025 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9026                               TypeSourceInfo *TInfo, LookupResult &Previous,
9027                               MultiTemplateParamsArg TemplateParamListsRef,
9028                               bool &AddToScope) {
9029   QualType R = TInfo->getType();
9030 
9031   assert(R->isFunctionType());
9032   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9033     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9034 
9035   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9036   for (TemplateParameterList *TPL : TemplateParamListsRef)
9037     TemplateParamLists.push_back(TPL);
9038   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9039     if (!TemplateParamLists.empty() &&
9040         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9041       TemplateParamLists.back() = Invented;
9042     else
9043       TemplateParamLists.push_back(Invented);
9044   }
9045 
9046   // TODO: consider using NameInfo for diagnostic.
9047   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9048   DeclarationName Name = NameInfo.getName();
9049   StorageClass SC = getFunctionStorageClass(*this, D);
9050 
9051   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9052     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9053          diag::err_invalid_thread)
9054       << DeclSpec::getSpecifierName(TSCS);
9055 
9056   if (D.isFirstDeclarationOfMember())
9057     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9058                            D.getIdentifierLoc());
9059 
9060   bool isFriend = false;
9061   FunctionTemplateDecl *FunctionTemplate = nullptr;
9062   bool isMemberSpecialization = false;
9063   bool isFunctionTemplateSpecialization = false;
9064 
9065   bool isDependentClassScopeExplicitSpecialization = false;
9066   bool HasExplicitTemplateArgs = false;
9067   TemplateArgumentListInfo TemplateArgs;
9068 
9069   bool isVirtualOkay = false;
9070 
9071   DeclContext *OriginalDC = DC;
9072   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9073 
9074   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9075                                               isVirtualOkay);
9076   if (!NewFD) return nullptr;
9077 
9078   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9079     NewFD->setTopLevelDeclInObjCContainer();
9080 
9081   // Set the lexical context. If this is a function-scope declaration, or has a
9082   // C++ scope specifier, or is the object of a friend declaration, the lexical
9083   // context will be different from the semantic context.
9084   NewFD->setLexicalDeclContext(CurContext);
9085 
9086   if (IsLocalExternDecl)
9087     NewFD->setLocalExternDecl();
9088 
9089   if (getLangOpts().CPlusPlus) {
9090     bool isInline = D.getDeclSpec().isInlineSpecified();
9091     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9092     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9093     isFriend = D.getDeclSpec().isFriendSpecified();
9094     if (isFriend && !isInline && D.isFunctionDefinition()) {
9095       // C++ [class.friend]p5
9096       //   A function can be defined in a friend declaration of a
9097       //   class . . . . Such a function is implicitly inline.
9098       NewFD->setImplicitlyInline();
9099     }
9100 
9101     // If this is a method defined in an __interface, and is not a constructor
9102     // or an overloaded operator, then set the pure flag (isVirtual will already
9103     // return true).
9104     if (const CXXRecordDecl *Parent =
9105           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9106       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9107         NewFD->setPure(true);
9108 
9109       // C++ [class.union]p2
9110       //   A union can have member functions, but not virtual functions.
9111       if (isVirtual && Parent->isUnion()) {
9112         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9113         NewFD->setInvalidDecl();
9114       }
9115     }
9116 
9117     SetNestedNameSpecifier(*this, NewFD, D);
9118     isMemberSpecialization = false;
9119     isFunctionTemplateSpecialization = false;
9120     if (D.isInvalidType())
9121       NewFD->setInvalidDecl();
9122 
9123     // Match up the template parameter lists with the scope specifier, then
9124     // determine whether we have a template or a template specialization.
9125     bool Invalid = false;
9126     TemplateParameterList *TemplateParams =
9127         MatchTemplateParametersToScopeSpecifier(
9128             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9129             D.getCXXScopeSpec(),
9130             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9131                 ? D.getName().TemplateId
9132                 : nullptr,
9133             TemplateParamLists, isFriend, isMemberSpecialization,
9134             Invalid);
9135     if (TemplateParams) {
9136       // Check that we can declare a template here.
9137       if (CheckTemplateDeclScope(S, TemplateParams))
9138         NewFD->setInvalidDecl();
9139 
9140       if (TemplateParams->size() > 0) {
9141         // This is a function template
9142 
9143         // A destructor cannot be a template.
9144         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9145           Diag(NewFD->getLocation(), diag::err_destructor_template);
9146           NewFD->setInvalidDecl();
9147         }
9148 
9149         // If we're adding a template to a dependent context, we may need to
9150         // rebuilding some of the types used within the template parameter list,
9151         // now that we know what the current instantiation is.
9152         if (DC->isDependentContext()) {
9153           ContextRAII SavedContext(*this, DC);
9154           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9155             Invalid = true;
9156         }
9157 
9158         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9159                                                         NewFD->getLocation(),
9160                                                         Name, TemplateParams,
9161                                                         NewFD);
9162         FunctionTemplate->setLexicalDeclContext(CurContext);
9163         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9164 
9165         // For source fidelity, store the other template param lists.
9166         if (TemplateParamLists.size() > 1) {
9167           NewFD->setTemplateParameterListsInfo(Context,
9168               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9169                   .drop_back(1));
9170         }
9171       } else {
9172         // This is a function template specialization.
9173         isFunctionTemplateSpecialization = true;
9174         // For source fidelity, store all the template param lists.
9175         if (TemplateParamLists.size() > 0)
9176           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9177 
9178         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9179         if (isFriend) {
9180           // We want to remove the "template<>", found here.
9181           SourceRange RemoveRange = TemplateParams->getSourceRange();
9182 
9183           // If we remove the template<> and the name is not a
9184           // template-id, we're actually silently creating a problem:
9185           // the friend declaration will refer to an untemplated decl,
9186           // and clearly the user wants a template specialization.  So
9187           // we need to insert '<>' after the name.
9188           SourceLocation InsertLoc;
9189           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9190             InsertLoc = D.getName().getSourceRange().getEnd();
9191             InsertLoc = getLocForEndOfToken(InsertLoc);
9192           }
9193 
9194           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9195             << Name << RemoveRange
9196             << FixItHint::CreateRemoval(RemoveRange)
9197             << FixItHint::CreateInsertion(InsertLoc, "<>");
9198         }
9199       }
9200     } else {
9201       // Check that we can declare a template here.
9202       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9203           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9204         NewFD->setInvalidDecl();
9205 
9206       // All template param lists were matched against the scope specifier:
9207       // this is NOT (an explicit specialization of) a template.
9208       if (TemplateParamLists.size() > 0)
9209         // For source fidelity, store all the template param lists.
9210         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9211     }
9212 
9213     if (Invalid) {
9214       NewFD->setInvalidDecl();
9215       if (FunctionTemplate)
9216         FunctionTemplate->setInvalidDecl();
9217     }
9218 
9219     // C++ [dcl.fct.spec]p5:
9220     //   The virtual specifier shall only be used in declarations of
9221     //   nonstatic class member functions that appear within a
9222     //   member-specification of a class declaration; see 10.3.
9223     //
9224     if (isVirtual && !NewFD->isInvalidDecl()) {
9225       if (!isVirtualOkay) {
9226         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9227              diag::err_virtual_non_function);
9228       } else if (!CurContext->isRecord()) {
9229         // 'virtual' was specified outside of the class.
9230         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9231              diag::err_virtual_out_of_class)
9232           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9233       } else if (NewFD->getDescribedFunctionTemplate()) {
9234         // C++ [temp.mem]p3:
9235         //  A member function template shall not be virtual.
9236         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9237              diag::err_virtual_member_function_template)
9238           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9239       } else {
9240         // Okay: Add virtual to the method.
9241         NewFD->setVirtualAsWritten(true);
9242       }
9243 
9244       if (getLangOpts().CPlusPlus14 &&
9245           NewFD->getReturnType()->isUndeducedType())
9246         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9247     }
9248 
9249     if (getLangOpts().CPlusPlus14 &&
9250         (NewFD->isDependentContext() ||
9251          (isFriend && CurContext->isDependentContext())) &&
9252         NewFD->getReturnType()->isUndeducedType()) {
9253       // If the function template is referenced directly (for instance, as a
9254       // member of the current instantiation), pretend it has a dependent type.
9255       // This is not really justified by the standard, but is the only sane
9256       // thing to do.
9257       // FIXME: For a friend function, we have not marked the function as being
9258       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9259       const FunctionProtoType *FPT =
9260           NewFD->getType()->castAs<FunctionProtoType>();
9261       QualType Result =
9262           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9263       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9264                                              FPT->getExtProtoInfo()));
9265     }
9266 
9267     // C++ [dcl.fct.spec]p3:
9268     //  The inline specifier shall not appear on a block scope function
9269     //  declaration.
9270     if (isInline && !NewFD->isInvalidDecl()) {
9271       if (CurContext->isFunctionOrMethod()) {
9272         // 'inline' is not allowed on block scope function declaration.
9273         Diag(D.getDeclSpec().getInlineSpecLoc(),
9274              diag::err_inline_declaration_block_scope) << Name
9275           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9276       }
9277     }
9278 
9279     // C++ [dcl.fct.spec]p6:
9280     //  The explicit specifier shall be used only in the declaration of a
9281     //  constructor or conversion function within its class definition;
9282     //  see 12.3.1 and 12.3.2.
9283     if (hasExplicit && !NewFD->isInvalidDecl() &&
9284         !isa<CXXDeductionGuideDecl>(NewFD)) {
9285       if (!CurContext->isRecord()) {
9286         // 'explicit' was specified outside of the class.
9287         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9288              diag::err_explicit_out_of_class)
9289             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9290       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9291                  !isa<CXXConversionDecl>(NewFD)) {
9292         // 'explicit' was specified on a function that wasn't a constructor
9293         // or conversion function.
9294         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9295              diag::err_explicit_non_ctor_or_conv_function)
9296             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9297       }
9298     }
9299 
9300     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9301     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9302       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9303       // are implicitly inline.
9304       NewFD->setImplicitlyInline();
9305 
9306       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9307       // be either constructors or to return a literal type. Therefore,
9308       // destructors cannot be declared constexpr.
9309       if (isa<CXXDestructorDecl>(NewFD) &&
9310           (!getLangOpts().CPlusPlus20 ||
9311            ConstexprKind == ConstexprSpecKind::Consteval)) {
9312         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9313             << static_cast<int>(ConstexprKind);
9314         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9315                                     ? ConstexprSpecKind::Unspecified
9316                                     : ConstexprSpecKind::Constexpr);
9317       }
9318       // C++20 [dcl.constexpr]p2: An allocation function, or a
9319       // deallocation function shall not be declared with the consteval
9320       // specifier.
9321       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9322           (NewFD->getOverloadedOperator() == OO_New ||
9323            NewFD->getOverloadedOperator() == OO_Array_New ||
9324            NewFD->getOverloadedOperator() == OO_Delete ||
9325            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9326         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9327              diag::err_invalid_consteval_decl_kind)
9328             << NewFD;
9329         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9330       }
9331     }
9332 
9333     // If __module_private__ was specified, mark the function accordingly.
9334     if (D.getDeclSpec().isModulePrivateSpecified()) {
9335       if (isFunctionTemplateSpecialization) {
9336         SourceLocation ModulePrivateLoc
9337           = D.getDeclSpec().getModulePrivateSpecLoc();
9338         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9339           << 0
9340           << FixItHint::CreateRemoval(ModulePrivateLoc);
9341       } else {
9342         NewFD->setModulePrivate();
9343         if (FunctionTemplate)
9344           FunctionTemplate->setModulePrivate();
9345       }
9346     }
9347 
9348     if (isFriend) {
9349       if (FunctionTemplate) {
9350         FunctionTemplate->setObjectOfFriendDecl();
9351         FunctionTemplate->setAccess(AS_public);
9352       }
9353       NewFD->setObjectOfFriendDecl();
9354       NewFD->setAccess(AS_public);
9355     }
9356 
9357     // If a function is defined as defaulted or deleted, mark it as such now.
9358     // We'll do the relevant checks on defaulted / deleted functions later.
9359     switch (D.getFunctionDefinitionKind()) {
9360     case FunctionDefinitionKind::Declaration:
9361     case FunctionDefinitionKind::Definition:
9362       break;
9363 
9364     case FunctionDefinitionKind::Defaulted:
9365       NewFD->setDefaulted();
9366       break;
9367 
9368     case FunctionDefinitionKind::Deleted:
9369       NewFD->setDeletedAsWritten();
9370       break;
9371     }
9372 
9373     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9374         D.isFunctionDefinition()) {
9375       // C++ [class.mfct]p2:
9376       //   A member function may be defined (8.4) in its class definition, in
9377       //   which case it is an inline member function (7.1.2)
9378       NewFD->setImplicitlyInline();
9379     }
9380 
9381     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9382         !CurContext->isRecord()) {
9383       // C++ [class.static]p1:
9384       //   A data or function member of a class may be declared static
9385       //   in a class definition, in which case it is a static member of
9386       //   the class.
9387 
9388       // Complain about the 'static' specifier if it's on an out-of-line
9389       // member function definition.
9390 
9391       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9392       // member function template declaration and class member template
9393       // declaration (MSVC versions before 2015), warn about this.
9394       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9395            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9396              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9397            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9398            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9399         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9400     }
9401 
9402     // C++11 [except.spec]p15:
9403     //   A deallocation function with no exception-specification is treated
9404     //   as if it were specified with noexcept(true).
9405     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9406     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9407          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9408         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9409       NewFD->setType(Context.getFunctionType(
9410           FPT->getReturnType(), FPT->getParamTypes(),
9411           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9412   }
9413 
9414   // Filter out previous declarations that don't match the scope.
9415   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9416                        D.getCXXScopeSpec().isNotEmpty() ||
9417                        isMemberSpecialization ||
9418                        isFunctionTemplateSpecialization);
9419 
9420   // Handle GNU asm-label extension (encoded as an attribute).
9421   if (Expr *E = (Expr*) D.getAsmLabel()) {
9422     // The parser guarantees this is a string.
9423     StringLiteral *SE = cast<StringLiteral>(E);
9424     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9425                                         /*IsLiteralLabel=*/true,
9426                                         SE->getStrTokenLoc(0)));
9427   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9428     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9429       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9430     if (I != ExtnameUndeclaredIdentifiers.end()) {
9431       if (isDeclExternC(NewFD)) {
9432         NewFD->addAttr(I->second);
9433         ExtnameUndeclaredIdentifiers.erase(I);
9434       } else
9435         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9436             << /*Variable*/0 << NewFD;
9437     }
9438   }
9439 
9440   // Copy the parameter declarations from the declarator D to the function
9441   // declaration NewFD, if they are available.  First scavenge them into Params.
9442   SmallVector<ParmVarDecl*, 16> Params;
9443   unsigned FTIIdx;
9444   if (D.isFunctionDeclarator(FTIIdx)) {
9445     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9446 
9447     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9448     // function that takes no arguments, not a function that takes a
9449     // single void argument.
9450     // We let through "const void" here because Sema::GetTypeForDeclarator
9451     // already checks for that case.
9452     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9453       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9454         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9455         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9456         Param->setDeclContext(NewFD);
9457         Params.push_back(Param);
9458 
9459         if (Param->isInvalidDecl())
9460           NewFD->setInvalidDecl();
9461       }
9462     }
9463 
9464     if (!getLangOpts().CPlusPlus) {
9465       // In C, find all the tag declarations from the prototype and move them
9466       // into the function DeclContext. Remove them from the surrounding tag
9467       // injection context of the function, which is typically but not always
9468       // the TU.
9469       DeclContext *PrototypeTagContext =
9470           getTagInjectionContext(NewFD->getLexicalDeclContext());
9471       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9472         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9473 
9474         // We don't want to reparent enumerators. Look at their parent enum
9475         // instead.
9476         if (!TD) {
9477           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9478             TD = cast<EnumDecl>(ECD->getDeclContext());
9479         }
9480         if (!TD)
9481           continue;
9482         DeclContext *TagDC = TD->getLexicalDeclContext();
9483         if (!TagDC->containsDecl(TD))
9484           continue;
9485         TagDC->removeDecl(TD);
9486         TD->setDeclContext(NewFD);
9487         NewFD->addDecl(TD);
9488 
9489         // Preserve the lexical DeclContext if it is not the surrounding tag
9490         // injection context of the FD. In this example, the semantic context of
9491         // E will be f and the lexical context will be S, while both the
9492         // semantic and lexical contexts of S will be f:
9493         //   void f(struct S { enum E { a } f; } s);
9494         if (TagDC != PrototypeTagContext)
9495           TD->setLexicalDeclContext(TagDC);
9496       }
9497     }
9498   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9499     // When we're declaring a function with a typedef, typeof, etc as in the
9500     // following example, we'll need to synthesize (unnamed)
9501     // parameters for use in the declaration.
9502     //
9503     // @code
9504     // typedef void fn(int);
9505     // fn f;
9506     // @endcode
9507 
9508     // Synthesize a parameter for each argument type.
9509     for (const auto &AI : FT->param_types()) {
9510       ParmVarDecl *Param =
9511           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9512       Param->setScopeInfo(0, Params.size());
9513       Params.push_back(Param);
9514     }
9515   } else {
9516     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9517            "Should not need args for typedef of non-prototype fn");
9518   }
9519 
9520   // Finally, we know we have the right number of parameters, install them.
9521   NewFD->setParams(Params);
9522 
9523   if (D.getDeclSpec().isNoreturnSpecified())
9524     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9525                                            D.getDeclSpec().getNoreturnSpecLoc(),
9526                                            AttributeCommonInfo::AS_Keyword));
9527 
9528   // Functions returning a variably modified type violate C99 6.7.5.2p2
9529   // because all functions have linkage.
9530   if (!NewFD->isInvalidDecl() &&
9531       NewFD->getReturnType()->isVariablyModifiedType()) {
9532     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9533     NewFD->setInvalidDecl();
9534   }
9535 
9536   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9537   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9538       !NewFD->hasAttr<SectionAttr>())
9539     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9540         Context, PragmaClangTextSection.SectionName,
9541         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9542 
9543   // Apply an implicit SectionAttr if #pragma code_seg is active.
9544   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9545       !NewFD->hasAttr<SectionAttr>()) {
9546     NewFD->addAttr(SectionAttr::CreateImplicit(
9547         Context, CodeSegStack.CurrentValue->getString(),
9548         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9549         SectionAttr::Declspec_allocate));
9550     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9551                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9552                          ASTContext::PSF_Read,
9553                      NewFD))
9554       NewFD->dropAttr<SectionAttr>();
9555   }
9556 
9557   // Apply an implicit CodeSegAttr from class declspec or
9558   // apply an implicit SectionAttr from #pragma code_seg if active.
9559   if (!NewFD->hasAttr<CodeSegAttr>()) {
9560     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9561                                                                  D.isFunctionDefinition())) {
9562       NewFD->addAttr(SAttr);
9563     }
9564   }
9565 
9566   // Handle attributes.
9567   ProcessDeclAttributes(S, NewFD, D);
9568 
9569   if (getLangOpts().OpenCL) {
9570     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9571     // type declaration will generate a compilation error.
9572     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9573     if (AddressSpace != LangAS::Default) {
9574       Diag(NewFD->getLocation(),
9575            diag::err_opencl_return_value_with_address_space);
9576       NewFD->setInvalidDecl();
9577     }
9578   }
9579 
9580   if (!getLangOpts().CPlusPlus) {
9581     // Perform semantic checking on the function declaration.
9582     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9583       CheckMain(NewFD, D.getDeclSpec());
9584 
9585     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9586       CheckMSVCRTEntryPoint(NewFD);
9587 
9588     if (!NewFD->isInvalidDecl())
9589       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9590                                                   isMemberSpecialization));
9591     else if (!Previous.empty())
9592       // Recover gracefully from an invalid redeclaration.
9593       D.setRedeclaration(true);
9594     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9595             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9596            "previous declaration set still overloaded");
9597 
9598     // Diagnose no-prototype function declarations with calling conventions that
9599     // don't support variadic calls. Only do this in C and do it after merging
9600     // possibly prototyped redeclarations.
9601     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9602     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9603       CallingConv CC = FT->getExtInfo().getCC();
9604       if (!supportsVariadicCall(CC)) {
9605         // Windows system headers sometimes accidentally use stdcall without
9606         // (void) parameters, so we relax this to a warning.
9607         int DiagID =
9608             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9609         Diag(NewFD->getLocation(), DiagID)
9610             << FunctionType::getNameForCallConv(CC);
9611       }
9612     }
9613 
9614    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9615        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9616      checkNonTrivialCUnion(NewFD->getReturnType(),
9617                            NewFD->getReturnTypeSourceRange().getBegin(),
9618                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9619   } else {
9620     // C++11 [replacement.functions]p3:
9621     //  The program's definitions shall not be specified as inline.
9622     //
9623     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9624     //
9625     // Suppress the diagnostic if the function is __attribute__((used)), since
9626     // that forces an external definition to be emitted.
9627     if (D.getDeclSpec().isInlineSpecified() &&
9628         NewFD->isReplaceableGlobalAllocationFunction() &&
9629         !NewFD->hasAttr<UsedAttr>())
9630       Diag(D.getDeclSpec().getInlineSpecLoc(),
9631            diag::ext_operator_new_delete_declared_inline)
9632         << NewFD->getDeclName();
9633 
9634     // If the declarator is a template-id, translate the parser's template
9635     // argument list into our AST format.
9636     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9637       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9638       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9639       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9640       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9641                                          TemplateId->NumArgs);
9642       translateTemplateArguments(TemplateArgsPtr,
9643                                  TemplateArgs);
9644 
9645       HasExplicitTemplateArgs = true;
9646 
9647       if (NewFD->isInvalidDecl()) {
9648         HasExplicitTemplateArgs = false;
9649       } else if (FunctionTemplate) {
9650         // Function template with explicit template arguments.
9651         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9652           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9653 
9654         HasExplicitTemplateArgs = false;
9655       } else {
9656         assert((isFunctionTemplateSpecialization ||
9657                 D.getDeclSpec().isFriendSpecified()) &&
9658                "should have a 'template<>' for this decl");
9659         // "friend void foo<>(int);" is an implicit specialization decl.
9660         isFunctionTemplateSpecialization = true;
9661       }
9662     } else if (isFriend && isFunctionTemplateSpecialization) {
9663       // This combination is only possible in a recovery case;  the user
9664       // wrote something like:
9665       //   template <> friend void foo(int);
9666       // which we're recovering from as if the user had written:
9667       //   friend void foo<>(int);
9668       // Go ahead and fake up a template id.
9669       HasExplicitTemplateArgs = true;
9670       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9671       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9672     }
9673 
9674     // We do not add HD attributes to specializations here because
9675     // they may have different constexpr-ness compared to their
9676     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9677     // may end up with different effective targets. Instead, a
9678     // specialization inherits its target attributes from its template
9679     // in the CheckFunctionTemplateSpecialization() call below.
9680     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9681       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9682 
9683     // If it's a friend (and only if it's a friend), it's possible
9684     // that either the specialized function type or the specialized
9685     // template is dependent, and therefore matching will fail.  In
9686     // this case, don't check the specialization yet.
9687     if (isFunctionTemplateSpecialization && isFriend &&
9688         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9689          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9690              TemplateArgs.arguments()))) {
9691       assert(HasExplicitTemplateArgs &&
9692              "friend function specialization without template args");
9693       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9694                                                        Previous))
9695         NewFD->setInvalidDecl();
9696     } else if (isFunctionTemplateSpecialization) {
9697       if (CurContext->isDependentContext() && CurContext->isRecord()
9698           && !isFriend) {
9699         isDependentClassScopeExplicitSpecialization = true;
9700       } else if (!NewFD->isInvalidDecl() &&
9701                  CheckFunctionTemplateSpecialization(
9702                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9703                      Previous))
9704         NewFD->setInvalidDecl();
9705 
9706       // C++ [dcl.stc]p1:
9707       //   A storage-class-specifier shall not be specified in an explicit
9708       //   specialization (14.7.3)
9709       FunctionTemplateSpecializationInfo *Info =
9710           NewFD->getTemplateSpecializationInfo();
9711       if (Info && SC != SC_None) {
9712         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9713           Diag(NewFD->getLocation(),
9714                diag::err_explicit_specialization_inconsistent_storage_class)
9715             << SC
9716             << FixItHint::CreateRemoval(
9717                                       D.getDeclSpec().getStorageClassSpecLoc());
9718 
9719         else
9720           Diag(NewFD->getLocation(),
9721                diag::ext_explicit_specialization_storage_class)
9722             << FixItHint::CreateRemoval(
9723                                       D.getDeclSpec().getStorageClassSpecLoc());
9724       }
9725     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9726       if (CheckMemberSpecialization(NewFD, Previous))
9727           NewFD->setInvalidDecl();
9728     }
9729 
9730     // Perform semantic checking on the function declaration.
9731     if (!isDependentClassScopeExplicitSpecialization) {
9732       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9733         CheckMain(NewFD, D.getDeclSpec());
9734 
9735       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9736         CheckMSVCRTEntryPoint(NewFD);
9737 
9738       if (!NewFD->isInvalidDecl())
9739         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9740                                                     isMemberSpecialization));
9741       else if (!Previous.empty())
9742         // Recover gracefully from an invalid redeclaration.
9743         D.setRedeclaration(true);
9744     }
9745 
9746     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9747             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9748            "previous declaration set still overloaded");
9749 
9750     NamedDecl *PrincipalDecl = (FunctionTemplate
9751                                 ? cast<NamedDecl>(FunctionTemplate)
9752                                 : NewFD);
9753 
9754     if (isFriend && NewFD->getPreviousDecl()) {
9755       AccessSpecifier Access = AS_public;
9756       if (!NewFD->isInvalidDecl())
9757         Access = NewFD->getPreviousDecl()->getAccess();
9758 
9759       NewFD->setAccess(Access);
9760       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9761     }
9762 
9763     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9764         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9765       PrincipalDecl->setNonMemberOperator();
9766 
9767     // If we have a function template, check the template parameter
9768     // list. This will check and merge default template arguments.
9769     if (FunctionTemplate) {
9770       FunctionTemplateDecl *PrevTemplate =
9771                                      FunctionTemplate->getPreviousDecl();
9772       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9773                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9774                                     : nullptr,
9775                             D.getDeclSpec().isFriendSpecified()
9776                               ? (D.isFunctionDefinition()
9777                                    ? TPC_FriendFunctionTemplateDefinition
9778                                    : TPC_FriendFunctionTemplate)
9779                               : (D.getCXXScopeSpec().isSet() &&
9780                                  DC && DC->isRecord() &&
9781                                  DC->isDependentContext())
9782                                   ? TPC_ClassTemplateMember
9783                                   : TPC_FunctionTemplate);
9784     }
9785 
9786     if (NewFD->isInvalidDecl()) {
9787       // Ignore all the rest of this.
9788     } else if (!D.isRedeclaration()) {
9789       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9790                                        AddToScope };
9791       // Fake up an access specifier if it's supposed to be a class member.
9792       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9793         NewFD->setAccess(AS_public);
9794 
9795       // Qualified decls generally require a previous declaration.
9796       if (D.getCXXScopeSpec().isSet()) {
9797         // ...with the major exception of templated-scope or
9798         // dependent-scope friend declarations.
9799 
9800         // TODO: we currently also suppress this check in dependent
9801         // contexts because (1) the parameter depth will be off when
9802         // matching friend templates and (2) we might actually be
9803         // selecting a friend based on a dependent factor.  But there
9804         // are situations where these conditions don't apply and we
9805         // can actually do this check immediately.
9806         //
9807         // Unless the scope is dependent, it's always an error if qualified
9808         // redeclaration lookup found nothing at all. Diagnose that now;
9809         // nothing will diagnose that error later.
9810         if (isFriend &&
9811             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9812              (!Previous.empty() && CurContext->isDependentContext()))) {
9813           // ignore these
9814         } else if (NewFD->isCPUDispatchMultiVersion() ||
9815                    NewFD->isCPUSpecificMultiVersion()) {
9816           // ignore this, we allow the redeclaration behavior here to create new
9817           // versions of the function.
9818         } else {
9819           // The user tried to provide an out-of-line definition for a
9820           // function that is a member of a class or namespace, but there
9821           // was no such member function declared (C++ [class.mfct]p2,
9822           // C++ [namespace.memdef]p2). For example:
9823           //
9824           // class X {
9825           //   void f() const;
9826           // };
9827           //
9828           // void X::f() { } // ill-formed
9829           //
9830           // Complain about this problem, and attempt to suggest close
9831           // matches (e.g., those that differ only in cv-qualifiers and
9832           // whether the parameter types are references).
9833 
9834           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9835                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9836             AddToScope = ExtraArgs.AddToScope;
9837             return Result;
9838           }
9839         }
9840 
9841         // Unqualified local friend declarations are required to resolve
9842         // to something.
9843       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9844         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9845                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9846           AddToScope = ExtraArgs.AddToScope;
9847           return Result;
9848         }
9849       }
9850     } else if (!D.isFunctionDefinition() &&
9851                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9852                !isFriend && !isFunctionTemplateSpecialization &&
9853                !isMemberSpecialization) {
9854       // An out-of-line member function declaration must also be a
9855       // definition (C++ [class.mfct]p2).
9856       // Note that this is not the case for explicit specializations of
9857       // function templates or member functions of class templates, per
9858       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9859       // extension for compatibility with old SWIG code which likes to
9860       // generate them.
9861       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9862         << D.getCXXScopeSpec().getRange();
9863     }
9864   }
9865 
9866   // If this is the first declaration of a library builtin function, add
9867   // attributes as appropriate.
9868   if (!D.isRedeclaration() &&
9869       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9870     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9871       if (unsigned BuiltinID = II->getBuiltinID()) {
9872         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9873           // Validate the type matches unless this builtin is specified as
9874           // matching regardless of its declared type.
9875           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9876             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9877           } else {
9878             ASTContext::GetBuiltinTypeError Error;
9879             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9880             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9881 
9882             if (!Error && !BuiltinType.isNull() &&
9883                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9884                     NewFD->getType(), BuiltinType))
9885               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9886           }
9887         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9888                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9889           // FIXME: We should consider this a builtin only in the std namespace.
9890           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9891         }
9892       }
9893     }
9894   }
9895 
9896   ProcessPragmaWeak(S, NewFD);
9897   checkAttributesAfterMerging(*this, *NewFD);
9898 
9899   AddKnownFunctionAttributes(NewFD);
9900 
9901   if (NewFD->hasAttr<OverloadableAttr>() &&
9902       !NewFD->getType()->getAs<FunctionProtoType>()) {
9903     Diag(NewFD->getLocation(),
9904          diag::err_attribute_overloadable_no_prototype)
9905       << NewFD;
9906 
9907     // Turn this into a variadic function with no parameters.
9908     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9909     FunctionProtoType::ExtProtoInfo EPI(
9910         Context.getDefaultCallingConvention(true, false));
9911     EPI.Variadic = true;
9912     EPI.ExtInfo = FT->getExtInfo();
9913 
9914     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9915     NewFD->setType(R);
9916   }
9917 
9918   // If there's a #pragma GCC visibility in scope, and this isn't a class
9919   // member, set the visibility of this function.
9920   if (!DC->isRecord() && NewFD->isExternallyVisible())
9921     AddPushedVisibilityAttribute(NewFD);
9922 
9923   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9924   // marking the function.
9925   AddCFAuditedAttribute(NewFD);
9926 
9927   // If this is a function definition, check if we have to apply optnone due to
9928   // a pragma.
9929   if(D.isFunctionDefinition())
9930     AddRangeBasedOptnone(NewFD);
9931 
9932   // If this is the first declaration of an extern C variable, update
9933   // the map of such variables.
9934   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9935       isIncompleteDeclExternC(*this, NewFD))
9936     RegisterLocallyScopedExternCDecl(NewFD, S);
9937 
9938   // Set this FunctionDecl's range up to the right paren.
9939   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9940 
9941   if (D.isRedeclaration() && !Previous.empty()) {
9942     NamedDecl *Prev = Previous.getRepresentativeDecl();
9943     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9944                                    isMemberSpecialization ||
9945                                        isFunctionTemplateSpecialization,
9946                                    D.isFunctionDefinition());
9947   }
9948 
9949   if (getLangOpts().CUDA) {
9950     IdentifierInfo *II = NewFD->getIdentifier();
9951     if (II && II->isStr(getCudaConfigureFuncName()) &&
9952         !NewFD->isInvalidDecl() &&
9953         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9954       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9955         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9956             << getCudaConfigureFuncName();
9957       Context.setcudaConfigureCallDecl(NewFD);
9958     }
9959 
9960     // Variadic functions, other than a *declaration* of printf, are not allowed
9961     // in device-side CUDA code, unless someone passed
9962     // -fcuda-allow-variadic-functions.
9963     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9964         (NewFD->hasAttr<CUDADeviceAttr>() ||
9965          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9966         !(II && II->isStr("printf") && NewFD->isExternC() &&
9967           !D.isFunctionDefinition())) {
9968       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9969     }
9970   }
9971 
9972   MarkUnusedFileScopedDecl(NewFD);
9973 
9974 
9975 
9976   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9977     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9978     if (SC == SC_Static) {
9979       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9980       D.setInvalidType();
9981     }
9982 
9983     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9984     if (!NewFD->getReturnType()->isVoidType()) {
9985       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9986       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9987           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9988                                 : FixItHint());
9989       D.setInvalidType();
9990     }
9991 
9992     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9993     for (auto Param : NewFD->parameters())
9994       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9995 
9996     if (getLangOpts().OpenCLCPlusPlus) {
9997       if (DC->isRecord()) {
9998         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9999         D.setInvalidType();
10000       }
10001       if (FunctionTemplate) {
10002         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10003         D.setInvalidType();
10004       }
10005     }
10006   }
10007 
10008   if (getLangOpts().CPlusPlus) {
10009     if (FunctionTemplate) {
10010       if (NewFD->isInvalidDecl())
10011         FunctionTemplate->setInvalidDecl();
10012       return FunctionTemplate;
10013     }
10014 
10015     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10016       CompleteMemberSpecialization(NewFD, Previous);
10017   }
10018 
10019   for (const ParmVarDecl *Param : NewFD->parameters()) {
10020     QualType PT = Param->getType();
10021 
10022     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10023     // types.
10024     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10025       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10026         QualType ElemTy = PipeTy->getElementType();
10027           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10028             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10029             D.setInvalidType();
10030           }
10031       }
10032     }
10033   }
10034 
10035   // Here we have an function template explicit specialization at class scope.
10036   // The actual specialization will be postponed to template instatiation
10037   // time via the ClassScopeFunctionSpecializationDecl node.
10038   if (isDependentClassScopeExplicitSpecialization) {
10039     ClassScopeFunctionSpecializationDecl *NewSpec =
10040                          ClassScopeFunctionSpecializationDecl::Create(
10041                                 Context, CurContext, NewFD->getLocation(),
10042                                 cast<CXXMethodDecl>(NewFD),
10043                                 HasExplicitTemplateArgs, TemplateArgs);
10044     CurContext->addDecl(NewSpec);
10045     AddToScope = false;
10046   }
10047 
10048   // Diagnose availability attributes. Availability cannot be used on functions
10049   // that are run during load/unload.
10050   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10051     if (NewFD->hasAttr<ConstructorAttr>()) {
10052       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10053           << 1;
10054       NewFD->dropAttr<AvailabilityAttr>();
10055     }
10056     if (NewFD->hasAttr<DestructorAttr>()) {
10057       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10058           << 2;
10059       NewFD->dropAttr<AvailabilityAttr>();
10060     }
10061   }
10062 
10063   // Diagnose no_builtin attribute on function declaration that are not a
10064   // definition.
10065   // FIXME: We should really be doing this in
10066   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10067   // the FunctionDecl and at this point of the code
10068   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10069   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10070   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10071     switch (D.getFunctionDefinitionKind()) {
10072     case FunctionDefinitionKind::Defaulted:
10073     case FunctionDefinitionKind::Deleted:
10074       Diag(NBA->getLocation(),
10075            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10076           << NBA->getSpelling();
10077       break;
10078     case FunctionDefinitionKind::Declaration:
10079       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10080           << NBA->getSpelling();
10081       break;
10082     case FunctionDefinitionKind::Definition:
10083       break;
10084     }
10085 
10086   return NewFD;
10087 }
10088 
10089 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10090 /// when __declspec(code_seg) "is applied to a class, all member functions of
10091 /// the class and nested classes -- this includes compiler-generated special
10092 /// member functions -- are put in the specified segment."
10093 /// The actual behavior is a little more complicated. The Microsoft compiler
10094 /// won't check outer classes if there is an active value from #pragma code_seg.
10095 /// The CodeSeg is always applied from the direct parent but only from outer
10096 /// classes when the #pragma code_seg stack is empty. See:
10097 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10098 /// available since MS has removed the page.
10099 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10100   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10101   if (!Method)
10102     return nullptr;
10103   const CXXRecordDecl *Parent = Method->getParent();
10104   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10105     Attr *NewAttr = SAttr->clone(S.getASTContext());
10106     NewAttr->setImplicit(true);
10107     return NewAttr;
10108   }
10109 
10110   // The Microsoft compiler won't check outer classes for the CodeSeg
10111   // when the #pragma code_seg stack is active.
10112   if (S.CodeSegStack.CurrentValue)
10113    return nullptr;
10114 
10115   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10116     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10117       Attr *NewAttr = SAttr->clone(S.getASTContext());
10118       NewAttr->setImplicit(true);
10119       return NewAttr;
10120     }
10121   }
10122   return nullptr;
10123 }
10124 
10125 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10126 /// containing class. Otherwise it will return implicit SectionAttr if the
10127 /// function is a definition and there is an active value on CodeSegStack
10128 /// (from the current #pragma code-seg value).
10129 ///
10130 /// \param FD Function being declared.
10131 /// \param IsDefinition Whether it is a definition or just a declarartion.
10132 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10133 ///          nullptr if no attribute should be added.
10134 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10135                                                        bool IsDefinition) {
10136   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10137     return A;
10138   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10139       CodeSegStack.CurrentValue)
10140     return SectionAttr::CreateImplicit(
10141         getASTContext(), CodeSegStack.CurrentValue->getString(),
10142         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10143         SectionAttr::Declspec_allocate);
10144   return nullptr;
10145 }
10146 
10147 /// Determines if we can perform a correct type check for \p D as a
10148 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10149 /// best-effort check.
10150 ///
10151 /// \param NewD The new declaration.
10152 /// \param OldD The old declaration.
10153 /// \param NewT The portion of the type of the new declaration to check.
10154 /// \param OldT The portion of the type of the old declaration to check.
10155 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10156                                           QualType NewT, QualType OldT) {
10157   if (!NewD->getLexicalDeclContext()->isDependentContext())
10158     return true;
10159 
10160   // For dependently-typed local extern declarations and friends, we can't
10161   // perform a correct type check in general until instantiation:
10162   //
10163   //   int f();
10164   //   template<typename T> void g() { T f(); }
10165   //
10166   // (valid if g() is only instantiated with T = int).
10167   if (NewT->isDependentType() &&
10168       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10169     return false;
10170 
10171   // Similarly, if the previous declaration was a dependent local extern
10172   // declaration, we don't really know its type yet.
10173   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10174     return false;
10175 
10176   return true;
10177 }
10178 
10179 /// Checks if the new declaration declared in dependent context must be
10180 /// put in the same redeclaration chain as the specified declaration.
10181 ///
10182 /// \param D Declaration that is checked.
10183 /// \param PrevDecl Previous declaration found with proper lookup method for the
10184 ///                 same declaration name.
10185 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10186 ///          belongs to.
10187 ///
10188 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10189   if (!D->getLexicalDeclContext()->isDependentContext())
10190     return true;
10191 
10192   // Don't chain dependent friend function definitions until instantiation, to
10193   // permit cases like
10194   //
10195   //   void func();
10196   //   template<typename T> class C1 { friend void func() {} };
10197   //   template<typename T> class C2 { friend void func() {} };
10198   //
10199   // ... which is valid if only one of C1 and C2 is ever instantiated.
10200   //
10201   // FIXME: This need only apply to function definitions. For now, we proxy
10202   // this by checking for a file-scope function. We do not want this to apply
10203   // to friend declarations nominating member functions, because that gets in
10204   // the way of access checks.
10205   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10206     return false;
10207 
10208   auto *VD = dyn_cast<ValueDecl>(D);
10209   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10210   return !VD || !PrevVD ||
10211          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10212                                         PrevVD->getType());
10213 }
10214 
10215 /// Check the target attribute of the function for MultiVersion
10216 /// validity.
10217 ///
10218 /// Returns true if there was an error, false otherwise.
10219 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10220   const auto *TA = FD->getAttr<TargetAttr>();
10221   assert(TA && "MultiVersion Candidate requires a target attribute");
10222   ParsedTargetAttr ParseInfo = TA->parse();
10223   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10224   enum ErrType { Feature = 0, Architecture = 1 };
10225 
10226   if (!ParseInfo.Architecture.empty() &&
10227       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10228     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10229         << Architecture << ParseInfo.Architecture;
10230     return true;
10231   }
10232 
10233   for (const auto &Feat : ParseInfo.Features) {
10234     auto BareFeat = StringRef{Feat}.substr(1);
10235     if (Feat[0] == '-') {
10236       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10237           << Feature << ("no-" + BareFeat).str();
10238       return true;
10239     }
10240 
10241     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10242         !TargetInfo.isValidFeatureName(BareFeat)) {
10243       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10244           << Feature << BareFeat;
10245       return true;
10246     }
10247   }
10248   return false;
10249 }
10250 
10251 // Provide a white-list of attributes that are allowed to be combined with
10252 // multiversion functions.
10253 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10254                                            MultiVersionKind MVType) {
10255   // Note: this list/diagnosis must match the list in
10256   // checkMultiversionAttributesAllSame.
10257   switch (Kind) {
10258   default:
10259     return false;
10260   case attr::Used:
10261     return MVType == MultiVersionKind::Target;
10262   case attr::NonNull:
10263   case attr::NoThrow:
10264     return true;
10265   }
10266 }
10267 
10268 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10269                                                  const FunctionDecl *FD,
10270                                                  const FunctionDecl *CausedFD,
10271                                                  MultiVersionKind MVType) {
10272   bool IsCPUSpecificCPUDispatchMVType =
10273       MVType == MultiVersionKind::CPUDispatch ||
10274       MVType == MultiVersionKind::CPUSpecific;
10275   const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10276                             Sema &S, const Attr *A) {
10277     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10278         << IsCPUSpecificCPUDispatchMVType << A;
10279     if (CausedFD)
10280       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10281     return true;
10282   };
10283 
10284   for (const Attr *A : FD->attrs()) {
10285     switch (A->getKind()) {
10286     case attr::CPUDispatch:
10287     case attr::CPUSpecific:
10288       if (MVType != MultiVersionKind::CPUDispatch &&
10289           MVType != MultiVersionKind::CPUSpecific)
10290         return Diagnose(S, A);
10291       break;
10292     case attr::Target:
10293       if (MVType != MultiVersionKind::Target)
10294         return Diagnose(S, A);
10295       break;
10296     default:
10297       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10298         return Diagnose(S, A);
10299       break;
10300     }
10301   }
10302   return false;
10303 }
10304 
10305 bool Sema::areMultiversionVariantFunctionsCompatible(
10306     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10307     const PartialDiagnostic &NoProtoDiagID,
10308     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10309     const PartialDiagnosticAt &NoSupportDiagIDAt,
10310     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10311     bool ConstexprSupported, bool CLinkageMayDiffer) {
10312   enum DoesntSupport {
10313     FuncTemplates = 0,
10314     VirtFuncs = 1,
10315     DeducedReturn = 2,
10316     Constructors = 3,
10317     Destructors = 4,
10318     DeletedFuncs = 5,
10319     DefaultedFuncs = 6,
10320     ConstexprFuncs = 7,
10321     ConstevalFuncs = 8,
10322   };
10323   enum Different {
10324     CallingConv = 0,
10325     ReturnType = 1,
10326     ConstexprSpec = 2,
10327     InlineSpec = 3,
10328     Linkage = 4,
10329     LanguageLinkage = 5,
10330   };
10331 
10332   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10333       !OldFD->getType()->getAs<FunctionProtoType>()) {
10334     Diag(OldFD->getLocation(), NoProtoDiagID);
10335     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10336     return true;
10337   }
10338 
10339   if (NoProtoDiagID.getDiagID() != 0 &&
10340       !NewFD->getType()->getAs<FunctionProtoType>())
10341     return Diag(NewFD->getLocation(), NoProtoDiagID);
10342 
10343   if (!TemplatesSupported &&
10344       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10345     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10346            << FuncTemplates;
10347 
10348   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10349     if (NewCXXFD->isVirtual())
10350       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10351              << VirtFuncs;
10352 
10353     if (isa<CXXConstructorDecl>(NewCXXFD))
10354       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10355              << Constructors;
10356 
10357     if (isa<CXXDestructorDecl>(NewCXXFD))
10358       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10359              << Destructors;
10360   }
10361 
10362   if (NewFD->isDeleted())
10363     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10364            << DeletedFuncs;
10365 
10366   if (NewFD->isDefaulted())
10367     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10368            << DefaultedFuncs;
10369 
10370   if (!ConstexprSupported && NewFD->isConstexpr())
10371     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10372            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10373 
10374   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10375   const auto *NewType = cast<FunctionType>(NewQType);
10376   QualType NewReturnType = NewType->getReturnType();
10377 
10378   if (NewReturnType->isUndeducedType())
10379     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10380            << DeducedReturn;
10381 
10382   // Ensure the return type is identical.
10383   if (OldFD) {
10384     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10385     const auto *OldType = cast<FunctionType>(OldQType);
10386     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10387     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10388 
10389     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10390       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10391 
10392     QualType OldReturnType = OldType->getReturnType();
10393 
10394     if (OldReturnType != NewReturnType)
10395       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10396 
10397     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10398       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10399 
10400     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10401       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10402 
10403     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10404       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10405 
10406     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10407       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10408 
10409     if (CheckEquivalentExceptionSpec(
10410             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10411             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10412       return true;
10413   }
10414   return false;
10415 }
10416 
10417 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10418                                              const FunctionDecl *NewFD,
10419                                              bool CausesMV,
10420                                              MultiVersionKind MVType) {
10421   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10422     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10423     if (OldFD)
10424       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10425     return true;
10426   }
10427 
10428   bool IsCPUSpecificCPUDispatchMVType =
10429       MVType == MultiVersionKind::CPUDispatch ||
10430       MVType == MultiVersionKind::CPUSpecific;
10431 
10432   if (CausesMV && OldFD &&
10433       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10434     return true;
10435 
10436   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10437     return true;
10438 
10439   // Only allow transition to MultiVersion if it hasn't been used.
10440   if (OldFD && CausesMV && OldFD->isUsed(false))
10441     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10442 
10443   return S.areMultiversionVariantFunctionsCompatible(
10444       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10445       PartialDiagnosticAt(NewFD->getLocation(),
10446                           S.PDiag(diag::note_multiversioning_caused_here)),
10447       PartialDiagnosticAt(NewFD->getLocation(),
10448                           S.PDiag(diag::err_multiversion_doesnt_support)
10449                               << IsCPUSpecificCPUDispatchMVType),
10450       PartialDiagnosticAt(NewFD->getLocation(),
10451                           S.PDiag(diag::err_multiversion_diff)),
10452       /*TemplatesSupported=*/false,
10453       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10454       /*CLinkageMayDiffer=*/false);
10455 }
10456 
10457 /// Check the validity of a multiversion function declaration that is the
10458 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10459 ///
10460 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10461 ///
10462 /// Returns true if there was an error, false otherwise.
10463 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10464                                            MultiVersionKind MVType,
10465                                            const TargetAttr *TA) {
10466   assert(MVType != MultiVersionKind::None &&
10467          "Function lacks multiversion attribute");
10468 
10469   // Target only causes MV if it is default, otherwise this is a normal
10470   // function.
10471   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10472     return false;
10473 
10474   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10475     FD->setInvalidDecl();
10476     return true;
10477   }
10478 
10479   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10480     FD->setInvalidDecl();
10481     return true;
10482   }
10483 
10484   FD->setIsMultiVersion();
10485   return false;
10486 }
10487 
10488 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10489   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10490     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10491       return true;
10492   }
10493 
10494   return false;
10495 }
10496 
10497 static bool CheckTargetCausesMultiVersioning(
10498     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10499     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10500     LookupResult &Previous) {
10501   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10502   ParsedTargetAttr NewParsed = NewTA->parse();
10503   // Sort order doesn't matter, it just needs to be consistent.
10504   llvm::sort(NewParsed.Features);
10505 
10506   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10507   // to change, this is a simple redeclaration.
10508   if (!NewTA->isDefaultVersion() &&
10509       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10510     return false;
10511 
10512   // Otherwise, this decl causes MultiVersioning.
10513   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10514     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10515     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10516     NewFD->setInvalidDecl();
10517     return true;
10518   }
10519 
10520   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10521                                        MultiVersionKind::Target)) {
10522     NewFD->setInvalidDecl();
10523     return true;
10524   }
10525 
10526   if (CheckMultiVersionValue(S, NewFD)) {
10527     NewFD->setInvalidDecl();
10528     return true;
10529   }
10530 
10531   // If this is 'default', permit the forward declaration.
10532   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10533     Redeclaration = true;
10534     OldDecl = OldFD;
10535     OldFD->setIsMultiVersion();
10536     NewFD->setIsMultiVersion();
10537     return false;
10538   }
10539 
10540   if (CheckMultiVersionValue(S, OldFD)) {
10541     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10542     NewFD->setInvalidDecl();
10543     return true;
10544   }
10545 
10546   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10547 
10548   if (OldParsed == NewParsed) {
10549     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10550     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10551     NewFD->setInvalidDecl();
10552     return true;
10553   }
10554 
10555   for (const auto *FD : OldFD->redecls()) {
10556     const auto *CurTA = FD->getAttr<TargetAttr>();
10557     // We allow forward declarations before ANY multiversioning attributes, but
10558     // nothing after the fact.
10559     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10560         (!CurTA || CurTA->isInherited())) {
10561       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10562           << 0;
10563       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10564       NewFD->setInvalidDecl();
10565       return true;
10566     }
10567   }
10568 
10569   OldFD->setIsMultiVersion();
10570   NewFD->setIsMultiVersion();
10571   Redeclaration = false;
10572   MergeTypeWithPrevious = false;
10573   OldDecl = nullptr;
10574   Previous.clear();
10575   return false;
10576 }
10577 
10578 /// Check the validity of a new function declaration being added to an existing
10579 /// multiversioned declaration collection.
10580 static bool CheckMultiVersionAdditionalDecl(
10581     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10582     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10583     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10584     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10585     LookupResult &Previous) {
10586 
10587   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10588   // Disallow mixing of multiversioning types.
10589   if ((OldMVType == MultiVersionKind::Target &&
10590        NewMVType != MultiVersionKind::Target) ||
10591       (NewMVType == MultiVersionKind::Target &&
10592        OldMVType != MultiVersionKind::Target)) {
10593     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10594     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10595     NewFD->setInvalidDecl();
10596     return true;
10597   }
10598 
10599   ParsedTargetAttr NewParsed;
10600   if (NewTA) {
10601     NewParsed = NewTA->parse();
10602     llvm::sort(NewParsed.Features);
10603   }
10604 
10605   bool UseMemberUsingDeclRules =
10606       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10607 
10608   // Next, check ALL non-overloads to see if this is a redeclaration of a
10609   // previous member of the MultiVersion set.
10610   for (NamedDecl *ND : Previous) {
10611     FunctionDecl *CurFD = ND->getAsFunction();
10612     if (!CurFD)
10613       continue;
10614     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10615       continue;
10616 
10617     if (NewMVType == MultiVersionKind::Target) {
10618       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10619       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10620         NewFD->setIsMultiVersion();
10621         Redeclaration = true;
10622         OldDecl = ND;
10623         return false;
10624       }
10625 
10626       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10627       if (CurParsed == NewParsed) {
10628         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10629         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10630         NewFD->setInvalidDecl();
10631         return true;
10632       }
10633     } else {
10634       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10635       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10636       // Handle CPUDispatch/CPUSpecific versions.
10637       // Only 1 CPUDispatch function is allowed, this will make it go through
10638       // the redeclaration errors.
10639       if (NewMVType == MultiVersionKind::CPUDispatch &&
10640           CurFD->hasAttr<CPUDispatchAttr>()) {
10641         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10642             std::equal(
10643                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10644                 NewCPUDisp->cpus_begin(),
10645                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10646                   return Cur->getName() == New->getName();
10647                 })) {
10648           NewFD->setIsMultiVersion();
10649           Redeclaration = true;
10650           OldDecl = ND;
10651           return false;
10652         }
10653 
10654         // If the declarations don't match, this is an error condition.
10655         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10656         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10657         NewFD->setInvalidDecl();
10658         return true;
10659       }
10660       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10661 
10662         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10663             std::equal(
10664                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10665                 NewCPUSpec->cpus_begin(),
10666                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10667                   return Cur->getName() == New->getName();
10668                 })) {
10669           NewFD->setIsMultiVersion();
10670           Redeclaration = true;
10671           OldDecl = ND;
10672           return false;
10673         }
10674 
10675         // Only 1 version of CPUSpecific is allowed for each CPU.
10676         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10677           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10678             if (CurII == NewII) {
10679               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10680                   << NewII;
10681               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10682               NewFD->setInvalidDecl();
10683               return true;
10684             }
10685           }
10686         }
10687       }
10688       // If the two decls aren't the same MVType, there is no possible error
10689       // condition.
10690     }
10691   }
10692 
10693   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10694   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10695   // handled in the attribute adding step.
10696   if (NewMVType == MultiVersionKind::Target &&
10697       CheckMultiVersionValue(S, NewFD)) {
10698     NewFD->setInvalidDecl();
10699     return true;
10700   }
10701 
10702   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10703                                        !OldFD->isMultiVersion(), NewMVType)) {
10704     NewFD->setInvalidDecl();
10705     return true;
10706   }
10707 
10708   // Permit forward declarations in the case where these two are compatible.
10709   if (!OldFD->isMultiVersion()) {
10710     OldFD->setIsMultiVersion();
10711     NewFD->setIsMultiVersion();
10712     Redeclaration = true;
10713     OldDecl = OldFD;
10714     return false;
10715   }
10716 
10717   NewFD->setIsMultiVersion();
10718   Redeclaration = false;
10719   MergeTypeWithPrevious = false;
10720   OldDecl = nullptr;
10721   Previous.clear();
10722   return false;
10723 }
10724 
10725 
10726 /// Check the validity of a mulitversion function declaration.
10727 /// Also sets the multiversion'ness' of the function itself.
10728 ///
10729 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10730 ///
10731 /// Returns true if there was an error, false otherwise.
10732 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10733                                       bool &Redeclaration, NamedDecl *&OldDecl,
10734                                       bool &MergeTypeWithPrevious,
10735                                       LookupResult &Previous) {
10736   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10737   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10738   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10739 
10740   // Mixing Multiversioning types is prohibited.
10741   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10742       (NewCPUDisp && NewCPUSpec)) {
10743     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10744     NewFD->setInvalidDecl();
10745     return true;
10746   }
10747 
10748   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
10749 
10750   // Main isn't allowed to become a multiversion function, however it IS
10751   // permitted to have 'main' be marked with the 'target' optimization hint.
10752   if (NewFD->isMain()) {
10753     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10754         MVType == MultiVersionKind::CPUDispatch ||
10755         MVType == MultiVersionKind::CPUSpecific) {
10756       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10757       NewFD->setInvalidDecl();
10758       return true;
10759     }
10760     return false;
10761   }
10762 
10763   if (!OldDecl || !OldDecl->getAsFunction() ||
10764       OldDecl->getDeclContext()->getRedeclContext() !=
10765           NewFD->getDeclContext()->getRedeclContext()) {
10766     // If there's no previous declaration, AND this isn't attempting to cause
10767     // multiversioning, this isn't an error condition.
10768     if (MVType == MultiVersionKind::None)
10769       return false;
10770     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10771   }
10772 
10773   FunctionDecl *OldFD = OldDecl->getAsFunction();
10774 
10775   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10776     return false;
10777 
10778   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10779     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10780         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10781     NewFD->setInvalidDecl();
10782     return true;
10783   }
10784 
10785   // Handle the target potentially causes multiversioning case.
10786   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10787     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10788                                             Redeclaration, OldDecl,
10789                                             MergeTypeWithPrevious, Previous);
10790 
10791   // At this point, we have a multiversion function decl (in OldFD) AND an
10792   // appropriate attribute in the current function decl.  Resolve that these are
10793   // still compatible with previous declarations.
10794   return CheckMultiVersionAdditionalDecl(
10795       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10796       OldDecl, MergeTypeWithPrevious, Previous);
10797 }
10798 
10799 /// Perform semantic checking of a new function declaration.
10800 ///
10801 /// Performs semantic analysis of the new function declaration
10802 /// NewFD. This routine performs all semantic checking that does not
10803 /// require the actual declarator involved in the declaration, and is
10804 /// used both for the declaration of functions as they are parsed
10805 /// (called via ActOnDeclarator) and for the declaration of functions
10806 /// that have been instantiated via C++ template instantiation (called
10807 /// via InstantiateDecl).
10808 ///
10809 /// \param IsMemberSpecialization whether this new function declaration is
10810 /// a member specialization (that replaces any definition provided by the
10811 /// previous declaration).
10812 ///
10813 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10814 ///
10815 /// \returns true if the function declaration is a redeclaration.
10816 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10817                                     LookupResult &Previous,
10818                                     bool IsMemberSpecialization) {
10819   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10820          "Variably modified return types are not handled here");
10821 
10822   // Determine whether the type of this function should be merged with
10823   // a previous visible declaration. This never happens for functions in C++,
10824   // and always happens in C if the previous declaration was visible.
10825   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10826                                !Previous.isShadowed();
10827 
10828   bool Redeclaration = false;
10829   NamedDecl *OldDecl = nullptr;
10830   bool MayNeedOverloadableChecks = false;
10831 
10832   // Merge or overload the declaration with an existing declaration of
10833   // the same name, if appropriate.
10834   if (!Previous.empty()) {
10835     // Determine whether NewFD is an overload of PrevDecl or
10836     // a declaration that requires merging. If it's an overload,
10837     // there's no more work to do here; we'll just add the new
10838     // function to the scope.
10839     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10840       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10841       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10842         Redeclaration = true;
10843         OldDecl = Candidate;
10844       }
10845     } else {
10846       MayNeedOverloadableChecks = true;
10847       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10848                             /*NewIsUsingDecl*/ false)) {
10849       case Ovl_Match:
10850         Redeclaration = true;
10851         break;
10852 
10853       case Ovl_NonFunction:
10854         Redeclaration = true;
10855         break;
10856 
10857       case Ovl_Overload:
10858         Redeclaration = false;
10859         break;
10860       }
10861     }
10862   }
10863 
10864   // Check for a previous extern "C" declaration with this name.
10865   if (!Redeclaration &&
10866       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10867     if (!Previous.empty()) {
10868       // This is an extern "C" declaration with the same name as a previous
10869       // declaration, and thus redeclares that entity...
10870       Redeclaration = true;
10871       OldDecl = Previous.getFoundDecl();
10872       MergeTypeWithPrevious = false;
10873 
10874       // ... except in the presence of __attribute__((overloadable)).
10875       if (OldDecl->hasAttr<OverloadableAttr>() ||
10876           NewFD->hasAttr<OverloadableAttr>()) {
10877         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10878           MayNeedOverloadableChecks = true;
10879           Redeclaration = false;
10880           OldDecl = nullptr;
10881         }
10882       }
10883     }
10884   }
10885 
10886   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10887                                 MergeTypeWithPrevious, Previous))
10888     return Redeclaration;
10889 
10890   // PPC MMA non-pointer types are not allowed as function return types.
10891   if (Context.getTargetInfo().getTriple().isPPC64() &&
10892       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10893     NewFD->setInvalidDecl();
10894   }
10895 
10896   // C++11 [dcl.constexpr]p8:
10897   //   A constexpr specifier for a non-static member function that is not
10898   //   a constructor declares that member function to be const.
10899   //
10900   // This needs to be delayed until we know whether this is an out-of-line
10901   // definition of a static member function.
10902   //
10903   // This rule is not present in C++1y, so we produce a backwards
10904   // compatibility warning whenever it happens in C++11.
10905   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10906   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10907       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10908       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10909     CXXMethodDecl *OldMD = nullptr;
10910     if (OldDecl)
10911       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10912     if (!OldMD || !OldMD->isStatic()) {
10913       const FunctionProtoType *FPT =
10914         MD->getType()->castAs<FunctionProtoType>();
10915       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10916       EPI.TypeQuals.addConst();
10917       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10918                                           FPT->getParamTypes(), EPI));
10919 
10920       // Warn that we did this, if we're not performing template instantiation.
10921       // In that case, we'll have warned already when the template was defined.
10922       if (!inTemplateInstantiation()) {
10923         SourceLocation AddConstLoc;
10924         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10925                 .IgnoreParens().getAs<FunctionTypeLoc>())
10926           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10927 
10928         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10929           << FixItHint::CreateInsertion(AddConstLoc, " const");
10930       }
10931     }
10932   }
10933 
10934   if (Redeclaration) {
10935     // NewFD and OldDecl represent declarations that need to be
10936     // merged.
10937     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10938       NewFD->setInvalidDecl();
10939       return Redeclaration;
10940     }
10941 
10942     Previous.clear();
10943     Previous.addDecl(OldDecl);
10944 
10945     if (FunctionTemplateDecl *OldTemplateDecl =
10946             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10947       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10948       FunctionTemplateDecl *NewTemplateDecl
10949         = NewFD->getDescribedFunctionTemplate();
10950       assert(NewTemplateDecl && "Template/non-template mismatch");
10951 
10952       // The call to MergeFunctionDecl above may have created some state in
10953       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10954       // can add it as a redeclaration.
10955       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10956 
10957       NewFD->setPreviousDeclaration(OldFD);
10958       if (NewFD->isCXXClassMember()) {
10959         NewFD->setAccess(OldTemplateDecl->getAccess());
10960         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10961       }
10962 
10963       // If this is an explicit specialization of a member that is a function
10964       // template, mark it as a member specialization.
10965       if (IsMemberSpecialization &&
10966           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10967         NewTemplateDecl->setMemberSpecialization();
10968         assert(OldTemplateDecl->isMemberSpecialization());
10969         // Explicit specializations of a member template do not inherit deleted
10970         // status from the parent member template that they are specializing.
10971         if (OldFD->isDeleted()) {
10972           // FIXME: This assert will not hold in the presence of modules.
10973           assert(OldFD->getCanonicalDecl() == OldFD);
10974           // FIXME: We need an update record for this AST mutation.
10975           OldFD->setDeletedAsWritten(false);
10976         }
10977       }
10978 
10979     } else {
10980       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10981         auto *OldFD = cast<FunctionDecl>(OldDecl);
10982         // This needs to happen first so that 'inline' propagates.
10983         NewFD->setPreviousDeclaration(OldFD);
10984         if (NewFD->isCXXClassMember())
10985           NewFD->setAccess(OldFD->getAccess());
10986       }
10987     }
10988   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10989              !NewFD->getAttr<OverloadableAttr>()) {
10990     assert((Previous.empty() ||
10991             llvm::any_of(Previous,
10992                          [](const NamedDecl *ND) {
10993                            return ND->hasAttr<OverloadableAttr>();
10994                          })) &&
10995            "Non-redecls shouldn't happen without overloadable present");
10996 
10997     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10998       const auto *FD = dyn_cast<FunctionDecl>(ND);
10999       return FD && !FD->hasAttr<OverloadableAttr>();
11000     });
11001 
11002     if (OtherUnmarkedIter != Previous.end()) {
11003       Diag(NewFD->getLocation(),
11004            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11005       Diag((*OtherUnmarkedIter)->getLocation(),
11006            diag::note_attribute_overloadable_prev_overload)
11007           << false;
11008 
11009       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11010     }
11011   }
11012 
11013   if (LangOpts.OpenMP)
11014     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11015 
11016   // Semantic checking for this function declaration (in isolation).
11017 
11018   if (getLangOpts().CPlusPlus) {
11019     // C++-specific checks.
11020     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11021       CheckConstructor(Constructor);
11022     } else if (CXXDestructorDecl *Destructor =
11023                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11024       CXXRecordDecl *Record = Destructor->getParent();
11025       QualType ClassType = Context.getTypeDeclType(Record);
11026 
11027       // FIXME: Shouldn't we be able to perform this check even when the class
11028       // type is dependent? Both gcc and edg can handle that.
11029       if (!ClassType->isDependentType()) {
11030         DeclarationName Name
11031           = Context.DeclarationNames.getCXXDestructorName(
11032                                         Context.getCanonicalType(ClassType));
11033         if (NewFD->getDeclName() != Name) {
11034           Diag(NewFD->getLocation(), diag::err_destructor_name);
11035           NewFD->setInvalidDecl();
11036           return Redeclaration;
11037         }
11038       }
11039     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11040       if (auto *TD = Guide->getDescribedFunctionTemplate())
11041         CheckDeductionGuideTemplate(TD);
11042 
11043       // A deduction guide is not on the list of entities that can be
11044       // explicitly specialized.
11045       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11046         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11047             << /*explicit specialization*/ 1;
11048     }
11049 
11050     // Find any virtual functions that this function overrides.
11051     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11052       if (!Method->isFunctionTemplateSpecialization() &&
11053           !Method->getDescribedFunctionTemplate() &&
11054           Method->isCanonicalDecl()) {
11055         AddOverriddenMethods(Method->getParent(), Method);
11056       }
11057       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11058         // C++2a [class.virtual]p6
11059         // A virtual method shall not have a requires-clause.
11060         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11061              diag::err_constrained_virtual_method);
11062 
11063       if (Method->isStatic())
11064         checkThisInStaticMemberFunctionType(Method);
11065     }
11066 
11067     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11068       ActOnConversionDeclarator(Conversion);
11069 
11070     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11071     if (NewFD->isOverloadedOperator() &&
11072         CheckOverloadedOperatorDeclaration(NewFD)) {
11073       NewFD->setInvalidDecl();
11074       return Redeclaration;
11075     }
11076 
11077     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11078     if (NewFD->getLiteralIdentifier() &&
11079         CheckLiteralOperatorDeclaration(NewFD)) {
11080       NewFD->setInvalidDecl();
11081       return Redeclaration;
11082     }
11083 
11084     // In C++, check default arguments now that we have merged decls. Unless
11085     // the lexical context is the class, because in this case this is done
11086     // during delayed parsing anyway.
11087     if (!CurContext->isRecord())
11088       CheckCXXDefaultArguments(NewFD);
11089 
11090     // If this function is declared as being extern "C", then check to see if
11091     // the function returns a UDT (class, struct, or union type) that is not C
11092     // compatible, and if it does, warn the user.
11093     // But, issue any diagnostic on the first declaration only.
11094     if (Previous.empty() && NewFD->isExternC()) {
11095       QualType R = NewFD->getReturnType();
11096       if (R->isIncompleteType() && !R->isVoidType())
11097         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11098             << NewFD << R;
11099       else if (!R.isPODType(Context) && !R->isVoidType() &&
11100                !R->isObjCObjectPointerType())
11101         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11102     }
11103 
11104     // C++1z [dcl.fct]p6:
11105     //   [...] whether the function has a non-throwing exception-specification
11106     //   [is] part of the function type
11107     //
11108     // This results in an ABI break between C++14 and C++17 for functions whose
11109     // declared type includes an exception-specification in a parameter or
11110     // return type. (Exception specifications on the function itself are OK in
11111     // most cases, and exception specifications are not permitted in most other
11112     // contexts where they could make it into a mangling.)
11113     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11114       auto HasNoexcept = [&](QualType T) -> bool {
11115         // Strip off declarator chunks that could be between us and a function
11116         // type. We don't need to look far, exception specifications are very
11117         // restricted prior to C++17.
11118         if (auto *RT = T->getAs<ReferenceType>())
11119           T = RT->getPointeeType();
11120         else if (T->isAnyPointerType())
11121           T = T->getPointeeType();
11122         else if (auto *MPT = T->getAs<MemberPointerType>())
11123           T = MPT->getPointeeType();
11124         if (auto *FPT = T->getAs<FunctionProtoType>())
11125           if (FPT->isNothrow())
11126             return true;
11127         return false;
11128       };
11129 
11130       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11131       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11132       for (QualType T : FPT->param_types())
11133         AnyNoexcept |= HasNoexcept(T);
11134       if (AnyNoexcept)
11135         Diag(NewFD->getLocation(),
11136              diag::warn_cxx17_compat_exception_spec_in_signature)
11137             << NewFD;
11138     }
11139 
11140     if (!Redeclaration && LangOpts.CUDA)
11141       checkCUDATargetOverload(NewFD, Previous);
11142   }
11143   return Redeclaration;
11144 }
11145 
11146 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11147   // C++11 [basic.start.main]p3:
11148   //   A program that [...] declares main to be inline, static or
11149   //   constexpr is ill-formed.
11150   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11151   //   appear in a declaration of main.
11152   // static main is not an error under C99, but we should warn about it.
11153   // We accept _Noreturn main as an extension.
11154   if (FD->getStorageClass() == SC_Static)
11155     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11156          ? diag::err_static_main : diag::warn_static_main)
11157       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11158   if (FD->isInlineSpecified())
11159     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11160       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11161   if (DS.isNoreturnSpecified()) {
11162     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11163     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11164     Diag(NoreturnLoc, diag::ext_noreturn_main);
11165     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11166       << FixItHint::CreateRemoval(NoreturnRange);
11167   }
11168   if (FD->isConstexpr()) {
11169     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11170         << FD->isConsteval()
11171         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11172     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11173   }
11174 
11175   if (getLangOpts().OpenCL) {
11176     Diag(FD->getLocation(), diag::err_opencl_no_main)
11177         << FD->hasAttr<OpenCLKernelAttr>();
11178     FD->setInvalidDecl();
11179     return;
11180   }
11181 
11182   QualType T = FD->getType();
11183   assert(T->isFunctionType() && "function decl is not of function type");
11184   const FunctionType* FT = T->castAs<FunctionType>();
11185 
11186   // Set default calling convention for main()
11187   if (FT->getCallConv() != CC_C) {
11188     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11189     FD->setType(QualType(FT, 0));
11190     T = Context.getCanonicalType(FD->getType());
11191   }
11192 
11193   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11194     // In C with GNU extensions we allow main() to have non-integer return
11195     // type, but we should warn about the extension, and we disable the
11196     // implicit-return-zero rule.
11197 
11198     // GCC in C mode accepts qualified 'int'.
11199     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11200       FD->setHasImplicitReturnZero(true);
11201     else {
11202       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11203       SourceRange RTRange = FD->getReturnTypeSourceRange();
11204       if (RTRange.isValid())
11205         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11206             << FixItHint::CreateReplacement(RTRange, "int");
11207     }
11208   } else {
11209     // In C and C++, main magically returns 0 if you fall off the end;
11210     // set the flag which tells us that.
11211     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11212 
11213     // All the standards say that main() should return 'int'.
11214     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11215       FD->setHasImplicitReturnZero(true);
11216     else {
11217       // Otherwise, this is just a flat-out error.
11218       SourceRange RTRange = FD->getReturnTypeSourceRange();
11219       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11220           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11221                                 : FixItHint());
11222       FD->setInvalidDecl(true);
11223     }
11224   }
11225 
11226   // Treat protoless main() as nullary.
11227   if (isa<FunctionNoProtoType>(FT)) return;
11228 
11229   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11230   unsigned nparams = FTP->getNumParams();
11231   assert(FD->getNumParams() == nparams);
11232 
11233   bool HasExtraParameters = (nparams > 3);
11234 
11235   if (FTP->isVariadic()) {
11236     Diag(FD->getLocation(), diag::ext_variadic_main);
11237     // FIXME: if we had information about the location of the ellipsis, we
11238     // could add a FixIt hint to remove it as a parameter.
11239   }
11240 
11241   // Darwin passes an undocumented fourth argument of type char**.  If
11242   // other platforms start sprouting these, the logic below will start
11243   // getting shifty.
11244   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11245     HasExtraParameters = false;
11246 
11247   if (HasExtraParameters) {
11248     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11249     FD->setInvalidDecl(true);
11250     nparams = 3;
11251   }
11252 
11253   // FIXME: a lot of the following diagnostics would be improved
11254   // if we had some location information about types.
11255 
11256   QualType CharPP =
11257     Context.getPointerType(Context.getPointerType(Context.CharTy));
11258   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11259 
11260   for (unsigned i = 0; i < nparams; ++i) {
11261     QualType AT = FTP->getParamType(i);
11262 
11263     bool mismatch = true;
11264 
11265     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11266       mismatch = false;
11267     else if (Expected[i] == CharPP) {
11268       // As an extension, the following forms are okay:
11269       //   char const **
11270       //   char const * const *
11271       //   char * const *
11272 
11273       QualifierCollector qs;
11274       const PointerType* PT;
11275       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11276           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11277           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11278                               Context.CharTy)) {
11279         qs.removeConst();
11280         mismatch = !qs.empty();
11281       }
11282     }
11283 
11284     if (mismatch) {
11285       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11286       // TODO: suggest replacing given type with expected type
11287       FD->setInvalidDecl(true);
11288     }
11289   }
11290 
11291   if (nparams == 1 && !FD->isInvalidDecl()) {
11292     Diag(FD->getLocation(), diag::warn_main_one_arg);
11293   }
11294 
11295   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11296     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11297     FD->setInvalidDecl();
11298   }
11299 }
11300 
11301 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11302 
11303   // Default calling convention for main and wmain is __cdecl
11304   if (FD->getName() == "main" || FD->getName() == "wmain")
11305     return false;
11306 
11307   // Default calling convention for MinGW is __cdecl
11308   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11309   if (T.isWindowsGNUEnvironment())
11310     return false;
11311 
11312   // Default calling convention for WinMain, wWinMain and DllMain
11313   // is __stdcall on 32 bit Windows
11314   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11315     return true;
11316 
11317   return false;
11318 }
11319 
11320 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11321   QualType T = FD->getType();
11322   assert(T->isFunctionType() && "function decl is not of function type");
11323   const FunctionType *FT = T->castAs<FunctionType>();
11324 
11325   // Set an implicit return of 'zero' if the function can return some integral,
11326   // enumeration, pointer or nullptr type.
11327   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11328       FT->getReturnType()->isAnyPointerType() ||
11329       FT->getReturnType()->isNullPtrType())
11330     // DllMain is exempt because a return value of zero means it failed.
11331     if (FD->getName() != "DllMain")
11332       FD->setHasImplicitReturnZero(true);
11333 
11334   // Explicity specified calling conventions are applied to MSVC entry points
11335   if (!hasExplicitCallingConv(T)) {
11336     if (isDefaultStdCall(FD, *this)) {
11337       if (FT->getCallConv() != CC_X86StdCall) {
11338         FT = Context.adjustFunctionType(
11339             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11340         FD->setType(QualType(FT, 0));
11341       }
11342     } else if (FT->getCallConv() != CC_C) {
11343       FT = Context.adjustFunctionType(FT,
11344                                       FT->getExtInfo().withCallingConv(CC_C));
11345       FD->setType(QualType(FT, 0));
11346     }
11347   }
11348 
11349   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11350     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11351     FD->setInvalidDecl();
11352   }
11353 }
11354 
11355 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11356   // FIXME: Need strict checking.  In C89, we need to check for
11357   // any assignment, increment, decrement, function-calls, or
11358   // commas outside of a sizeof.  In C99, it's the same list,
11359   // except that the aforementioned are allowed in unevaluated
11360   // expressions.  Everything else falls under the
11361   // "may accept other forms of constant expressions" exception.
11362   //
11363   // Regular C++ code will not end up here (exceptions: language extensions,
11364   // OpenCL C++ etc), so the constant expression rules there don't matter.
11365   if (Init->isValueDependent()) {
11366     assert(Init->containsErrors() &&
11367            "Dependent code should only occur in error-recovery path.");
11368     return true;
11369   }
11370   const Expr *Culprit;
11371   if (Init->isConstantInitializer(Context, false, &Culprit))
11372     return false;
11373   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11374     << Culprit->getSourceRange();
11375   return true;
11376 }
11377 
11378 namespace {
11379   // Visits an initialization expression to see if OrigDecl is evaluated in
11380   // its own initialization and throws a warning if it does.
11381   class SelfReferenceChecker
11382       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11383     Sema &S;
11384     Decl *OrigDecl;
11385     bool isRecordType;
11386     bool isPODType;
11387     bool isReferenceType;
11388 
11389     bool isInitList;
11390     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11391 
11392   public:
11393     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11394 
11395     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11396                                                     S(S), OrigDecl(OrigDecl) {
11397       isPODType = false;
11398       isRecordType = false;
11399       isReferenceType = false;
11400       isInitList = false;
11401       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11402         isPODType = VD->getType().isPODType(S.Context);
11403         isRecordType = VD->getType()->isRecordType();
11404         isReferenceType = VD->getType()->isReferenceType();
11405       }
11406     }
11407 
11408     // For most expressions, just call the visitor.  For initializer lists,
11409     // track the index of the field being initialized since fields are
11410     // initialized in order allowing use of previously initialized fields.
11411     void CheckExpr(Expr *E) {
11412       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11413       if (!InitList) {
11414         Visit(E);
11415         return;
11416       }
11417 
11418       // Track and increment the index here.
11419       isInitList = true;
11420       InitFieldIndex.push_back(0);
11421       for (auto Child : InitList->children()) {
11422         CheckExpr(cast<Expr>(Child));
11423         ++InitFieldIndex.back();
11424       }
11425       InitFieldIndex.pop_back();
11426     }
11427 
11428     // Returns true if MemberExpr is checked and no further checking is needed.
11429     // Returns false if additional checking is required.
11430     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11431       llvm::SmallVector<FieldDecl*, 4> Fields;
11432       Expr *Base = E;
11433       bool ReferenceField = false;
11434 
11435       // Get the field members used.
11436       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11437         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11438         if (!FD)
11439           return false;
11440         Fields.push_back(FD);
11441         if (FD->getType()->isReferenceType())
11442           ReferenceField = true;
11443         Base = ME->getBase()->IgnoreParenImpCasts();
11444       }
11445 
11446       // Keep checking only if the base Decl is the same.
11447       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11448       if (!DRE || DRE->getDecl() != OrigDecl)
11449         return false;
11450 
11451       // A reference field can be bound to an unininitialized field.
11452       if (CheckReference && !ReferenceField)
11453         return true;
11454 
11455       // Convert FieldDecls to their index number.
11456       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11457       for (const FieldDecl *I : llvm::reverse(Fields))
11458         UsedFieldIndex.push_back(I->getFieldIndex());
11459 
11460       // See if a warning is needed by checking the first difference in index
11461       // numbers.  If field being used has index less than the field being
11462       // initialized, then the use is safe.
11463       for (auto UsedIter = UsedFieldIndex.begin(),
11464                 UsedEnd = UsedFieldIndex.end(),
11465                 OrigIter = InitFieldIndex.begin(),
11466                 OrigEnd = InitFieldIndex.end();
11467            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11468         if (*UsedIter < *OrigIter)
11469           return true;
11470         if (*UsedIter > *OrigIter)
11471           break;
11472       }
11473 
11474       // TODO: Add a different warning which will print the field names.
11475       HandleDeclRefExpr(DRE);
11476       return true;
11477     }
11478 
11479     // For most expressions, the cast is directly above the DeclRefExpr.
11480     // For conditional operators, the cast can be outside the conditional
11481     // operator if both expressions are DeclRefExpr's.
11482     void HandleValue(Expr *E) {
11483       E = E->IgnoreParens();
11484       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11485         HandleDeclRefExpr(DRE);
11486         return;
11487       }
11488 
11489       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11490         Visit(CO->getCond());
11491         HandleValue(CO->getTrueExpr());
11492         HandleValue(CO->getFalseExpr());
11493         return;
11494       }
11495 
11496       if (BinaryConditionalOperator *BCO =
11497               dyn_cast<BinaryConditionalOperator>(E)) {
11498         Visit(BCO->getCond());
11499         HandleValue(BCO->getFalseExpr());
11500         return;
11501       }
11502 
11503       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11504         HandleValue(OVE->getSourceExpr());
11505         return;
11506       }
11507 
11508       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11509         if (BO->getOpcode() == BO_Comma) {
11510           Visit(BO->getLHS());
11511           HandleValue(BO->getRHS());
11512           return;
11513         }
11514       }
11515 
11516       if (isa<MemberExpr>(E)) {
11517         if (isInitList) {
11518           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11519                                       false /*CheckReference*/))
11520             return;
11521         }
11522 
11523         Expr *Base = E->IgnoreParenImpCasts();
11524         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11525           // Check for static member variables and don't warn on them.
11526           if (!isa<FieldDecl>(ME->getMemberDecl()))
11527             return;
11528           Base = ME->getBase()->IgnoreParenImpCasts();
11529         }
11530         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11531           HandleDeclRefExpr(DRE);
11532         return;
11533       }
11534 
11535       Visit(E);
11536     }
11537 
11538     // Reference types not handled in HandleValue are handled here since all
11539     // uses of references are bad, not just r-value uses.
11540     void VisitDeclRefExpr(DeclRefExpr *E) {
11541       if (isReferenceType)
11542         HandleDeclRefExpr(E);
11543     }
11544 
11545     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11546       if (E->getCastKind() == CK_LValueToRValue) {
11547         HandleValue(E->getSubExpr());
11548         return;
11549       }
11550 
11551       Inherited::VisitImplicitCastExpr(E);
11552     }
11553 
11554     void VisitMemberExpr(MemberExpr *E) {
11555       if (isInitList) {
11556         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11557           return;
11558       }
11559 
11560       // Don't warn on arrays since they can be treated as pointers.
11561       if (E->getType()->canDecayToPointerType()) return;
11562 
11563       // Warn when a non-static method call is followed by non-static member
11564       // field accesses, which is followed by a DeclRefExpr.
11565       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11566       bool Warn = (MD && !MD->isStatic());
11567       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11568       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11569         if (!isa<FieldDecl>(ME->getMemberDecl()))
11570           Warn = false;
11571         Base = ME->getBase()->IgnoreParenImpCasts();
11572       }
11573 
11574       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11575         if (Warn)
11576           HandleDeclRefExpr(DRE);
11577         return;
11578       }
11579 
11580       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11581       // Visit that expression.
11582       Visit(Base);
11583     }
11584 
11585     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11586       Expr *Callee = E->getCallee();
11587 
11588       if (isa<UnresolvedLookupExpr>(Callee))
11589         return Inherited::VisitCXXOperatorCallExpr(E);
11590 
11591       Visit(Callee);
11592       for (auto Arg: E->arguments())
11593         HandleValue(Arg->IgnoreParenImpCasts());
11594     }
11595 
11596     void VisitUnaryOperator(UnaryOperator *E) {
11597       // For POD record types, addresses of its own members are well-defined.
11598       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11599           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11600         if (!isPODType)
11601           HandleValue(E->getSubExpr());
11602         return;
11603       }
11604 
11605       if (E->isIncrementDecrementOp()) {
11606         HandleValue(E->getSubExpr());
11607         return;
11608       }
11609 
11610       Inherited::VisitUnaryOperator(E);
11611     }
11612 
11613     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11614 
11615     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11616       if (E->getConstructor()->isCopyConstructor()) {
11617         Expr *ArgExpr = E->getArg(0);
11618         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11619           if (ILE->getNumInits() == 1)
11620             ArgExpr = ILE->getInit(0);
11621         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11622           if (ICE->getCastKind() == CK_NoOp)
11623             ArgExpr = ICE->getSubExpr();
11624         HandleValue(ArgExpr);
11625         return;
11626       }
11627       Inherited::VisitCXXConstructExpr(E);
11628     }
11629 
11630     void VisitCallExpr(CallExpr *E) {
11631       // Treat std::move as a use.
11632       if (E->isCallToStdMove()) {
11633         HandleValue(E->getArg(0));
11634         return;
11635       }
11636 
11637       Inherited::VisitCallExpr(E);
11638     }
11639 
11640     void VisitBinaryOperator(BinaryOperator *E) {
11641       if (E->isCompoundAssignmentOp()) {
11642         HandleValue(E->getLHS());
11643         Visit(E->getRHS());
11644         return;
11645       }
11646 
11647       Inherited::VisitBinaryOperator(E);
11648     }
11649 
11650     // A custom visitor for BinaryConditionalOperator is needed because the
11651     // regular visitor would check the condition and true expression separately
11652     // but both point to the same place giving duplicate diagnostics.
11653     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11654       Visit(E->getCond());
11655       Visit(E->getFalseExpr());
11656     }
11657 
11658     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11659       Decl* ReferenceDecl = DRE->getDecl();
11660       if (OrigDecl != ReferenceDecl) return;
11661       unsigned diag;
11662       if (isReferenceType) {
11663         diag = diag::warn_uninit_self_reference_in_reference_init;
11664       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11665         diag = diag::warn_static_self_reference_in_init;
11666       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11667                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11668                  DRE->getDecl()->getType()->isRecordType()) {
11669         diag = diag::warn_uninit_self_reference_in_init;
11670       } else {
11671         // Local variables will be handled by the CFG analysis.
11672         return;
11673       }
11674 
11675       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11676                             S.PDiag(diag)
11677                                 << DRE->getDecl() << OrigDecl->getLocation()
11678                                 << DRE->getSourceRange());
11679     }
11680   };
11681 
11682   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11683   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11684                                  bool DirectInit) {
11685     // Parameters arguments are occassionially constructed with itself,
11686     // for instance, in recursive functions.  Skip them.
11687     if (isa<ParmVarDecl>(OrigDecl))
11688       return;
11689 
11690     E = E->IgnoreParens();
11691 
11692     // Skip checking T a = a where T is not a record or reference type.
11693     // Doing so is a way to silence uninitialized warnings.
11694     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11695       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11696         if (ICE->getCastKind() == CK_LValueToRValue)
11697           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11698             if (DRE->getDecl() == OrigDecl)
11699               return;
11700 
11701     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11702   }
11703 } // end anonymous namespace
11704 
11705 namespace {
11706   // Simple wrapper to add the name of a variable or (if no variable is
11707   // available) a DeclarationName into a diagnostic.
11708   struct VarDeclOrName {
11709     VarDecl *VDecl;
11710     DeclarationName Name;
11711 
11712     friend const Sema::SemaDiagnosticBuilder &
11713     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11714       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11715     }
11716   };
11717 } // end anonymous namespace
11718 
11719 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11720                                             DeclarationName Name, QualType Type,
11721                                             TypeSourceInfo *TSI,
11722                                             SourceRange Range, bool DirectInit,
11723                                             Expr *Init) {
11724   bool IsInitCapture = !VDecl;
11725   assert((!VDecl || !VDecl->isInitCapture()) &&
11726          "init captures are expected to be deduced prior to initialization");
11727 
11728   VarDeclOrName VN{VDecl, Name};
11729 
11730   DeducedType *Deduced = Type->getContainedDeducedType();
11731   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11732 
11733   // C++11 [dcl.spec.auto]p3
11734   if (!Init) {
11735     assert(VDecl && "no init for init capture deduction?");
11736 
11737     // Except for class argument deduction, and then for an initializing
11738     // declaration only, i.e. no static at class scope or extern.
11739     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11740         VDecl->hasExternalStorage() ||
11741         VDecl->isStaticDataMember()) {
11742       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11743         << VDecl->getDeclName() << Type;
11744       return QualType();
11745     }
11746   }
11747 
11748   ArrayRef<Expr*> DeduceInits;
11749   if (Init)
11750     DeduceInits = Init;
11751 
11752   if (DirectInit) {
11753     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11754       DeduceInits = PL->exprs();
11755   }
11756 
11757   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11758     assert(VDecl && "non-auto type for init capture deduction?");
11759     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11760     InitializationKind Kind = InitializationKind::CreateForInit(
11761         VDecl->getLocation(), DirectInit, Init);
11762     // FIXME: Initialization should not be taking a mutable list of inits.
11763     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11764     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11765                                                        InitsCopy);
11766   }
11767 
11768   if (DirectInit) {
11769     if (auto *IL = dyn_cast<InitListExpr>(Init))
11770       DeduceInits = IL->inits();
11771   }
11772 
11773   // Deduction only works if we have exactly one source expression.
11774   if (DeduceInits.empty()) {
11775     // It isn't possible to write this directly, but it is possible to
11776     // end up in this situation with "auto x(some_pack...);"
11777     Diag(Init->getBeginLoc(), IsInitCapture
11778                                   ? diag::err_init_capture_no_expression
11779                                   : diag::err_auto_var_init_no_expression)
11780         << VN << Type << Range;
11781     return QualType();
11782   }
11783 
11784   if (DeduceInits.size() > 1) {
11785     Diag(DeduceInits[1]->getBeginLoc(),
11786          IsInitCapture ? diag::err_init_capture_multiple_expressions
11787                        : diag::err_auto_var_init_multiple_expressions)
11788         << VN << Type << Range;
11789     return QualType();
11790   }
11791 
11792   Expr *DeduceInit = DeduceInits[0];
11793   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11794     Diag(Init->getBeginLoc(), IsInitCapture
11795                                   ? diag::err_init_capture_paren_braces
11796                                   : diag::err_auto_var_init_paren_braces)
11797         << isa<InitListExpr>(Init) << VN << Type << Range;
11798     return QualType();
11799   }
11800 
11801   // Expressions default to 'id' when we're in a debugger.
11802   bool DefaultedAnyToId = false;
11803   if (getLangOpts().DebuggerCastResultToId &&
11804       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11805     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11806     if (Result.isInvalid()) {
11807       return QualType();
11808     }
11809     Init = Result.get();
11810     DefaultedAnyToId = true;
11811   }
11812 
11813   // C++ [dcl.decomp]p1:
11814   //   If the assignment-expression [...] has array type A and no ref-qualifier
11815   //   is present, e has type cv A
11816   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11817       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11818       DeduceInit->getType()->isConstantArrayType())
11819     return Context.getQualifiedType(DeduceInit->getType(),
11820                                     Type.getQualifiers());
11821 
11822   QualType DeducedType;
11823   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11824     if (!IsInitCapture)
11825       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11826     else if (isa<InitListExpr>(Init))
11827       Diag(Range.getBegin(),
11828            diag::err_init_capture_deduction_failure_from_init_list)
11829           << VN
11830           << (DeduceInit->getType().isNull() ? TSI->getType()
11831                                              : DeduceInit->getType())
11832           << DeduceInit->getSourceRange();
11833     else
11834       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11835           << VN << TSI->getType()
11836           << (DeduceInit->getType().isNull() ? TSI->getType()
11837                                              : DeduceInit->getType())
11838           << DeduceInit->getSourceRange();
11839   }
11840 
11841   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11842   // 'id' instead of a specific object type prevents most of our usual
11843   // checks.
11844   // We only want to warn outside of template instantiations, though:
11845   // inside a template, the 'id' could have come from a parameter.
11846   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11847       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11848     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11849     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11850   }
11851 
11852   return DeducedType;
11853 }
11854 
11855 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11856                                          Expr *Init) {
11857   assert(!Init || !Init->containsErrors());
11858   QualType DeducedType = deduceVarTypeFromInitializer(
11859       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11860       VDecl->getSourceRange(), DirectInit, Init);
11861   if (DeducedType.isNull()) {
11862     VDecl->setInvalidDecl();
11863     return true;
11864   }
11865 
11866   VDecl->setType(DeducedType);
11867   assert(VDecl->isLinkageValid());
11868 
11869   // In ARC, infer lifetime.
11870   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11871     VDecl->setInvalidDecl();
11872 
11873   if (getLangOpts().OpenCL)
11874     deduceOpenCLAddressSpace(VDecl);
11875 
11876   // If this is a redeclaration, check that the type we just deduced matches
11877   // the previously declared type.
11878   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11879     // We never need to merge the type, because we cannot form an incomplete
11880     // array of auto, nor deduce such a type.
11881     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11882   }
11883 
11884   // Check the deduced type is valid for a variable declaration.
11885   CheckVariableDeclarationType(VDecl);
11886   return VDecl->isInvalidDecl();
11887 }
11888 
11889 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11890                                               SourceLocation Loc) {
11891   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11892     Init = EWC->getSubExpr();
11893 
11894   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11895     Init = CE->getSubExpr();
11896 
11897   QualType InitType = Init->getType();
11898   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11899           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11900          "shouldn't be called if type doesn't have a non-trivial C struct");
11901   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11902     for (auto I : ILE->inits()) {
11903       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11904           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11905         continue;
11906       SourceLocation SL = I->getExprLoc();
11907       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11908     }
11909     return;
11910   }
11911 
11912   if (isa<ImplicitValueInitExpr>(Init)) {
11913     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11914       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11915                             NTCUK_Init);
11916   } else {
11917     // Assume all other explicit initializers involving copying some existing
11918     // object.
11919     // TODO: ignore any explicit initializers where we can guarantee
11920     // copy-elision.
11921     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11922       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11923   }
11924 }
11925 
11926 namespace {
11927 
11928 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11929   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11930   // in the source code or implicitly by the compiler if it is in a union
11931   // defined in a system header and has non-trivial ObjC ownership
11932   // qualifications. We don't want those fields to participate in determining
11933   // whether the containing union is non-trivial.
11934   return FD->hasAttr<UnavailableAttr>();
11935 }
11936 
11937 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11938     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11939                                     void> {
11940   using Super =
11941       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11942                                     void>;
11943 
11944   DiagNonTrivalCUnionDefaultInitializeVisitor(
11945       QualType OrigTy, SourceLocation OrigLoc,
11946       Sema::NonTrivialCUnionContext UseContext, Sema &S)
11947       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11948 
11949   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11950                      const FieldDecl *FD, bool InNonTrivialUnion) {
11951     if (const auto *AT = S.Context.getAsArrayType(QT))
11952       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11953                                      InNonTrivialUnion);
11954     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11955   }
11956 
11957   void visitARCStrong(QualType QT, const FieldDecl *FD,
11958                       bool InNonTrivialUnion) {
11959     if (InNonTrivialUnion)
11960       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11961           << 1 << 0 << QT << FD->getName();
11962   }
11963 
11964   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11965     if (InNonTrivialUnion)
11966       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11967           << 1 << 0 << QT << FD->getName();
11968   }
11969 
11970   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11971     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11972     if (RD->isUnion()) {
11973       if (OrigLoc.isValid()) {
11974         bool IsUnion = false;
11975         if (auto *OrigRD = OrigTy->getAsRecordDecl())
11976           IsUnion = OrigRD->isUnion();
11977         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11978             << 0 << OrigTy << IsUnion << UseContext;
11979         // Reset OrigLoc so that this diagnostic is emitted only once.
11980         OrigLoc = SourceLocation();
11981       }
11982       InNonTrivialUnion = true;
11983     }
11984 
11985     if (InNonTrivialUnion)
11986       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11987           << 0 << 0 << QT.getUnqualifiedType() << "";
11988 
11989     for (const FieldDecl *FD : RD->fields())
11990       if (!shouldIgnoreForRecordTriviality(FD))
11991         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11992   }
11993 
11994   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11995 
11996   // The non-trivial C union type or the struct/union type that contains a
11997   // non-trivial C union.
11998   QualType OrigTy;
11999   SourceLocation OrigLoc;
12000   Sema::NonTrivialCUnionContext UseContext;
12001   Sema &S;
12002 };
12003 
12004 struct DiagNonTrivalCUnionDestructedTypeVisitor
12005     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12006   using Super =
12007       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12008 
12009   DiagNonTrivalCUnionDestructedTypeVisitor(
12010       QualType OrigTy, SourceLocation OrigLoc,
12011       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12012       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12013 
12014   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12015                      const FieldDecl *FD, bool InNonTrivialUnion) {
12016     if (const auto *AT = S.Context.getAsArrayType(QT))
12017       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12018                                      InNonTrivialUnion);
12019     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12020   }
12021 
12022   void visitARCStrong(QualType QT, const FieldDecl *FD,
12023                       bool InNonTrivialUnion) {
12024     if (InNonTrivialUnion)
12025       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12026           << 1 << 1 << QT << FD->getName();
12027   }
12028 
12029   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12030     if (InNonTrivialUnion)
12031       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12032           << 1 << 1 << QT << FD->getName();
12033   }
12034 
12035   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12036     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12037     if (RD->isUnion()) {
12038       if (OrigLoc.isValid()) {
12039         bool IsUnion = false;
12040         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12041           IsUnion = OrigRD->isUnion();
12042         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12043             << 1 << OrigTy << IsUnion << UseContext;
12044         // Reset OrigLoc so that this diagnostic is emitted only once.
12045         OrigLoc = SourceLocation();
12046       }
12047       InNonTrivialUnion = true;
12048     }
12049 
12050     if (InNonTrivialUnion)
12051       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12052           << 0 << 1 << QT.getUnqualifiedType() << "";
12053 
12054     for (const FieldDecl *FD : RD->fields())
12055       if (!shouldIgnoreForRecordTriviality(FD))
12056         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12057   }
12058 
12059   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12060   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12061                           bool InNonTrivialUnion) {}
12062 
12063   // The non-trivial C union type or the struct/union type that contains a
12064   // non-trivial C union.
12065   QualType OrigTy;
12066   SourceLocation OrigLoc;
12067   Sema::NonTrivialCUnionContext UseContext;
12068   Sema &S;
12069 };
12070 
12071 struct DiagNonTrivalCUnionCopyVisitor
12072     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12073   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12074 
12075   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12076                                  Sema::NonTrivialCUnionContext UseContext,
12077                                  Sema &S)
12078       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12079 
12080   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12081                      const FieldDecl *FD, bool InNonTrivialUnion) {
12082     if (const auto *AT = S.Context.getAsArrayType(QT))
12083       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12084                                      InNonTrivialUnion);
12085     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12086   }
12087 
12088   void visitARCStrong(QualType QT, const FieldDecl *FD,
12089                       bool InNonTrivialUnion) {
12090     if (InNonTrivialUnion)
12091       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12092           << 1 << 2 << QT << FD->getName();
12093   }
12094 
12095   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12096     if (InNonTrivialUnion)
12097       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12098           << 1 << 2 << QT << FD->getName();
12099   }
12100 
12101   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12102     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12103     if (RD->isUnion()) {
12104       if (OrigLoc.isValid()) {
12105         bool IsUnion = false;
12106         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12107           IsUnion = OrigRD->isUnion();
12108         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12109             << 2 << OrigTy << IsUnion << UseContext;
12110         // Reset OrigLoc so that this diagnostic is emitted only once.
12111         OrigLoc = SourceLocation();
12112       }
12113       InNonTrivialUnion = true;
12114     }
12115 
12116     if (InNonTrivialUnion)
12117       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12118           << 0 << 2 << QT.getUnqualifiedType() << "";
12119 
12120     for (const FieldDecl *FD : RD->fields())
12121       if (!shouldIgnoreForRecordTriviality(FD))
12122         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12123   }
12124 
12125   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12126                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12127   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12128   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12129                             bool InNonTrivialUnion) {}
12130 
12131   // The non-trivial C union type or the struct/union type that contains a
12132   // non-trivial C union.
12133   QualType OrigTy;
12134   SourceLocation OrigLoc;
12135   Sema::NonTrivialCUnionContext UseContext;
12136   Sema &S;
12137 };
12138 
12139 } // namespace
12140 
12141 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12142                                  NonTrivialCUnionContext UseContext,
12143                                  unsigned NonTrivialKind) {
12144   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12145           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12146           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12147          "shouldn't be called if type doesn't have a non-trivial C union");
12148 
12149   if ((NonTrivialKind & NTCUK_Init) &&
12150       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12151     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12152         .visit(QT, nullptr, false);
12153   if ((NonTrivialKind & NTCUK_Destruct) &&
12154       QT.hasNonTrivialToPrimitiveDestructCUnion())
12155     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12156         .visit(QT, nullptr, false);
12157   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12158     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12159         .visit(QT, nullptr, false);
12160 }
12161 
12162 /// AddInitializerToDecl - Adds the initializer Init to the
12163 /// declaration dcl. If DirectInit is true, this is C++ direct
12164 /// initialization rather than copy initialization.
12165 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12166   // If there is no declaration, there was an error parsing it.  Just ignore
12167   // the initializer.
12168   if (!RealDecl || RealDecl->isInvalidDecl()) {
12169     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12170     return;
12171   }
12172 
12173   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12174     // Pure-specifiers are handled in ActOnPureSpecifier.
12175     Diag(Method->getLocation(), diag::err_member_function_initialization)
12176       << Method->getDeclName() << Init->getSourceRange();
12177     Method->setInvalidDecl();
12178     return;
12179   }
12180 
12181   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12182   if (!VDecl) {
12183     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12184     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12185     RealDecl->setInvalidDecl();
12186     return;
12187   }
12188 
12189   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12190   if (VDecl->getType()->isUndeducedType()) {
12191     // Attempt typo correction early so that the type of the init expression can
12192     // be deduced based on the chosen correction if the original init contains a
12193     // TypoExpr.
12194     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12195     if (!Res.isUsable()) {
12196       // There are unresolved typos in Init, just drop them.
12197       // FIXME: improve the recovery strategy to preserve the Init.
12198       RealDecl->setInvalidDecl();
12199       return;
12200     }
12201     if (Res.get()->containsErrors()) {
12202       // Invalidate the decl as we don't know the type for recovery-expr yet.
12203       RealDecl->setInvalidDecl();
12204       VDecl->setInit(Res.get());
12205       return;
12206     }
12207     Init = Res.get();
12208 
12209     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12210       return;
12211   }
12212 
12213   // dllimport cannot be used on variable definitions.
12214   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12215     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12216     VDecl->setInvalidDecl();
12217     return;
12218   }
12219 
12220   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12221     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12222     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12223     VDecl->setInvalidDecl();
12224     return;
12225   }
12226 
12227   if (!VDecl->getType()->isDependentType()) {
12228     // A definition must end up with a complete type, which means it must be
12229     // complete with the restriction that an array type might be completed by
12230     // the initializer; note that later code assumes this restriction.
12231     QualType BaseDeclType = VDecl->getType();
12232     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12233       BaseDeclType = Array->getElementType();
12234     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12235                             diag::err_typecheck_decl_incomplete_type)) {
12236       RealDecl->setInvalidDecl();
12237       return;
12238     }
12239 
12240     // The variable can not have an abstract class type.
12241     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12242                                diag::err_abstract_type_in_decl,
12243                                AbstractVariableType))
12244       VDecl->setInvalidDecl();
12245   }
12246 
12247   // If adding the initializer will turn this declaration into a definition,
12248   // and we already have a definition for this variable, diagnose or otherwise
12249   // handle the situation.
12250   if (VarDecl *Def = VDecl->getDefinition())
12251     if (Def != VDecl &&
12252         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12253         !VDecl->isThisDeclarationADemotedDefinition() &&
12254         checkVarDeclRedefinition(Def, VDecl))
12255       return;
12256 
12257   if (getLangOpts().CPlusPlus) {
12258     // C++ [class.static.data]p4
12259     //   If a static data member is of const integral or const
12260     //   enumeration type, its declaration in the class definition can
12261     //   specify a constant-initializer which shall be an integral
12262     //   constant expression (5.19). In that case, the member can appear
12263     //   in integral constant expressions. The member shall still be
12264     //   defined in a namespace scope if it is used in the program and the
12265     //   namespace scope definition shall not contain an initializer.
12266     //
12267     // We already performed a redefinition check above, but for static
12268     // data members we also need to check whether there was an in-class
12269     // declaration with an initializer.
12270     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12271       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12272           << VDecl->getDeclName();
12273       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12274            diag::note_previous_initializer)
12275           << 0;
12276       return;
12277     }
12278 
12279     if (VDecl->hasLocalStorage())
12280       setFunctionHasBranchProtectedScope();
12281 
12282     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12283       VDecl->setInvalidDecl();
12284       return;
12285     }
12286   }
12287 
12288   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12289   // a kernel function cannot be initialized."
12290   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12291     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12292     VDecl->setInvalidDecl();
12293     return;
12294   }
12295 
12296   // The LoaderUninitialized attribute acts as a definition (of undef).
12297   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12298     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12299     VDecl->setInvalidDecl();
12300     return;
12301   }
12302 
12303   // Get the decls type and save a reference for later, since
12304   // CheckInitializerTypes may change it.
12305   QualType DclT = VDecl->getType(), SavT = DclT;
12306 
12307   // Expressions default to 'id' when we're in a debugger
12308   // and we are assigning it to a variable of Objective-C pointer type.
12309   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12310       Init->getType() == Context.UnknownAnyTy) {
12311     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12312     if (Result.isInvalid()) {
12313       VDecl->setInvalidDecl();
12314       return;
12315     }
12316     Init = Result.get();
12317   }
12318 
12319   // Perform the initialization.
12320   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12321   if (!VDecl->isInvalidDecl()) {
12322     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12323     InitializationKind Kind = InitializationKind::CreateForInit(
12324         VDecl->getLocation(), DirectInit, Init);
12325 
12326     MultiExprArg Args = Init;
12327     if (CXXDirectInit)
12328       Args = MultiExprArg(CXXDirectInit->getExprs(),
12329                           CXXDirectInit->getNumExprs());
12330 
12331     // Try to correct any TypoExprs in the initialization arguments.
12332     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12333       ExprResult Res = CorrectDelayedTyposInExpr(
12334           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12335           [this, Entity, Kind](Expr *E) {
12336             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12337             return Init.Failed() ? ExprError() : E;
12338           });
12339       if (Res.isInvalid()) {
12340         VDecl->setInvalidDecl();
12341       } else if (Res.get() != Args[Idx]) {
12342         Args[Idx] = Res.get();
12343       }
12344     }
12345     if (VDecl->isInvalidDecl())
12346       return;
12347 
12348     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12349                                    /*TopLevelOfInitList=*/false,
12350                                    /*TreatUnavailableAsInvalid=*/false);
12351     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12352     if (Result.isInvalid()) {
12353       // If the provied initializer fails to initialize the var decl,
12354       // we attach a recovery expr for better recovery.
12355       auto RecoveryExpr =
12356           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12357       if (RecoveryExpr.get())
12358         VDecl->setInit(RecoveryExpr.get());
12359       return;
12360     }
12361 
12362     Init = Result.getAs<Expr>();
12363   }
12364 
12365   // Check for self-references within variable initializers.
12366   // Variables declared within a function/method body (except for references)
12367   // are handled by a dataflow analysis.
12368   // This is undefined behavior in C++, but valid in C.
12369   if (getLangOpts().CPlusPlus)
12370     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12371         VDecl->getType()->isReferenceType())
12372       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12373 
12374   // If the type changed, it means we had an incomplete type that was
12375   // completed by the initializer. For example:
12376   //   int ary[] = { 1, 3, 5 };
12377   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12378   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12379     VDecl->setType(DclT);
12380 
12381   if (!VDecl->isInvalidDecl()) {
12382     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12383 
12384     if (VDecl->hasAttr<BlocksAttr>())
12385       checkRetainCycles(VDecl, Init);
12386 
12387     // It is safe to assign a weak reference into a strong variable.
12388     // Although this code can still have problems:
12389     //   id x = self.weakProp;
12390     //   id y = self.weakProp;
12391     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12392     // paths through the function. This should be revisited if
12393     // -Wrepeated-use-of-weak is made flow-sensitive.
12394     if (FunctionScopeInfo *FSI = getCurFunction())
12395       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12396            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12397           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12398                            Init->getBeginLoc()))
12399         FSI->markSafeWeakUse(Init);
12400   }
12401 
12402   // The initialization is usually a full-expression.
12403   //
12404   // FIXME: If this is a braced initialization of an aggregate, it is not
12405   // an expression, and each individual field initializer is a separate
12406   // full-expression. For instance, in:
12407   //
12408   //   struct Temp { ~Temp(); };
12409   //   struct S { S(Temp); };
12410   //   struct T { S a, b; } t = { Temp(), Temp() }
12411   //
12412   // we should destroy the first Temp before constructing the second.
12413   ExprResult Result =
12414       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12415                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12416   if (Result.isInvalid()) {
12417     VDecl->setInvalidDecl();
12418     return;
12419   }
12420   Init = Result.get();
12421 
12422   // Attach the initializer to the decl.
12423   VDecl->setInit(Init);
12424 
12425   if (VDecl->isLocalVarDecl()) {
12426     // Don't check the initializer if the declaration is malformed.
12427     if (VDecl->isInvalidDecl()) {
12428       // do nothing
12429 
12430     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12431     // This is true even in C++ for OpenCL.
12432     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12433       CheckForConstantInitializer(Init, DclT);
12434 
12435     // Otherwise, C++ does not restrict the initializer.
12436     } else if (getLangOpts().CPlusPlus) {
12437       // do nothing
12438 
12439     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12440     // static storage duration shall be constant expressions or string literals.
12441     } else if (VDecl->getStorageClass() == SC_Static) {
12442       CheckForConstantInitializer(Init, DclT);
12443 
12444     // C89 is stricter than C99 for aggregate initializers.
12445     // C89 6.5.7p3: All the expressions [...] in an initializer list
12446     // for an object that has aggregate or union type shall be
12447     // constant expressions.
12448     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12449                isa<InitListExpr>(Init)) {
12450       const Expr *Culprit;
12451       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12452         Diag(Culprit->getExprLoc(),
12453              diag::ext_aggregate_init_not_constant)
12454           << Culprit->getSourceRange();
12455       }
12456     }
12457 
12458     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12459       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12460         if (VDecl->hasLocalStorage())
12461           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12462   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12463              VDecl->getLexicalDeclContext()->isRecord()) {
12464     // This is an in-class initialization for a static data member, e.g.,
12465     //
12466     // struct S {
12467     //   static const int value = 17;
12468     // };
12469 
12470     // C++ [class.mem]p4:
12471     //   A member-declarator can contain a constant-initializer only
12472     //   if it declares a static member (9.4) of const integral or
12473     //   const enumeration type, see 9.4.2.
12474     //
12475     // C++11 [class.static.data]p3:
12476     //   If a non-volatile non-inline const static data member is of integral
12477     //   or enumeration type, its declaration in the class definition can
12478     //   specify a brace-or-equal-initializer in which every initializer-clause
12479     //   that is an assignment-expression is a constant expression. A static
12480     //   data member of literal type can be declared in the class definition
12481     //   with the constexpr specifier; if so, its declaration shall specify a
12482     //   brace-or-equal-initializer in which every initializer-clause that is
12483     //   an assignment-expression is a constant expression.
12484 
12485     // Do nothing on dependent types.
12486     if (DclT->isDependentType()) {
12487 
12488     // Allow any 'static constexpr' members, whether or not they are of literal
12489     // type. We separately check that every constexpr variable is of literal
12490     // type.
12491     } else if (VDecl->isConstexpr()) {
12492 
12493     // Require constness.
12494     } else if (!DclT.isConstQualified()) {
12495       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12496         << Init->getSourceRange();
12497       VDecl->setInvalidDecl();
12498 
12499     // We allow integer constant expressions in all cases.
12500     } else if (DclT->isIntegralOrEnumerationType()) {
12501       // Check whether the expression is a constant expression.
12502       SourceLocation Loc;
12503       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12504         // In C++11, a non-constexpr const static data member with an
12505         // in-class initializer cannot be volatile.
12506         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12507       else if (Init->isValueDependent())
12508         ; // Nothing to check.
12509       else if (Init->isIntegerConstantExpr(Context, &Loc))
12510         ; // Ok, it's an ICE!
12511       else if (Init->getType()->isScopedEnumeralType() &&
12512                Init->isCXX11ConstantExpr(Context))
12513         ; // Ok, it is a scoped-enum constant expression.
12514       else if (Init->isEvaluatable(Context)) {
12515         // If we can constant fold the initializer through heroics, accept it,
12516         // but report this as a use of an extension for -pedantic.
12517         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12518           << Init->getSourceRange();
12519       } else {
12520         // Otherwise, this is some crazy unknown case.  Report the issue at the
12521         // location provided by the isIntegerConstantExpr failed check.
12522         Diag(Loc, diag::err_in_class_initializer_non_constant)
12523           << Init->getSourceRange();
12524         VDecl->setInvalidDecl();
12525       }
12526 
12527     // We allow foldable floating-point constants as an extension.
12528     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12529       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12530       // it anyway and provide a fixit to add the 'constexpr'.
12531       if (getLangOpts().CPlusPlus11) {
12532         Diag(VDecl->getLocation(),
12533              diag::ext_in_class_initializer_float_type_cxx11)
12534             << DclT << Init->getSourceRange();
12535         Diag(VDecl->getBeginLoc(),
12536              diag::note_in_class_initializer_float_type_cxx11)
12537             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12538       } else {
12539         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12540           << DclT << Init->getSourceRange();
12541 
12542         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12543           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12544             << Init->getSourceRange();
12545           VDecl->setInvalidDecl();
12546         }
12547       }
12548 
12549     // Suggest adding 'constexpr' in C++11 for literal types.
12550     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12551       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12552           << DclT << Init->getSourceRange()
12553           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12554       VDecl->setConstexpr(true);
12555 
12556     } else {
12557       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12558         << DclT << Init->getSourceRange();
12559       VDecl->setInvalidDecl();
12560     }
12561   } else if (VDecl->isFileVarDecl()) {
12562     // In C, extern is typically used to avoid tentative definitions when
12563     // declaring variables in headers, but adding an intializer makes it a
12564     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12565     // In C++, extern is often used to give implictly static const variables
12566     // external linkage, so don't warn in that case. If selectany is present,
12567     // this might be header code intended for C and C++ inclusion, so apply the
12568     // C++ rules.
12569     if (VDecl->getStorageClass() == SC_Extern &&
12570         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12571          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12572         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12573         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12574       Diag(VDecl->getLocation(), diag::warn_extern_init);
12575 
12576     // In Microsoft C++ mode, a const variable defined in namespace scope has
12577     // external linkage by default if the variable is declared with
12578     // __declspec(dllexport).
12579     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12580         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12581         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12582       VDecl->setStorageClass(SC_Extern);
12583 
12584     // C99 6.7.8p4. All file scoped initializers need to be constant.
12585     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12586       CheckForConstantInitializer(Init, DclT);
12587   }
12588 
12589   QualType InitType = Init->getType();
12590   if (!InitType.isNull() &&
12591       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12592        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12593     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12594 
12595   // We will represent direct-initialization similarly to copy-initialization:
12596   //    int x(1);  -as-> int x = 1;
12597   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12598   //
12599   // Clients that want to distinguish between the two forms, can check for
12600   // direct initializer using VarDecl::getInitStyle().
12601   // A major benefit is that clients that don't particularly care about which
12602   // exactly form was it (like the CodeGen) can handle both cases without
12603   // special case code.
12604 
12605   // C++ 8.5p11:
12606   // The form of initialization (using parentheses or '=') is generally
12607   // insignificant, but does matter when the entity being initialized has a
12608   // class type.
12609   if (CXXDirectInit) {
12610     assert(DirectInit && "Call-style initializer must be direct init.");
12611     VDecl->setInitStyle(VarDecl::CallInit);
12612   } else if (DirectInit) {
12613     // This must be list-initialization. No other way is direct-initialization.
12614     VDecl->setInitStyle(VarDecl::ListInit);
12615   }
12616 
12617   if (LangOpts.OpenMP &&
12618       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12619       VDecl->isFileVarDecl())
12620     DeclsToCheckForDeferredDiags.insert(VDecl);
12621   CheckCompleteVariableDeclaration(VDecl);
12622 }
12623 
12624 /// ActOnInitializerError - Given that there was an error parsing an
12625 /// initializer for the given declaration, try to return to some form
12626 /// of sanity.
12627 void Sema::ActOnInitializerError(Decl *D) {
12628   // Our main concern here is re-establishing invariants like "a
12629   // variable's type is either dependent or complete".
12630   if (!D || D->isInvalidDecl()) return;
12631 
12632   VarDecl *VD = dyn_cast<VarDecl>(D);
12633   if (!VD) return;
12634 
12635   // Bindings are not usable if we can't make sense of the initializer.
12636   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12637     for (auto *BD : DD->bindings())
12638       BD->setInvalidDecl();
12639 
12640   // Auto types are meaningless if we can't make sense of the initializer.
12641   if (VD->getType()->isUndeducedType()) {
12642     D->setInvalidDecl();
12643     return;
12644   }
12645 
12646   QualType Ty = VD->getType();
12647   if (Ty->isDependentType()) return;
12648 
12649   // Require a complete type.
12650   if (RequireCompleteType(VD->getLocation(),
12651                           Context.getBaseElementType(Ty),
12652                           diag::err_typecheck_decl_incomplete_type)) {
12653     VD->setInvalidDecl();
12654     return;
12655   }
12656 
12657   // Require a non-abstract type.
12658   if (RequireNonAbstractType(VD->getLocation(), Ty,
12659                              diag::err_abstract_type_in_decl,
12660                              AbstractVariableType)) {
12661     VD->setInvalidDecl();
12662     return;
12663   }
12664 
12665   // Don't bother complaining about constructors or destructors,
12666   // though.
12667 }
12668 
12669 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12670   // If there is no declaration, there was an error parsing it. Just ignore it.
12671   if (!RealDecl)
12672     return;
12673 
12674   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12675     QualType Type = Var->getType();
12676 
12677     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12678     if (isa<DecompositionDecl>(RealDecl)) {
12679       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12680       Var->setInvalidDecl();
12681       return;
12682     }
12683 
12684     if (Type->isUndeducedType() &&
12685         DeduceVariableDeclarationType(Var, false, nullptr))
12686       return;
12687 
12688     // C++11 [class.static.data]p3: A static data member can be declared with
12689     // the constexpr specifier; if so, its declaration shall specify
12690     // a brace-or-equal-initializer.
12691     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12692     // the definition of a variable [...] or the declaration of a static data
12693     // member.
12694     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12695         !Var->isThisDeclarationADemotedDefinition()) {
12696       if (Var->isStaticDataMember()) {
12697         // C++1z removes the relevant rule; the in-class declaration is always
12698         // a definition there.
12699         if (!getLangOpts().CPlusPlus17 &&
12700             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12701           Diag(Var->getLocation(),
12702                diag::err_constexpr_static_mem_var_requires_init)
12703               << Var;
12704           Var->setInvalidDecl();
12705           return;
12706         }
12707       } else {
12708         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12709         Var->setInvalidDecl();
12710         return;
12711       }
12712     }
12713 
12714     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12715     // be initialized.
12716     if (!Var->isInvalidDecl() &&
12717         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12718         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12719       bool HasConstExprDefaultConstructor = false;
12720       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12721         for (auto *Ctor : RD->ctors()) {
12722           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12723               Ctor->getMethodQualifiers().getAddressSpace() ==
12724                   LangAS::opencl_constant) {
12725             HasConstExprDefaultConstructor = true;
12726           }
12727         }
12728       }
12729       if (!HasConstExprDefaultConstructor) {
12730         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12731         Var->setInvalidDecl();
12732         return;
12733       }
12734     }
12735 
12736     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12737       if (Var->getStorageClass() == SC_Extern) {
12738         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12739             << Var;
12740         Var->setInvalidDecl();
12741         return;
12742       }
12743       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12744                               diag::err_typecheck_decl_incomplete_type)) {
12745         Var->setInvalidDecl();
12746         return;
12747       }
12748       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12749         if (!RD->hasTrivialDefaultConstructor()) {
12750           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12751           Var->setInvalidDecl();
12752           return;
12753         }
12754       }
12755       // The declaration is unitialized, no need for further checks.
12756       return;
12757     }
12758 
12759     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12760     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12761         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12762       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12763                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12764 
12765 
12766     switch (DefKind) {
12767     case VarDecl::Definition:
12768       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12769         break;
12770 
12771       // We have an out-of-line definition of a static data member
12772       // that has an in-class initializer, so we type-check this like
12773       // a declaration.
12774       //
12775       LLVM_FALLTHROUGH;
12776 
12777     case VarDecl::DeclarationOnly:
12778       // It's only a declaration.
12779 
12780       // Block scope. C99 6.7p7: If an identifier for an object is
12781       // declared with no linkage (C99 6.2.2p6), the type for the
12782       // object shall be complete.
12783       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12784           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12785           RequireCompleteType(Var->getLocation(), Type,
12786                               diag::err_typecheck_decl_incomplete_type))
12787         Var->setInvalidDecl();
12788 
12789       // Make sure that the type is not abstract.
12790       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12791           RequireNonAbstractType(Var->getLocation(), Type,
12792                                  diag::err_abstract_type_in_decl,
12793                                  AbstractVariableType))
12794         Var->setInvalidDecl();
12795       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12796           Var->getStorageClass() == SC_PrivateExtern) {
12797         Diag(Var->getLocation(), diag::warn_private_extern);
12798         Diag(Var->getLocation(), diag::note_private_extern);
12799       }
12800 
12801       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12802           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12803         ExternalDeclarations.push_back(Var);
12804 
12805       return;
12806 
12807     case VarDecl::TentativeDefinition:
12808       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12809       // object that has file scope without an initializer, and without a
12810       // storage-class specifier or with the storage-class specifier "static",
12811       // constitutes a tentative definition. Note: A tentative definition with
12812       // external linkage is valid (C99 6.2.2p5).
12813       if (!Var->isInvalidDecl()) {
12814         if (const IncompleteArrayType *ArrayT
12815                                     = Context.getAsIncompleteArrayType(Type)) {
12816           if (RequireCompleteSizedType(
12817                   Var->getLocation(), ArrayT->getElementType(),
12818                   diag::err_array_incomplete_or_sizeless_type))
12819             Var->setInvalidDecl();
12820         } else if (Var->getStorageClass() == SC_Static) {
12821           // C99 6.9.2p3: If the declaration of an identifier for an object is
12822           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12823           // declared type shall not be an incomplete type.
12824           // NOTE: code such as the following
12825           //     static struct s;
12826           //     struct s { int a; };
12827           // is accepted by gcc. Hence here we issue a warning instead of
12828           // an error and we do not invalidate the static declaration.
12829           // NOTE: to avoid multiple warnings, only check the first declaration.
12830           if (Var->isFirstDecl())
12831             RequireCompleteType(Var->getLocation(), Type,
12832                                 diag::ext_typecheck_decl_incomplete_type);
12833         }
12834       }
12835 
12836       // Record the tentative definition; we're done.
12837       if (!Var->isInvalidDecl())
12838         TentativeDefinitions.push_back(Var);
12839       return;
12840     }
12841 
12842     // Provide a specific diagnostic for uninitialized variable
12843     // definitions with incomplete array type.
12844     if (Type->isIncompleteArrayType()) {
12845       Diag(Var->getLocation(),
12846            diag::err_typecheck_incomplete_array_needs_initializer);
12847       Var->setInvalidDecl();
12848       return;
12849     }
12850 
12851     // Provide a specific diagnostic for uninitialized variable
12852     // definitions with reference type.
12853     if (Type->isReferenceType()) {
12854       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12855           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12856       Var->setInvalidDecl();
12857       return;
12858     }
12859 
12860     // Do not attempt to type-check the default initializer for a
12861     // variable with dependent type.
12862     if (Type->isDependentType())
12863       return;
12864 
12865     if (Var->isInvalidDecl())
12866       return;
12867 
12868     if (!Var->hasAttr<AliasAttr>()) {
12869       if (RequireCompleteType(Var->getLocation(),
12870                               Context.getBaseElementType(Type),
12871                               diag::err_typecheck_decl_incomplete_type)) {
12872         Var->setInvalidDecl();
12873         return;
12874       }
12875     } else {
12876       return;
12877     }
12878 
12879     // The variable can not have an abstract class type.
12880     if (RequireNonAbstractType(Var->getLocation(), Type,
12881                                diag::err_abstract_type_in_decl,
12882                                AbstractVariableType)) {
12883       Var->setInvalidDecl();
12884       return;
12885     }
12886 
12887     // Check for jumps past the implicit initializer.  C++0x
12888     // clarifies that this applies to a "variable with automatic
12889     // storage duration", not a "local variable".
12890     // C++11 [stmt.dcl]p3
12891     //   A program that jumps from a point where a variable with automatic
12892     //   storage duration is not in scope to a point where it is in scope is
12893     //   ill-formed unless the variable has scalar type, class type with a
12894     //   trivial default constructor and a trivial destructor, a cv-qualified
12895     //   version of one of these types, or an array of one of the preceding
12896     //   types and is declared without an initializer.
12897     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12898       if (const RecordType *Record
12899             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12900         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12901         // Mark the function (if we're in one) for further checking even if the
12902         // looser rules of C++11 do not require such checks, so that we can
12903         // diagnose incompatibilities with C++98.
12904         if (!CXXRecord->isPOD())
12905           setFunctionHasBranchProtectedScope();
12906       }
12907     }
12908     // In OpenCL, we can't initialize objects in the __local address space,
12909     // even implicitly, so don't synthesize an implicit initializer.
12910     if (getLangOpts().OpenCL &&
12911         Var->getType().getAddressSpace() == LangAS::opencl_local)
12912       return;
12913     // C++03 [dcl.init]p9:
12914     //   If no initializer is specified for an object, and the
12915     //   object is of (possibly cv-qualified) non-POD class type (or
12916     //   array thereof), the object shall be default-initialized; if
12917     //   the object is of const-qualified type, the underlying class
12918     //   type shall have a user-declared default
12919     //   constructor. Otherwise, if no initializer is specified for
12920     //   a non- static object, the object and its subobjects, if
12921     //   any, have an indeterminate initial value); if the object
12922     //   or any of its subobjects are of const-qualified type, the
12923     //   program is ill-formed.
12924     // C++0x [dcl.init]p11:
12925     //   If no initializer is specified for an object, the object is
12926     //   default-initialized; [...].
12927     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12928     InitializationKind Kind
12929       = InitializationKind::CreateDefault(Var->getLocation());
12930 
12931     InitializationSequence InitSeq(*this, Entity, Kind, None);
12932     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12933 
12934     if (Init.get()) {
12935       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12936       // This is important for template substitution.
12937       Var->setInitStyle(VarDecl::CallInit);
12938     } else if (Init.isInvalid()) {
12939       // If default-init fails, attach a recovery-expr initializer to track
12940       // that initialization was attempted and failed.
12941       auto RecoveryExpr =
12942           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12943       if (RecoveryExpr.get())
12944         Var->setInit(RecoveryExpr.get());
12945     }
12946 
12947     CheckCompleteVariableDeclaration(Var);
12948   }
12949 }
12950 
12951 void Sema::ActOnCXXForRangeDecl(Decl *D) {
12952   // If there is no declaration, there was an error parsing it. Ignore it.
12953   if (!D)
12954     return;
12955 
12956   VarDecl *VD = dyn_cast<VarDecl>(D);
12957   if (!VD) {
12958     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12959     D->setInvalidDecl();
12960     return;
12961   }
12962 
12963   VD->setCXXForRangeDecl(true);
12964 
12965   // for-range-declaration cannot be given a storage class specifier.
12966   int Error = -1;
12967   switch (VD->getStorageClass()) {
12968   case SC_None:
12969     break;
12970   case SC_Extern:
12971     Error = 0;
12972     break;
12973   case SC_Static:
12974     Error = 1;
12975     break;
12976   case SC_PrivateExtern:
12977     Error = 2;
12978     break;
12979   case SC_Auto:
12980     Error = 3;
12981     break;
12982   case SC_Register:
12983     Error = 4;
12984     break;
12985   }
12986 
12987   // for-range-declaration cannot be given a storage class specifier con't.
12988   switch (VD->getTSCSpec()) {
12989   case TSCS_thread_local:
12990     Error = 6;
12991     break;
12992   case TSCS___thread:
12993   case TSCS__Thread_local:
12994   case TSCS_unspecified:
12995     break;
12996   }
12997 
12998   if (Error != -1) {
12999     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13000         << VD << Error;
13001     D->setInvalidDecl();
13002   }
13003 }
13004 
13005 StmtResult
13006 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13007                                  IdentifierInfo *Ident,
13008                                  ParsedAttributes &Attrs,
13009                                  SourceLocation AttrEnd) {
13010   // C++1y [stmt.iter]p1:
13011   //   A range-based for statement of the form
13012   //      for ( for-range-identifier : for-range-initializer ) statement
13013   //   is equivalent to
13014   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13015   DeclSpec DS(Attrs.getPool().getFactory());
13016 
13017   const char *PrevSpec;
13018   unsigned DiagID;
13019   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13020                      getPrintingPolicy());
13021 
13022   Declarator D(DS, DeclaratorContext::ForInit);
13023   D.SetIdentifier(Ident, IdentLoc);
13024   D.takeAttributes(Attrs, AttrEnd);
13025 
13026   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13027                 IdentLoc);
13028   Decl *Var = ActOnDeclarator(S, D);
13029   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13030   FinalizeDeclaration(Var);
13031   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13032                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13033 }
13034 
13035 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13036   if (var->isInvalidDecl()) return;
13037 
13038   MaybeAddCUDAConstantAttr(var);
13039 
13040   if (getLangOpts().OpenCL) {
13041     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13042     // initialiser
13043     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13044         !var->hasInit()) {
13045       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13046           << 1 /*Init*/;
13047       var->setInvalidDecl();
13048       return;
13049     }
13050   }
13051 
13052   // In Objective-C, don't allow jumps past the implicit initialization of a
13053   // local retaining variable.
13054   if (getLangOpts().ObjC &&
13055       var->hasLocalStorage()) {
13056     switch (var->getType().getObjCLifetime()) {
13057     case Qualifiers::OCL_None:
13058     case Qualifiers::OCL_ExplicitNone:
13059     case Qualifiers::OCL_Autoreleasing:
13060       break;
13061 
13062     case Qualifiers::OCL_Weak:
13063     case Qualifiers::OCL_Strong:
13064       setFunctionHasBranchProtectedScope();
13065       break;
13066     }
13067   }
13068 
13069   if (var->hasLocalStorage() &&
13070       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13071     setFunctionHasBranchProtectedScope();
13072 
13073   // Warn about externally-visible variables being defined without a
13074   // prior declaration.  We only want to do this for global
13075   // declarations, but we also specifically need to avoid doing it for
13076   // class members because the linkage of an anonymous class can
13077   // change if it's later given a typedef name.
13078   if (var->isThisDeclarationADefinition() &&
13079       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13080       var->isExternallyVisible() && var->hasLinkage() &&
13081       !var->isInline() && !var->getDescribedVarTemplate() &&
13082       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13083       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13084       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13085                                   var->getLocation())) {
13086     // Find a previous declaration that's not a definition.
13087     VarDecl *prev = var->getPreviousDecl();
13088     while (prev && prev->isThisDeclarationADefinition())
13089       prev = prev->getPreviousDecl();
13090 
13091     if (!prev) {
13092       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13093       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13094           << /* variable */ 0;
13095     }
13096   }
13097 
13098   // Cache the result of checking for constant initialization.
13099   Optional<bool> CacheHasConstInit;
13100   const Expr *CacheCulprit = nullptr;
13101   auto checkConstInit = [&]() mutable {
13102     if (!CacheHasConstInit)
13103       CacheHasConstInit = var->getInit()->isConstantInitializer(
13104             Context, var->getType()->isReferenceType(), &CacheCulprit);
13105     return *CacheHasConstInit;
13106   };
13107 
13108   if (var->getTLSKind() == VarDecl::TLS_Static) {
13109     if (var->getType().isDestructedType()) {
13110       // GNU C++98 edits for __thread, [basic.start.term]p3:
13111       //   The type of an object with thread storage duration shall not
13112       //   have a non-trivial destructor.
13113       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13114       if (getLangOpts().CPlusPlus11)
13115         Diag(var->getLocation(), diag::note_use_thread_local);
13116     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13117       if (!checkConstInit()) {
13118         // GNU C++98 edits for __thread, [basic.start.init]p4:
13119         //   An object of thread storage duration shall not require dynamic
13120         //   initialization.
13121         // FIXME: Need strict checking here.
13122         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13123           << CacheCulprit->getSourceRange();
13124         if (getLangOpts().CPlusPlus11)
13125           Diag(var->getLocation(), diag::note_use_thread_local);
13126       }
13127     }
13128   }
13129 
13130 
13131   if (!var->getType()->isStructureType() && var->hasInit() &&
13132       isa<InitListExpr>(var->getInit())) {
13133     const auto *ILE = cast<InitListExpr>(var->getInit());
13134     unsigned NumInits = ILE->getNumInits();
13135     if (NumInits > 2)
13136       for (unsigned I = 0; I < NumInits; ++I) {
13137         const auto *Init = ILE->getInit(I);
13138         if (!Init)
13139           break;
13140         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13141         if (!SL)
13142           break;
13143 
13144         unsigned NumConcat = SL->getNumConcatenated();
13145         // Diagnose missing comma in string array initialization.
13146         // Do not warn when all the elements in the initializer are concatenated
13147         // together. Do not warn for macros too.
13148         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13149           bool OnlyOneMissingComma = true;
13150           for (unsigned J = I + 1; J < NumInits; ++J) {
13151             const auto *Init = ILE->getInit(J);
13152             if (!Init)
13153               break;
13154             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13155             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13156               OnlyOneMissingComma = false;
13157               break;
13158             }
13159           }
13160 
13161           if (OnlyOneMissingComma) {
13162             SmallVector<FixItHint, 1> Hints;
13163             for (unsigned i = 0; i < NumConcat - 1; ++i)
13164               Hints.push_back(FixItHint::CreateInsertion(
13165                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13166 
13167             Diag(SL->getStrTokenLoc(1),
13168                  diag::warn_concatenated_literal_array_init)
13169                 << Hints;
13170             Diag(SL->getBeginLoc(),
13171                  diag::note_concatenated_string_literal_silence);
13172           }
13173           // In any case, stop now.
13174           break;
13175         }
13176       }
13177   }
13178 
13179 
13180   QualType type = var->getType();
13181 
13182   if (var->hasAttr<BlocksAttr>())
13183     getCurFunction()->addByrefBlockVar(var);
13184 
13185   Expr *Init = var->getInit();
13186   bool GlobalStorage = var->hasGlobalStorage();
13187   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13188   QualType baseType = Context.getBaseElementType(type);
13189   bool HasConstInit = true;
13190 
13191   // Check whether the initializer is sufficiently constant.
13192   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13193       !Init->isValueDependent() &&
13194       (GlobalStorage || var->isConstexpr() ||
13195        var->mightBeUsableInConstantExpressions(Context))) {
13196     // If this variable might have a constant initializer or might be usable in
13197     // constant expressions, check whether or not it actually is now.  We can't
13198     // do this lazily, because the result might depend on things that change
13199     // later, such as which constexpr functions happen to be defined.
13200     SmallVector<PartialDiagnosticAt, 8> Notes;
13201     if (!getLangOpts().CPlusPlus11) {
13202       // Prior to C++11, in contexts where a constant initializer is required,
13203       // the set of valid constant initializers is described by syntactic rules
13204       // in [expr.const]p2-6.
13205       // FIXME: Stricter checking for these rules would be useful for constinit /
13206       // -Wglobal-constructors.
13207       HasConstInit = checkConstInit();
13208 
13209       // Compute and cache the constant value, and remember that we have a
13210       // constant initializer.
13211       if (HasConstInit) {
13212         (void)var->checkForConstantInitialization(Notes);
13213         Notes.clear();
13214       } else if (CacheCulprit) {
13215         Notes.emplace_back(CacheCulprit->getExprLoc(),
13216                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13217         Notes.back().second << CacheCulprit->getSourceRange();
13218       }
13219     } else {
13220       // Evaluate the initializer to see if it's a constant initializer.
13221       HasConstInit = var->checkForConstantInitialization(Notes);
13222     }
13223 
13224     if (HasConstInit) {
13225       // FIXME: Consider replacing the initializer with a ConstantExpr.
13226     } else if (var->isConstexpr()) {
13227       SourceLocation DiagLoc = var->getLocation();
13228       // If the note doesn't add any useful information other than a source
13229       // location, fold it into the primary diagnostic.
13230       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13231                                    diag::note_invalid_subexpr_in_const_expr) {
13232         DiagLoc = Notes[0].first;
13233         Notes.clear();
13234       }
13235       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13236           << var << Init->getSourceRange();
13237       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13238         Diag(Notes[I].first, Notes[I].second);
13239     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13240       auto *Attr = var->getAttr<ConstInitAttr>();
13241       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13242           << Init->getSourceRange();
13243       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13244           << Attr->getRange() << Attr->isConstinit();
13245       for (auto &it : Notes)
13246         Diag(it.first, it.second);
13247     } else if (IsGlobal &&
13248                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13249                                            var->getLocation())) {
13250       // Warn about globals which don't have a constant initializer.  Don't
13251       // warn about globals with a non-trivial destructor because we already
13252       // warned about them.
13253       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13254       if (!(RD && !RD->hasTrivialDestructor())) {
13255         // checkConstInit() here permits trivial default initialization even in
13256         // C++11 onwards, where such an initializer is not a constant initializer
13257         // but nonetheless doesn't require a global constructor.
13258         if (!checkConstInit())
13259           Diag(var->getLocation(), diag::warn_global_constructor)
13260               << Init->getSourceRange();
13261       }
13262     }
13263   }
13264 
13265   // Apply section attributes and pragmas to global variables.
13266   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13267       !inTemplateInstantiation()) {
13268     PragmaStack<StringLiteral *> *Stack = nullptr;
13269     int SectionFlags = ASTContext::PSF_Read;
13270     if (var->getType().isConstQualified()) {
13271       if (HasConstInit)
13272         Stack = &ConstSegStack;
13273       else {
13274         Stack = &BSSSegStack;
13275         SectionFlags |= ASTContext::PSF_Write;
13276       }
13277     } else if (var->hasInit() && HasConstInit) {
13278       Stack = &DataSegStack;
13279       SectionFlags |= ASTContext::PSF_Write;
13280     } else {
13281       Stack = &BSSSegStack;
13282       SectionFlags |= ASTContext::PSF_Write;
13283     }
13284     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13285       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13286         SectionFlags |= ASTContext::PSF_Implicit;
13287       UnifySection(SA->getName(), SectionFlags, var);
13288     } else if (Stack->CurrentValue) {
13289       SectionFlags |= ASTContext::PSF_Implicit;
13290       auto SectionName = Stack->CurrentValue->getString();
13291       var->addAttr(SectionAttr::CreateImplicit(
13292           Context, SectionName, Stack->CurrentPragmaLocation,
13293           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13294       if (UnifySection(SectionName, SectionFlags, var))
13295         var->dropAttr<SectionAttr>();
13296     }
13297 
13298     // Apply the init_seg attribute if this has an initializer.  If the
13299     // initializer turns out to not be dynamic, we'll end up ignoring this
13300     // attribute.
13301     if (CurInitSeg && var->getInit())
13302       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13303                                                CurInitSegLoc,
13304                                                AttributeCommonInfo::AS_Pragma));
13305   }
13306 
13307   // All the following checks are C++ only.
13308   if (!getLangOpts().CPlusPlus) {
13309     // If this variable must be emitted, add it as an initializer for the
13310     // current module.
13311     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13312       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13313     return;
13314   }
13315 
13316   // Require the destructor.
13317   if (!type->isDependentType())
13318     if (const RecordType *recordType = baseType->getAs<RecordType>())
13319       FinalizeVarWithDestructor(var, recordType);
13320 
13321   // If this variable must be emitted, add it as an initializer for the current
13322   // module.
13323   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13324     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13325 
13326   // Build the bindings if this is a structured binding declaration.
13327   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13328     CheckCompleteDecompositionDeclaration(DD);
13329 }
13330 
13331 /// Check if VD needs to be dllexport/dllimport due to being in a
13332 /// dllexport/import function.
13333 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13334   assert(VD->isStaticLocal());
13335 
13336   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13337 
13338   // Find outermost function when VD is in lambda function.
13339   while (FD && !getDLLAttr(FD) &&
13340          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13341          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13342     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13343   }
13344 
13345   if (!FD)
13346     return;
13347 
13348   // Static locals inherit dll attributes from their function.
13349   if (Attr *A = getDLLAttr(FD)) {
13350     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13351     NewAttr->setInherited(true);
13352     VD->addAttr(NewAttr);
13353   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13354     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13355     NewAttr->setInherited(true);
13356     VD->addAttr(NewAttr);
13357 
13358     // Export this function to enforce exporting this static variable even
13359     // if it is not used in this compilation unit.
13360     if (!FD->hasAttr<DLLExportAttr>())
13361       FD->addAttr(NewAttr);
13362 
13363   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13364     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13365     NewAttr->setInherited(true);
13366     VD->addAttr(NewAttr);
13367   }
13368 }
13369 
13370 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13371 /// any semantic actions necessary after any initializer has been attached.
13372 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13373   // Note that we are no longer parsing the initializer for this declaration.
13374   ParsingInitForAutoVars.erase(ThisDecl);
13375 
13376   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13377   if (!VD)
13378     return;
13379 
13380   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13381   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13382       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13383     if (PragmaClangBSSSection.Valid)
13384       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13385           Context, PragmaClangBSSSection.SectionName,
13386           PragmaClangBSSSection.PragmaLocation,
13387           AttributeCommonInfo::AS_Pragma));
13388     if (PragmaClangDataSection.Valid)
13389       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13390           Context, PragmaClangDataSection.SectionName,
13391           PragmaClangDataSection.PragmaLocation,
13392           AttributeCommonInfo::AS_Pragma));
13393     if (PragmaClangRodataSection.Valid)
13394       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13395           Context, PragmaClangRodataSection.SectionName,
13396           PragmaClangRodataSection.PragmaLocation,
13397           AttributeCommonInfo::AS_Pragma));
13398     if (PragmaClangRelroSection.Valid)
13399       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13400           Context, PragmaClangRelroSection.SectionName,
13401           PragmaClangRelroSection.PragmaLocation,
13402           AttributeCommonInfo::AS_Pragma));
13403   }
13404 
13405   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13406     for (auto *BD : DD->bindings()) {
13407       FinalizeDeclaration(BD);
13408     }
13409   }
13410 
13411   checkAttributesAfterMerging(*this, *VD);
13412 
13413   // Perform TLS alignment check here after attributes attached to the variable
13414   // which may affect the alignment have been processed. Only perform the check
13415   // if the target has a maximum TLS alignment (zero means no constraints).
13416   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13417     // Protect the check so that it's not performed on dependent types and
13418     // dependent alignments (we can't determine the alignment in that case).
13419     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13420       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13421       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13422         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13423           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13424           << (unsigned)MaxAlignChars.getQuantity();
13425       }
13426     }
13427   }
13428 
13429   if (VD->isStaticLocal())
13430     CheckStaticLocalForDllExport(VD);
13431 
13432   // Perform check for initializers of device-side global variables.
13433   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13434   // 7.5). We must also apply the same checks to all __shared__
13435   // variables whether they are local or not. CUDA also allows
13436   // constant initializers for __constant__ and __device__ variables.
13437   if (getLangOpts().CUDA)
13438     checkAllowedCUDAInitializer(VD);
13439 
13440   // Grab the dllimport or dllexport attribute off of the VarDecl.
13441   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13442 
13443   // Imported static data members cannot be defined out-of-line.
13444   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13445     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13446         VD->isThisDeclarationADefinition()) {
13447       // We allow definitions of dllimport class template static data members
13448       // with a warning.
13449       CXXRecordDecl *Context =
13450         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13451       bool IsClassTemplateMember =
13452           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13453           Context->getDescribedClassTemplate();
13454 
13455       Diag(VD->getLocation(),
13456            IsClassTemplateMember
13457                ? diag::warn_attribute_dllimport_static_field_definition
13458                : diag::err_attribute_dllimport_static_field_definition);
13459       Diag(IA->getLocation(), diag::note_attribute);
13460       if (!IsClassTemplateMember)
13461         VD->setInvalidDecl();
13462     }
13463   }
13464 
13465   // dllimport/dllexport variables cannot be thread local, their TLS index
13466   // isn't exported with the variable.
13467   if (DLLAttr && VD->getTLSKind()) {
13468     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13469     if (F && getDLLAttr(F)) {
13470       assert(VD->isStaticLocal());
13471       // But if this is a static local in a dlimport/dllexport function, the
13472       // function will never be inlined, which means the var would never be
13473       // imported, so having it marked import/export is safe.
13474     } else {
13475       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13476                                                                     << DLLAttr;
13477       VD->setInvalidDecl();
13478     }
13479   }
13480 
13481   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13482     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13483       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13484           << Attr;
13485       VD->dropAttr<UsedAttr>();
13486     }
13487   }
13488   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13489     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13490       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13491           << Attr;
13492       VD->dropAttr<RetainAttr>();
13493     }
13494   }
13495 
13496   const DeclContext *DC = VD->getDeclContext();
13497   // If there's a #pragma GCC visibility in scope, and this isn't a class
13498   // member, set the visibility of this variable.
13499   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13500     AddPushedVisibilityAttribute(VD);
13501 
13502   // FIXME: Warn on unused var template partial specializations.
13503   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13504     MarkUnusedFileScopedDecl(VD);
13505 
13506   // Now we have parsed the initializer and can update the table of magic
13507   // tag values.
13508   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13509       !VD->getType()->isIntegralOrEnumerationType())
13510     return;
13511 
13512   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13513     const Expr *MagicValueExpr = VD->getInit();
13514     if (!MagicValueExpr) {
13515       continue;
13516     }
13517     Optional<llvm::APSInt> MagicValueInt;
13518     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13519       Diag(I->getRange().getBegin(),
13520            diag::err_type_tag_for_datatype_not_ice)
13521         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13522       continue;
13523     }
13524     if (MagicValueInt->getActiveBits() > 64) {
13525       Diag(I->getRange().getBegin(),
13526            diag::err_type_tag_for_datatype_too_large)
13527         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13528       continue;
13529     }
13530     uint64_t MagicValue = MagicValueInt->getZExtValue();
13531     RegisterTypeTagForDatatype(I->getArgumentKind(),
13532                                MagicValue,
13533                                I->getMatchingCType(),
13534                                I->getLayoutCompatible(),
13535                                I->getMustBeNull());
13536   }
13537 }
13538 
13539 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13540   auto *VD = dyn_cast<VarDecl>(DD);
13541   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13542 }
13543 
13544 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13545                                                    ArrayRef<Decl *> Group) {
13546   SmallVector<Decl*, 8> Decls;
13547 
13548   if (DS.isTypeSpecOwned())
13549     Decls.push_back(DS.getRepAsDecl());
13550 
13551   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13552   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13553   bool DiagnosedMultipleDecomps = false;
13554   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13555   bool DiagnosedNonDeducedAuto = false;
13556 
13557   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13558     if (Decl *D = Group[i]) {
13559       // For declarators, there are some additional syntactic-ish checks we need
13560       // to perform.
13561       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13562         if (!FirstDeclaratorInGroup)
13563           FirstDeclaratorInGroup = DD;
13564         if (!FirstDecompDeclaratorInGroup)
13565           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13566         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13567             !hasDeducedAuto(DD))
13568           FirstNonDeducedAutoInGroup = DD;
13569 
13570         if (FirstDeclaratorInGroup != DD) {
13571           // A decomposition declaration cannot be combined with any other
13572           // declaration in the same group.
13573           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13574             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13575                  diag::err_decomp_decl_not_alone)
13576                 << FirstDeclaratorInGroup->getSourceRange()
13577                 << DD->getSourceRange();
13578             DiagnosedMultipleDecomps = true;
13579           }
13580 
13581           // A declarator that uses 'auto' in any way other than to declare a
13582           // variable with a deduced type cannot be combined with any other
13583           // declarator in the same group.
13584           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13585             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13586                  diag::err_auto_non_deduced_not_alone)
13587                 << FirstNonDeducedAutoInGroup->getType()
13588                        ->hasAutoForTrailingReturnType()
13589                 << FirstDeclaratorInGroup->getSourceRange()
13590                 << DD->getSourceRange();
13591             DiagnosedNonDeducedAuto = true;
13592           }
13593         }
13594       }
13595 
13596       Decls.push_back(D);
13597     }
13598   }
13599 
13600   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13601     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13602       handleTagNumbering(Tag, S);
13603       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13604           getLangOpts().CPlusPlus)
13605         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13606     }
13607   }
13608 
13609   return BuildDeclaratorGroup(Decls);
13610 }
13611 
13612 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13613 /// group, performing any necessary semantic checking.
13614 Sema::DeclGroupPtrTy
13615 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13616   // C++14 [dcl.spec.auto]p7: (DR1347)
13617   //   If the type that replaces the placeholder type is not the same in each
13618   //   deduction, the program is ill-formed.
13619   if (Group.size() > 1) {
13620     QualType Deduced;
13621     VarDecl *DeducedDecl = nullptr;
13622     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13623       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13624       if (!D || D->isInvalidDecl())
13625         break;
13626       DeducedType *DT = D->getType()->getContainedDeducedType();
13627       if (!DT || DT->getDeducedType().isNull())
13628         continue;
13629       if (Deduced.isNull()) {
13630         Deduced = DT->getDeducedType();
13631         DeducedDecl = D;
13632       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13633         auto *AT = dyn_cast<AutoType>(DT);
13634         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13635                         diag::err_auto_different_deductions)
13636                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13637                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13638                    << D->getDeclName();
13639         if (DeducedDecl->hasInit())
13640           Dia << DeducedDecl->getInit()->getSourceRange();
13641         if (D->getInit())
13642           Dia << D->getInit()->getSourceRange();
13643         D->setInvalidDecl();
13644         break;
13645       }
13646     }
13647   }
13648 
13649   ActOnDocumentableDecls(Group);
13650 
13651   return DeclGroupPtrTy::make(
13652       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13653 }
13654 
13655 void Sema::ActOnDocumentableDecl(Decl *D) {
13656   ActOnDocumentableDecls(D);
13657 }
13658 
13659 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13660   // Don't parse the comment if Doxygen diagnostics are ignored.
13661   if (Group.empty() || !Group[0])
13662     return;
13663 
13664   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13665                       Group[0]->getLocation()) &&
13666       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13667                       Group[0]->getLocation()))
13668     return;
13669 
13670   if (Group.size() >= 2) {
13671     // This is a decl group.  Normally it will contain only declarations
13672     // produced from declarator list.  But in case we have any definitions or
13673     // additional declaration references:
13674     //   'typedef struct S {} S;'
13675     //   'typedef struct S *S;'
13676     //   'struct S *pS;'
13677     // FinalizeDeclaratorGroup adds these as separate declarations.
13678     Decl *MaybeTagDecl = Group[0];
13679     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13680       Group = Group.slice(1);
13681     }
13682   }
13683 
13684   // FIMXE: We assume every Decl in the group is in the same file.
13685   // This is false when preprocessor constructs the group from decls in
13686   // different files (e. g. macros or #include).
13687   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13688 }
13689 
13690 /// Common checks for a parameter-declaration that should apply to both function
13691 /// parameters and non-type template parameters.
13692 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13693   // Check that there are no default arguments inside the type of this
13694   // parameter.
13695   if (getLangOpts().CPlusPlus)
13696     CheckExtraCXXDefaultArguments(D);
13697 
13698   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13699   if (D.getCXXScopeSpec().isSet()) {
13700     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13701       << D.getCXXScopeSpec().getRange();
13702   }
13703 
13704   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13705   // simple identifier except [...irrelevant cases...].
13706   switch (D.getName().getKind()) {
13707   case UnqualifiedIdKind::IK_Identifier:
13708     break;
13709 
13710   case UnqualifiedIdKind::IK_OperatorFunctionId:
13711   case UnqualifiedIdKind::IK_ConversionFunctionId:
13712   case UnqualifiedIdKind::IK_LiteralOperatorId:
13713   case UnqualifiedIdKind::IK_ConstructorName:
13714   case UnqualifiedIdKind::IK_DestructorName:
13715   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13716   case UnqualifiedIdKind::IK_DeductionGuideName:
13717     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13718       << GetNameForDeclarator(D).getName();
13719     break;
13720 
13721   case UnqualifiedIdKind::IK_TemplateId:
13722   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13723     // GetNameForDeclarator would not produce a useful name in this case.
13724     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13725     break;
13726   }
13727 }
13728 
13729 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13730 /// to introduce parameters into function prototype scope.
13731 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13732   const DeclSpec &DS = D.getDeclSpec();
13733 
13734   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13735 
13736   // C++03 [dcl.stc]p2 also permits 'auto'.
13737   StorageClass SC = SC_None;
13738   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13739     SC = SC_Register;
13740     // In C++11, the 'register' storage class specifier is deprecated.
13741     // In C++17, it is not allowed, but we tolerate it as an extension.
13742     if (getLangOpts().CPlusPlus11) {
13743       Diag(DS.getStorageClassSpecLoc(),
13744            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13745                                      : diag::warn_deprecated_register)
13746         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13747     }
13748   } else if (getLangOpts().CPlusPlus &&
13749              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13750     SC = SC_Auto;
13751   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13752     Diag(DS.getStorageClassSpecLoc(),
13753          diag::err_invalid_storage_class_in_func_decl);
13754     D.getMutableDeclSpec().ClearStorageClassSpecs();
13755   }
13756 
13757   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13758     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13759       << DeclSpec::getSpecifierName(TSCS);
13760   if (DS.isInlineSpecified())
13761     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13762         << getLangOpts().CPlusPlus17;
13763   if (DS.hasConstexprSpecifier())
13764     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13765         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13766 
13767   DiagnoseFunctionSpecifiers(DS);
13768 
13769   CheckFunctionOrTemplateParamDeclarator(S, D);
13770 
13771   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13772   QualType parmDeclType = TInfo->getType();
13773 
13774   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13775   IdentifierInfo *II = D.getIdentifier();
13776   if (II) {
13777     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13778                    ForVisibleRedeclaration);
13779     LookupName(R, S);
13780     if (R.isSingleResult()) {
13781       NamedDecl *PrevDecl = R.getFoundDecl();
13782       if (PrevDecl->isTemplateParameter()) {
13783         // Maybe we will complain about the shadowed template parameter.
13784         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13785         // Just pretend that we didn't see the previous declaration.
13786         PrevDecl = nullptr;
13787       } else if (S->isDeclScope(PrevDecl)) {
13788         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13789         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13790 
13791         // Recover by removing the name
13792         II = nullptr;
13793         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13794         D.setInvalidType(true);
13795       }
13796     }
13797   }
13798 
13799   // Temporarily put parameter variables in the translation unit, not
13800   // the enclosing context.  This prevents them from accidentally
13801   // looking like class members in C++.
13802   ParmVarDecl *New =
13803       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13804                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13805 
13806   if (D.isInvalidType())
13807     New->setInvalidDecl();
13808 
13809   assert(S->isFunctionPrototypeScope());
13810   assert(S->getFunctionPrototypeDepth() >= 1);
13811   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13812                     S->getNextFunctionPrototypeIndex());
13813 
13814   // Add the parameter declaration into this scope.
13815   S->AddDecl(New);
13816   if (II)
13817     IdResolver.AddDecl(New);
13818 
13819   ProcessDeclAttributes(S, New, D);
13820 
13821   if (D.getDeclSpec().isModulePrivateSpecified())
13822     Diag(New->getLocation(), diag::err_module_private_local)
13823         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13824         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13825 
13826   if (New->hasAttr<BlocksAttr>()) {
13827     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13828   }
13829 
13830   if (getLangOpts().OpenCL)
13831     deduceOpenCLAddressSpace(New);
13832 
13833   return New;
13834 }
13835 
13836 /// Synthesizes a variable for a parameter arising from a
13837 /// typedef.
13838 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13839                                               SourceLocation Loc,
13840                                               QualType T) {
13841   /* FIXME: setting StartLoc == Loc.
13842      Would it be worth to modify callers so as to provide proper source
13843      location for the unnamed parameters, embedding the parameter's type? */
13844   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13845                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13846                                            SC_None, nullptr);
13847   Param->setImplicit();
13848   return Param;
13849 }
13850 
13851 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13852   // Don't diagnose unused-parameter errors in template instantiations; we
13853   // will already have done so in the template itself.
13854   if (inTemplateInstantiation())
13855     return;
13856 
13857   for (const ParmVarDecl *Parameter : Parameters) {
13858     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13859         !Parameter->hasAttr<UnusedAttr>()) {
13860       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13861         << Parameter->getDeclName();
13862     }
13863   }
13864 }
13865 
13866 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13867     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13868   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13869     return;
13870 
13871   // Warn if the return value is pass-by-value and larger than the specified
13872   // threshold.
13873   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13874     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13875     if (Size > LangOpts.NumLargeByValueCopy)
13876       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13877   }
13878 
13879   // Warn if any parameter is pass-by-value and larger than the specified
13880   // threshold.
13881   for (const ParmVarDecl *Parameter : Parameters) {
13882     QualType T = Parameter->getType();
13883     if (T->isDependentType() || !T.isPODType(Context))
13884       continue;
13885     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13886     if (Size > LangOpts.NumLargeByValueCopy)
13887       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13888           << Parameter << Size;
13889   }
13890 }
13891 
13892 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13893                                   SourceLocation NameLoc, IdentifierInfo *Name,
13894                                   QualType T, TypeSourceInfo *TSInfo,
13895                                   StorageClass SC) {
13896   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13897   if (getLangOpts().ObjCAutoRefCount &&
13898       T.getObjCLifetime() == Qualifiers::OCL_None &&
13899       T->isObjCLifetimeType()) {
13900 
13901     Qualifiers::ObjCLifetime lifetime;
13902 
13903     // Special cases for arrays:
13904     //   - if it's const, use __unsafe_unretained
13905     //   - otherwise, it's an error
13906     if (T->isArrayType()) {
13907       if (!T.isConstQualified()) {
13908         if (DelayedDiagnostics.shouldDelayDiagnostics())
13909           DelayedDiagnostics.add(
13910               sema::DelayedDiagnostic::makeForbiddenType(
13911               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13912         else
13913           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13914               << TSInfo->getTypeLoc().getSourceRange();
13915       }
13916       lifetime = Qualifiers::OCL_ExplicitNone;
13917     } else {
13918       lifetime = T->getObjCARCImplicitLifetime();
13919     }
13920     T = Context.getLifetimeQualifiedType(T, lifetime);
13921   }
13922 
13923   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13924                                          Context.getAdjustedParameterType(T),
13925                                          TSInfo, SC, nullptr);
13926 
13927   // Make a note if we created a new pack in the scope of a lambda, so that
13928   // we know that references to that pack must also be expanded within the
13929   // lambda scope.
13930   if (New->isParameterPack())
13931     if (auto *LSI = getEnclosingLambda())
13932       LSI->LocalPacks.push_back(New);
13933 
13934   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13935       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13936     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13937                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13938 
13939   // Parameters can not be abstract class types.
13940   // For record types, this is done by the AbstractClassUsageDiagnoser once
13941   // the class has been completely parsed.
13942   if (!CurContext->isRecord() &&
13943       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13944                              AbstractParamType))
13945     New->setInvalidDecl();
13946 
13947   // Parameter declarators cannot be interface types. All ObjC objects are
13948   // passed by reference.
13949   if (T->isObjCObjectType()) {
13950     SourceLocation TypeEndLoc =
13951         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13952     Diag(NameLoc,
13953          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13954       << FixItHint::CreateInsertion(TypeEndLoc, "*");
13955     T = Context.getObjCObjectPointerType(T);
13956     New->setType(T);
13957   }
13958 
13959   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13960   // duration shall not be qualified by an address-space qualifier."
13961   // Since all parameters have automatic store duration, they can not have
13962   // an address space.
13963   if (T.getAddressSpace() != LangAS::Default &&
13964       // OpenCL allows function arguments declared to be an array of a type
13965       // to be qualified with an address space.
13966       !(getLangOpts().OpenCL &&
13967         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13968     Diag(NameLoc, diag::err_arg_with_address_space);
13969     New->setInvalidDecl();
13970   }
13971 
13972   // PPC MMA non-pointer types are not allowed as function argument types.
13973   if (Context.getTargetInfo().getTriple().isPPC64() &&
13974       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13975     New->setInvalidDecl();
13976   }
13977 
13978   return New;
13979 }
13980 
13981 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13982                                            SourceLocation LocAfterDecls) {
13983   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13984 
13985   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13986   // for a K&R function.
13987   if (!FTI.hasPrototype) {
13988     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13989       --i;
13990       if (FTI.Params[i].Param == nullptr) {
13991         SmallString<256> Code;
13992         llvm::raw_svector_ostream(Code)
13993             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
13994         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13995             << FTI.Params[i].Ident
13996             << FixItHint::CreateInsertion(LocAfterDecls, Code);
13997 
13998         // Implicitly declare the argument as type 'int' for lack of a better
13999         // type.
14000         AttributeFactory attrs;
14001         DeclSpec DS(attrs);
14002         const char* PrevSpec; // unused
14003         unsigned DiagID; // unused
14004         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14005                            DiagID, Context.getPrintingPolicy());
14006         // Use the identifier location for the type source range.
14007         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14008         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14009         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14010         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14011         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14012       }
14013     }
14014   }
14015 }
14016 
14017 Decl *
14018 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14019                               MultiTemplateParamsArg TemplateParameterLists,
14020                               SkipBodyInfo *SkipBody) {
14021   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14022   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14023   Scope *ParentScope = FnBodyScope->getParent();
14024 
14025   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14026   // we define a non-templated function definition, we will create a declaration
14027   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14028   // The base function declaration will have the equivalent of an `omp declare
14029   // variant` annotation which specifies the mangled definition as a
14030   // specialization function under the OpenMP context defined as part of the
14031   // `omp begin declare variant`.
14032   SmallVector<FunctionDecl *, 4> Bases;
14033   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14034     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14035         ParentScope, D, TemplateParameterLists, Bases);
14036 
14037   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14038   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14039   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14040 
14041   if (!Bases.empty())
14042     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14043 
14044   return Dcl;
14045 }
14046 
14047 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14048   Consumer.HandleInlineFunctionDefinition(D);
14049 }
14050 
14051 static bool
14052 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14053                                 const FunctionDecl *&PossiblePrototype) {
14054   // Don't warn about invalid declarations.
14055   if (FD->isInvalidDecl())
14056     return false;
14057 
14058   // Or declarations that aren't global.
14059   if (!FD->isGlobal())
14060     return false;
14061 
14062   // Don't warn about C++ member functions.
14063   if (isa<CXXMethodDecl>(FD))
14064     return false;
14065 
14066   // Don't warn about 'main'.
14067   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14068     if (IdentifierInfo *II = FD->getIdentifier())
14069       if (II->isStr("main") || II->isStr("efi_main"))
14070         return false;
14071 
14072   // Don't warn about inline functions.
14073   if (FD->isInlined())
14074     return false;
14075 
14076   // Don't warn about function templates.
14077   if (FD->getDescribedFunctionTemplate())
14078     return false;
14079 
14080   // Don't warn about function template specializations.
14081   if (FD->isFunctionTemplateSpecialization())
14082     return false;
14083 
14084   // Don't warn for OpenCL kernels.
14085   if (FD->hasAttr<OpenCLKernelAttr>())
14086     return false;
14087 
14088   // Don't warn on explicitly deleted functions.
14089   if (FD->isDeleted())
14090     return false;
14091 
14092   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14093        Prev; Prev = Prev->getPreviousDecl()) {
14094     // Ignore any declarations that occur in function or method
14095     // scope, because they aren't visible from the header.
14096     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14097       continue;
14098 
14099     PossiblePrototype = Prev;
14100     return Prev->getType()->isFunctionNoProtoType();
14101   }
14102 
14103   return true;
14104 }
14105 
14106 void
14107 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14108                                    const FunctionDecl *EffectiveDefinition,
14109                                    SkipBodyInfo *SkipBody) {
14110   const FunctionDecl *Definition = EffectiveDefinition;
14111   if (!Definition &&
14112       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14113     return;
14114 
14115   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14116     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14117       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14118         // A merged copy of the same function, instantiated as a member of
14119         // the same class, is OK.
14120         if (declaresSameEntity(OrigFD, OrigDef) &&
14121             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14122                                cast<Decl>(FD->getLexicalDeclContext())))
14123           return;
14124       }
14125     }
14126   }
14127 
14128   if (canRedefineFunction(Definition, getLangOpts()))
14129     return;
14130 
14131   // Don't emit an error when this is redefinition of a typo-corrected
14132   // definition.
14133   if (TypoCorrectedFunctionDefinitions.count(Definition))
14134     return;
14135 
14136   // If we don't have a visible definition of the function, and it's inline or
14137   // a template, skip the new definition.
14138   if (SkipBody && !hasVisibleDefinition(Definition) &&
14139       (Definition->getFormalLinkage() == InternalLinkage ||
14140        Definition->isInlined() ||
14141        Definition->getDescribedFunctionTemplate() ||
14142        Definition->getNumTemplateParameterLists())) {
14143     SkipBody->ShouldSkip = true;
14144     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14145     if (auto *TD = Definition->getDescribedFunctionTemplate())
14146       makeMergedDefinitionVisible(TD);
14147     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14148     return;
14149   }
14150 
14151   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14152       Definition->getStorageClass() == SC_Extern)
14153     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14154         << FD << getLangOpts().CPlusPlus;
14155   else
14156     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14157 
14158   Diag(Definition->getLocation(), diag::note_previous_definition);
14159   FD->setInvalidDecl();
14160 }
14161 
14162 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14163                                    Sema &S) {
14164   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14165 
14166   LambdaScopeInfo *LSI = S.PushLambdaScope();
14167   LSI->CallOperator = CallOperator;
14168   LSI->Lambda = LambdaClass;
14169   LSI->ReturnType = CallOperator->getReturnType();
14170   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14171 
14172   if (LCD == LCD_None)
14173     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14174   else if (LCD == LCD_ByCopy)
14175     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14176   else if (LCD == LCD_ByRef)
14177     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14178   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14179 
14180   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14181   LSI->Mutable = !CallOperator->isConst();
14182 
14183   // Add the captures to the LSI so they can be noted as already
14184   // captured within tryCaptureVar.
14185   auto I = LambdaClass->field_begin();
14186   for (const auto &C : LambdaClass->captures()) {
14187     if (C.capturesVariable()) {
14188       VarDecl *VD = C.getCapturedVar();
14189       if (VD->isInitCapture())
14190         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14191       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14192       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14193           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14194           /*EllipsisLoc*/C.isPackExpansion()
14195                          ? C.getEllipsisLoc() : SourceLocation(),
14196           I->getType(), /*Invalid*/false);
14197 
14198     } else if (C.capturesThis()) {
14199       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14200                           C.getCaptureKind() == LCK_StarThis);
14201     } else {
14202       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14203                              I->getType());
14204     }
14205     ++I;
14206   }
14207 }
14208 
14209 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14210                                     SkipBodyInfo *SkipBody) {
14211   if (!D) {
14212     // Parsing the function declaration failed in some way. Push on a fake scope
14213     // anyway so we can try to parse the function body.
14214     PushFunctionScope();
14215     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14216     return D;
14217   }
14218 
14219   FunctionDecl *FD = nullptr;
14220 
14221   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14222     FD = FunTmpl->getTemplatedDecl();
14223   else
14224     FD = cast<FunctionDecl>(D);
14225 
14226   // Do not push if it is a lambda because one is already pushed when building
14227   // the lambda in ActOnStartOfLambdaDefinition().
14228   if (!isLambdaCallOperator(FD))
14229     PushExpressionEvaluationContext(
14230         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14231                           : ExprEvalContexts.back().Context);
14232 
14233   // Check for defining attributes before the check for redefinition.
14234   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14235     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14236     FD->dropAttr<AliasAttr>();
14237     FD->setInvalidDecl();
14238   }
14239   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14240     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14241     FD->dropAttr<IFuncAttr>();
14242     FD->setInvalidDecl();
14243   }
14244 
14245   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14246     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14247         Ctor->isDefaultConstructor() &&
14248         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14249       // If this is an MS ABI dllexport default constructor, instantiate any
14250       // default arguments.
14251       InstantiateDefaultCtorDefaultArgs(Ctor);
14252     }
14253   }
14254 
14255   // See if this is a redefinition. If 'will have body' (or similar) is already
14256   // set, then these checks were already performed when it was set.
14257   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14258       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14259     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14260 
14261     // If we're skipping the body, we're done. Don't enter the scope.
14262     if (SkipBody && SkipBody->ShouldSkip)
14263       return D;
14264   }
14265 
14266   // Mark this function as "will have a body eventually".  This lets users to
14267   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14268   // this function.
14269   FD->setWillHaveBody();
14270 
14271   // If we are instantiating a generic lambda call operator, push
14272   // a LambdaScopeInfo onto the function stack.  But use the information
14273   // that's already been calculated (ActOnLambdaExpr) to prime the current
14274   // LambdaScopeInfo.
14275   // When the template operator is being specialized, the LambdaScopeInfo,
14276   // has to be properly restored so that tryCaptureVariable doesn't try
14277   // and capture any new variables. In addition when calculating potential
14278   // captures during transformation of nested lambdas, it is necessary to
14279   // have the LSI properly restored.
14280   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14281     assert(inTemplateInstantiation() &&
14282            "There should be an active template instantiation on the stack "
14283            "when instantiating a generic lambda!");
14284     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14285   } else {
14286     // Enter a new function scope
14287     PushFunctionScope();
14288   }
14289 
14290   // Builtin functions cannot be defined.
14291   if (unsigned BuiltinID = FD->getBuiltinID()) {
14292     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14293         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14294       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14295       FD->setInvalidDecl();
14296     }
14297   }
14298 
14299   // The return type of a function definition must be complete
14300   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14301   QualType ResultType = FD->getReturnType();
14302   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14303       !FD->isInvalidDecl() &&
14304       RequireCompleteType(FD->getLocation(), ResultType,
14305                           diag::err_func_def_incomplete_result))
14306     FD->setInvalidDecl();
14307 
14308   if (FnBodyScope)
14309     PushDeclContext(FnBodyScope, FD);
14310 
14311   // Check the validity of our function parameters
14312   CheckParmsForFunctionDef(FD->parameters(),
14313                            /*CheckParameterNames=*/true);
14314 
14315   // Add non-parameter declarations already in the function to the current
14316   // scope.
14317   if (FnBodyScope) {
14318     for (Decl *NPD : FD->decls()) {
14319       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14320       if (!NonParmDecl)
14321         continue;
14322       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14323              "parameters should not be in newly created FD yet");
14324 
14325       // If the decl has a name, make it accessible in the current scope.
14326       if (NonParmDecl->getDeclName())
14327         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14328 
14329       // Similarly, dive into enums and fish their constants out, making them
14330       // accessible in this scope.
14331       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14332         for (auto *EI : ED->enumerators())
14333           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14334       }
14335     }
14336   }
14337 
14338   // Introduce our parameters into the function scope
14339   for (auto Param : FD->parameters()) {
14340     Param->setOwningFunction(FD);
14341 
14342     // If this has an identifier, add it to the scope stack.
14343     if (Param->getIdentifier() && FnBodyScope) {
14344       CheckShadow(FnBodyScope, Param);
14345 
14346       PushOnScopeChains(Param, FnBodyScope);
14347     }
14348   }
14349 
14350   // Ensure that the function's exception specification is instantiated.
14351   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14352     ResolveExceptionSpec(D->getLocation(), FPT);
14353 
14354   // dllimport cannot be applied to non-inline function definitions.
14355   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14356       !FD->isTemplateInstantiation()) {
14357     assert(!FD->hasAttr<DLLExportAttr>());
14358     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14359     FD->setInvalidDecl();
14360     return D;
14361   }
14362   // We want to attach documentation to original Decl (which might be
14363   // a function template).
14364   ActOnDocumentableDecl(D);
14365   if (getCurLexicalContext()->isObjCContainer() &&
14366       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14367       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14368     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14369 
14370   return D;
14371 }
14372 
14373 /// Given the set of return statements within a function body,
14374 /// compute the variables that are subject to the named return value
14375 /// optimization.
14376 ///
14377 /// Each of the variables that is subject to the named return value
14378 /// optimization will be marked as NRVO variables in the AST, and any
14379 /// return statement that has a marked NRVO variable as its NRVO candidate can
14380 /// use the named return value optimization.
14381 ///
14382 /// This function applies a very simplistic algorithm for NRVO: if every return
14383 /// statement in the scope of a variable has the same NRVO candidate, that
14384 /// candidate is an NRVO variable.
14385 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14386   ReturnStmt **Returns = Scope->Returns.data();
14387 
14388   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14389     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14390       if (!NRVOCandidate->isNRVOVariable())
14391         Returns[I]->setNRVOCandidate(nullptr);
14392     }
14393   }
14394 }
14395 
14396 bool Sema::canDelayFunctionBody(const Declarator &D) {
14397   // We can't delay parsing the body of a constexpr function template (yet).
14398   if (D.getDeclSpec().hasConstexprSpecifier())
14399     return false;
14400 
14401   // We can't delay parsing the body of a function template with a deduced
14402   // return type (yet).
14403   if (D.getDeclSpec().hasAutoTypeSpec()) {
14404     // If the placeholder introduces a non-deduced trailing return type,
14405     // we can still delay parsing it.
14406     if (D.getNumTypeObjects()) {
14407       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14408       if (Outer.Kind == DeclaratorChunk::Function &&
14409           Outer.Fun.hasTrailingReturnType()) {
14410         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14411         return Ty.isNull() || !Ty->isUndeducedType();
14412       }
14413     }
14414     return false;
14415   }
14416 
14417   return true;
14418 }
14419 
14420 bool Sema::canSkipFunctionBody(Decl *D) {
14421   // We cannot skip the body of a function (or function template) which is
14422   // constexpr, since we may need to evaluate its body in order to parse the
14423   // rest of the file.
14424   // We cannot skip the body of a function with an undeduced return type,
14425   // because any callers of that function need to know the type.
14426   if (const FunctionDecl *FD = D->getAsFunction()) {
14427     if (FD->isConstexpr())
14428       return false;
14429     // We can't simply call Type::isUndeducedType here, because inside template
14430     // auto can be deduced to a dependent type, which is not considered
14431     // "undeduced".
14432     if (FD->getReturnType()->getContainedDeducedType())
14433       return false;
14434   }
14435   return Consumer.shouldSkipFunctionBody(D);
14436 }
14437 
14438 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14439   if (!Decl)
14440     return nullptr;
14441   if (FunctionDecl *FD = Decl->getAsFunction())
14442     FD->setHasSkippedBody();
14443   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14444     MD->setHasSkippedBody();
14445   return Decl;
14446 }
14447 
14448 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14449   return ActOnFinishFunctionBody(D, BodyArg, false);
14450 }
14451 
14452 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14453 /// body.
14454 class ExitFunctionBodyRAII {
14455 public:
14456   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14457   ~ExitFunctionBodyRAII() {
14458     if (!IsLambda)
14459       S.PopExpressionEvaluationContext();
14460   }
14461 
14462 private:
14463   Sema &S;
14464   bool IsLambda = false;
14465 };
14466 
14467 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14468   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14469 
14470   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14471     if (EscapeInfo.count(BD))
14472       return EscapeInfo[BD];
14473 
14474     bool R = false;
14475     const BlockDecl *CurBD = BD;
14476 
14477     do {
14478       R = !CurBD->doesNotEscape();
14479       if (R)
14480         break;
14481       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14482     } while (CurBD);
14483 
14484     return EscapeInfo[BD] = R;
14485   };
14486 
14487   // If the location where 'self' is implicitly retained is inside a escaping
14488   // block, emit a diagnostic.
14489   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14490        S.ImplicitlyRetainedSelfLocs)
14491     if (IsOrNestedInEscapingBlock(P.second))
14492       S.Diag(P.first, diag::warn_implicitly_retains_self)
14493           << FixItHint::CreateInsertion(P.first, "self->");
14494 }
14495 
14496 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14497                                     bool IsInstantiation) {
14498   FunctionScopeInfo *FSI = getCurFunction();
14499   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14500 
14501   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14502     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14503 
14504   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14505   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14506 
14507   if (getLangOpts().Coroutines && FSI->isCoroutine())
14508     CheckCompletedCoroutineBody(FD, Body);
14509 
14510   {
14511     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14512     // one is already popped when finishing the lambda in BuildLambdaExpr().
14513     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14514     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14515 
14516     if (FD) {
14517       FD->setBody(Body);
14518       FD->setWillHaveBody(false);
14519 
14520       if (getLangOpts().CPlusPlus14) {
14521         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14522             FD->getReturnType()->isUndeducedType()) {
14523           // If the function has a deduced result type but contains no 'return'
14524           // statements, the result type as written must be exactly 'auto', and
14525           // the deduced result type is 'void'.
14526           if (!FD->getReturnType()->getAs<AutoType>()) {
14527             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14528                 << FD->getReturnType();
14529             FD->setInvalidDecl();
14530           } else {
14531             // Substitute 'void' for the 'auto' in the type.
14532             TypeLoc ResultType = getReturnTypeLoc(FD);
14533             Context.adjustDeducedFunctionResultType(
14534                 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14535           }
14536         }
14537       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14538         // In C++11, we don't use 'auto' deduction rules for lambda call
14539         // operators because we don't support return type deduction.
14540         auto *LSI = getCurLambda();
14541         if (LSI->HasImplicitReturnType) {
14542           deduceClosureReturnType(*LSI);
14543 
14544           // C++11 [expr.prim.lambda]p4:
14545           //   [...] if there are no return statements in the compound-statement
14546           //   [the deduced type is] the type void
14547           QualType RetType =
14548               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14549 
14550           // Update the return type to the deduced type.
14551           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14552           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14553                                               Proto->getExtProtoInfo()));
14554         }
14555       }
14556 
14557       // If the function implicitly returns zero (like 'main') or is naked,
14558       // don't complain about missing return statements.
14559       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14560         WP.disableCheckFallThrough();
14561 
14562       // MSVC permits the use of pure specifier (=0) on function definition,
14563       // defined at class scope, warn about this non-standard construct.
14564       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14565         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14566 
14567       if (!FD->isInvalidDecl()) {
14568         // Don't diagnose unused parameters of defaulted or deleted functions.
14569         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14570           DiagnoseUnusedParameters(FD->parameters());
14571         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14572                                                FD->getReturnType(), FD);
14573 
14574         // If this is a structor, we need a vtable.
14575         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14576           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14577         else if (CXXDestructorDecl *Destructor =
14578                      dyn_cast<CXXDestructorDecl>(FD))
14579           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14580 
14581         // Try to apply the named return value optimization. We have to check
14582         // if we can do this here because lambdas keep return statements around
14583         // to deduce an implicit return type.
14584         if (FD->getReturnType()->isRecordType() &&
14585             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14586           computeNRVO(Body, FSI);
14587       }
14588 
14589       // GNU warning -Wmissing-prototypes:
14590       //   Warn if a global function is defined without a previous
14591       //   prototype declaration. This warning is issued even if the
14592       //   definition itself provides a prototype. The aim is to detect
14593       //   global functions that fail to be declared in header files.
14594       const FunctionDecl *PossiblePrototype = nullptr;
14595       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14596         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14597 
14598         if (PossiblePrototype) {
14599           // We found a declaration that is not a prototype,
14600           // but that could be a zero-parameter prototype
14601           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14602             TypeLoc TL = TI->getTypeLoc();
14603             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14604               Diag(PossiblePrototype->getLocation(),
14605                    diag::note_declaration_not_a_prototype)
14606                   << (FD->getNumParams() != 0)
14607                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14608                                                     FTL.getRParenLoc(), "void")
14609                                               : FixItHint{});
14610           }
14611         } else {
14612           // Returns true if the token beginning at this Loc is `const`.
14613           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14614                                   const LangOptions &LangOpts) {
14615             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14616             if (LocInfo.first.isInvalid())
14617               return false;
14618 
14619             bool Invalid = false;
14620             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14621             if (Invalid)
14622               return false;
14623 
14624             if (LocInfo.second > Buffer.size())
14625               return false;
14626 
14627             const char *LexStart = Buffer.data() + LocInfo.second;
14628             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14629 
14630             return StartTok.consume_front("const") &&
14631                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14632                     StartTok.startswith("/*") || StartTok.startswith("//"));
14633           };
14634 
14635           auto findBeginLoc = [&]() {
14636             // If the return type has `const` qualifier, we want to insert
14637             // `static` before `const` (and not before the typename).
14638             if ((FD->getReturnType()->isAnyPointerType() &&
14639                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14640                 FD->getReturnType().isConstQualified()) {
14641               // But only do this if we can determine where the `const` is.
14642 
14643               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14644                                getLangOpts()))
14645 
14646                 return FD->getBeginLoc();
14647             }
14648             return FD->getTypeSpecStartLoc();
14649           };
14650           Diag(FD->getTypeSpecStartLoc(),
14651                diag::note_static_for_internal_linkage)
14652               << /* function */ 1
14653               << (FD->getStorageClass() == SC_None
14654                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14655                       : FixItHint{});
14656         }
14657 
14658         // GNU warning -Wstrict-prototypes
14659         //   Warn if K&R function is defined without a previous declaration.
14660         //   This warning is issued only if the definition itself does not
14661         //   provide a prototype. Only K&R definitions do not provide a
14662         //   prototype.
14663         if (!FD->hasWrittenPrototype()) {
14664           TypeSourceInfo *TI = FD->getTypeSourceInfo();
14665           TypeLoc TL = TI->getTypeLoc();
14666           FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14667           Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14668         }
14669       }
14670 
14671       // Warn on CPUDispatch with an actual body.
14672       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14673         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14674           if (!CmpndBody->body_empty())
14675             Diag(CmpndBody->body_front()->getBeginLoc(),
14676                  diag::warn_dispatch_body_ignored);
14677 
14678       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14679         const CXXMethodDecl *KeyFunction;
14680         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14681             MD->isVirtual() &&
14682             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14683             MD == KeyFunction->getCanonicalDecl()) {
14684           // Update the key-function state if necessary for this ABI.
14685           if (FD->isInlined() &&
14686               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14687             Context.setNonKeyFunction(MD);
14688 
14689             // If the newly-chosen key function is already defined, then we
14690             // need to mark the vtable as used retroactively.
14691             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14692             const FunctionDecl *Definition;
14693             if (KeyFunction && KeyFunction->isDefined(Definition))
14694               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14695           } else {
14696             // We just defined they key function; mark the vtable as used.
14697             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14698           }
14699         }
14700       }
14701 
14702       assert(
14703           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14704           "Function parsing confused");
14705     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14706       assert(MD == getCurMethodDecl() && "Method parsing confused");
14707       MD->setBody(Body);
14708       if (!MD->isInvalidDecl()) {
14709         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14710                                                MD->getReturnType(), MD);
14711 
14712         if (Body)
14713           computeNRVO(Body, FSI);
14714       }
14715       if (FSI->ObjCShouldCallSuper) {
14716         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14717             << MD->getSelector().getAsString();
14718         FSI->ObjCShouldCallSuper = false;
14719       }
14720       if (FSI->ObjCWarnForNoDesignatedInitChain) {
14721         const ObjCMethodDecl *InitMethod = nullptr;
14722         bool isDesignated =
14723             MD->isDesignatedInitializerForTheInterface(&InitMethod);
14724         assert(isDesignated && InitMethod);
14725         (void)isDesignated;
14726 
14727         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14728           auto IFace = MD->getClassInterface();
14729           if (!IFace)
14730             return false;
14731           auto SuperD = IFace->getSuperClass();
14732           if (!SuperD)
14733             return false;
14734           return SuperD->getIdentifier() ==
14735                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14736         };
14737         // Don't issue this warning for unavailable inits or direct subclasses
14738         // of NSObject.
14739         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14740           Diag(MD->getLocation(),
14741                diag::warn_objc_designated_init_missing_super_call);
14742           Diag(InitMethod->getLocation(),
14743                diag::note_objc_designated_init_marked_here);
14744         }
14745         FSI->ObjCWarnForNoDesignatedInitChain = false;
14746       }
14747       if (FSI->ObjCWarnForNoInitDelegation) {
14748         // Don't issue this warning for unavaialable inits.
14749         if (!MD->isUnavailable())
14750           Diag(MD->getLocation(),
14751                diag::warn_objc_secondary_init_missing_init_call);
14752         FSI->ObjCWarnForNoInitDelegation = false;
14753       }
14754 
14755       diagnoseImplicitlyRetainedSelf(*this);
14756     } else {
14757       // Parsing the function declaration failed in some way. Pop the fake scope
14758       // we pushed on.
14759       PopFunctionScopeInfo(ActivePolicy, dcl);
14760       return nullptr;
14761     }
14762 
14763     if (Body && FSI->HasPotentialAvailabilityViolations)
14764       DiagnoseUnguardedAvailabilityViolations(dcl);
14765 
14766     assert(!FSI->ObjCShouldCallSuper &&
14767            "This should only be set for ObjC methods, which should have been "
14768            "handled in the block above.");
14769 
14770     // Verify and clean out per-function state.
14771     if (Body && (!FD || !FD->isDefaulted())) {
14772       // C++ constructors that have function-try-blocks can't have return
14773       // statements in the handlers of that block. (C++ [except.handle]p14)
14774       // Verify this.
14775       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14776         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14777 
14778       // Verify that gotos and switch cases don't jump into scopes illegally.
14779       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
14780         DiagnoseInvalidJumps(Body);
14781 
14782       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14783         if (!Destructor->getParent()->isDependentType())
14784           CheckDestructor(Destructor);
14785 
14786         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14787                                                Destructor->getParent());
14788       }
14789 
14790       // If any errors have occurred, clear out any temporaries that may have
14791       // been leftover. This ensures that these temporaries won't be picked up
14792       // for deletion in some later function.
14793       if (hasUncompilableErrorOccurred() ||
14794           getDiagnostics().getSuppressAllDiagnostics()) {
14795         DiscardCleanupsInEvaluationContext();
14796       }
14797       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
14798         // Since the body is valid, issue any analysis-based warnings that are
14799         // enabled.
14800         ActivePolicy = &WP;
14801       }
14802 
14803       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14804           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14805         FD->setInvalidDecl();
14806 
14807       if (FD && FD->hasAttr<NakedAttr>()) {
14808         for (const Stmt *S : Body->children()) {
14809           // Allow local register variables without initializer as they don't
14810           // require prologue.
14811           bool RegisterVariables = false;
14812           if (auto *DS = dyn_cast<DeclStmt>(S)) {
14813             for (const auto *Decl : DS->decls()) {
14814               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14815                 RegisterVariables =
14816                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14817                 if (!RegisterVariables)
14818                   break;
14819               }
14820             }
14821           }
14822           if (RegisterVariables)
14823             continue;
14824           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14825             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14826             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14827             FD->setInvalidDecl();
14828             break;
14829           }
14830         }
14831       }
14832 
14833       assert(ExprCleanupObjects.size() ==
14834                  ExprEvalContexts.back().NumCleanupObjects &&
14835              "Leftover temporaries in function");
14836       assert(!Cleanup.exprNeedsCleanups() &&
14837              "Unaccounted cleanups in function");
14838       assert(MaybeODRUseExprs.empty() &&
14839              "Leftover expressions for odr-use checking");
14840     }
14841   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
14842     // the declaration context below. Otherwise, we're unable to transform
14843     // 'this' expressions when transforming immediate context functions.
14844 
14845   if (!IsInstantiation)
14846     PopDeclContext();
14847 
14848   PopFunctionScopeInfo(ActivePolicy, dcl);
14849   // If any errors have occurred, clear out any temporaries that may have
14850   // been leftover. This ensures that these temporaries won't be picked up for
14851   // deletion in some later function.
14852   if (hasUncompilableErrorOccurred()) {
14853     DiscardCleanupsInEvaluationContext();
14854   }
14855 
14856   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
14857                                   !LangOpts.OMPTargetTriples.empty())) ||
14858              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14859     auto ES = getEmissionStatus(FD);
14860     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14861         ES == Sema::FunctionEmissionStatus::Unknown)
14862       DeclsToCheckForDeferredDiags.insert(FD);
14863   }
14864 
14865   if (FD && !FD->isDeleted())
14866     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
14867 
14868   return dcl;
14869 }
14870 
14871 /// When we finish delayed parsing of an attribute, we must attach it to the
14872 /// relevant Decl.
14873 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14874                                        ParsedAttributes &Attrs) {
14875   // Always attach attributes to the underlying decl.
14876   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14877     D = TD->getTemplatedDecl();
14878   ProcessDeclAttributeList(S, D, Attrs);
14879 
14880   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14881     if (Method->isStatic())
14882       checkThisInStaticMemberFunctionAttributes(Method);
14883 }
14884 
14885 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14886 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14887 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14888                                           IdentifierInfo &II, Scope *S) {
14889   // Find the scope in which the identifier is injected and the corresponding
14890   // DeclContext.
14891   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14892   // In that case, we inject the declaration into the translation unit scope
14893   // instead.
14894   Scope *BlockScope = S;
14895   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14896     BlockScope = BlockScope->getParent();
14897 
14898   Scope *ContextScope = BlockScope;
14899   while (!ContextScope->getEntity())
14900     ContextScope = ContextScope->getParent();
14901   ContextRAII SavedContext(*this, ContextScope->getEntity());
14902 
14903   // Before we produce a declaration for an implicitly defined
14904   // function, see whether there was a locally-scoped declaration of
14905   // this name as a function or variable. If so, use that
14906   // (non-visible) declaration, and complain about it.
14907   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14908   if (ExternCPrev) {
14909     // We still need to inject the function into the enclosing block scope so
14910     // that later (non-call) uses can see it.
14911     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14912 
14913     // C89 footnote 38:
14914     //   If in fact it is not defined as having type "function returning int",
14915     //   the behavior is undefined.
14916     if (!isa<FunctionDecl>(ExternCPrev) ||
14917         !Context.typesAreCompatible(
14918             cast<FunctionDecl>(ExternCPrev)->getType(),
14919             Context.getFunctionNoProtoType(Context.IntTy))) {
14920       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14921           << ExternCPrev << !getLangOpts().C99;
14922       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14923       return ExternCPrev;
14924     }
14925   }
14926 
14927   // Extension in C99.  Legal in C90, but warn about it.
14928   unsigned diag_id;
14929   if (II.getName().startswith("__builtin_"))
14930     diag_id = diag::warn_builtin_unknown;
14931   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14932   else if (getLangOpts().OpenCL)
14933     diag_id = diag::err_opencl_implicit_function_decl;
14934   else if (getLangOpts().C99)
14935     diag_id = diag::ext_implicit_function_decl;
14936   else
14937     diag_id = diag::warn_implicit_function_decl;
14938   Diag(Loc, diag_id) << &II;
14939 
14940   // If we found a prior declaration of this function, don't bother building
14941   // another one. We've already pushed that one into scope, so there's nothing
14942   // more to do.
14943   if (ExternCPrev)
14944     return ExternCPrev;
14945 
14946   // Because typo correction is expensive, only do it if the implicit
14947   // function declaration is going to be treated as an error.
14948   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14949     TypoCorrection Corrected;
14950     DeclFilterCCC<FunctionDecl> CCC{};
14951     if (S && (Corrected =
14952                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14953                               S, nullptr, CCC, CTK_NonError)))
14954       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14955                    /*ErrorRecovery*/false);
14956   }
14957 
14958   // Set a Declarator for the implicit definition: int foo();
14959   const char *Dummy;
14960   AttributeFactory attrFactory;
14961   DeclSpec DS(attrFactory);
14962   unsigned DiagID;
14963   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14964                                   Context.getPrintingPolicy());
14965   (void)Error; // Silence warning.
14966   assert(!Error && "Error setting up implicit decl!");
14967   SourceLocation NoLoc;
14968   Declarator D(DS, DeclaratorContext::Block);
14969   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14970                                              /*IsAmbiguous=*/false,
14971                                              /*LParenLoc=*/NoLoc,
14972                                              /*Params=*/nullptr,
14973                                              /*NumParams=*/0,
14974                                              /*EllipsisLoc=*/NoLoc,
14975                                              /*RParenLoc=*/NoLoc,
14976                                              /*RefQualifierIsLvalueRef=*/true,
14977                                              /*RefQualifierLoc=*/NoLoc,
14978                                              /*MutableLoc=*/NoLoc, EST_None,
14979                                              /*ESpecRange=*/SourceRange(),
14980                                              /*Exceptions=*/nullptr,
14981                                              /*ExceptionRanges=*/nullptr,
14982                                              /*NumExceptions=*/0,
14983                                              /*NoexceptExpr=*/nullptr,
14984                                              /*ExceptionSpecTokens=*/nullptr,
14985                                              /*DeclsInPrototype=*/None, Loc,
14986                                              Loc, D),
14987                 std::move(DS.getAttributes()), SourceLocation());
14988   D.SetIdentifier(&II, Loc);
14989 
14990   // Insert this function into the enclosing block scope.
14991   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14992   FD->setImplicit();
14993 
14994   AddKnownFunctionAttributes(FD);
14995 
14996   return FD;
14997 }
14998 
14999 /// If this function is a C++ replaceable global allocation function
15000 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15001 /// adds any function attributes that we know a priori based on the standard.
15002 ///
15003 /// We need to check for duplicate attributes both here and where user-written
15004 /// attributes are applied to declarations.
15005 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15006     FunctionDecl *FD) {
15007   if (FD->isInvalidDecl())
15008     return;
15009 
15010   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15011       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15012     return;
15013 
15014   Optional<unsigned> AlignmentParam;
15015   bool IsNothrow = false;
15016   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15017     return;
15018 
15019   // C++2a [basic.stc.dynamic.allocation]p4:
15020   //   An allocation function that has a non-throwing exception specification
15021   //   indicates failure by returning a null pointer value. Any other allocation
15022   //   function never returns a null pointer value and indicates failure only by
15023   //   throwing an exception [...]
15024   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15025     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15026 
15027   // C++2a [basic.stc.dynamic.allocation]p2:
15028   //   An allocation function attempts to allocate the requested amount of
15029   //   storage. [...] If the request succeeds, the value returned by a
15030   //   replaceable allocation function is a [...] pointer value p0 different
15031   //   from any previously returned value p1 [...]
15032   //
15033   // However, this particular information is being added in codegen,
15034   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15035 
15036   // C++2a [basic.stc.dynamic.allocation]p2:
15037   //   An allocation function attempts to allocate the requested amount of
15038   //   storage. If it is successful, it returns the address of the start of a
15039   //   block of storage whose length in bytes is at least as large as the
15040   //   requested size.
15041   if (!FD->hasAttr<AllocSizeAttr>()) {
15042     FD->addAttr(AllocSizeAttr::CreateImplicit(
15043         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15044         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15045   }
15046 
15047   // C++2a [basic.stc.dynamic.allocation]p3:
15048   //   For an allocation function [...], the pointer returned on a successful
15049   //   call shall represent the address of storage that is aligned as follows:
15050   //   (3.1) If the allocation function takes an argument of type
15051   //         std​::​align_­val_­t, the storage will have the alignment
15052   //         specified by the value of this argument.
15053   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15054     FD->addAttr(AllocAlignAttr::CreateImplicit(
15055         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15056   }
15057 
15058   // FIXME:
15059   // C++2a [basic.stc.dynamic.allocation]p3:
15060   //   For an allocation function [...], the pointer returned on a successful
15061   //   call shall represent the address of storage that is aligned as follows:
15062   //   (3.2) Otherwise, if the allocation function is named operator new[],
15063   //         the storage is aligned for any object that does not have
15064   //         new-extended alignment ([basic.align]) and is no larger than the
15065   //         requested size.
15066   //   (3.3) Otherwise, the storage is aligned for any object that does not
15067   //         have new-extended alignment and is of the requested size.
15068 }
15069 
15070 /// Adds any function attributes that we know a priori based on
15071 /// the declaration of this function.
15072 ///
15073 /// These attributes can apply both to implicitly-declared builtins
15074 /// (like __builtin___printf_chk) or to library-declared functions
15075 /// like NSLog or printf.
15076 ///
15077 /// We need to check for duplicate attributes both here and where user-written
15078 /// attributes are applied to declarations.
15079 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15080   if (FD->isInvalidDecl())
15081     return;
15082 
15083   // If this is a built-in function, map its builtin attributes to
15084   // actual attributes.
15085   if (unsigned BuiltinID = FD->getBuiltinID()) {
15086     // Handle printf-formatting attributes.
15087     unsigned FormatIdx;
15088     bool HasVAListArg;
15089     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15090       if (!FD->hasAttr<FormatAttr>()) {
15091         const char *fmt = "printf";
15092         unsigned int NumParams = FD->getNumParams();
15093         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15094             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15095           fmt = "NSString";
15096         FD->addAttr(FormatAttr::CreateImplicit(Context,
15097                                                &Context.Idents.get(fmt),
15098                                                FormatIdx+1,
15099                                                HasVAListArg ? 0 : FormatIdx+2,
15100                                                FD->getLocation()));
15101       }
15102     }
15103     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15104                                              HasVAListArg)) {
15105      if (!FD->hasAttr<FormatAttr>())
15106        FD->addAttr(FormatAttr::CreateImplicit(Context,
15107                                               &Context.Idents.get("scanf"),
15108                                               FormatIdx+1,
15109                                               HasVAListArg ? 0 : FormatIdx+2,
15110                                               FD->getLocation()));
15111     }
15112 
15113     // Handle automatically recognized callbacks.
15114     SmallVector<int, 4> Encoding;
15115     if (!FD->hasAttr<CallbackAttr>() &&
15116         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15117       FD->addAttr(CallbackAttr::CreateImplicit(
15118           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15119 
15120     // Mark const if we don't care about errno and that is the only thing
15121     // preventing the function from being const. This allows IRgen to use LLVM
15122     // intrinsics for such functions.
15123     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15124         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15125       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15126 
15127     // We make "fma" on some platforms const because we know it does not set
15128     // errno in those environments even though it could set errno based on the
15129     // C standard.
15130     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15131     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15132         !FD->hasAttr<ConstAttr>()) {
15133       switch (BuiltinID) {
15134       case Builtin::BI__builtin_fma:
15135       case Builtin::BI__builtin_fmaf:
15136       case Builtin::BI__builtin_fmal:
15137       case Builtin::BIfma:
15138       case Builtin::BIfmaf:
15139       case Builtin::BIfmal:
15140         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15141         break;
15142       default:
15143         break;
15144       }
15145     }
15146 
15147     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15148         !FD->hasAttr<ReturnsTwiceAttr>())
15149       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15150                                          FD->getLocation()));
15151     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15152       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15153     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15154       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15155     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15156       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15157     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15158         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15159       // Add the appropriate attribute, depending on the CUDA compilation mode
15160       // and which target the builtin belongs to. For example, during host
15161       // compilation, aux builtins are __device__, while the rest are __host__.
15162       if (getLangOpts().CUDAIsDevice !=
15163           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15164         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15165       else
15166         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15167     }
15168 
15169     // Add known guaranteed alignment for allocation functions.
15170     switch (BuiltinID) {
15171     case Builtin::BIaligned_alloc:
15172       if (!FD->hasAttr<AllocAlignAttr>())
15173         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15174                                                    FD->getLocation()));
15175       LLVM_FALLTHROUGH;
15176     case Builtin::BIcalloc:
15177     case Builtin::BImalloc:
15178     case Builtin::BImemalign:
15179     case Builtin::BIrealloc:
15180     case Builtin::BIstrdup:
15181     case Builtin::BIstrndup: {
15182       if (!FD->hasAttr<AssumeAlignedAttr>()) {
15183         unsigned NewAlign = Context.getTargetInfo().getNewAlign() /
15184                             Context.getTargetInfo().getCharWidth();
15185         IntegerLiteral *Alignment = IntegerLiteral::Create(
15186             Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy),
15187             Context.UnsignedIntTy, FD->getLocation());
15188         FD->addAttr(AssumeAlignedAttr::CreateImplicit(
15189             Context, Alignment, /*Offset=*/nullptr, FD->getLocation()));
15190       }
15191       break;
15192     }
15193     default:
15194       break;
15195     }
15196   }
15197 
15198   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15199 
15200   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15201   // throw, add an implicit nothrow attribute to any extern "C" function we come
15202   // across.
15203   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15204       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15205     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15206     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15207       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15208   }
15209 
15210   IdentifierInfo *Name = FD->getIdentifier();
15211   if (!Name)
15212     return;
15213   if ((!getLangOpts().CPlusPlus &&
15214        FD->getDeclContext()->isTranslationUnit()) ||
15215       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15216        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15217        LinkageSpecDecl::lang_c)) {
15218     // Okay: this could be a libc/libm/Objective-C function we know
15219     // about.
15220   } else
15221     return;
15222 
15223   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15224     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15225     // target-specific builtins, perhaps?
15226     if (!FD->hasAttr<FormatAttr>())
15227       FD->addAttr(FormatAttr::CreateImplicit(Context,
15228                                              &Context.Idents.get("printf"), 2,
15229                                              Name->isStr("vasprintf") ? 0 : 3,
15230                                              FD->getLocation()));
15231   }
15232 
15233   if (Name->isStr("__CFStringMakeConstantString")) {
15234     // We already have a __builtin___CFStringMakeConstantString,
15235     // but builds that use -fno-constant-cfstrings don't go through that.
15236     if (!FD->hasAttr<FormatArgAttr>())
15237       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15238                                                 FD->getLocation()));
15239   }
15240 }
15241 
15242 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15243                                     TypeSourceInfo *TInfo) {
15244   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15245   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15246 
15247   if (!TInfo) {
15248     assert(D.isInvalidType() && "no declarator info for valid type");
15249     TInfo = Context.getTrivialTypeSourceInfo(T);
15250   }
15251 
15252   // Scope manipulation handled by caller.
15253   TypedefDecl *NewTD =
15254       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15255                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15256 
15257   // Bail out immediately if we have an invalid declaration.
15258   if (D.isInvalidType()) {
15259     NewTD->setInvalidDecl();
15260     return NewTD;
15261   }
15262 
15263   if (D.getDeclSpec().isModulePrivateSpecified()) {
15264     if (CurContext->isFunctionOrMethod())
15265       Diag(NewTD->getLocation(), diag::err_module_private_local)
15266           << 2 << NewTD
15267           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15268           << FixItHint::CreateRemoval(
15269                  D.getDeclSpec().getModulePrivateSpecLoc());
15270     else
15271       NewTD->setModulePrivate();
15272   }
15273 
15274   // C++ [dcl.typedef]p8:
15275   //   If the typedef declaration defines an unnamed class (or
15276   //   enum), the first typedef-name declared by the declaration
15277   //   to be that class type (or enum type) is used to denote the
15278   //   class type (or enum type) for linkage purposes only.
15279   // We need to check whether the type was declared in the declaration.
15280   switch (D.getDeclSpec().getTypeSpecType()) {
15281   case TST_enum:
15282   case TST_struct:
15283   case TST_interface:
15284   case TST_union:
15285   case TST_class: {
15286     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15287     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15288     break;
15289   }
15290 
15291   default:
15292     break;
15293   }
15294 
15295   return NewTD;
15296 }
15297 
15298 /// Check that this is a valid underlying type for an enum declaration.
15299 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15300   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15301   QualType T = TI->getType();
15302 
15303   if (T->isDependentType())
15304     return false;
15305 
15306   // This doesn't use 'isIntegralType' despite the error message mentioning
15307   // integral type because isIntegralType would also allow enum types in C.
15308   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15309     if (BT->isInteger())
15310       return false;
15311 
15312   if (T->isExtIntType())
15313     return false;
15314 
15315   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15316 }
15317 
15318 /// Check whether this is a valid redeclaration of a previous enumeration.
15319 /// \return true if the redeclaration was invalid.
15320 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15321                                   QualType EnumUnderlyingTy, bool IsFixed,
15322                                   const EnumDecl *Prev) {
15323   if (IsScoped != Prev->isScoped()) {
15324     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15325       << Prev->isScoped();
15326     Diag(Prev->getLocation(), diag::note_previous_declaration);
15327     return true;
15328   }
15329 
15330   if (IsFixed && Prev->isFixed()) {
15331     if (!EnumUnderlyingTy->isDependentType() &&
15332         !Prev->getIntegerType()->isDependentType() &&
15333         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15334                                         Prev->getIntegerType())) {
15335       // TODO: Highlight the underlying type of the redeclaration.
15336       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15337         << EnumUnderlyingTy << Prev->getIntegerType();
15338       Diag(Prev->getLocation(), diag::note_previous_declaration)
15339           << Prev->getIntegerTypeRange();
15340       return true;
15341     }
15342   } else if (IsFixed != Prev->isFixed()) {
15343     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15344       << Prev->isFixed();
15345     Diag(Prev->getLocation(), diag::note_previous_declaration);
15346     return true;
15347   }
15348 
15349   return false;
15350 }
15351 
15352 /// Get diagnostic %select index for tag kind for
15353 /// redeclaration diagnostic message.
15354 /// WARNING: Indexes apply to particular diagnostics only!
15355 ///
15356 /// \returns diagnostic %select index.
15357 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15358   switch (Tag) {
15359   case TTK_Struct: return 0;
15360   case TTK_Interface: return 1;
15361   case TTK_Class:  return 2;
15362   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15363   }
15364 }
15365 
15366 /// Determine if tag kind is a class-key compatible with
15367 /// class for redeclaration (class, struct, or __interface).
15368 ///
15369 /// \returns true iff the tag kind is compatible.
15370 static bool isClassCompatTagKind(TagTypeKind Tag)
15371 {
15372   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15373 }
15374 
15375 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15376                                              TagTypeKind TTK) {
15377   if (isa<TypedefDecl>(PrevDecl))
15378     return NTK_Typedef;
15379   else if (isa<TypeAliasDecl>(PrevDecl))
15380     return NTK_TypeAlias;
15381   else if (isa<ClassTemplateDecl>(PrevDecl))
15382     return NTK_Template;
15383   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15384     return NTK_TypeAliasTemplate;
15385   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15386     return NTK_TemplateTemplateArgument;
15387   switch (TTK) {
15388   case TTK_Struct:
15389   case TTK_Interface:
15390   case TTK_Class:
15391     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15392   case TTK_Union:
15393     return NTK_NonUnion;
15394   case TTK_Enum:
15395     return NTK_NonEnum;
15396   }
15397   llvm_unreachable("invalid TTK");
15398 }
15399 
15400 /// Determine whether a tag with a given kind is acceptable
15401 /// as a redeclaration of the given tag declaration.
15402 ///
15403 /// \returns true if the new tag kind is acceptable, false otherwise.
15404 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15405                                         TagTypeKind NewTag, bool isDefinition,
15406                                         SourceLocation NewTagLoc,
15407                                         const IdentifierInfo *Name) {
15408   // C++ [dcl.type.elab]p3:
15409   //   The class-key or enum keyword present in the
15410   //   elaborated-type-specifier shall agree in kind with the
15411   //   declaration to which the name in the elaborated-type-specifier
15412   //   refers. This rule also applies to the form of
15413   //   elaborated-type-specifier that declares a class-name or
15414   //   friend class since it can be construed as referring to the
15415   //   definition of the class. Thus, in any
15416   //   elaborated-type-specifier, the enum keyword shall be used to
15417   //   refer to an enumeration (7.2), the union class-key shall be
15418   //   used to refer to a union (clause 9), and either the class or
15419   //   struct class-key shall be used to refer to a class (clause 9)
15420   //   declared using the class or struct class-key.
15421   TagTypeKind OldTag = Previous->getTagKind();
15422   if (OldTag != NewTag &&
15423       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15424     return false;
15425 
15426   // Tags are compatible, but we might still want to warn on mismatched tags.
15427   // Non-class tags can't be mismatched at this point.
15428   if (!isClassCompatTagKind(NewTag))
15429     return true;
15430 
15431   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15432   // by our warning analysis. We don't want to warn about mismatches with (eg)
15433   // declarations in system headers that are designed to be specialized, but if
15434   // a user asks us to warn, we should warn if their code contains mismatched
15435   // declarations.
15436   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15437     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15438                                       Loc);
15439   };
15440   if (IsIgnoredLoc(NewTagLoc))
15441     return true;
15442 
15443   auto IsIgnored = [&](const TagDecl *Tag) {
15444     return IsIgnoredLoc(Tag->getLocation());
15445   };
15446   while (IsIgnored(Previous)) {
15447     Previous = Previous->getPreviousDecl();
15448     if (!Previous)
15449       return true;
15450     OldTag = Previous->getTagKind();
15451   }
15452 
15453   bool isTemplate = false;
15454   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15455     isTemplate = Record->getDescribedClassTemplate();
15456 
15457   if (inTemplateInstantiation()) {
15458     if (OldTag != NewTag) {
15459       // In a template instantiation, do not offer fix-its for tag mismatches
15460       // since they usually mess up the template instead of fixing the problem.
15461       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15462         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15463         << getRedeclDiagFromTagKind(OldTag);
15464       // FIXME: Note previous location?
15465     }
15466     return true;
15467   }
15468 
15469   if (isDefinition) {
15470     // On definitions, check all previous tags and issue a fix-it for each
15471     // one that doesn't match the current tag.
15472     if (Previous->getDefinition()) {
15473       // Don't suggest fix-its for redefinitions.
15474       return true;
15475     }
15476 
15477     bool previousMismatch = false;
15478     for (const TagDecl *I : Previous->redecls()) {
15479       if (I->getTagKind() != NewTag) {
15480         // Ignore previous declarations for which the warning was disabled.
15481         if (IsIgnored(I))
15482           continue;
15483 
15484         if (!previousMismatch) {
15485           previousMismatch = true;
15486           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15487             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15488             << getRedeclDiagFromTagKind(I->getTagKind());
15489         }
15490         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15491           << getRedeclDiagFromTagKind(NewTag)
15492           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15493                TypeWithKeyword::getTagTypeKindName(NewTag));
15494       }
15495     }
15496     return true;
15497   }
15498 
15499   // Identify the prevailing tag kind: this is the kind of the definition (if
15500   // there is a non-ignored definition), or otherwise the kind of the prior
15501   // (non-ignored) declaration.
15502   const TagDecl *PrevDef = Previous->getDefinition();
15503   if (PrevDef && IsIgnored(PrevDef))
15504     PrevDef = nullptr;
15505   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15506   if (Redecl->getTagKind() != NewTag) {
15507     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15508       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15509       << getRedeclDiagFromTagKind(OldTag);
15510     Diag(Redecl->getLocation(), diag::note_previous_use);
15511 
15512     // If there is a previous definition, suggest a fix-it.
15513     if (PrevDef) {
15514       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15515         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15516         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15517              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15518     }
15519   }
15520 
15521   return true;
15522 }
15523 
15524 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15525 /// from an outer enclosing namespace or file scope inside a friend declaration.
15526 /// This should provide the commented out code in the following snippet:
15527 ///   namespace N {
15528 ///     struct X;
15529 ///     namespace M {
15530 ///       struct Y { friend struct /*N::*/ X; };
15531 ///     }
15532 ///   }
15533 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15534                                          SourceLocation NameLoc) {
15535   // While the decl is in a namespace, do repeated lookup of that name and see
15536   // if we get the same namespace back.  If we do not, continue until
15537   // translation unit scope, at which point we have a fully qualified NNS.
15538   SmallVector<IdentifierInfo *, 4> Namespaces;
15539   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15540   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15541     // This tag should be declared in a namespace, which can only be enclosed by
15542     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15543     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15544     if (!Namespace || Namespace->isAnonymousNamespace())
15545       return FixItHint();
15546     IdentifierInfo *II = Namespace->getIdentifier();
15547     Namespaces.push_back(II);
15548     NamedDecl *Lookup = SemaRef.LookupSingleName(
15549         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15550     if (Lookup == Namespace)
15551       break;
15552   }
15553 
15554   // Once we have all the namespaces, reverse them to go outermost first, and
15555   // build an NNS.
15556   SmallString<64> Insertion;
15557   llvm::raw_svector_ostream OS(Insertion);
15558   if (DC->isTranslationUnit())
15559     OS << "::";
15560   std::reverse(Namespaces.begin(), Namespaces.end());
15561   for (auto *II : Namespaces)
15562     OS << II->getName() << "::";
15563   return FixItHint::CreateInsertion(NameLoc, Insertion);
15564 }
15565 
15566 /// Determine whether a tag originally declared in context \p OldDC can
15567 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15568 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15569 /// using-declaration).
15570 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15571                                          DeclContext *NewDC) {
15572   OldDC = OldDC->getRedeclContext();
15573   NewDC = NewDC->getRedeclContext();
15574 
15575   if (OldDC->Equals(NewDC))
15576     return true;
15577 
15578   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15579   // encloses the other).
15580   if (S.getLangOpts().MSVCCompat &&
15581       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15582     return true;
15583 
15584   return false;
15585 }
15586 
15587 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15588 /// former case, Name will be non-null.  In the later case, Name will be null.
15589 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15590 /// reference/declaration/definition of a tag.
15591 ///
15592 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15593 /// trailing-type-specifier) other than one in an alias-declaration.
15594 ///
15595 /// \param SkipBody If non-null, will be set to indicate if the caller should
15596 /// skip the definition of this tag and treat it as if it were a declaration.
15597 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15598                      SourceLocation KWLoc, CXXScopeSpec &SS,
15599                      IdentifierInfo *Name, SourceLocation NameLoc,
15600                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15601                      SourceLocation ModulePrivateLoc,
15602                      MultiTemplateParamsArg TemplateParameterLists,
15603                      bool &OwnedDecl, bool &IsDependent,
15604                      SourceLocation ScopedEnumKWLoc,
15605                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15606                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15607                      SkipBodyInfo *SkipBody) {
15608   // If this is not a definition, it must have a name.
15609   IdentifierInfo *OrigName = Name;
15610   assert((Name != nullptr || TUK == TUK_Definition) &&
15611          "Nameless record must be a definition!");
15612   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15613 
15614   OwnedDecl = false;
15615   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15616   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15617 
15618   // FIXME: Check member specializations more carefully.
15619   bool isMemberSpecialization = false;
15620   bool Invalid = false;
15621 
15622   // We only need to do this matching if we have template parameters
15623   // or a scope specifier, which also conveniently avoids this work
15624   // for non-C++ cases.
15625   if (TemplateParameterLists.size() > 0 ||
15626       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15627     if (TemplateParameterList *TemplateParams =
15628             MatchTemplateParametersToScopeSpecifier(
15629                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15630                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15631       if (Kind == TTK_Enum) {
15632         Diag(KWLoc, diag::err_enum_template);
15633         return nullptr;
15634       }
15635 
15636       if (TemplateParams->size() > 0) {
15637         // This is a declaration or definition of a class template (which may
15638         // be a member of another template).
15639 
15640         if (Invalid)
15641           return nullptr;
15642 
15643         OwnedDecl = false;
15644         DeclResult Result = CheckClassTemplate(
15645             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15646             AS, ModulePrivateLoc,
15647             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15648             TemplateParameterLists.data(), SkipBody);
15649         return Result.get();
15650       } else {
15651         // The "template<>" header is extraneous.
15652         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15653           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15654         isMemberSpecialization = true;
15655       }
15656     }
15657 
15658     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15659         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15660       return nullptr;
15661   }
15662 
15663   // Figure out the underlying type if this a enum declaration. We need to do
15664   // this early, because it's needed to detect if this is an incompatible
15665   // redeclaration.
15666   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15667   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15668 
15669   if (Kind == TTK_Enum) {
15670     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15671       // No underlying type explicitly specified, or we failed to parse the
15672       // type, default to int.
15673       EnumUnderlying = Context.IntTy.getTypePtr();
15674     } else if (UnderlyingType.get()) {
15675       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15676       // integral type; any cv-qualification is ignored.
15677       TypeSourceInfo *TI = nullptr;
15678       GetTypeFromParser(UnderlyingType.get(), &TI);
15679       EnumUnderlying = TI;
15680 
15681       if (CheckEnumUnderlyingType(TI))
15682         // Recover by falling back to int.
15683         EnumUnderlying = Context.IntTy.getTypePtr();
15684 
15685       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15686                                           UPPC_FixedUnderlyingType))
15687         EnumUnderlying = Context.IntTy.getTypePtr();
15688 
15689     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15690       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15691       // of 'int'. However, if this is an unfixed forward declaration, don't set
15692       // the underlying type unless the user enables -fms-compatibility. This
15693       // makes unfixed forward declared enums incomplete and is more conforming.
15694       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15695         EnumUnderlying = Context.IntTy.getTypePtr();
15696     }
15697   }
15698 
15699   DeclContext *SearchDC = CurContext;
15700   DeclContext *DC = CurContext;
15701   bool isStdBadAlloc = false;
15702   bool isStdAlignValT = false;
15703 
15704   RedeclarationKind Redecl = forRedeclarationInCurContext();
15705   if (TUK == TUK_Friend || TUK == TUK_Reference)
15706     Redecl = NotForRedeclaration;
15707 
15708   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15709   /// implemented asks for structural equivalence checking, the returned decl
15710   /// here is passed back to the parser, allowing the tag body to be parsed.
15711   auto createTagFromNewDecl = [&]() -> TagDecl * {
15712     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15713     // If there is an identifier, use the location of the identifier as the
15714     // location of the decl, otherwise use the location of the struct/union
15715     // keyword.
15716     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15717     TagDecl *New = nullptr;
15718 
15719     if (Kind == TTK_Enum) {
15720       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15721                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15722       // If this is an undefined enum, bail.
15723       if (TUK != TUK_Definition && !Invalid)
15724         return nullptr;
15725       if (EnumUnderlying) {
15726         EnumDecl *ED = cast<EnumDecl>(New);
15727         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15728           ED->setIntegerTypeSourceInfo(TI);
15729         else
15730           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15731         ED->setPromotionType(ED->getIntegerType());
15732       }
15733     } else { // struct/union
15734       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15735                                nullptr);
15736     }
15737 
15738     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15739       // Add alignment attributes if necessary; these attributes are checked
15740       // when the ASTContext lays out the structure.
15741       //
15742       // It is important for implementing the correct semantics that this
15743       // happen here (in ActOnTag). The #pragma pack stack is
15744       // maintained as a result of parser callbacks which can occur at
15745       // many points during the parsing of a struct declaration (because
15746       // the #pragma tokens are effectively skipped over during the
15747       // parsing of the struct).
15748       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15749         AddAlignmentAttributesForRecord(RD);
15750         AddMsStructLayoutForRecord(RD);
15751       }
15752     }
15753     New->setLexicalDeclContext(CurContext);
15754     return New;
15755   };
15756 
15757   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15758   if (Name && SS.isNotEmpty()) {
15759     // We have a nested-name tag ('struct foo::bar').
15760 
15761     // Check for invalid 'foo::'.
15762     if (SS.isInvalid()) {
15763       Name = nullptr;
15764       goto CreateNewDecl;
15765     }
15766 
15767     // If this is a friend or a reference to a class in a dependent
15768     // context, don't try to make a decl for it.
15769     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15770       DC = computeDeclContext(SS, false);
15771       if (!DC) {
15772         IsDependent = true;
15773         return nullptr;
15774       }
15775     } else {
15776       DC = computeDeclContext(SS, true);
15777       if (!DC) {
15778         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15779           << SS.getRange();
15780         return nullptr;
15781       }
15782     }
15783 
15784     if (RequireCompleteDeclContext(SS, DC))
15785       return nullptr;
15786 
15787     SearchDC = DC;
15788     // Look-up name inside 'foo::'.
15789     LookupQualifiedName(Previous, DC);
15790 
15791     if (Previous.isAmbiguous())
15792       return nullptr;
15793 
15794     if (Previous.empty()) {
15795       // Name lookup did not find anything. However, if the
15796       // nested-name-specifier refers to the current instantiation,
15797       // and that current instantiation has any dependent base
15798       // classes, we might find something at instantiation time: treat
15799       // this as a dependent elaborated-type-specifier.
15800       // But this only makes any sense for reference-like lookups.
15801       if (Previous.wasNotFoundInCurrentInstantiation() &&
15802           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15803         IsDependent = true;
15804         return nullptr;
15805       }
15806 
15807       // A tag 'foo::bar' must already exist.
15808       Diag(NameLoc, diag::err_not_tag_in_scope)
15809         << Kind << Name << DC << SS.getRange();
15810       Name = nullptr;
15811       Invalid = true;
15812       goto CreateNewDecl;
15813     }
15814   } else if (Name) {
15815     // C++14 [class.mem]p14:
15816     //   If T is the name of a class, then each of the following shall have a
15817     //   name different from T:
15818     //    -- every member of class T that is itself a type
15819     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15820         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15821       return nullptr;
15822 
15823     // If this is a named struct, check to see if there was a previous forward
15824     // declaration or definition.
15825     // FIXME: We're looking into outer scopes here, even when we
15826     // shouldn't be. Doing so can result in ambiguities that we
15827     // shouldn't be diagnosing.
15828     LookupName(Previous, S);
15829 
15830     // When declaring or defining a tag, ignore ambiguities introduced
15831     // by types using'ed into this scope.
15832     if (Previous.isAmbiguous() &&
15833         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15834       LookupResult::Filter F = Previous.makeFilter();
15835       while (F.hasNext()) {
15836         NamedDecl *ND = F.next();
15837         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15838                 SearchDC->getRedeclContext()))
15839           F.erase();
15840       }
15841       F.done();
15842     }
15843 
15844     // C++11 [namespace.memdef]p3:
15845     //   If the name in a friend declaration is neither qualified nor
15846     //   a template-id and the declaration is a function or an
15847     //   elaborated-type-specifier, the lookup to determine whether
15848     //   the entity has been previously declared shall not consider
15849     //   any scopes outside the innermost enclosing namespace.
15850     //
15851     // MSVC doesn't implement the above rule for types, so a friend tag
15852     // declaration may be a redeclaration of a type declared in an enclosing
15853     // scope.  They do implement this rule for friend functions.
15854     //
15855     // Does it matter that this should be by scope instead of by
15856     // semantic context?
15857     if (!Previous.empty() && TUK == TUK_Friend) {
15858       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15859       LookupResult::Filter F = Previous.makeFilter();
15860       bool FriendSawTagOutsideEnclosingNamespace = false;
15861       while (F.hasNext()) {
15862         NamedDecl *ND = F.next();
15863         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15864         if (DC->isFileContext() &&
15865             !EnclosingNS->Encloses(ND->getDeclContext())) {
15866           if (getLangOpts().MSVCCompat)
15867             FriendSawTagOutsideEnclosingNamespace = true;
15868           else
15869             F.erase();
15870         }
15871       }
15872       F.done();
15873 
15874       // Diagnose this MSVC extension in the easy case where lookup would have
15875       // unambiguously found something outside the enclosing namespace.
15876       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15877         NamedDecl *ND = Previous.getFoundDecl();
15878         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15879             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15880       }
15881     }
15882 
15883     // Note:  there used to be some attempt at recovery here.
15884     if (Previous.isAmbiguous())
15885       return nullptr;
15886 
15887     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15888       // FIXME: This makes sure that we ignore the contexts associated
15889       // with C structs, unions, and enums when looking for a matching
15890       // tag declaration or definition. See the similar lookup tweak
15891       // in Sema::LookupName; is there a better way to deal with this?
15892       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15893         SearchDC = SearchDC->getParent();
15894     }
15895   }
15896 
15897   if (Previous.isSingleResult() &&
15898       Previous.getFoundDecl()->isTemplateParameter()) {
15899     // Maybe we will complain about the shadowed template parameter.
15900     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15901     // Just pretend that we didn't see the previous declaration.
15902     Previous.clear();
15903   }
15904 
15905   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15906       DC->Equals(getStdNamespace())) {
15907     if (Name->isStr("bad_alloc")) {
15908       // This is a declaration of or a reference to "std::bad_alloc".
15909       isStdBadAlloc = true;
15910 
15911       // If std::bad_alloc has been implicitly declared (but made invisible to
15912       // name lookup), fill in this implicit declaration as the previous
15913       // declaration, so that the declarations get chained appropriately.
15914       if (Previous.empty() && StdBadAlloc)
15915         Previous.addDecl(getStdBadAlloc());
15916     } else if (Name->isStr("align_val_t")) {
15917       isStdAlignValT = true;
15918       if (Previous.empty() && StdAlignValT)
15919         Previous.addDecl(getStdAlignValT());
15920     }
15921   }
15922 
15923   // If we didn't find a previous declaration, and this is a reference
15924   // (or friend reference), move to the correct scope.  In C++, we
15925   // also need to do a redeclaration lookup there, just in case
15926   // there's a shadow friend decl.
15927   if (Name && Previous.empty() &&
15928       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15929     if (Invalid) goto CreateNewDecl;
15930     assert(SS.isEmpty());
15931 
15932     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15933       // C++ [basic.scope.pdecl]p5:
15934       //   -- for an elaborated-type-specifier of the form
15935       //
15936       //          class-key identifier
15937       //
15938       //      if the elaborated-type-specifier is used in the
15939       //      decl-specifier-seq or parameter-declaration-clause of a
15940       //      function defined in namespace scope, the identifier is
15941       //      declared as a class-name in the namespace that contains
15942       //      the declaration; otherwise, except as a friend
15943       //      declaration, the identifier is declared in the smallest
15944       //      non-class, non-function-prototype scope that contains the
15945       //      declaration.
15946       //
15947       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15948       // C structs and unions.
15949       //
15950       // It is an error in C++ to declare (rather than define) an enum
15951       // type, including via an elaborated type specifier.  We'll
15952       // diagnose that later; for now, declare the enum in the same
15953       // scope as we would have picked for any other tag type.
15954       //
15955       // GNU C also supports this behavior as part of its incomplete
15956       // enum types extension, while GNU C++ does not.
15957       //
15958       // Find the context where we'll be declaring the tag.
15959       // FIXME: We would like to maintain the current DeclContext as the
15960       // lexical context,
15961       SearchDC = getTagInjectionContext(SearchDC);
15962 
15963       // Find the scope where we'll be declaring the tag.
15964       S = getTagInjectionScope(S, getLangOpts());
15965     } else {
15966       assert(TUK == TUK_Friend);
15967       // C++ [namespace.memdef]p3:
15968       //   If a friend declaration in a non-local class first declares a
15969       //   class or function, the friend class or function is a member of
15970       //   the innermost enclosing namespace.
15971       SearchDC = SearchDC->getEnclosingNamespaceContext();
15972     }
15973 
15974     // In C++, we need to do a redeclaration lookup to properly
15975     // diagnose some problems.
15976     // FIXME: redeclaration lookup is also used (with and without C++) to find a
15977     // hidden declaration so that we don't get ambiguity errors when using a
15978     // type declared by an elaborated-type-specifier.  In C that is not correct
15979     // and we should instead merge compatible types found by lookup.
15980     if (getLangOpts().CPlusPlus) {
15981       // FIXME: This can perform qualified lookups into function contexts,
15982       // which are meaningless.
15983       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15984       LookupQualifiedName(Previous, SearchDC);
15985     } else {
15986       Previous.setRedeclarationKind(forRedeclarationInCurContext());
15987       LookupName(Previous, S);
15988     }
15989   }
15990 
15991   // If we have a known previous declaration to use, then use it.
15992   if (Previous.empty() && SkipBody && SkipBody->Previous)
15993     Previous.addDecl(SkipBody->Previous);
15994 
15995   if (!Previous.empty()) {
15996     NamedDecl *PrevDecl = Previous.getFoundDecl();
15997     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15998 
15999     // It's okay to have a tag decl in the same scope as a typedef
16000     // which hides a tag decl in the same scope.  Finding this
16001     // insanity with a redeclaration lookup can only actually happen
16002     // in C++.
16003     //
16004     // This is also okay for elaborated-type-specifiers, which is
16005     // technically forbidden by the current standard but which is
16006     // okay according to the likely resolution of an open issue;
16007     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16008     if (getLangOpts().CPlusPlus) {
16009       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16010         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16011           TagDecl *Tag = TT->getDecl();
16012           if (Tag->getDeclName() == Name &&
16013               Tag->getDeclContext()->getRedeclContext()
16014                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16015             PrevDecl = Tag;
16016             Previous.clear();
16017             Previous.addDecl(Tag);
16018             Previous.resolveKind();
16019           }
16020         }
16021       }
16022     }
16023 
16024     // If this is a redeclaration of a using shadow declaration, it must
16025     // declare a tag in the same context. In MSVC mode, we allow a
16026     // redefinition if either context is within the other.
16027     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16028       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16029       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16030           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16031           !(OldTag && isAcceptableTagRedeclContext(
16032                           *this, OldTag->getDeclContext(), SearchDC))) {
16033         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16034         Diag(Shadow->getTargetDecl()->getLocation(),
16035              diag::note_using_decl_target);
16036         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16037             << 0;
16038         // Recover by ignoring the old declaration.
16039         Previous.clear();
16040         goto CreateNewDecl;
16041       }
16042     }
16043 
16044     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16045       // If this is a use of a previous tag, or if the tag is already declared
16046       // in the same scope (so that the definition/declaration completes or
16047       // rementions the tag), reuse the decl.
16048       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16049           isDeclInScope(DirectPrevDecl, SearchDC, S,
16050                         SS.isNotEmpty() || isMemberSpecialization)) {
16051         // Make sure that this wasn't declared as an enum and now used as a
16052         // struct or something similar.
16053         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16054                                           TUK == TUK_Definition, KWLoc,
16055                                           Name)) {
16056           bool SafeToContinue
16057             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16058                Kind != TTK_Enum);
16059           if (SafeToContinue)
16060             Diag(KWLoc, diag::err_use_with_wrong_tag)
16061               << Name
16062               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16063                                               PrevTagDecl->getKindName());
16064           else
16065             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16066           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16067 
16068           if (SafeToContinue)
16069             Kind = PrevTagDecl->getTagKind();
16070           else {
16071             // Recover by making this an anonymous redefinition.
16072             Name = nullptr;
16073             Previous.clear();
16074             Invalid = true;
16075           }
16076         }
16077 
16078         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16079           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16080           if (TUK == TUK_Reference || TUK == TUK_Friend)
16081             return PrevTagDecl;
16082 
16083           QualType EnumUnderlyingTy;
16084           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16085             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16086           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16087             EnumUnderlyingTy = QualType(T, 0);
16088 
16089           // All conflicts with previous declarations are recovered by
16090           // returning the previous declaration, unless this is a definition,
16091           // in which case we want the caller to bail out.
16092           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16093                                      ScopedEnum, EnumUnderlyingTy,
16094                                      IsFixed, PrevEnum))
16095             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16096         }
16097 
16098         // C++11 [class.mem]p1:
16099         //   A member shall not be declared twice in the member-specification,
16100         //   except that a nested class or member class template can be declared
16101         //   and then later defined.
16102         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16103             S->isDeclScope(PrevDecl)) {
16104           Diag(NameLoc, diag::ext_member_redeclared);
16105           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16106         }
16107 
16108         if (!Invalid) {
16109           // If this is a use, just return the declaration we found, unless
16110           // we have attributes.
16111           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16112             if (!Attrs.empty()) {
16113               // FIXME: Diagnose these attributes. For now, we create a new
16114               // declaration to hold them.
16115             } else if (TUK == TUK_Reference &&
16116                        (PrevTagDecl->getFriendObjectKind() ==
16117                             Decl::FOK_Undeclared ||
16118                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16119                        SS.isEmpty()) {
16120               // This declaration is a reference to an existing entity, but
16121               // has different visibility from that entity: it either makes
16122               // a friend visible or it makes a type visible in a new module.
16123               // In either case, create a new declaration. We only do this if
16124               // the declaration would have meant the same thing if no prior
16125               // declaration were found, that is, if it was found in the same
16126               // scope where we would have injected a declaration.
16127               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16128                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16129                 return PrevTagDecl;
16130               // This is in the injected scope, create a new declaration in
16131               // that scope.
16132               S = getTagInjectionScope(S, getLangOpts());
16133             } else {
16134               return PrevTagDecl;
16135             }
16136           }
16137 
16138           // Diagnose attempts to redefine a tag.
16139           if (TUK == TUK_Definition) {
16140             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16141               // If we're defining a specialization and the previous definition
16142               // is from an implicit instantiation, don't emit an error
16143               // here; we'll catch this in the general case below.
16144               bool IsExplicitSpecializationAfterInstantiation = false;
16145               if (isMemberSpecialization) {
16146                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16147                   IsExplicitSpecializationAfterInstantiation =
16148                     RD->getTemplateSpecializationKind() !=
16149                     TSK_ExplicitSpecialization;
16150                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16151                   IsExplicitSpecializationAfterInstantiation =
16152                     ED->getTemplateSpecializationKind() !=
16153                     TSK_ExplicitSpecialization;
16154               }
16155 
16156               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16157               // not keep more that one definition around (merge them). However,
16158               // ensure the decl passes the structural compatibility check in
16159               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16160               NamedDecl *Hidden = nullptr;
16161               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16162                 // There is a definition of this tag, but it is not visible. We
16163                 // explicitly make use of C++'s one definition rule here, and
16164                 // assume that this definition is identical to the hidden one
16165                 // we already have. Make the existing definition visible and
16166                 // use it in place of this one.
16167                 if (!getLangOpts().CPlusPlus) {
16168                   // Postpone making the old definition visible until after we
16169                   // complete parsing the new one and do the structural
16170                   // comparison.
16171                   SkipBody->CheckSameAsPrevious = true;
16172                   SkipBody->New = createTagFromNewDecl();
16173                   SkipBody->Previous = Def;
16174                   return Def;
16175                 } else {
16176                   SkipBody->ShouldSkip = true;
16177                   SkipBody->Previous = Def;
16178                   makeMergedDefinitionVisible(Hidden);
16179                   // Carry on and handle it like a normal definition. We'll
16180                   // skip starting the definitiion later.
16181                 }
16182               } else if (!IsExplicitSpecializationAfterInstantiation) {
16183                 // A redeclaration in function prototype scope in C isn't
16184                 // visible elsewhere, so merely issue a warning.
16185                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16186                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16187                 else
16188                   Diag(NameLoc, diag::err_redefinition) << Name;
16189                 notePreviousDefinition(Def,
16190                                        NameLoc.isValid() ? NameLoc : KWLoc);
16191                 // If this is a redefinition, recover by making this
16192                 // struct be anonymous, which will make any later
16193                 // references get the previous definition.
16194                 Name = nullptr;
16195                 Previous.clear();
16196                 Invalid = true;
16197               }
16198             } else {
16199               // If the type is currently being defined, complain
16200               // about a nested redefinition.
16201               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16202               if (TD->isBeingDefined()) {
16203                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16204                 Diag(PrevTagDecl->getLocation(),
16205                      diag::note_previous_definition);
16206                 Name = nullptr;
16207                 Previous.clear();
16208                 Invalid = true;
16209               }
16210             }
16211 
16212             // Okay, this is definition of a previously declared or referenced
16213             // tag. We're going to create a new Decl for it.
16214           }
16215 
16216           // Okay, we're going to make a redeclaration.  If this is some kind
16217           // of reference, make sure we build the redeclaration in the same DC
16218           // as the original, and ignore the current access specifier.
16219           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16220             SearchDC = PrevTagDecl->getDeclContext();
16221             AS = AS_none;
16222           }
16223         }
16224         // If we get here we have (another) forward declaration or we
16225         // have a definition.  Just create a new decl.
16226 
16227       } else {
16228         // If we get here, this is a definition of a new tag type in a nested
16229         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16230         // new decl/type.  We set PrevDecl to NULL so that the entities
16231         // have distinct types.
16232         Previous.clear();
16233       }
16234       // If we get here, we're going to create a new Decl. If PrevDecl
16235       // is non-NULL, it's a definition of the tag declared by
16236       // PrevDecl. If it's NULL, we have a new definition.
16237 
16238     // Otherwise, PrevDecl is not a tag, but was found with tag
16239     // lookup.  This is only actually possible in C++, where a few
16240     // things like templates still live in the tag namespace.
16241     } else {
16242       // Use a better diagnostic if an elaborated-type-specifier
16243       // found the wrong kind of type on the first
16244       // (non-redeclaration) lookup.
16245       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16246           !Previous.isForRedeclaration()) {
16247         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16248         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16249                                                        << Kind;
16250         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16251         Invalid = true;
16252 
16253       // Otherwise, only diagnose if the declaration is in scope.
16254       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16255                                 SS.isNotEmpty() || isMemberSpecialization)) {
16256         // do nothing
16257 
16258       // Diagnose implicit declarations introduced by elaborated types.
16259       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16260         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16261         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16262         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16263         Invalid = true;
16264 
16265       // Otherwise it's a declaration.  Call out a particularly common
16266       // case here.
16267       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16268         unsigned Kind = 0;
16269         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16270         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16271           << Name << Kind << TND->getUnderlyingType();
16272         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16273         Invalid = true;
16274 
16275       // Otherwise, diagnose.
16276       } else {
16277         // The tag name clashes with something else in the target scope,
16278         // issue an error and recover by making this tag be anonymous.
16279         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16280         notePreviousDefinition(PrevDecl, NameLoc);
16281         Name = nullptr;
16282         Invalid = true;
16283       }
16284 
16285       // The existing declaration isn't relevant to us; we're in a
16286       // new scope, so clear out the previous declaration.
16287       Previous.clear();
16288     }
16289   }
16290 
16291 CreateNewDecl:
16292 
16293   TagDecl *PrevDecl = nullptr;
16294   if (Previous.isSingleResult())
16295     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16296 
16297   // If there is an identifier, use the location of the identifier as the
16298   // location of the decl, otherwise use the location of the struct/union
16299   // keyword.
16300   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16301 
16302   // Otherwise, create a new declaration. If there is a previous
16303   // declaration of the same entity, the two will be linked via
16304   // PrevDecl.
16305   TagDecl *New;
16306 
16307   if (Kind == TTK_Enum) {
16308     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16309     // enum X { A, B, C } D;    D should chain to X.
16310     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16311                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16312                            ScopedEnumUsesClassTag, IsFixed);
16313 
16314     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16315       StdAlignValT = cast<EnumDecl>(New);
16316 
16317     // If this is an undefined enum, warn.
16318     if (TUK != TUK_Definition && !Invalid) {
16319       TagDecl *Def;
16320       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16321         // C++0x: 7.2p2: opaque-enum-declaration.
16322         // Conflicts are diagnosed above. Do nothing.
16323       }
16324       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16325         Diag(Loc, diag::ext_forward_ref_enum_def)
16326           << New;
16327         Diag(Def->getLocation(), diag::note_previous_definition);
16328       } else {
16329         unsigned DiagID = diag::ext_forward_ref_enum;
16330         if (getLangOpts().MSVCCompat)
16331           DiagID = diag::ext_ms_forward_ref_enum;
16332         else if (getLangOpts().CPlusPlus)
16333           DiagID = diag::err_forward_ref_enum;
16334         Diag(Loc, DiagID);
16335       }
16336     }
16337 
16338     if (EnumUnderlying) {
16339       EnumDecl *ED = cast<EnumDecl>(New);
16340       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16341         ED->setIntegerTypeSourceInfo(TI);
16342       else
16343         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16344       ED->setPromotionType(ED->getIntegerType());
16345       assert(ED->isComplete() && "enum with type should be complete");
16346     }
16347   } else {
16348     // struct/union/class
16349 
16350     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16351     // struct X { int A; } D;    D should chain to X.
16352     if (getLangOpts().CPlusPlus) {
16353       // FIXME: Look for a way to use RecordDecl for simple structs.
16354       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16355                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16356 
16357       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16358         StdBadAlloc = cast<CXXRecordDecl>(New);
16359     } else
16360       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16361                                cast_or_null<RecordDecl>(PrevDecl));
16362   }
16363 
16364   // C++11 [dcl.type]p3:
16365   //   A type-specifier-seq shall not define a class or enumeration [...].
16366   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16367       TUK == TUK_Definition) {
16368     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16369       << Context.getTagDeclType(New);
16370     Invalid = true;
16371   }
16372 
16373   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16374       DC->getDeclKind() == Decl::Enum) {
16375     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16376       << Context.getTagDeclType(New);
16377     Invalid = true;
16378   }
16379 
16380   // Maybe add qualifier info.
16381   if (SS.isNotEmpty()) {
16382     if (SS.isSet()) {
16383       // If this is either a declaration or a definition, check the
16384       // nested-name-specifier against the current context.
16385       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16386           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16387                                        isMemberSpecialization))
16388         Invalid = true;
16389 
16390       New->setQualifierInfo(SS.getWithLocInContext(Context));
16391       if (TemplateParameterLists.size() > 0) {
16392         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16393       }
16394     }
16395     else
16396       Invalid = true;
16397   }
16398 
16399   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16400     // Add alignment attributes if necessary; these attributes are checked when
16401     // the ASTContext lays out the structure.
16402     //
16403     // It is important for implementing the correct semantics that this
16404     // happen here (in ActOnTag). The #pragma pack stack is
16405     // maintained as a result of parser callbacks which can occur at
16406     // many points during the parsing of a struct declaration (because
16407     // the #pragma tokens are effectively skipped over during the
16408     // parsing of the struct).
16409     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16410       AddAlignmentAttributesForRecord(RD);
16411       AddMsStructLayoutForRecord(RD);
16412     }
16413   }
16414 
16415   if (ModulePrivateLoc.isValid()) {
16416     if (isMemberSpecialization)
16417       Diag(New->getLocation(), diag::err_module_private_specialization)
16418         << 2
16419         << FixItHint::CreateRemoval(ModulePrivateLoc);
16420     // __module_private__ does not apply to local classes. However, we only
16421     // diagnose this as an error when the declaration specifiers are
16422     // freestanding. Here, we just ignore the __module_private__.
16423     else if (!SearchDC->isFunctionOrMethod())
16424       New->setModulePrivate();
16425   }
16426 
16427   // If this is a specialization of a member class (of a class template),
16428   // check the specialization.
16429   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16430     Invalid = true;
16431 
16432   // If we're declaring or defining a tag in function prototype scope in C,
16433   // note that this type can only be used within the function and add it to
16434   // the list of decls to inject into the function definition scope.
16435   if ((Name || Kind == TTK_Enum) &&
16436       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16437     if (getLangOpts().CPlusPlus) {
16438       // C++ [dcl.fct]p6:
16439       //   Types shall not be defined in return or parameter types.
16440       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16441         Diag(Loc, diag::err_type_defined_in_param_type)
16442             << Name;
16443         Invalid = true;
16444       }
16445     } else if (!PrevDecl) {
16446       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16447     }
16448   }
16449 
16450   if (Invalid)
16451     New->setInvalidDecl();
16452 
16453   // Set the lexical context. If the tag has a C++ scope specifier, the
16454   // lexical context will be different from the semantic context.
16455   New->setLexicalDeclContext(CurContext);
16456 
16457   // Mark this as a friend decl if applicable.
16458   // In Microsoft mode, a friend declaration also acts as a forward
16459   // declaration so we always pass true to setObjectOfFriendDecl to make
16460   // the tag name visible.
16461   if (TUK == TUK_Friend)
16462     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16463 
16464   // Set the access specifier.
16465   if (!Invalid && SearchDC->isRecord())
16466     SetMemberAccessSpecifier(New, PrevDecl, AS);
16467 
16468   if (PrevDecl)
16469     CheckRedeclarationModuleOwnership(New, PrevDecl);
16470 
16471   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16472     New->startDefinition();
16473 
16474   ProcessDeclAttributeList(S, New, Attrs);
16475   AddPragmaAttributes(S, New);
16476 
16477   // If this has an identifier, add it to the scope stack.
16478   if (TUK == TUK_Friend) {
16479     // We might be replacing an existing declaration in the lookup tables;
16480     // if so, borrow its access specifier.
16481     if (PrevDecl)
16482       New->setAccess(PrevDecl->getAccess());
16483 
16484     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16485     DC->makeDeclVisibleInContext(New);
16486     if (Name) // can be null along some error paths
16487       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16488         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16489   } else if (Name) {
16490     S = getNonFieldDeclScope(S);
16491     PushOnScopeChains(New, S, true);
16492   } else {
16493     CurContext->addDecl(New);
16494   }
16495 
16496   // If this is the C FILE type, notify the AST context.
16497   if (IdentifierInfo *II = New->getIdentifier())
16498     if (!New->isInvalidDecl() &&
16499         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16500         II->isStr("FILE"))
16501       Context.setFILEDecl(New);
16502 
16503   if (PrevDecl)
16504     mergeDeclAttributes(New, PrevDecl);
16505 
16506   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16507     inferGslOwnerPointerAttribute(CXXRD);
16508 
16509   // If there's a #pragma GCC visibility in scope, set the visibility of this
16510   // record.
16511   AddPushedVisibilityAttribute(New);
16512 
16513   if (isMemberSpecialization && !New->isInvalidDecl())
16514     CompleteMemberSpecialization(New, Previous);
16515 
16516   OwnedDecl = true;
16517   // In C++, don't return an invalid declaration. We can't recover well from
16518   // the cases where we make the type anonymous.
16519   if (Invalid && getLangOpts().CPlusPlus) {
16520     if (New->isBeingDefined())
16521       if (auto RD = dyn_cast<RecordDecl>(New))
16522         RD->completeDefinition();
16523     return nullptr;
16524   } else if (SkipBody && SkipBody->ShouldSkip) {
16525     return SkipBody->Previous;
16526   } else {
16527     return New;
16528   }
16529 }
16530 
16531 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16532   AdjustDeclIfTemplate(TagD);
16533   TagDecl *Tag = cast<TagDecl>(TagD);
16534 
16535   // Enter the tag context.
16536   PushDeclContext(S, Tag);
16537 
16538   ActOnDocumentableDecl(TagD);
16539 
16540   // If there's a #pragma GCC visibility in scope, set the visibility of this
16541   // record.
16542   AddPushedVisibilityAttribute(Tag);
16543 }
16544 
16545 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16546                                     SkipBodyInfo &SkipBody) {
16547   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16548     return false;
16549 
16550   // Make the previous decl visible.
16551   makeMergedDefinitionVisible(SkipBody.Previous);
16552   return true;
16553 }
16554 
16555 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16556   assert(isa<ObjCContainerDecl>(IDecl) &&
16557          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16558   DeclContext *OCD = cast<DeclContext>(IDecl);
16559   assert(OCD->getLexicalParent() == CurContext &&
16560       "The next DeclContext should be lexically contained in the current one.");
16561   CurContext = OCD;
16562   return IDecl;
16563 }
16564 
16565 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16566                                            SourceLocation FinalLoc,
16567                                            bool IsFinalSpelledSealed,
16568                                            bool IsAbstract,
16569                                            SourceLocation LBraceLoc) {
16570   AdjustDeclIfTemplate(TagD);
16571   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16572 
16573   FieldCollector->StartClass();
16574 
16575   if (!Record->getIdentifier())
16576     return;
16577 
16578   if (IsAbstract)
16579     Record->markAbstract();
16580 
16581   if (FinalLoc.isValid()) {
16582     Record->addAttr(FinalAttr::Create(
16583         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16584         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16585   }
16586   // C++ [class]p2:
16587   //   [...] The class-name is also inserted into the scope of the
16588   //   class itself; this is known as the injected-class-name. For
16589   //   purposes of access checking, the injected-class-name is treated
16590   //   as if it were a public member name.
16591   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16592       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16593       Record->getLocation(), Record->getIdentifier(),
16594       /*PrevDecl=*/nullptr,
16595       /*DelayTypeCreation=*/true);
16596   Context.getTypeDeclType(InjectedClassName, Record);
16597   InjectedClassName->setImplicit();
16598   InjectedClassName->setAccess(AS_public);
16599   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16600       InjectedClassName->setDescribedClassTemplate(Template);
16601   PushOnScopeChains(InjectedClassName, S);
16602   assert(InjectedClassName->isInjectedClassName() &&
16603          "Broken injected-class-name");
16604 }
16605 
16606 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16607                                     SourceRange BraceRange) {
16608   AdjustDeclIfTemplate(TagD);
16609   TagDecl *Tag = cast<TagDecl>(TagD);
16610   Tag->setBraceRange(BraceRange);
16611 
16612   // Make sure we "complete" the definition even it is invalid.
16613   if (Tag->isBeingDefined()) {
16614     assert(Tag->isInvalidDecl() && "We should already have completed it");
16615     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16616       RD->completeDefinition();
16617   }
16618 
16619   if (isa<CXXRecordDecl>(Tag)) {
16620     FieldCollector->FinishClass();
16621   }
16622 
16623   // Exit this scope of this tag's definition.
16624   PopDeclContext();
16625 
16626   if (getCurLexicalContext()->isObjCContainer() &&
16627       Tag->getDeclContext()->isFileContext())
16628     Tag->setTopLevelDeclInObjCContainer();
16629 
16630   // Notify the consumer that we've defined a tag.
16631   if (!Tag->isInvalidDecl())
16632     Consumer.HandleTagDeclDefinition(Tag);
16633 
16634   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16635   // from XLs and instead matches the XL #pragma pack(1) behavior.
16636   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16637       AlignPackStack.hasValue()) {
16638     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16639     // Only diagnose #pragma align(packed).
16640     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16641       return;
16642     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16643     if (!RD)
16644       return;
16645     // Only warn if there is at least 1 bitfield member.
16646     if (llvm::any_of(RD->fields(),
16647                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16648       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16649   }
16650 }
16651 
16652 void Sema::ActOnObjCContainerFinishDefinition() {
16653   // Exit this scope of this interface definition.
16654   PopDeclContext();
16655 }
16656 
16657 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16658   assert(DC == CurContext && "Mismatch of container contexts");
16659   OriginalLexicalContext = DC;
16660   ActOnObjCContainerFinishDefinition();
16661 }
16662 
16663 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16664   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16665   OriginalLexicalContext = nullptr;
16666 }
16667 
16668 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16669   AdjustDeclIfTemplate(TagD);
16670   TagDecl *Tag = cast<TagDecl>(TagD);
16671   Tag->setInvalidDecl();
16672 
16673   // Make sure we "complete" the definition even it is invalid.
16674   if (Tag->isBeingDefined()) {
16675     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16676       RD->completeDefinition();
16677   }
16678 
16679   // We're undoing ActOnTagStartDefinition here, not
16680   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16681   // the FieldCollector.
16682 
16683   PopDeclContext();
16684 }
16685 
16686 // Note that FieldName may be null for anonymous bitfields.
16687 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16688                                 IdentifierInfo *FieldName,
16689                                 QualType FieldTy, bool IsMsStruct,
16690                                 Expr *BitWidth, bool *ZeroWidth) {
16691   assert(BitWidth);
16692   if (BitWidth->containsErrors())
16693     return ExprError();
16694 
16695   // Default to true; that shouldn't confuse checks for emptiness
16696   if (ZeroWidth)
16697     *ZeroWidth = true;
16698 
16699   // C99 6.7.2.1p4 - verify the field type.
16700   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16701   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16702     // Handle incomplete and sizeless types with a specific error.
16703     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16704                                  diag::err_field_incomplete_or_sizeless))
16705       return ExprError();
16706     if (FieldName)
16707       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16708         << FieldName << FieldTy << BitWidth->getSourceRange();
16709     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16710       << FieldTy << BitWidth->getSourceRange();
16711   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16712                                              UPPC_BitFieldWidth))
16713     return ExprError();
16714 
16715   // If the bit-width is type- or value-dependent, don't try to check
16716   // it now.
16717   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16718     return BitWidth;
16719 
16720   llvm::APSInt Value;
16721   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16722   if (ICE.isInvalid())
16723     return ICE;
16724   BitWidth = ICE.get();
16725 
16726   if (Value != 0 && ZeroWidth)
16727     *ZeroWidth = false;
16728 
16729   // Zero-width bitfield is ok for anonymous field.
16730   if (Value == 0 && FieldName)
16731     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16732 
16733   if (Value.isSigned() && Value.isNegative()) {
16734     if (FieldName)
16735       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16736                << FieldName << toString(Value, 10);
16737     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16738       << toString(Value, 10);
16739   }
16740 
16741   // The size of the bit-field must not exceed our maximum permitted object
16742   // size.
16743   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16744     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16745            << !FieldName << FieldName << toString(Value, 10);
16746   }
16747 
16748   if (!FieldTy->isDependentType()) {
16749     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16750     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16751     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16752 
16753     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16754     // ABI.
16755     bool CStdConstraintViolation =
16756         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16757     bool MSBitfieldViolation =
16758         Value.ugt(TypeStorageSize) &&
16759         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16760     if (CStdConstraintViolation || MSBitfieldViolation) {
16761       unsigned DiagWidth =
16762           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16763       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16764              << (bool)FieldName << FieldName << toString(Value, 10)
16765              << !CStdConstraintViolation << DiagWidth;
16766     }
16767 
16768     // Warn on types where the user might conceivably expect to get all
16769     // specified bits as value bits: that's all integral types other than
16770     // 'bool'.
16771     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16772       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16773           << FieldName << toString(Value, 10)
16774           << (unsigned)TypeWidth;
16775     }
16776   }
16777 
16778   return BitWidth;
16779 }
16780 
16781 /// ActOnField - Each field of a C struct/union is passed into this in order
16782 /// to create a FieldDecl object for it.
16783 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16784                        Declarator &D, Expr *BitfieldWidth) {
16785   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16786                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16787                                /*InitStyle=*/ICIS_NoInit, AS_public);
16788   return Res;
16789 }
16790 
16791 /// HandleField - Analyze a field of a C struct or a C++ data member.
16792 ///
16793 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16794                              SourceLocation DeclStart,
16795                              Declarator &D, Expr *BitWidth,
16796                              InClassInitStyle InitStyle,
16797                              AccessSpecifier AS) {
16798   if (D.isDecompositionDeclarator()) {
16799     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16800     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16801       << Decomp.getSourceRange();
16802     return nullptr;
16803   }
16804 
16805   IdentifierInfo *II = D.getIdentifier();
16806   SourceLocation Loc = DeclStart;
16807   if (II) Loc = D.getIdentifierLoc();
16808 
16809   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16810   QualType T = TInfo->getType();
16811   if (getLangOpts().CPlusPlus) {
16812     CheckExtraCXXDefaultArguments(D);
16813 
16814     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16815                                         UPPC_DataMemberType)) {
16816       D.setInvalidType();
16817       T = Context.IntTy;
16818       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16819     }
16820   }
16821 
16822   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16823 
16824   if (D.getDeclSpec().isInlineSpecified())
16825     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16826         << getLangOpts().CPlusPlus17;
16827   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16828     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16829          diag::err_invalid_thread)
16830       << DeclSpec::getSpecifierName(TSCS);
16831 
16832   // Check to see if this name was declared as a member previously
16833   NamedDecl *PrevDecl = nullptr;
16834   LookupResult Previous(*this, II, Loc, LookupMemberName,
16835                         ForVisibleRedeclaration);
16836   LookupName(Previous, S);
16837   switch (Previous.getResultKind()) {
16838     case LookupResult::Found:
16839     case LookupResult::FoundUnresolvedValue:
16840       PrevDecl = Previous.getAsSingle<NamedDecl>();
16841       break;
16842 
16843     case LookupResult::FoundOverloaded:
16844       PrevDecl = Previous.getRepresentativeDecl();
16845       break;
16846 
16847     case LookupResult::NotFound:
16848     case LookupResult::NotFoundInCurrentInstantiation:
16849     case LookupResult::Ambiguous:
16850       break;
16851   }
16852   Previous.suppressDiagnostics();
16853 
16854   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16855     // Maybe we will complain about the shadowed template parameter.
16856     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16857     // Just pretend that we didn't see the previous declaration.
16858     PrevDecl = nullptr;
16859   }
16860 
16861   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16862     PrevDecl = nullptr;
16863 
16864   bool Mutable
16865     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16866   SourceLocation TSSL = D.getBeginLoc();
16867   FieldDecl *NewFD
16868     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16869                      TSSL, AS, PrevDecl, &D);
16870 
16871   if (NewFD->isInvalidDecl())
16872     Record->setInvalidDecl();
16873 
16874   if (D.getDeclSpec().isModulePrivateSpecified())
16875     NewFD->setModulePrivate();
16876 
16877   if (NewFD->isInvalidDecl() && PrevDecl) {
16878     // Don't introduce NewFD into scope; there's already something
16879     // with the same name in the same scope.
16880   } else if (II) {
16881     PushOnScopeChains(NewFD, S);
16882   } else
16883     Record->addDecl(NewFD);
16884 
16885   return NewFD;
16886 }
16887 
16888 /// Build a new FieldDecl and check its well-formedness.
16889 ///
16890 /// This routine builds a new FieldDecl given the fields name, type,
16891 /// record, etc. \p PrevDecl should refer to any previous declaration
16892 /// with the same name and in the same scope as the field to be
16893 /// created.
16894 ///
16895 /// \returns a new FieldDecl.
16896 ///
16897 /// \todo The Declarator argument is a hack. It will be removed once
16898 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16899                                 TypeSourceInfo *TInfo,
16900                                 RecordDecl *Record, SourceLocation Loc,
16901                                 bool Mutable, Expr *BitWidth,
16902                                 InClassInitStyle InitStyle,
16903                                 SourceLocation TSSL,
16904                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16905                                 Declarator *D) {
16906   IdentifierInfo *II = Name.getAsIdentifierInfo();
16907   bool InvalidDecl = false;
16908   if (D) InvalidDecl = D->isInvalidType();
16909 
16910   // If we receive a broken type, recover by assuming 'int' and
16911   // marking this declaration as invalid.
16912   if (T.isNull() || T->containsErrors()) {
16913     InvalidDecl = true;
16914     T = Context.IntTy;
16915   }
16916 
16917   QualType EltTy = Context.getBaseElementType(T);
16918   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16919     if (RequireCompleteSizedType(Loc, EltTy,
16920                                  diag::err_field_incomplete_or_sizeless)) {
16921       // Fields of incomplete type force their record to be invalid.
16922       Record->setInvalidDecl();
16923       InvalidDecl = true;
16924     } else {
16925       NamedDecl *Def;
16926       EltTy->isIncompleteType(&Def);
16927       if (Def && Def->isInvalidDecl()) {
16928         Record->setInvalidDecl();
16929         InvalidDecl = true;
16930       }
16931     }
16932   }
16933 
16934   // TR 18037 does not allow fields to be declared with address space
16935   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16936       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16937     Diag(Loc, diag::err_field_with_address_space);
16938     Record->setInvalidDecl();
16939     InvalidDecl = true;
16940   }
16941 
16942   if (LangOpts.OpenCL) {
16943     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16944     // used as structure or union field: image, sampler, event or block types.
16945     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16946         T->isBlockPointerType()) {
16947       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16948       Record->setInvalidDecl();
16949       InvalidDecl = true;
16950     }
16951     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
16952     // is enabled.
16953     if (BitWidth && !getOpenCLOptions().isAvailableOption(
16954                         "__cl_clang_bitfields", LangOpts)) {
16955       Diag(Loc, diag::err_opencl_bitfields);
16956       InvalidDecl = true;
16957     }
16958   }
16959 
16960   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16961   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16962       T.hasQualifiers()) {
16963     InvalidDecl = true;
16964     Diag(Loc, diag::err_anon_bitfield_qualifiers);
16965   }
16966 
16967   // C99 6.7.2.1p8: A member of a structure or union may have any type other
16968   // than a variably modified type.
16969   if (!InvalidDecl && T->isVariablyModifiedType()) {
16970     if (!tryToFixVariablyModifiedVarType(
16971             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16972       InvalidDecl = true;
16973   }
16974 
16975   // Fields can not have abstract class types
16976   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16977                                              diag::err_abstract_type_in_decl,
16978                                              AbstractFieldType))
16979     InvalidDecl = true;
16980 
16981   bool ZeroWidth = false;
16982   if (InvalidDecl)
16983     BitWidth = nullptr;
16984   // If this is declared as a bit-field, check the bit-field.
16985   if (BitWidth) {
16986     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16987                               &ZeroWidth).get();
16988     if (!BitWidth) {
16989       InvalidDecl = true;
16990       BitWidth = nullptr;
16991       ZeroWidth = false;
16992     }
16993   }
16994 
16995   // Check that 'mutable' is consistent with the type of the declaration.
16996   if (!InvalidDecl && Mutable) {
16997     unsigned DiagID = 0;
16998     if (T->isReferenceType())
16999       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17000                                         : diag::err_mutable_reference;
17001     else if (T.isConstQualified())
17002       DiagID = diag::err_mutable_const;
17003 
17004     if (DiagID) {
17005       SourceLocation ErrLoc = Loc;
17006       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17007         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17008       Diag(ErrLoc, DiagID);
17009       if (DiagID != diag::ext_mutable_reference) {
17010         Mutable = false;
17011         InvalidDecl = true;
17012       }
17013     }
17014   }
17015 
17016   // C++11 [class.union]p8 (DR1460):
17017   //   At most one variant member of a union may have a
17018   //   brace-or-equal-initializer.
17019   if (InitStyle != ICIS_NoInit)
17020     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17021 
17022   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17023                                        BitWidth, Mutable, InitStyle);
17024   if (InvalidDecl)
17025     NewFD->setInvalidDecl();
17026 
17027   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17028     Diag(Loc, diag::err_duplicate_member) << II;
17029     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17030     NewFD->setInvalidDecl();
17031   }
17032 
17033   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17034     if (Record->isUnion()) {
17035       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17036         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17037         if (RDecl->getDefinition()) {
17038           // C++ [class.union]p1: An object of a class with a non-trivial
17039           // constructor, a non-trivial copy constructor, a non-trivial
17040           // destructor, or a non-trivial copy assignment operator
17041           // cannot be a member of a union, nor can an array of such
17042           // objects.
17043           if (CheckNontrivialField(NewFD))
17044             NewFD->setInvalidDecl();
17045         }
17046       }
17047 
17048       // C++ [class.union]p1: If a union contains a member of reference type,
17049       // the program is ill-formed, except when compiling with MSVC extensions
17050       // enabled.
17051       if (EltTy->isReferenceType()) {
17052         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17053                                     diag::ext_union_member_of_reference_type :
17054                                     diag::err_union_member_of_reference_type)
17055           << NewFD->getDeclName() << EltTy;
17056         if (!getLangOpts().MicrosoftExt)
17057           NewFD->setInvalidDecl();
17058       }
17059     }
17060   }
17061 
17062   // FIXME: We need to pass in the attributes given an AST
17063   // representation, not a parser representation.
17064   if (D) {
17065     // FIXME: The current scope is almost... but not entirely... correct here.
17066     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17067 
17068     if (NewFD->hasAttrs())
17069       CheckAlignasUnderalignment(NewFD);
17070   }
17071 
17072   // In auto-retain/release, infer strong retension for fields of
17073   // retainable type.
17074   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17075     NewFD->setInvalidDecl();
17076 
17077   if (T.isObjCGCWeak())
17078     Diag(Loc, diag::warn_attribute_weak_on_field);
17079 
17080   // PPC MMA non-pointer types are not allowed as field types.
17081   if (Context.getTargetInfo().getTriple().isPPC64() &&
17082       CheckPPCMMAType(T, NewFD->getLocation()))
17083     NewFD->setInvalidDecl();
17084 
17085   NewFD->setAccess(AS);
17086   return NewFD;
17087 }
17088 
17089 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17090   assert(FD);
17091   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17092 
17093   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17094     return false;
17095 
17096   QualType EltTy = Context.getBaseElementType(FD->getType());
17097   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17098     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17099     if (RDecl->getDefinition()) {
17100       // We check for copy constructors before constructors
17101       // because otherwise we'll never get complaints about
17102       // copy constructors.
17103 
17104       CXXSpecialMember member = CXXInvalid;
17105       // We're required to check for any non-trivial constructors. Since the
17106       // implicit default constructor is suppressed if there are any
17107       // user-declared constructors, we just need to check that there is a
17108       // trivial default constructor and a trivial copy constructor. (We don't
17109       // worry about move constructors here, since this is a C++98 check.)
17110       if (RDecl->hasNonTrivialCopyConstructor())
17111         member = CXXCopyConstructor;
17112       else if (!RDecl->hasTrivialDefaultConstructor())
17113         member = CXXDefaultConstructor;
17114       else if (RDecl->hasNonTrivialCopyAssignment())
17115         member = CXXCopyAssignment;
17116       else if (RDecl->hasNonTrivialDestructor())
17117         member = CXXDestructor;
17118 
17119       if (member != CXXInvalid) {
17120         if (!getLangOpts().CPlusPlus11 &&
17121             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17122           // Objective-C++ ARC: it is an error to have a non-trivial field of
17123           // a union. However, system headers in Objective-C programs
17124           // occasionally have Objective-C lifetime objects within unions,
17125           // and rather than cause the program to fail, we make those
17126           // members unavailable.
17127           SourceLocation Loc = FD->getLocation();
17128           if (getSourceManager().isInSystemHeader(Loc)) {
17129             if (!FD->hasAttr<UnavailableAttr>())
17130               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17131                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17132             return false;
17133           }
17134         }
17135 
17136         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17137                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17138                diag::err_illegal_union_or_anon_struct_member)
17139           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17140         DiagnoseNontrivial(RDecl, member);
17141         return !getLangOpts().CPlusPlus11;
17142       }
17143     }
17144   }
17145 
17146   return false;
17147 }
17148 
17149 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17150 ///  AST enum value.
17151 static ObjCIvarDecl::AccessControl
17152 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17153   switch (ivarVisibility) {
17154   default: llvm_unreachable("Unknown visitibility kind");
17155   case tok::objc_private: return ObjCIvarDecl::Private;
17156   case tok::objc_public: return ObjCIvarDecl::Public;
17157   case tok::objc_protected: return ObjCIvarDecl::Protected;
17158   case tok::objc_package: return ObjCIvarDecl::Package;
17159   }
17160 }
17161 
17162 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17163 /// in order to create an IvarDecl object for it.
17164 Decl *Sema::ActOnIvar(Scope *S,
17165                                 SourceLocation DeclStart,
17166                                 Declarator &D, Expr *BitfieldWidth,
17167                                 tok::ObjCKeywordKind Visibility) {
17168 
17169   IdentifierInfo *II = D.getIdentifier();
17170   Expr *BitWidth = (Expr*)BitfieldWidth;
17171   SourceLocation Loc = DeclStart;
17172   if (II) Loc = D.getIdentifierLoc();
17173 
17174   // FIXME: Unnamed fields can be handled in various different ways, for
17175   // example, unnamed unions inject all members into the struct namespace!
17176 
17177   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17178   QualType T = TInfo->getType();
17179 
17180   if (BitWidth) {
17181     // 6.7.2.1p3, 6.7.2.1p4
17182     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17183     if (!BitWidth)
17184       D.setInvalidType();
17185   } else {
17186     // Not a bitfield.
17187 
17188     // validate II.
17189 
17190   }
17191   if (T->isReferenceType()) {
17192     Diag(Loc, diag::err_ivar_reference_type);
17193     D.setInvalidType();
17194   }
17195   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17196   // than a variably modified type.
17197   else if (T->isVariablyModifiedType()) {
17198     if (!tryToFixVariablyModifiedVarType(
17199             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17200       D.setInvalidType();
17201   }
17202 
17203   // Get the visibility (access control) for this ivar.
17204   ObjCIvarDecl::AccessControl ac =
17205     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17206                                         : ObjCIvarDecl::None;
17207   // Must set ivar's DeclContext to its enclosing interface.
17208   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17209   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17210     return nullptr;
17211   ObjCContainerDecl *EnclosingContext;
17212   if (ObjCImplementationDecl *IMPDecl =
17213       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17214     if (LangOpts.ObjCRuntime.isFragile()) {
17215     // Case of ivar declared in an implementation. Context is that of its class.
17216       EnclosingContext = IMPDecl->getClassInterface();
17217       assert(EnclosingContext && "Implementation has no class interface!");
17218     }
17219     else
17220       EnclosingContext = EnclosingDecl;
17221   } else {
17222     if (ObjCCategoryDecl *CDecl =
17223         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17224       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17225         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17226         return nullptr;
17227       }
17228     }
17229     EnclosingContext = EnclosingDecl;
17230   }
17231 
17232   // Construct the decl.
17233   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17234                                              DeclStart, Loc, II, T,
17235                                              TInfo, ac, (Expr *)BitfieldWidth);
17236 
17237   if (II) {
17238     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17239                                            ForVisibleRedeclaration);
17240     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17241         && !isa<TagDecl>(PrevDecl)) {
17242       Diag(Loc, diag::err_duplicate_member) << II;
17243       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17244       NewID->setInvalidDecl();
17245     }
17246   }
17247 
17248   // Process attributes attached to the ivar.
17249   ProcessDeclAttributes(S, NewID, D);
17250 
17251   if (D.isInvalidType())
17252     NewID->setInvalidDecl();
17253 
17254   // In ARC, infer 'retaining' for ivars of retainable type.
17255   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17256     NewID->setInvalidDecl();
17257 
17258   if (D.getDeclSpec().isModulePrivateSpecified())
17259     NewID->setModulePrivate();
17260 
17261   if (II) {
17262     // FIXME: When interfaces are DeclContexts, we'll need to add
17263     // these to the interface.
17264     S->AddDecl(NewID);
17265     IdResolver.AddDecl(NewID);
17266   }
17267 
17268   if (LangOpts.ObjCRuntime.isNonFragile() &&
17269       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17270     Diag(Loc, diag::warn_ivars_in_interface);
17271 
17272   return NewID;
17273 }
17274 
17275 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17276 /// class and class extensions. For every class \@interface and class
17277 /// extension \@interface, if the last ivar is a bitfield of any type,
17278 /// then add an implicit `char :0` ivar to the end of that interface.
17279 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17280                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17281   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17282     return;
17283 
17284   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17285   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17286 
17287   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17288     return;
17289   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17290   if (!ID) {
17291     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17292       if (!CD->IsClassExtension())
17293         return;
17294     }
17295     // No need to add this to end of @implementation.
17296     else
17297       return;
17298   }
17299   // All conditions are met. Add a new bitfield to the tail end of ivars.
17300   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17301   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17302 
17303   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17304                               DeclLoc, DeclLoc, nullptr,
17305                               Context.CharTy,
17306                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17307                                                                DeclLoc),
17308                               ObjCIvarDecl::Private, BW,
17309                               true);
17310   AllIvarDecls.push_back(Ivar);
17311 }
17312 
17313 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17314                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17315                        SourceLocation RBrac,
17316                        const ParsedAttributesView &Attrs) {
17317   assert(EnclosingDecl && "missing record or interface decl");
17318 
17319   // If this is an Objective-C @implementation or category and we have
17320   // new fields here we should reset the layout of the interface since
17321   // it will now change.
17322   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17323     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17324     switch (DC->getKind()) {
17325     default: break;
17326     case Decl::ObjCCategory:
17327       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17328       break;
17329     case Decl::ObjCImplementation:
17330       Context.
17331         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17332       break;
17333     }
17334   }
17335 
17336   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17337   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17338 
17339   // Start counting up the number of named members; make sure to include
17340   // members of anonymous structs and unions in the total.
17341   unsigned NumNamedMembers = 0;
17342   if (Record) {
17343     for (const auto *I : Record->decls()) {
17344       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17345         if (IFD->getDeclName())
17346           ++NumNamedMembers;
17347     }
17348   }
17349 
17350   // Verify that all the fields are okay.
17351   SmallVector<FieldDecl*, 32> RecFields;
17352 
17353   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17354        i != end; ++i) {
17355     FieldDecl *FD = cast<FieldDecl>(*i);
17356 
17357     // Get the type for the field.
17358     const Type *FDTy = FD->getType().getTypePtr();
17359 
17360     if (!FD->isAnonymousStructOrUnion()) {
17361       // Remember all fields written by the user.
17362       RecFields.push_back(FD);
17363     }
17364 
17365     // If the field is already invalid for some reason, don't emit more
17366     // diagnostics about it.
17367     if (FD->isInvalidDecl()) {
17368       EnclosingDecl->setInvalidDecl();
17369       continue;
17370     }
17371 
17372     // C99 6.7.2.1p2:
17373     //   A structure or union shall not contain a member with
17374     //   incomplete or function type (hence, a structure shall not
17375     //   contain an instance of itself, but may contain a pointer to
17376     //   an instance of itself), except that the last member of a
17377     //   structure with more than one named member may have incomplete
17378     //   array type; such a structure (and any union containing,
17379     //   possibly recursively, a member that is such a structure)
17380     //   shall not be a member of a structure or an element of an
17381     //   array.
17382     bool IsLastField = (i + 1 == Fields.end());
17383     if (FDTy->isFunctionType()) {
17384       // Field declared as a function.
17385       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17386         << FD->getDeclName();
17387       FD->setInvalidDecl();
17388       EnclosingDecl->setInvalidDecl();
17389       continue;
17390     } else if (FDTy->isIncompleteArrayType() &&
17391                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17392       if (Record) {
17393         // Flexible array member.
17394         // Microsoft and g++ is more permissive regarding flexible array.
17395         // It will accept flexible array in union and also
17396         // as the sole element of a struct/class.
17397         unsigned DiagID = 0;
17398         if (!Record->isUnion() && !IsLastField) {
17399           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17400             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17401           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17402           FD->setInvalidDecl();
17403           EnclosingDecl->setInvalidDecl();
17404           continue;
17405         } else if (Record->isUnion())
17406           DiagID = getLangOpts().MicrosoftExt
17407                        ? diag::ext_flexible_array_union_ms
17408                        : getLangOpts().CPlusPlus
17409                              ? diag::ext_flexible_array_union_gnu
17410                              : diag::err_flexible_array_union;
17411         else if (NumNamedMembers < 1)
17412           DiagID = getLangOpts().MicrosoftExt
17413                        ? diag::ext_flexible_array_empty_aggregate_ms
17414                        : getLangOpts().CPlusPlus
17415                              ? diag::ext_flexible_array_empty_aggregate_gnu
17416                              : diag::err_flexible_array_empty_aggregate;
17417 
17418         if (DiagID)
17419           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17420                                           << Record->getTagKind();
17421         // While the layout of types that contain virtual bases is not specified
17422         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17423         // virtual bases after the derived members.  This would make a flexible
17424         // array member declared at the end of an object not adjacent to the end
17425         // of the type.
17426         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17427           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17428               << FD->getDeclName() << Record->getTagKind();
17429         if (!getLangOpts().C99)
17430           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17431             << FD->getDeclName() << Record->getTagKind();
17432 
17433         // If the element type has a non-trivial destructor, we would not
17434         // implicitly destroy the elements, so disallow it for now.
17435         //
17436         // FIXME: GCC allows this. We should probably either implicitly delete
17437         // the destructor of the containing class, or just allow this.
17438         QualType BaseElem = Context.getBaseElementType(FD->getType());
17439         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17440           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17441             << FD->getDeclName() << FD->getType();
17442           FD->setInvalidDecl();
17443           EnclosingDecl->setInvalidDecl();
17444           continue;
17445         }
17446         // Okay, we have a legal flexible array member at the end of the struct.
17447         Record->setHasFlexibleArrayMember(true);
17448       } else {
17449         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17450         // unless they are followed by another ivar. That check is done
17451         // elsewhere, after synthesized ivars are known.
17452       }
17453     } else if (!FDTy->isDependentType() &&
17454                RequireCompleteSizedType(
17455                    FD->getLocation(), FD->getType(),
17456                    diag::err_field_incomplete_or_sizeless)) {
17457       // Incomplete type
17458       FD->setInvalidDecl();
17459       EnclosingDecl->setInvalidDecl();
17460       continue;
17461     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17462       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17463         // A type which contains a flexible array member is considered to be a
17464         // flexible array member.
17465         Record->setHasFlexibleArrayMember(true);
17466         if (!Record->isUnion()) {
17467           // If this is a struct/class and this is not the last element, reject
17468           // it.  Note that GCC supports variable sized arrays in the middle of
17469           // structures.
17470           if (!IsLastField)
17471             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17472               << FD->getDeclName() << FD->getType();
17473           else {
17474             // We support flexible arrays at the end of structs in
17475             // other structs as an extension.
17476             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17477               << FD->getDeclName();
17478           }
17479         }
17480       }
17481       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17482           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17483                                  diag::err_abstract_type_in_decl,
17484                                  AbstractIvarType)) {
17485         // Ivars can not have abstract class types
17486         FD->setInvalidDecl();
17487       }
17488       if (Record && FDTTy->getDecl()->hasObjectMember())
17489         Record->setHasObjectMember(true);
17490       if (Record && FDTTy->getDecl()->hasVolatileMember())
17491         Record->setHasVolatileMember(true);
17492     } else if (FDTy->isObjCObjectType()) {
17493       /// A field cannot be an Objective-c object
17494       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17495         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17496       QualType T = Context.getObjCObjectPointerType(FD->getType());
17497       FD->setType(T);
17498     } else if (Record && Record->isUnion() &&
17499                FD->getType().hasNonTrivialObjCLifetime() &&
17500                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17501                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17502                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17503                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17504       // For backward compatibility, fields of C unions declared in system
17505       // headers that have non-trivial ObjC ownership qualifications are marked
17506       // as unavailable unless the qualifier is explicit and __strong. This can
17507       // break ABI compatibility between programs compiled with ARC and MRR, but
17508       // is a better option than rejecting programs using those unions under
17509       // ARC.
17510       FD->addAttr(UnavailableAttr::CreateImplicit(
17511           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17512           FD->getLocation()));
17513     } else if (getLangOpts().ObjC &&
17514                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17515                !Record->hasObjectMember()) {
17516       if (FD->getType()->isObjCObjectPointerType() ||
17517           FD->getType().isObjCGCStrong())
17518         Record->setHasObjectMember(true);
17519       else if (Context.getAsArrayType(FD->getType())) {
17520         QualType BaseType = Context.getBaseElementType(FD->getType());
17521         if (BaseType->isRecordType() &&
17522             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17523           Record->setHasObjectMember(true);
17524         else if (BaseType->isObjCObjectPointerType() ||
17525                  BaseType.isObjCGCStrong())
17526                Record->setHasObjectMember(true);
17527       }
17528     }
17529 
17530     if (Record && !getLangOpts().CPlusPlus &&
17531         !shouldIgnoreForRecordTriviality(FD)) {
17532       QualType FT = FD->getType();
17533       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17534         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17535         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17536             Record->isUnion())
17537           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17538       }
17539       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17540       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17541         Record->setNonTrivialToPrimitiveCopy(true);
17542         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17543           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17544       }
17545       if (FT.isDestructedType()) {
17546         Record->setNonTrivialToPrimitiveDestroy(true);
17547         Record->setParamDestroyedInCallee(true);
17548         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17549           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17550       }
17551 
17552       if (const auto *RT = FT->getAs<RecordType>()) {
17553         if (RT->getDecl()->getArgPassingRestrictions() ==
17554             RecordDecl::APK_CanNeverPassInRegs)
17555           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17556       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17557         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17558     }
17559 
17560     if (Record && FD->getType().isVolatileQualified())
17561       Record->setHasVolatileMember(true);
17562     // Keep track of the number of named members.
17563     if (FD->getIdentifier())
17564       ++NumNamedMembers;
17565   }
17566 
17567   // Okay, we successfully defined 'Record'.
17568   if (Record) {
17569     bool Completed = false;
17570     if (CXXRecord) {
17571       if (!CXXRecord->isInvalidDecl()) {
17572         // Set access bits correctly on the directly-declared conversions.
17573         for (CXXRecordDecl::conversion_iterator
17574                I = CXXRecord->conversion_begin(),
17575                E = CXXRecord->conversion_end(); I != E; ++I)
17576           I.setAccess((*I)->getAccess());
17577       }
17578 
17579       // Add any implicitly-declared members to this class.
17580       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17581 
17582       if (!CXXRecord->isDependentType()) {
17583         if (!CXXRecord->isInvalidDecl()) {
17584           // If we have virtual base classes, we may end up finding multiple
17585           // final overriders for a given virtual function. Check for this
17586           // problem now.
17587           if (CXXRecord->getNumVBases()) {
17588             CXXFinalOverriderMap FinalOverriders;
17589             CXXRecord->getFinalOverriders(FinalOverriders);
17590 
17591             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17592                                              MEnd = FinalOverriders.end();
17593                  M != MEnd; ++M) {
17594               for (OverridingMethods::iterator SO = M->second.begin(),
17595                                             SOEnd = M->second.end();
17596                    SO != SOEnd; ++SO) {
17597                 assert(SO->second.size() > 0 &&
17598                        "Virtual function without overriding functions?");
17599                 if (SO->second.size() == 1)
17600                   continue;
17601 
17602                 // C++ [class.virtual]p2:
17603                 //   In a derived class, if a virtual member function of a base
17604                 //   class subobject has more than one final overrider the
17605                 //   program is ill-formed.
17606                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17607                   << (const NamedDecl *)M->first << Record;
17608                 Diag(M->first->getLocation(),
17609                      diag::note_overridden_virtual_function);
17610                 for (OverridingMethods::overriding_iterator
17611                           OM = SO->second.begin(),
17612                        OMEnd = SO->second.end();
17613                      OM != OMEnd; ++OM)
17614                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17615                     << (const NamedDecl *)M->first << OM->Method->getParent();
17616 
17617                 Record->setInvalidDecl();
17618               }
17619             }
17620             CXXRecord->completeDefinition(&FinalOverriders);
17621             Completed = true;
17622           }
17623         }
17624       }
17625     }
17626 
17627     if (!Completed)
17628       Record->completeDefinition();
17629 
17630     // Handle attributes before checking the layout.
17631     ProcessDeclAttributeList(S, Record, Attrs);
17632 
17633     // We may have deferred checking for a deleted destructor. Check now.
17634     if (CXXRecord) {
17635       auto *Dtor = CXXRecord->getDestructor();
17636       if (Dtor && Dtor->isImplicit() &&
17637           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17638         CXXRecord->setImplicitDestructorIsDeleted();
17639         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17640       }
17641     }
17642 
17643     if (Record->hasAttrs()) {
17644       CheckAlignasUnderalignment(Record);
17645 
17646       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17647         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17648                                            IA->getRange(), IA->getBestCase(),
17649                                            IA->getInheritanceModel());
17650     }
17651 
17652     // Check if the structure/union declaration is a type that can have zero
17653     // size in C. For C this is a language extension, for C++ it may cause
17654     // compatibility problems.
17655     bool CheckForZeroSize;
17656     if (!getLangOpts().CPlusPlus) {
17657       CheckForZeroSize = true;
17658     } else {
17659       // For C++ filter out types that cannot be referenced in C code.
17660       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17661       CheckForZeroSize =
17662           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17663           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17664           CXXRecord->isCLike();
17665     }
17666     if (CheckForZeroSize) {
17667       bool ZeroSize = true;
17668       bool IsEmpty = true;
17669       unsigned NonBitFields = 0;
17670       for (RecordDecl::field_iterator I = Record->field_begin(),
17671                                       E = Record->field_end();
17672            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17673         IsEmpty = false;
17674         if (I->isUnnamedBitfield()) {
17675           if (!I->isZeroLengthBitField(Context))
17676             ZeroSize = false;
17677         } else {
17678           ++NonBitFields;
17679           QualType FieldType = I->getType();
17680           if (FieldType->isIncompleteType() ||
17681               !Context.getTypeSizeInChars(FieldType).isZero())
17682             ZeroSize = false;
17683         }
17684       }
17685 
17686       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17687       // allowed in C++, but warn if its declaration is inside
17688       // extern "C" block.
17689       if (ZeroSize) {
17690         Diag(RecLoc, getLangOpts().CPlusPlus ?
17691                          diag::warn_zero_size_struct_union_in_extern_c :
17692                          diag::warn_zero_size_struct_union_compat)
17693           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17694       }
17695 
17696       // Structs without named members are extension in C (C99 6.7.2.1p7),
17697       // but are accepted by GCC.
17698       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17699         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17700                                diag::ext_no_named_members_in_struct_union)
17701           << Record->isUnion();
17702       }
17703     }
17704   } else {
17705     ObjCIvarDecl **ClsFields =
17706       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17707     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17708       ID->setEndOfDefinitionLoc(RBrac);
17709       // Add ivar's to class's DeclContext.
17710       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17711         ClsFields[i]->setLexicalDeclContext(ID);
17712         ID->addDecl(ClsFields[i]);
17713       }
17714       // Must enforce the rule that ivars in the base classes may not be
17715       // duplicates.
17716       if (ID->getSuperClass())
17717         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17718     } else if (ObjCImplementationDecl *IMPDecl =
17719                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17720       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17721       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17722         // Ivar declared in @implementation never belongs to the implementation.
17723         // Only it is in implementation's lexical context.
17724         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17725       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17726       IMPDecl->setIvarLBraceLoc(LBrac);
17727       IMPDecl->setIvarRBraceLoc(RBrac);
17728     } else if (ObjCCategoryDecl *CDecl =
17729                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17730       // case of ivars in class extension; all other cases have been
17731       // reported as errors elsewhere.
17732       // FIXME. Class extension does not have a LocEnd field.
17733       // CDecl->setLocEnd(RBrac);
17734       // Add ivar's to class extension's DeclContext.
17735       // Diagnose redeclaration of private ivars.
17736       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17737       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17738         if (IDecl) {
17739           if (const ObjCIvarDecl *ClsIvar =
17740               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17741             Diag(ClsFields[i]->getLocation(),
17742                  diag::err_duplicate_ivar_declaration);
17743             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17744             continue;
17745           }
17746           for (const auto *Ext : IDecl->known_extensions()) {
17747             if (const ObjCIvarDecl *ClsExtIvar
17748                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17749               Diag(ClsFields[i]->getLocation(),
17750                    diag::err_duplicate_ivar_declaration);
17751               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17752               continue;
17753             }
17754           }
17755         }
17756         ClsFields[i]->setLexicalDeclContext(CDecl);
17757         CDecl->addDecl(ClsFields[i]);
17758       }
17759       CDecl->setIvarLBraceLoc(LBrac);
17760       CDecl->setIvarRBraceLoc(RBrac);
17761     }
17762   }
17763 }
17764 
17765 /// Determine whether the given integral value is representable within
17766 /// the given type T.
17767 static bool isRepresentableIntegerValue(ASTContext &Context,
17768                                         llvm::APSInt &Value,
17769                                         QualType T) {
17770   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17771          "Integral type required!");
17772   unsigned BitWidth = Context.getIntWidth(T);
17773 
17774   if (Value.isUnsigned() || Value.isNonNegative()) {
17775     if (T->isSignedIntegerOrEnumerationType())
17776       --BitWidth;
17777     return Value.getActiveBits() <= BitWidth;
17778   }
17779   return Value.getMinSignedBits() <= BitWidth;
17780 }
17781 
17782 // Given an integral type, return the next larger integral type
17783 // (or a NULL type of no such type exists).
17784 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17785   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17786   // enum checking below.
17787   assert((T->isIntegralType(Context) ||
17788          T->isEnumeralType()) && "Integral type required!");
17789   const unsigned NumTypes = 4;
17790   QualType SignedIntegralTypes[NumTypes] = {
17791     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17792   };
17793   QualType UnsignedIntegralTypes[NumTypes] = {
17794     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17795     Context.UnsignedLongLongTy
17796   };
17797 
17798   unsigned BitWidth = Context.getTypeSize(T);
17799   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17800                                                         : UnsignedIntegralTypes;
17801   for (unsigned I = 0; I != NumTypes; ++I)
17802     if (Context.getTypeSize(Types[I]) > BitWidth)
17803       return Types[I];
17804 
17805   return QualType();
17806 }
17807 
17808 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17809                                           EnumConstantDecl *LastEnumConst,
17810                                           SourceLocation IdLoc,
17811                                           IdentifierInfo *Id,
17812                                           Expr *Val) {
17813   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17814   llvm::APSInt EnumVal(IntWidth);
17815   QualType EltTy;
17816 
17817   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17818     Val = nullptr;
17819 
17820   if (Val)
17821     Val = DefaultLvalueConversion(Val).get();
17822 
17823   if (Val) {
17824     if (Enum->isDependentType() || Val->isTypeDependent() ||
17825         Val->containsErrors())
17826       EltTy = Context.DependentTy;
17827     else {
17828       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17829       // underlying type, but do allow it in all other contexts.
17830       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17831         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17832         // constant-expression in the enumerator-definition shall be a converted
17833         // constant expression of the underlying type.
17834         EltTy = Enum->getIntegerType();
17835         ExprResult Converted =
17836           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17837                                            CCEK_Enumerator);
17838         if (Converted.isInvalid())
17839           Val = nullptr;
17840         else
17841           Val = Converted.get();
17842       } else if (!Val->isValueDependent() &&
17843                  !(Val =
17844                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17845                            .get())) {
17846         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17847       } else {
17848         if (Enum->isComplete()) {
17849           EltTy = Enum->getIntegerType();
17850 
17851           // In Obj-C and Microsoft mode, require the enumeration value to be
17852           // representable in the underlying type of the enumeration. In C++11,
17853           // we perform a non-narrowing conversion as part of converted constant
17854           // expression checking.
17855           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17856             if (Context.getTargetInfo()
17857                     .getTriple()
17858                     .isWindowsMSVCEnvironment()) {
17859               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17860             } else {
17861               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17862             }
17863           }
17864 
17865           // Cast to the underlying type.
17866           Val = ImpCastExprToType(Val, EltTy,
17867                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17868                                                          : CK_IntegralCast)
17869                     .get();
17870         } else if (getLangOpts().CPlusPlus) {
17871           // C++11 [dcl.enum]p5:
17872           //   If the underlying type is not fixed, the type of each enumerator
17873           //   is the type of its initializing value:
17874           //     - If an initializer is specified for an enumerator, the
17875           //       initializing value has the same type as the expression.
17876           EltTy = Val->getType();
17877         } else {
17878           // C99 6.7.2.2p2:
17879           //   The expression that defines the value of an enumeration constant
17880           //   shall be an integer constant expression that has a value
17881           //   representable as an int.
17882 
17883           // Complain if the value is not representable in an int.
17884           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17885             Diag(IdLoc, diag::ext_enum_value_not_int)
17886               << toString(EnumVal, 10) << Val->getSourceRange()
17887               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17888           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17889             // Force the type of the expression to 'int'.
17890             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17891           }
17892           EltTy = Val->getType();
17893         }
17894       }
17895     }
17896   }
17897 
17898   if (!Val) {
17899     if (Enum->isDependentType())
17900       EltTy = Context.DependentTy;
17901     else if (!LastEnumConst) {
17902       // C++0x [dcl.enum]p5:
17903       //   If the underlying type is not fixed, the type of each enumerator
17904       //   is the type of its initializing value:
17905       //     - If no initializer is specified for the first enumerator, the
17906       //       initializing value has an unspecified integral type.
17907       //
17908       // GCC uses 'int' for its unspecified integral type, as does
17909       // C99 6.7.2.2p3.
17910       if (Enum->isFixed()) {
17911         EltTy = Enum->getIntegerType();
17912       }
17913       else {
17914         EltTy = Context.IntTy;
17915       }
17916     } else {
17917       // Assign the last value + 1.
17918       EnumVal = LastEnumConst->getInitVal();
17919       ++EnumVal;
17920       EltTy = LastEnumConst->getType();
17921 
17922       // Check for overflow on increment.
17923       if (EnumVal < LastEnumConst->getInitVal()) {
17924         // C++0x [dcl.enum]p5:
17925         //   If the underlying type is not fixed, the type of each enumerator
17926         //   is the type of its initializing value:
17927         //
17928         //     - Otherwise the type of the initializing value is the same as
17929         //       the type of the initializing value of the preceding enumerator
17930         //       unless the incremented value is not representable in that type,
17931         //       in which case the type is an unspecified integral type
17932         //       sufficient to contain the incremented value. If no such type
17933         //       exists, the program is ill-formed.
17934         QualType T = getNextLargerIntegralType(Context, EltTy);
17935         if (T.isNull() || Enum->isFixed()) {
17936           // There is no integral type larger enough to represent this
17937           // value. Complain, then allow the value to wrap around.
17938           EnumVal = LastEnumConst->getInitVal();
17939           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17940           ++EnumVal;
17941           if (Enum->isFixed())
17942             // When the underlying type is fixed, this is ill-formed.
17943             Diag(IdLoc, diag::err_enumerator_wrapped)
17944               << toString(EnumVal, 10)
17945               << EltTy;
17946           else
17947             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17948               << toString(EnumVal, 10);
17949         } else {
17950           EltTy = T;
17951         }
17952 
17953         // Retrieve the last enumerator's value, extent that type to the
17954         // type that is supposed to be large enough to represent the incremented
17955         // value, then increment.
17956         EnumVal = LastEnumConst->getInitVal();
17957         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17958         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17959         ++EnumVal;
17960 
17961         // If we're not in C++, diagnose the overflow of enumerator values,
17962         // which in C99 means that the enumerator value is not representable in
17963         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17964         // permits enumerator values that are representable in some larger
17965         // integral type.
17966         if (!getLangOpts().CPlusPlus && !T.isNull())
17967           Diag(IdLoc, diag::warn_enum_value_overflow);
17968       } else if (!getLangOpts().CPlusPlus &&
17969                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17970         // Enforce C99 6.7.2.2p2 even when we compute the next value.
17971         Diag(IdLoc, diag::ext_enum_value_not_int)
17972           << toString(EnumVal, 10) << 1;
17973       }
17974     }
17975   }
17976 
17977   if (!EltTy->isDependentType()) {
17978     // Make the enumerator value match the signedness and size of the
17979     // enumerator's type.
17980     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17981     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17982   }
17983 
17984   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17985                                   Val, EnumVal);
17986 }
17987 
17988 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17989                                                 SourceLocation IILoc) {
17990   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17991       !getLangOpts().CPlusPlus)
17992     return SkipBodyInfo();
17993 
17994   // We have an anonymous enum definition. Look up the first enumerator to
17995   // determine if we should merge the definition with an existing one and
17996   // skip the body.
17997   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17998                                          forRedeclarationInCurContext());
17999   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18000   if (!PrevECD)
18001     return SkipBodyInfo();
18002 
18003   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18004   NamedDecl *Hidden;
18005   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18006     SkipBodyInfo Skip;
18007     Skip.Previous = Hidden;
18008     return Skip;
18009   }
18010 
18011   return SkipBodyInfo();
18012 }
18013 
18014 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18015                               SourceLocation IdLoc, IdentifierInfo *Id,
18016                               const ParsedAttributesView &Attrs,
18017                               SourceLocation EqualLoc, Expr *Val) {
18018   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18019   EnumConstantDecl *LastEnumConst =
18020     cast_or_null<EnumConstantDecl>(lastEnumConst);
18021 
18022   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18023   // we find one that is.
18024   S = getNonFieldDeclScope(S);
18025 
18026   // Verify that there isn't already something declared with this name in this
18027   // scope.
18028   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18029   LookupName(R, S);
18030   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18031 
18032   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18033     // Maybe we will complain about the shadowed template parameter.
18034     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18035     // Just pretend that we didn't see the previous declaration.
18036     PrevDecl = nullptr;
18037   }
18038 
18039   // C++ [class.mem]p15:
18040   // If T is the name of a class, then each of the following shall have a name
18041   // different from T:
18042   // - every enumerator of every member of class T that is an unscoped
18043   // enumerated type
18044   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18045     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18046                             DeclarationNameInfo(Id, IdLoc));
18047 
18048   EnumConstantDecl *New =
18049     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18050   if (!New)
18051     return nullptr;
18052 
18053   if (PrevDecl) {
18054     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18055       // Check for other kinds of shadowing not already handled.
18056       CheckShadow(New, PrevDecl, R);
18057     }
18058 
18059     // When in C++, we may get a TagDecl with the same name; in this case the
18060     // enum constant will 'hide' the tag.
18061     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18062            "Received TagDecl when not in C++!");
18063     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18064       if (isa<EnumConstantDecl>(PrevDecl))
18065         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18066       else
18067         Diag(IdLoc, diag::err_redefinition) << Id;
18068       notePreviousDefinition(PrevDecl, IdLoc);
18069       return nullptr;
18070     }
18071   }
18072 
18073   // Process attributes.
18074   ProcessDeclAttributeList(S, New, Attrs);
18075   AddPragmaAttributes(S, New);
18076 
18077   // Register this decl in the current scope stack.
18078   New->setAccess(TheEnumDecl->getAccess());
18079   PushOnScopeChains(New, S);
18080 
18081   ActOnDocumentableDecl(New);
18082 
18083   return New;
18084 }
18085 
18086 // Returns true when the enum initial expression does not trigger the
18087 // duplicate enum warning.  A few common cases are exempted as follows:
18088 // Element2 = Element1
18089 // Element2 = Element1 + 1
18090 // Element2 = Element1 - 1
18091 // Where Element2 and Element1 are from the same enum.
18092 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18093   Expr *InitExpr = ECD->getInitExpr();
18094   if (!InitExpr)
18095     return true;
18096   InitExpr = InitExpr->IgnoreImpCasts();
18097 
18098   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18099     if (!BO->isAdditiveOp())
18100       return true;
18101     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18102     if (!IL)
18103       return true;
18104     if (IL->getValue() != 1)
18105       return true;
18106 
18107     InitExpr = BO->getLHS();
18108   }
18109 
18110   // This checks if the elements are from the same enum.
18111   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18112   if (!DRE)
18113     return true;
18114 
18115   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18116   if (!EnumConstant)
18117     return true;
18118 
18119   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18120       Enum)
18121     return true;
18122 
18123   return false;
18124 }
18125 
18126 // Emits a warning when an element is implicitly set a value that
18127 // a previous element has already been set to.
18128 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18129                                         EnumDecl *Enum, QualType EnumType) {
18130   // Avoid anonymous enums
18131   if (!Enum->getIdentifier())
18132     return;
18133 
18134   // Only check for small enums.
18135   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18136     return;
18137 
18138   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18139     return;
18140 
18141   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18142   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18143 
18144   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18145 
18146   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18147   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18148 
18149   // Use int64_t as a key to avoid needing special handling for map keys.
18150   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18151     llvm::APSInt Val = D->getInitVal();
18152     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18153   };
18154 
18155   DuplicatesVector DupVector;
18156   ValueToVectorMap EnumMap;
18157 
18158   // Populate the EnumMap with all values represented by enum constants without
18159   // an initializer.
18160   for (auto *Element : Elements) {
18161     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18162 
18163     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18164     // this constant.  Skip this enum since it may be ill-formed.
18165     if (!ECD) {
18166       return;
18167     }
18168 
18169     // Constants with initalizers are handled in the next loop.
18170     if (ECD->getInitExpr())
18171       continue;
18172 
18173     // Duplicate values are handled in the next loop.
18174     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18175   }
18176 
18177   if (EnumMap.size() == 0)
18178     return;
18179 
18180   // Create vectors for any values that has duplicates.
18181   for (auto *Element : Elements) {
18182     // The last loop returned if any constant was null.
18183     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18184     if (!ValidDuplicateEnum(ECD, Enum))
18185       continue;
18186 
18187     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18188     if (Iter == EnumMap.end())
18189       continue;
18190 
18191     DeclOrVector& Entry = Iter->second;
18192     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18193       // Ensure constants are different.
18194       if (D == ECD)
18195         continue;
18196 
18197       // Create new vector and push values onto it.
18198       auto Vec = std::make_unique<ECDVector>();
18199       Vec->push_back(D);
18200       Vec->push_back(ECD);
18201 
18202       // Update entry to point to the duplicates vector.
18203       Entry = Vec.get();
18204 
18205       // Store the vector somewhere we can consult later for quick emission of
18206       // diagnostics.
18207       DupVector.emplace_back(std::move(Vec));
18208       continue;
18209     }
18210 
18211     ECDVector *Vec = Entry.get<ECDVector*>();
18212     // Make sure constants are not added more than once.
18213     if (*Vec->begin() == ECD)
18214       continue;
18215 
18216     Vec->push_back(ECD);
18217   }
18218 
18219   // Emit diagnostics.
18220   for (const auto &Vec : DupVector) {
18221     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18222 
18223     // Emit warning for one enum constant.
18224     auto *FirstECD = Vec->front();
18225     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18226       << FirstECD << toString(FirstECD->getInitVal(), 10)
18227       << FirstECD->getSourceRange();
18228 
18229     // Emit one note for each of the remaining enum constants with
18230     // the same value.
18231     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18232       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18233         << ECD << toString(ECD->getInitVal(), 10)
18234         << ECD->getSourceRange();
18235   }
18236 }
18237 
18238 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18239                              bool AllowMask) const {
18240   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18241   assert(ED->isCompleteDefinition() && "expected enum definition");
18242 
18243   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18244   llvm::APInt &FlagBits = R.first->second;
18245 
18246   if (R.second) {
18247     for (auto *E : ED->enumerators()) {
18248       const auto &EVal = E->getInitVal();
18249       // Only single-bit enumerators introduce new flag values.
18250       if (EVal.isPowerOf2())
18251         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18252     }
18253   }
18254 
18255   // A value is in a flag enum if either its bits are a subset of the enum's
18256   // flag bits (the first condition) or we are allowing masks and the same is
18257   // true of its complement (the second condition). When masks are allowed, we
18258   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18259   //
18260   // While it's true that any value could be used as a mask, the assumption is
18261   // that a mask will have all of the insignificant bits set. Anything else is
18262   // likely a logic error.
18263   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18264   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18265 }
18266 
18267 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18268                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18269                          const ParsedAttributesView &Attrs) {
18270   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18271   QualType EnumType = Context.getTypeDeclType(Enum);
18272 
18273   ProcessDeclAttributeList(S, Enum, Attrs);
18274 
18275   if (Enum->isDependentType()) {
18276     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18277       EnumConstantDecl *ECD =
18278         cast_or_null<EnumConstantDecl>(Elements[i]);
18279       if (!ECD) continue;
18280 
18281       ECD->setType(EnumType);
18282     }
18283 
18284     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18285     return;
18286   }
18287 
18288   // TODO: If the result value doesn't fit in an int, it must be a long or long
18289   // long value.  ISO C does not support this, but GCC does as an extension,
18290   // emit a warning.
18291   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18292   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18293   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18294 
18295   // Verify that all the values are okay, compute the size of the values, and
18296   // reverse the list.
18297   unsigned NumNegativeBits = 0;
18298   unsigned NumPositiveBits = 0;
18299 
18300   // Keep track of whether all elements have type int.
18301   bool AllElementsInt = true;
18302 
18303   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18304     EnumConstantDecl *ECD =
18305       cast_or_null<EnumConstantDecl>(Elements[i]);
18306     if (!ECD) continue;  // Already issued a diagnostic.
18307 
18308     const llvm::APSInt &InitVal = ECD->getInitVal();
18309 
18310     // Keep track of the size of positive and negative values.
18311     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18312       NumPositiveBits = std::max(NumPositiveBits,
18313                                  (unsigned)InitVal.getActiveBits());
18314     else
18315       NumNegativeBits = std::max(NumNegativeBits,
18316                                  (unsigned)InitVal.getMinSignedBits());
18317 
18318     // Keep track of whether every enum element has type int (very common).
18319     if (AllElementsInt)
18320       AllElementsInt = ECD->getType() == Context.IntTy;
18321   }
18322 
18323   // Figure out the type that should be used for this enum.
18324   QualType BestType;
18325   unsigned BestWidth;
18326 
18327   // C++0x N3000 [conv.prom]p3:
18328   //   An rvalue of an unscoped enumeration type whose underlying
18329   //   type is not fixed can be converted to an rvalue of the first
18330   //   of the following types that can represent all the values of
18331   //   the enumeration: int, unsigned int, long int, unsigned long
18332   //   int, long long int, or unsigned long long int.
18333   // C99 6.4.4.3p2:
18334   //   An identifier declared as an enumeration constant has type int.
18335   // The C99 rule is modified by a gcc extension
18336   QualType BestPromotionType;
18337 
18338   bool Packed = Enum->hasAttr<PackedAttr>();
18339   // -fshort-enums is the equivalent to specifying the packed attribute on all
18340   // enum definitions.
18341   if (LangOpts.ShortEnums)
18342     Packed = true;
18343 
18344   // If the enum already has a type because it is fixed or dictated by the
18345   // target, promote that type instead of analyzing the enumerators.
18346   if (Enum->isComplete()) {
18347     BestType = Enum->getIntegerType();
18348     if (BestType->isPromotableIntegerType())
18349       BestPromotionType = Context.getPromotedIntegerType(BestType);
18350     else
18351       BestPromotionType = BestType;
18352 
18353     BestWidth = Context.getIntWidth(BestType);
18354   }
18355   else if (NumNegativeBits) {
18356     // If there is a negative value, figure out the smallest integer type (of
18357     // int/long/longlong) that fits.
18358     // If it's packed, check also if it fits a char or a short.
18359     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18360       BestType = Context.SignedCharTy;
18361       BestWidth = CharWidth;
18362     } else if (Packed && NumNegativeBits <= ShortWidth &&
18363                NumPositiveBits < ShortWidth) {
18364       BestType = Context.ShortTy;
18365       BestWidth = ShortWidth;
18366     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18367       BestType = Context.IntTy;
18368       BestWidth = IntWidth;
18369     } else {
18370       BestWidth = Context.getTargetInfo().getLongWidth();
18371 
18372       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18373         BestType = Context.LongTy;
18374       } else {
18375         BestWidth = Context.getTargetInfo().getLongLongWidth();
18376 
18377         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18378           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18379         BestType = Context.LongLongTy;
18380       }
18381     }
18382     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18383   } else {
18384     // If there is no negative value, figure out the smallest type that fits
18385     // all of the enumerator values.
18386     // If it's packed, check also if it fits a char or a short.
18387     if (Packed && NumPositiveBits <= CharWidth) {
18388       BestType = Context.UnsignedCharTy;
18389       BestPromotionType = Context.IntTy;
18390       BestWidth = CharWidth;
18391     } else if (Packed && NumPositiveBits <= ShortWidth) {
18392       BestType = Context.UnsignedShortTy;
18393       BestPromotionType = Context.IntTy;
18394       BestWidth = ShortWidth;
18395     } else if (NumPositiveBits <= IntWidth) {
18396       BestType = Context.UnsignedIntTy;
18397       BestWidth = IntWidth;
18398       BestPromotionType
18399         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18400                            ? Context.UnsignedIntTy : Context.IntTy;
18401     } else if (NumPositiveBits <=
18402                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18403       BestType = Context.UnsignedLongTy;
18404       BestPromotionType
18405         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18406                            ? Context.UnsignedLongTy : Context.LongTy;
18407     } else {
18408       BestWidth = Context.getTargetInfo().getLongLongWidth();
18409       assert(NumPositiveBits <= BestWidth &&
18410              "How could an initializer get larger than ULL?");
18411       BestType = Context.UnsignedLongLongTy;
18412       BestPromotionType
18413         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18414                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18415     }
18416   }
18417 
18418   // Loop over all of the enumerator constants, changing their types to match
18419   // the type of the enum if needed.
18420   for (auto *D : Elements) {
18421     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18422     if (!ECD) continue;  // Already issued a diagnostic.
18423 
18424     // Standard C says the enumerators have int type, but we allow, as an
18425     // extension, the enumerators to be larger than int size.  If each
18426     // enumerator value fits in an int, type it as an int, otherwise type it the
18427     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18428     // that X has type 'int', not 'unsigned'.
18429 
18430     // Determine whether the value fits into an int.
18431     llvm::APSInt InitVal = ECD->getInitVal();
18432 
18433     // If it fits into an integer type, force it.  Otherwise force it to match
18434     // the enum decl type.
18435     QualType NewTy;
18436     unsigned NewWidth;
18437     bool NewSign;
18438     if (!getLangOpts().CPlusPlus &&
18439         !Enum->isFixed() &&
18440         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18441       NewTy = Context.IntTy;
18442       NewWidth = IntWidth;
18443       NewSign = true;
18444     } else if (ECD->getType() == BestType) {
18445       // Already the right type!
18446       if (getLangOpts().CPlusPlus)
18447         // C++ [dcl.enum]p4: Following the closing brace of an
18448         // enum-specifier, each enumerator has the type of its
18449         // enumeration.
18450         ECD->setType(EnumType);
18451       continue;
18452     } else {
18453       NewTy = BestType;
18454       NewWidth = BestWidth;
18455       NewSign = BestType->isSignedIntegerOrEnumerationType();
18456     }
18457 
18458     // Adjust the APSInt value.
18459     InitVal = InitVal.extOrTrunc(NewWidth);
18460     InitVal.setIsSigned(NewSign);
18461     ECD->setInitVal(InitVal);
18462 
18463     // Adjust the Expr initializer and type.
18464     if (ECD->getInitExpr() &&
18465         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18466       ECD->setInitExpr(ImplicitCastExpr::Create(
18467           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18468           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18469     if (getLangOpts().CPlusPlus)
18470       // C++ [dcl.enum]p4: Following the closing brace of an
18471       // enum-specifier, each enumerator has the type of its
18472       // enumeration.
18473       ECD->setType(EnumType);
18474     else
18475       ECD->setType(NewTy);
18476   }
18477 
18478   Enum->completeDefinition(BestType, BestPromotionType,
18479                            NumPositiveBits, NumNegativeBits);
18480 
18481   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18482 
18483   if (Enum->isClosedFlag()) {
18484     for (Decl *D : Elements) {
18485       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18486       if (!ECD) continue;  // Already issued a diagnostic.
18487 
18488       llvm::APSInt InitVal = ECD->getInitVal();
18489       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18490           !IsValueInFlagEnum(Enum, InitVal, true))
18491         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18492           << ECD << Enum;
18493     }
18494   }
18495 
18496   // Now that the enum type is defined, ensure it's not been underaligned.
18497   if (Enum->hasAttrs())
18498     CheckAlignasUnderalignment(Enum);
18499 }
18500 
18501 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18502                                   SourceLocation StartLoc,
18503                                   SourceLocation EndLoc) {
18504   StringLiteral *AsmString = cast<StringLiteral>(expr);
18505 
18506   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18507                                                    AsmString, StartLoc,
18508                                                    EndLoc);
18509   CurContext->addDecl(New);
18510   return New;
18511 }
18512 
18513 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18514                                       IdentifierInfo* AliasName,
18515                                       SourceLocation PragmaLoc,
18516                                       SourceLocation NameLoc,
18517                                       SourceLocation AliasNameLoc) {
18518   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18519                                          LookupOrdinaryName);
18520   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18521                            AttributeCommonInfo::AS_Pragma);
18522   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18523       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18524 
18525   // If a declaration that:
18526   // 1) declares a function or a variable
18527   // 2) has external linkage
18528   // already exists, add a label attribute to it.
18529   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18530     if (isDeclExternC(PrevDecl))
18531       PrevDecl->addAttr(Attr);
18532     else
18533       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18534           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18535   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18536   } else
18537     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18538 }
18539 
18540 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18541                              SourceLocation PragmaLoc,
18542                              SourceLocation NameLoc) {
18543   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18544 
18545   if (PrevDecl) {
18546     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18547   } else {
18548     (void)WeakUndeclaredIdentifiers.insert(
18549       std::pair<IdentifierInfo*,WeakInfo>
18550         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18551   }
18552 }
18553 
18554 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18555                                 IdentifierInfo* AliasName,
18556                                 SourceLocation PragmaLoc,
18557                                 SourceLocation NameLoc,
18558                                 SourceLocation AliasNameLoc) {
18559   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18560                                     LookupOrdinaryName);
18561   WeakInfo W = WeakInfo(Name, NameLoc);
18562 
18563   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18564     if (!PrevDecl->hasAttr<AliasAttr>())
18565       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18566         DeclApplyPragmaWeak(TUScope, ND, W);
18567   } else {
18568     (void)WeakUndeclaredIdentifiers.insert(
18569       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18570   }
18571 }
18572 
18573 Decl *Sema::getObjCDeclContext() const {
18574   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18575 }
18576 
18577 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18578                                                      bool Final) {
18579   assert(FD && "Expected non-null FunctionDecl");
18580 
18581   // SYCL functions can be template, so we check if they have appropriate
18582   // attribute prior to checking if it is a template.
18583   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18584     return FunctionEmissionStatus::Emitted;
18585 
18586   // Templates are emitted when they're instantiated.
18587   if (FD->isDependentContext())
18588     return FunctionEmissionStatus::TemplateDiscarded;
18589 
18590   // Check whether this function is an externally visible definition.
18591   auto IsEmittedForExternalSymbol = [this, FD]() {
18592     // We have to check the GVA linkage of the function's *definition* -- if we
18593     // only have a declaration, we don't know whether or not the function will
18594     // be emitted, because (say) the definition could include "inline".
18595     FunctionDecl *Def = FD->getDefinition();
18596 
18597     return Def && !isDiscardableGVALinkage(
18598                       getASTContext().GetGVALinkageForFunction(Def));
18599   };
18600 
18601   if (LangOpts.OpenMPIsDevice) {
18602     // In OpenMP device mode we will not emit host only functions, or functions
18603     // we don't need due to their linkage.
18604     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18605         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18606     // DevTy may be changed later by
18607     //  #pragma omp declare target to(*) device_type(*).
18608     // Therefore DevTy having no value does not imply host. The emission status
18609     // will be checked again at the end of compilation unit with Final = true.
18610     if (DevTy.hasValue())
18611       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18612         return FunctionEmissionStatus::OMPDiscarded;
18613     // If we have an explicit value for the device type, or we are in a target
18614     // declare context, we need to emit all extern and used symbols.
18615     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18616       if (IsEmittedForExternalSymbol())
18617         return FunctionEmissionStatus::Emitted;
18618     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18619     // we'll omit it.
18620     if (Final)
18621       return FunctionEmissionStatus::OMPDiscarded;
18622   } else if (LangOpts.OpenMP > 45) {
18623     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18624     // function. In 5.0, no_host was introduced which might cause a function to
18625     // be ommitted.
18626     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18627         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18628     if (DevTy.hasValue())
18629       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18630         return FunctionEmissionStatus::OMPDiscarded;
18631   }
18632 
18633   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18634     return FunctionEmissionStatus::Emitted;
18635 
18636   if (LangOpts.CUDA) {
18637     // When compiling for device, host functions are never emitted.  Similarly,
18638     // when compiling for host, device and global functions are never emitted.
18639     // (Technically, we do emit a host-side stub for global functions, but this
18640     // doesn't count for our purposes here.)
18641     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18642     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18643       return FunctionEmissionStatus::CUDADiscarded;
18644     if (!LangOpts.CUDAIsDevice &&
18645         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18646       return FunctionEmissionStatus::CUDADiscarded;
18647 
18648     if (IsEmittedForExternalSymbol())
18649       return FunctionEmissionStatus::Emitted;
18650   }
18651 
18652   // Otherwise, the function is known-emitted if it's in our set of
18653   // known-emitted functions.
18654   return FunctionEmissionStatus::Unknown;
18655 }
18656 
18657 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18658   // Host-side references to a __global__ function refer to the stub, so the
18659   // function itself is never emitted and therefore should not be marked.
18660   // If we have host fn calls kernel fn calls host+device, the HD function
18661   // does not get instantiated on the host. We model this by omitting at the
18662   // call to the kernel from the callgraph. This ensures that, when compiling
18663   // for host, only HD functions actually called from the host get marked as
18664   // known-emitted.
18665   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18666          IdentifyCUDATarget(Callee) == CFT_Global;
18667 }
18668